LCOV - code coverage report
Current view: top level - frmts/gtiff - gtiffdataset_write.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 3765 4105 91.7 %
Date: 2025-02-20 10:14:44 Functions: 108 132 81.8 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  GeoTIFF Driver
       4             :  * Purpose:  Write/set operations on GTiffDataset
       5             :  * Author:   Frank Warmerdam, warmerdam@pobox.com
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 1998, 2002, Frank Warmerdam <warmerdam@pobox.com>
       9             :  * Copyright (c) 2007-2015, Even Rouault <even dot rouault at spatialys dot com>
      10             :  *
      11             :  * SPDX-License-Identifier: MIT
      12             :  ****************************************************************************/
      13             : 
      14             : #include "gtiffdataset.h"
      15             : #include "gtiffrasterband.h"
      16             : #include "gtiffoddbitsband.h"
      17             : 
      18             : #include <cassert>
      19             : #include <cerrno>
      20             : 
      21             : #include <algorithm>
      22             : #include <cmath>
      23             : #include <limits>
      24             : #include <memory>
      25             : #include <mutex>
      26             : #include <set>
      27             : #include <string>
      28             : #include <tuple>
      29             : #include <utility>
      30             : 
      31             : #include "cpl_error.h"
      32             : #include "cpl_error_internal.h"  // CPLErrorHandlerAccumulatorStruct
      33             : #include "cpl_float.h"
      34             : #include "cpl_md5.h"
      35             : #include "cpl_vsi.h"
      36             : #include "cpl_vsi_virtual.h"
      37             : #include "cpl_worker_thread_pool.h"
      38             : #include "fetchbufferdirectio.h"
      39             : #include "gdal_mdreader.h"          // GDALWriteRPCTXTFile()
      40             : #include "gdal_priv_templates.hpp"  // GDALIsValueInRange<>
      41             : #include "gdal_thread_pool.h"       // GDALGetGlobalThreadPool()
      42             : #include "geovalues.h"              // RasterPixelIsPoint
      43             : #include "gt_jpeg_copy.h"
      44             : #include "gt_overview.h"  // GTIFFBuildOverviewMetadata()
      45             : #include "quant_table_md5sum.h"
      46             : #include "quant_table_md5sum_jpeg9e.h"
      47             : #include "tif_jxl.h"
      48             : #include "tifvsi.h"
      49             : #include "xtiffio.h"
      50             : 
      51             : #if LIFFLIB_VERSION > 20230908 || defined(INTERNAL_LIBTIFF)
      52             : /* libtiff < 4.6.1 doesn't generate a LERC mask for multi-band contig configuration */
      53             : #define LIBTIFF_MULTIBAND_LERC_NAN_OK
      54             : #endif
      55             : 
      56             : static const int knGTIFFJpegTablesModeDefault = JPEGTABLESMODE_QUANT;
      57             : 
      58             : static constexpr const char szPROFILE_BASELINE[] = "BASELINE";
      59             : static constexpr const char szPROFILE_GeoTIFF[] = "GeoTIFF";
      60             : static constexpr const char szPROFILE_GDALGeoTIFF[] = "GDALGeoTIFF";
      61             : 
      62             : // Due to libgeotiff/xtiff.c declaring TIFFTAG_GEOTIEPOINTS with field_readcount
      63             : // and field_writecount == -1 == TIFF_VARIABLE, we are limited to writing
      64             : // 65535 values in that tag. That could potentially be overcome by changing the tag
      65             : // declaration to using TIFF_VARIABLE2 where the count is a uint32_t.
      66             : constexpr int knMAX_GCP_COUNT =
      67             :     static_cast<int>(std::numeric_limits<uint16_t>::max() / 6);
      68             : 
      69             : enum
      70             : {
      71             :     ENDIANNESS_NATIVE,
      72             :     ENDIANNESS_LITTLE,
      73             :     ENDIANNESS_BIG
      74             : };
      75             : 
      76       12290 : static signed char GTiffGetWebPLevel(CSLConstList papszOptions)
      77             : {
      78       12290 :     int nWebPLevel = DEFAULT_WEBP_LEVEL;
      79       12290 :     const char *pszValue = CSLFetchNameValue(papszOptions, "WEBP_LEVEL");
      80       12290 :     if (pszValue != nullptr)
      81             :     {
      82          51 :         nWebPLevel = atoi(pszValue);
      83          51 :         if (!(nWebPLevel >= 1 && nWebPLevel <= 100))
      84             :         {
      85           0 :             CPLError(CE_Warning, CPLE_IllegalArg,
      86             :                      "WEBP_LEVEL=%s value not recognised, ignoring.", pszValue);
      87           0 :             nWebPLevel = DEFAULT_WEBP_LEVEL;
      88             :         }
      89             :     }
      90       12290 :     return static_cast<signed char>(nWebPLevel);
      91             : }
      92             : 
      93       12296 : static bool GTiffGetWebPLossless(CSLConstList papszOptions)
      94             : {
      95       12296 :     return CPLFetchBool(papszOptions, "WEBP_LOSSLESS", false);
      96             : }
      97             : 
      98       12362 : static double GTiffGetLERCMaxZError(CSLConstList papszOptions)
      99             : {
     100       12362 :     return CPLAtof(CSLFetchNameValueDef(papszOptions, "MAX_Z_ERROR", "0.0"));
     101             : }
     102             : 
     103        5220 : static double GTiffGetLERCMaxZErrorOverview(CSLConstList papszOptions)
     104             : {
     105        5220 :     return CPLAtof(CSLFetchNameValueDef(
     106             :         papszOptions, "MAX_Z_ERROR_OVERVIEW",
     107        5220 :         CSLFetchNameValueDef(papszOptions, "MAX_Z_ERROR", "0.0")));
     108             : }
     109             : 
     110             : #if HAVE_JXL
     111       12363 : static bool GTiffGetJXLLossless(CSLConstList papszOptions)
     112             : {
     113       12363 :     return CPLTestBool(
     114       12363 :         CSLFetchNameValueDef(papszOptions, "JXL_LOSSLESS", "TRUE"));
     115             : }
     116             : 
     117       12363 : static uint32_t GTiffGetJXLEffort(CSLConstList papszOptions)
     118             : {
     119       12363 :     return atoi(CSLFetchNameValueDef(papszOptions, "JXL_EFFORT", "5"));
     120             : }
     121             : 
     122       12283 : static float GTiffGetJXLDistance(CSLConstList papszOptions)
     123             : {
     124             :     return static_cast<float>(
     125       12283 :         CPLAtof(CSLFetchNameValueDef(papszOptions, "JXL_DISTANCE", "1.0")));
     126             : }
     127             : 
     128       12363 : static float GTiffGetJXLAlphaDistance(CSLConstList papszOptions)
     129             : {
     130       12363 :     return static_cast<float>(CPLAtof(
     131       12363 :         CSLFetchNameValueDef(papszOptions, "JXL_ALPHA_DISTANCE", "-1.0")));
     132             : }
     133             : 
     134             : #endif
     135             : 
     136             : /************************************************************************/
     137             : /*                           FillEmptyTiles()                           */
     138             : /************************************************************************/
     139             : 
     140        5381 : CPLErr GTiffDataset::FillEmptyTiles()
     141             : 
     142             : {
     143             :     /* -------------------------------------------------------------------- */
     144             :     /*      How many blocks are there in this file?                         */
     145             :     /* -------------------------------------------------------------------- */
     146       10762 :     const int nBlockCount = m_nPlanarConfig == PLANARCONFIG_SEPARATE
     147        5381 :                                 ? m_nBlocksPerBand * nBands
     148             :                                 : m_nBlocksPerBand;
     149             : 
     150             :     /* -------------------------------------------------------------------- */
     151             :     /*      Fetch block maps.                                               */
     152             :     /* -------------------------------------------------------------------- */
     153        5381 :     toff_t *panByteCounts = nullptr;
     154             : 
     155        5381 :     if (TIFFIsTiled(m_hTIFF))
     156         957 :         TIFFGetField(m_hTIFF, TIFFTAG_TILEBYTECOUNTS, &panByteCounts);
     157             :     else
     158        4424 :         TIFFGetField(m_hTIFF, TIFFTAG_STRIPBYTECOUNTS, &panByteCounts);
     159             : 
     160        5381 :     if (panByteCounts == nullptr)
     161             :     {
     162             :         // Got here with libtiff 3.9.3 and tiff_write_8 test.
     163           0 :         ReportError(CE_Failure, CPLE_AppDefined,
     164             :                     "FillEmptyTiles() failed because panByteCounts == NULL");
     165           0 :         return CE_Failure;
     166             :     }
     167             : 
     168             :     /* -------------------------------------------------------------------- */
     169             :     /*      Prepare a blank data buffer to write for uninitialized blocks.  */
     170             :     /* -------------------------------------------------------------------- */
     171             :     const GPtrDiff_t nBlockBytes =
     172        5381 :         TIFFIsTiled(m_hTIFF) ? static_cast<GPtrDiff_t>(TIFFTileSize(m_hTIFF))
     173        4424 :                              : static_cast<GPtrDiff_t>(TIFFStripSize(m_hTIFF));
     174             : 
     175        5381 :     GByte *pabyData = static_cast<GByte *>(VSI_CALLOC_VERBOSE(nBlockBytes, 1));
     176        5381 :     if (pabyData == nullptr)
     177             :     {
     178           0 :         return CE_Failure;
     179             :     }
     180             : 
     181             :     // Force tiles completely filled with the nodata value to be written.
     182        5381 :     m_bWriteEmptyTiles = true;
     183             : 
     184             :     /* -------------------------------------------------------------------- */
     185             :     /*      If set, fill data buffer with no data value.                    */
     186             :     /* -------------------------------------------------------------------- */
     187        5381 :     if ((m_bNoDataSet && m_dfNoDataValue != 0.0) ||
     188        5156 :         (m_bNoDataSetAsInt64 && m_nNoDataValueInt64 != 0) ||
     189        5154 :         (m_bNoDataSetAsUInt64 && m_nNoDataValueUInt64 != 0))
     190             :     {
     191         229 :         const GDALDataType eDataType = GetRasterBand(1)->GetRasterDataType();
     192         229 :         const int nDataTypeSize = GDALGetDataTypeSizeBytes(eDataType);
     193         229 :         if (nDataTypeSize &&
     194         229 :             nDataTypeSize * 8 == static_cast<int>(m_nBitsPerSample))
     195             :         {
     196         218 :             if (m_bNoDataSetAsInt64)
     197             :             {
     198           3 :                 GDALCopyWords64(&m_nNoDataValueInt64, GDT_Int64, 0, pabyData,
     199             :                                 eDataType, nDataTypeSize,
     200           3 :                                 nBlockBytes / nDataTypeSize);
     201             :             }
     202         215 :             else if (m_bNoDataSetAsUInt64)
     203             :             {
     204           2 :                 GDALCopyWords64(&m_nNoDataValueUInt64, GDT_UInt64, 0, pabyData,
     205             :                                 eDataType, nDataTypeSize,
     206           2 :                                 nBlockBytes / nDataTypeSize);
     207             :             }
     208             :             else
     209             :             {
     210         213 :                 double dfNoData = m_dfNoDataValue;
     211         213 :                 GDALCopyWords64(&dfNoData, GDT_Float64, 0, pabyData, eDataType,
     212         213 :                                 nDataTypeSize, nBlockBytes / nDataTypeSize);
     213         218 :             }
     214             :         }
     215          11 :         else if (nDataTypeSize)
     216             :         {
     217             :             // Handle non power-of-two depths.
     218             :             // Ideally make a packed buffer, but that is a bit tedious,
     219             :             // so use the normal I/O interfaces.
     220             : 
     221          11 :             CPLFree(pabyData);
     222             : 
     223          11 :             pabyData = static_cast<GByte *>(VSI_MALLOC3_VERBOSE(
     224             :                 m_nBlockXSize, m_nBlockYSize, nDataTypeSize));
     225          11 :             if (pabyData == nullptr)
     226           0 :                 return CE_Failure;
     227          11 :             if (m_bNoDataSetAsInt64)
     228             :             {
     229           0 :                 GDALCopyWords64(&m_nNoDataValueInt64, GDT_Int64, 0, pabyData,
     230             :                                 eDataType, nDataTypeSize,
     231           0 :                                 static_cast<GPtrDiff_t>(m_nBlockXSize) *
     232           0 :                                     m_nBlockYSize);
     233             :             }
     234          11 :             else if (m_bNoDataSetAsUInt64)
     235             :             {
     236           0 :                 GDALCopyWords64(&m_nNoDataValueUInt64, GDT_UInt64, 0, pabyData,
     237             :                                 eDataType, nDataTypeSize,
     238           0 :                                 static_cast<GPtrDiff_t>(m_nBlockXSize) *
     239           0 :                                     m_nBlockYSize);
     240             :             }
     241             :             else
     242             :             {
     243          11 :                 GDALCopyWords64(&m_dfNoDataValue, GDT_Float64, 0, pabyData,
     244             :                                 eDataType, nDataTypeSize,
     245          11 :                                 static_cast<GPtrDiff_t>(m_nBlockXSize) *
     246          11 :                                     m_nBlockYSize);
     247             :             }
     248          11 :             CPLErr eErr = CE_None;
     249          46 :             for (int iBlock = 0; iBlock < nBlockCount; ++iBlock)
     250             :             {
     251          35 :                 if (panByteCounts[iBlock] == 0)
     252             :                 {
     253          18 :                     if (m_nPlanarConfig == PLANARCONFIG_SEPARATE || nBands == 1)
     254             :                     {
     255          24 :                         if (GetRasterBand(1 + iBlock / m_nBlocksPerBand)
     256          12 :                                 ->WriteBlock((iBlock % m_nBlocksPerBand) %
     257          12 :                                                  m_nBlocksPerRow,
     258          12 :                                              (iBlock % m_nBlocksPerBand) /
     259          12 :                                                  m_nBlocksPerRow,
     260          12 :                                              pabyData) != CE_None)
     261             :                         {
     262           0 :                             eErr = CE_Failure;
     263             :                         }
     264             :                     }
     265             :                     else
     266             :                     {
     267             :                         // In contig case, don't directly call WriteBlock(), as
     268             :                         // it could cause useless decompression-recompression.
     269           6 :                         const int nXOff =
     270           6 :                             (iBlock % m_nBlocksPerRow) * m_nBlockXSize;
     271           6 :                         const int nYOff =
     272           6 :                             (iBlock / m_nBlocksPerRow) * m_nBlockYSize;
     273           6 :                         const int nXSize =
     274           6 :                             (nXOff + m_nBlockXSize <= nRasterXSize)
     275           6 :                                 ? m_nBlockXSize
     276           2 :                                 : nRasterXSize - nXOff;
     277           6 :                         const int nYSize =
     278           6 :                             (nYOff + m_nBlockYSize <= nRasterYSize)
     279           6 :                                 ? m_nBlockYSize
     280           3 :                                 : nRasterYSize - nYOff;
     281          18 :                         for (int iBand = 1; iBand <= nBands; ++iBand)
     282             :                         {
     283          12 :                             if (GetRasterBand(iBand)->RasterIO(
     284             :                                     GF_Write, nXOff, nYOff, nXSize, nYSize,
     285             :                                     pabyData, nXSize, nYSize, eDataType, 0, 0,
     286          12 :                                     nullptr) != CE_None)
     287             :                             {
     288           0 :                                 eErr = CE_Failure;
     289             :                             }
     290             :                         }
     291             :                     }
     292             :                 }
     293             :             }
     294          11 :             CPLFree(pabyData);
     295          11 :             return eErr;
     296         218 :         }
     297             :     }
     298             : 
     299             :     /* -------------------------------------------------------------------- */
     300             :     /*      When we must fill with zeroes, try to create non-sparse file    */
     301             :     /*      w.r.t TIFF spec ... as a sparse file w.r.t filesystem, ie by    */
     302             :     /*      seeking to end of file instead of writing zero blocks.          */
     303             :     /* -------------------------------------------------------------------- */
     304        5152 :     else if (m_nCompression == COMPRESSION_NONE && (m_nBitsPerSample % 8) == 0)
     305             :     {
     306        3847 :         CPLErr eErr = CE_None;
     307             :         // Only use libtiff to write the first sparse block to ensure that it
     308             :         // will serialize offset and count arrays back to disk.
     309        3847 :         int nCountBlocksToZero = 0;
     310     2276370 :         for (int iBlock = 0; iBlock < nBlockCount; ++iBlock)
     311             :         {
     312     2272520 :             if (panByteCounts[iBlock] == 0)
     313             :             {
     314     2181170 :                 if (nCountBlocksToZero == 0)
     315             :                 {
     316         958 :                     const bool bWriteEmptyTilesBak = m_bWriteEmptyTiles;
     317         958 :                     m_bWriteEmptyTiles = true;
     318         958 :                     const bool bOK = WriteEncodedTileOrStrip(iBlock, pabyData,
     319         958 :                                                              FALSE) == CE_None;
     320         958 :                     m_bWriteEmptyTiles = bWriteEmptyTilesBak;
     321         958 :                     if (!bOK)
     322             :                     {
     323           2 :                         eErr = CE_Failure;
     324           2 :                         break;
     325             :                     }
     326             :                 }
     327     2181170 :                 nCountBlocksToZero++;
     328             :             }
     329             :         }
     330        3847 :         CPLFree(pabyData);
     331             : 
     332        3847 :         --nCountBlocksToZero;
     333             : 
     334             :         // And then seek to end of file for other ones.
     335        3847 :         if (nCountBlocksToZero > 0)
     336             :         {
     337         309 :             toff_t *panByteOffsets = nullptr;
     338             : 
     339         309 :             if (TIFFIsTiled(m_hTIFF))
     340          86 :                 TIFFGetField(m_hTIFF, TIFFTAG_TILEOFFSETS, &panByteOffsets);
     341             :             else
     342         223 :                 TIFFGetField(m_hTIFF, TIFFTAG_STRIPOFFSETS, &panByteOffsets);
     343             : 
     344         309 :             if (panByteOffsets == nullptr)
     345             :             {
     346           0 :                 ReportError(
     347             :                     CE_Failure, CPLE_AppDefined,
     348             :                     "FillEmptyTiles() failed because panByteOffsets == NULL");
     349           0 :                 return CE_Failure;
     350             :             }
     351             : 
     352         309 :             VSILFILE *fpTIF = VSI_TIFFGetVSILFile(TIFFClientdata(m_hTIFF));
     353         309 :             VSIFSeekL(fpTIF, 0, SEEK_END);
     354         309 :             const vsi_l_offset nOffset = VSIFTellL(fpTIF);
     355             : 
     356         309 :             vsi_l_offset iBlockToZero = 0;
     357     2189360 :             for (int iBlock = 0; iBlock < nBlockCount; ++iBlock)
     358             :             {
     359     2189050 :                 if (panByteCounts[iBlock] == 0)
     360             :                 {
     361     2180210 :                     panByteOffsets[iBlock] = static_cast<toff_t>(
     362     2180210 :                         nOffset + iBlockToZero * nBlockBytes);
     363     2180210 :                     panByteCounts[iBlock] = nBlockBytes;
     364     2180210 :                     iBlockToZero++;
     365             :                 }
     366             :             }
     367         309 :             CPLAssert(iBlockToZero ==
     368             :                       static_cast<vsi_l_offset>(nCountBlocksToZero));
     369             : 
     370         309 :             if (VSIFTruncateL(fpTIF, nOffset + iBlockToZero * nBlockBytes) != 0)
     371             :             {
     372           0 :                 eErr = CE_Failure;
     373           0 :                 ReportError(CE_Failure, CPLE_FileIO,
     374             :                             "Cannot initialize empty blocks");
     375             :             }
     376             :         }
     377             : 
     378        3847 :         return eErr;
     379             :     }
     380             : 
     381             :     /* -------------------------------------------------------------------- */
     382             :     /*      Check all blocks, writing out data for uninitialized blocks.    */
     383             :     /* -------------------------------------------------------------------- */
     384             : 
     385        1523 :     GByte *pabyRaw = nullptr;
     386        1523 :     vsi_l_offset nRawSize = 0;
     387        1523 :     CPLErr eErr = CE_None;
     388       44543 :     for (int iBlock = 0; iBlock < nBlockCount; ++iBlock)
     389             :     {
     390       43027 :         if (panByteCounts[iBlock] == 0)
     391             :         {
     392        8843 :             if (pabyRaw == nullptr)
     393             :             {
     394        1565 :                 if (WriteEncodedTileOrStrip(iBlock, pabyData, FALSE) != CE_None)
     395             :                 {
     396           7 :                     eErr = CE_Failure;
     397           7 :                     break;
     398             :                 }
     399             : 
     400        1558 :                 vsi_l_offset nOffset = 0;
     401        1558 :                 if (!IsBlockAvailable(iBlock, &nOffset, &nRawSize, nullptr))
     402           0 :                     break;
     403             : 
     404             :                 // When using compression, get back the compressed block
     405             :                 // so we can use the raw API to write it faster.
     406        1558 :                 if (m_nCompression != COMPRESSION_NONE)
     407             :                 {
     408             :                     pabyRaw = static_cast<GByte *>(
     409         358 :                         VSI_MALLOC_VERBOSE(static_cast<size_t>(nRawSize)));
     410         358 :                     if (pabyRaw)
     411             :                     {
     412             :                         VSILFILE *fp =
     413         358 :                             VSI_TIFFGetVSILFile(TIFFClientdata(m_hTIFF));
     414         358 :                         const vsi_l_offset nCurOffset = VSIFTellL(fp);
     415         358 :                         VSIFSeekL(fp, nOffset, SEEK_SET);
     416         358 :                         VSIFReadL(pabyRaw, 1, static_cast<size_t>(nRawSize),
     417             :                                   fp);
     418         358 :                         VSIFSeekL(fp, nCurOffset, SEEK_SET);
     419             :                     }
     420             :                 }
     421             :             }
     422             :             else
     423             :             {
     424        7278 :                 WriteRawStripOrTile(iBlock, pabyRaw,
     425             :                                     static_cast<GPtrDiff_t>(nRawSize));
     426             :             }
     427             :         }
     428             :     }
     429             : 
     430        1523 :     CPLFree(pabyData);
     431        1523 :     VSIFree(pabyRaw);
     432        1523 :     return eErr;
     433             : }
     434             : 
     435             : /************************************************************************/
     436             : /*                         HasOnlyNoData()                              */
     437             : /************************************************************************/
     438             : 
     439       37967 : bool GTiffDataset::HasOnlyNoData(const void *pBuffer, int nWidth, int nHeight,
     440             :                                  int nLineStride, int nComponents)
     441             : {
     442       37967 :     if (m_nSampleFormat == SAMPLEFORMAT_COMPLEXINT ||
     443       37967 :         m_nSampleFormat == SAMPLEFORMAT_COMPLEXIEEEFP)
     444           0 :         return false;
     445       37967 :     if (m_bNoDataSetAsInt64 || m_bNoDataSetAsUInt64)
     446           2 :         return false;  // FIXME: over pessimistic
     447       75930 :     return GDALBufferHasOnlyNoData(
     448       37965 :         pBuffer, m_bNoDataSet ? m_dfNoDataValue : 0.0, nWidth, nHeight,
     449       37965 :         nLineStride, nComponents, m_nBitsPerSample,
     450       37965 :         m_nSampleFormat == SAMPLEFORMAT_UINT  ? GSF_UNSIGNED_INT
     451         784 :         : m_nSampleFormat == SAMPLEFORMAT_INT ? GSF_SIGNED_INT
     452       37965 :                                               : GSF_FLOATING_POINT);
     453             : }
     454             : 
     455             : /************************************************************************/
     456             : /*                     IsFirstPixelEqualToNoData()                      */
     457             : /************************************************************************/
     458             : 
     459      161388 : inline bool GTiffDataset::IsFirstPixelEqualToNoData(const void *pBuffer)
     460             : {
     461      161388 :     const GDALDataType eDT = GetRasterBand(1)->GetRasterDataType();
     462      161396 :     const double dfEffectiveNoData = (m_bNoDataSet) ? m_dfNoDataValue : 0.0;
     463      161396 :     if (m_bNoDataSetAsInt64 || m_bNoDataSetAsUInt64)
     464           4 :         return true;  // FIXME: over pessimistic
     465      161392 :     if (m_nBitsPerSample == 8 ||
     466       51190 :         (m_nBitsPerSample < 8 && dfEffectiveNoData == 0))
     467             :     {
     468      113650 :         if (eDT == GDT_Int8)
     469             :         {
     470          44 :             return GDALIsValueInRange<signed char>(dfEffectiveNoData) &&
     471          22 :                    *(static_cast<const signed char *>(pBuffer)) ==
     472          44 :                        static_cast<signed char>(dfEffectiveNoData);
     473             :         }
     474      227229 :         return GDALIsValueInRange<GByte>(dfEffectiveNoData) &&
     475      113601 :                *(static_cast<const GByte *>(pBuffer)) ==
     476      227229 :                    static_cast<GByte>(dfEffectiveNoData);
     477             :     }
     478       47742 :     if (m_nBitsPerSample == 16 && eDT == GDT_UInt16)
     479             :     {
     480        3500 :         return GDALIsValueInRange<GUInt16>(dfEffectiveNoData) &&
     481        1750 :                *(static_cast<const GUInt16 *>(pBuffer)) ==
     482        3500 :                    static_cast<GUInt16>(dfEffectiveNoData);
     483             :     }
     484       45992 :     if (m_nBitsPerSample == 16 && eDT == GDT_Int16)
     485             :     {
     486        6648 :         return GDALIsValueInRange<GInt16>(dfEffectiveNoData) &&
     487        3324 :                *(static_cast<const GInt16 *>(pBuffer)) ==
     488        6648 :                    static_cast<GInt16>(dfEffectiveNoData);
     489             :     }
     490       42668 :     if (m_nBitsPerSample == 32 && eDT == GDT_UInt32)
     491             :     {
     492         148 :         return GDALIsValueInRange<GUInt32>(dfEffectiveNoData) &&
     493          74 :                *(static_cast<const GUInt32 *>(pBuffer)) ==
     494         148 :                    static_cast<GUInt32>(dfEffectiveNoData);
     495             :     }
     496       42594 :     if (m_nBitsPerSample == 32 && eDT == GDT_Int32)
     497             :     {
     498         258 :         return GDALIsValueInRange<GInt32>(dfEffectiveNoData) &&
     499         129 :                *(static_cast<const GInt32 *>(pBuffer)) ==
     500         258 :                    static_cast<GInt32>(dfEffectiveNoData);
     501             :     }
     502       42465 :     if (m_nBitsPerSample == 64 && eDT == GDT_UInt64)
     503             :     {
     504          10 :         return GDALIsValueInRange<std::uint64_t>(dfEffectiveNoData) &&
     505           5 :                *(static_cast<const std::uint64_t *>(pBuffer)) ==
     506          10 :                    static_cast<std::uint64_t>(dfEffectiveNoData);
     507             :     }
     508       42460 :     if (m_nBitsPerSample == 64 && eDT == GDT_Int64)
     509             :     {
     510          12 :         return GDALIsValueInRange<std::int64_t>(dfEffectiveNoData) &&
     511           6 :                *(static_cast<const std::int64_t *>(pBuffer)) ==
     512          12 :                    static_cast<std::int64_t>(dfEffectiveNoData);
     513             :     }
     514       42454 :     if (m_nBitsPerSample == 32 && eDT == GDT_Float32)
     515             :     {
     516       40982 :         if (std::isnan(m_dfNoDataValue))
     517           3 :             return CPL_TO_BOOL(
     518           6 :                 std::isnan(*(static_cast<const float *>(pBuffer))));
     519       81936 :         return GDALIsValueInRange<float>(dfEffectiveNoData) &&
     520       40965 :                *(static_cast<const float *>(pBuffer)) ==
     521       81928 :                    static_cast<float>(dfEffectiveNoData);
     522             :     }
     523        1472 :     if (m_nBitsPerSample == 64 && eDT == GDT_Float64)
     524             :     {
     525         290 :         if (std::isnan(dfEffectiveNoData))
     526           0 :             return CPL_TO_BOOL(
     527           0 :                 std::isnan(*(static_cast<const double *>(pBuffer))));
     528         290 :         return *(static_cast<const double *>(pBuffer)) == dfEffectiveNoData;
     529             :     }
     530        1182 :     return false;
     531             : }
     532             : 
     533             : /************************************************************************/
     534             : /*                      WriteDealWithLercAndNan()                       */
     535             : /************************************************************************/
     536             : 
     537             : template <typename T>
     538           0 : void GTiffDataset::WriteDealWithLercAndNan(T *pBuffer, int nActualBlockWidth,
     539             :                                            int nActualBlockHeight,
     540             :                                            int nStrileHeight)
     541             : {
     542             :     // This method does 2 things:
     543             :     // - warn the user if he tries to write NaN values with libtiff < 4.6.1
     544             :     //   and multi-band PlanarConfig=Contig configuration
     545             :     // - and in right-most and bottom-most tiles, replace non accessible
     546             :     //   pixel values by a safe one.
     547             : 
     548           0 :     const auto fPaddingValue =
     549             : #if !defined(LIBTIFF_MULTIBAND_LERC_NAN_OK)
     550             :         m_nPlanarConfig == PLANARCONFIG_CONTIG && nBands > 1
     551             :             ? 0
     552             :             :
     553             : #endif
     554             :             std::numeric_limits<T>::quiet_NaN();
     555             : 
     556           0 :     const int nBandsPerStrile =
     557           0 :         m_nPlanarConfig == PLANARCONFIG_CONTIG ? nBands : 1;
     558           0 :     for (int j = 0; j < nActualBlockHeight; ++j)
     559             :     {
     560             : #if !defined(LIBTIFF_MULTIBAND_LERC_NAN_OK)
     561             :         static bool bHasWarned = false;
     562             :         if (m_nPlanarConfig == PLANARCONFIG_CONTIG && nBands > 1 && !bHasWarned)
     563             :         {
     564             :             for (int i = 0; i < nActualBlockWidth * nBandsPerStrile; ++i)
     565             :             {
     566             :                 if (std::isnan(
     567             :                         pBuffer[j * m_nBlockXSize * nBandsPerStrile + i]))
     568             :                 {
     569             :                     bHasWarned = true;
     570             :                     CPLError(CE_Warning, CPLE_AppDefined,
     571             :                              "libtiff < 4.6.1 does not handle properly NaN "
     572             :                              "values for multi-band PlanarConfig=Contig "
     573             :                              "configuration. As a workaround, you can set the "
     574             :                              "INTERLEAVE=BAND creation option.");
     575             :                     break;
     576             :                 }
     577             :             }
     578             :         }
     579             : #endif
     580           0 :         for (int i = nActualBlockWidth * nBandsPerStrile;
     581           0 :              i < m_nBlockXSize * nBandsPerStrile; ++i)
     582             :         {
     583           0 :             pBuffer[j * m_nBlockXSize * nBandsPerStrile + i] = fPaddingValue;
     584             :         }
     585             :     }
     586           0 :     for (int j = nActualBlockHeight; j < nStrileHeight; ++j)
     587             :     {
     588           0 :         for (int i = 0; i < m_nBlockXSize * nBandsPerStrile; ++i)
     589             :         {
     590           0 :             pBuffer[j * m_nBlockXSize * nBandsPerStrile + i] = fPaddingValue;
     591             :         }
     592             :     }
     593           0 : }
     594             : 
     595             : /************************************************************************/
     596             : /*                        WriteEncodedTile()                            */
     597             : /************************************************************************/
     598             : 
     599       47414 : bool GTiffDataset::WriteEncodedTile(uint32_t tile, GByte *pabyData,
     600             :                                     int bPreserveDataBuffer)
     601             : {
     602       47414 :     const int iColumn = (tile % m_nBlocksPerBand) % m_nBlocksPerRow;
     603       47414 :     const int iRow = (tile % m_nBlocksPerBand) / m_nBlocksPerRow;
     604             : 
     605       94828 :     const int nActualBlockWidth = (iColumn == m_nBlocksPerRow - 1)
     606       47414 :                                       ? nRasterXSize - iColumn * m_nBlockXSize
     607             :                                       : m_nBlockXSize;
     608       94828 :     const int nActualBlockHeight = (iRow == m_nBlocksPerColumn - 1)
     609       47414 :                                        ? nRasterYSize - iRow * m_nBlockYSize
     610             :                                        : m_nBlockYSize;
     611             : 
     612             :     /* -------------------------------------------------------------------- */
     613             :     /*      Don't write empty blocks in some cases.                         */
     614             :     /* -------------------------------------------------------------------- */
     615       47414 :     if (!m_bWriteEmptyTiles && IsFirstPixelEqualToNoData(pabyData))
     616             :     {
     617        1902 :         if (!IsBlockAvailable(tile, nullptr, nullptr, nullptr))
     618             :         {
     619        1902 :             const int nComponents =
     620        1902 :                 m_nPlanarConfig == PLANARCONFIG_CONTIG ? nBands : 1;
     621             : 
     622        1902 :             if (HasOnlyNoData(pabyData, nActualBlockWidth, nActualBlockHeight,
     623             :                               m_nBlockXSize, nComponents))
     624             :             {
     625        1156 :                 return true;
     626             :             }
     627             :         }
     628             :     }
     629             : 
     630             :     // Is this a partial right edge or bottom edge tile?
     631       90051 :     const bool bPartialTile = (nActualBlockWidth < m_nBlockXSize) ||
     632       43793 :                               (nActualBlockHeight < m_nBlockYSize);
     633             : 
     634             :     const bool bIsLercFloatingPoint =
     635       46323 :         m_nCompression == COMPRESSION_LERC &&
     636          66 :         (GetRasterBand(1)->GetRasterDataType() == GDT_Float32 ||
     637          64 :          GetRasterBand(1)->GetRasterDataType() == GDT_Float64);
     638             : 
     639             :     // Do we need to spread edge values right or down for a partial
     640             :     // JPEG encoded tile?  We do this to avoid edge artifacts.
     641             :     // We also need to be careful with LERC and NaN values
     642       46257 :     const bool bNeedTempBuffer =
     643       50162 :         bPartialTile &&
     644        3905 :         (m_nCompression == COMPRESSION_JPEG || bIsLercFloatingPoint);
     645             : 
     646             :     // If we need to fill out the tile, or if we want to prevent
     647             :     // TIFFWriteEncodedTile from altering the buffer as part of
     648             :     // byte swapping the data on write then we will need a temporary
     649             :     // working buffer.  If not, we can just do a direct write.
     650       46257 :     const GPtrDiff_t cc = static_cast<GPtrDiff_t>(TIFFTileSize(m_hTIFF));
     651             : 
     652       60051 :     if (bPreserveDataBuffer &&
     653       13801 :         (TIFFIsByteSwapped(m_hTIFF) || bNeedTempBuffer || m_panMaskOffsetLsb))
     654             :     {
     655         176 :         if (m_pabyTempWriteBuffer == nullptr)
     656             :         {
     657          39 :             m_pabyTempWriteBuffer = CPLMalloc(cc);
     658             :         }
     659         176 :         memcpy(m_pabyTempWriteBuffer, pabyData, cc);
     660             : 
     661         176 :         pabyData = static_cast<GByte *>(m_pabyTempWriteBuffer);
     662             :     }
     663             : 
     664             :     // Perform tile fill if needed.
     665             :     // TODO: we should also handle the case of nBitsPerSample == 12
     666             :     // but this is more involved.
     667       46250 :     if (bPartialTile && m_nCompression == COMPRESSION_JPEG &&
     668         134 :         m_nBitsPerSample == 8)
     669             :     {
     670         132 :         const int nComponents =
     671         132 :             m_nPlanarConfig == PLANARCONFIG_CONTIG ? nBands : 1;
     672             : 
     673         132 :         CPLDebug("GTiff", "Filling out jpeg edge tile on write.");
     674             : 
     675         132 :         const int nRightPixelsToFill =
     676         132 :             iColumn == m_nBlocksPerRow - 1
     677         132 :                 ? m_nBlockXSize * (iColumn + 1) - nRasterXSize
     678             :                 : 0;
     679         132 :         const int nBottomPixelsToFill =
     680         132 :             iRow == m_nBlocksPerColumn - 1
     681         132 :                 ? m_nBlockYSize * (iRow + 1) - nRasterYSize
     682             :                 : 0;
     683             : 
     684             :         // Fill out to the right.
     685         132 :         const int iSrcX = m_nBlockXSize - nRightPixelsToFill - 1;
     686             : 
     687       12461 :         for (int iX = iSrcX + 1; iX < m_nBlockXSize; ++iX)
     688             :         {
     689     3955880 :             for (int iY = 0; iY < m_nBlockYSize; ++iY)
     690             :             {
     691     3943550 :                 memcpy(pabyData +
     692     3943550 :                            (static_cast<GPtrDiff_t>(m_nBlockXSize) * iY + iX) *
     693     3943550 :                                nComponents,
     694     3943550 :                        pabyData + (static_cast<GPtrDiff_t>(m_nBlockXSize) * iY +
     695     3943550 :                                    iSrcX) *
     696     3943550 :                                       nComponents,
     697             :                        nComponents);
     698             :             }
     699             :         }
     700             : 
     701             :         // Now fill out the bottom.
     702         132 :         const int iSrcY = m_nBlockYSize - nBottomPixelsToFill - 1;
     703       17682 :         for (int iY = iSrcY + 1; iY < m_nBlockYSize; ++iY)
     704             :         {
     705       17550 :             memcpy(pabyData + static_cast<GPtrDiff_t>(m_nBlockXSize) *
     706       17550 :                                   nComponents * iY,
     707       17550 :                    pabyData + static_cast<GPtrDiff_t>(m_nBlockXSize) *
     708       17550 :                                   nComponents * iSrcY,
     709       17550 :                    static_cast<GPtrDiff_t>(m_nBlockXSize) * nComponents);
     710             :         }
     711             :     }
     712             : 
     713       46250 :     if (bIsLercFloatingPoint &&
     714             :         (bPartialTile
     715             : #if !defined(LIBTIFF_MULTIBAND_LERC_NAN_OK)
     716             :          /* libtiff < 4.6.1 doesn't generate a LERC mask for multi-band contig configuration */
     717             :          || (m_nPlanarConfig == PLANARCONFIG_CONTIG && nBands > 1)
     718             : #endif
     719             :              ))
     720             :     {
     721           0 :         if (GetRasterBand(1)->GetRasterDataType() == GDT_Float32)
     722           0 :             WriteDealWithLercAndNan(reinterpret_cast<float *>(pabyData),
     723             :                                     nActualBlockWidth, nActualBlockHeight,
     724             :                                     m_nBlockYSize);
     725             :         else
     726           0 :             WriteDealWithLercAndNan(reinterpret_cast<double *>(pabyData),
     727             :                                     nActualBlockWidth, nActualBlockHeight,
     728             :                                     m_nBlockYSize);
     729             :     }
     730             : 
     731       46250 :     if (m_panMaskOffsetLsb)
     732             :     {
     733           0 :         const int iBand = m_nPlanarConfig == PLANARCONFIG_SEPARATE
     734           0 :                               ? static_cast<int>(tile) / m_nBlocksPerBand
     735             :                               : -1;
     736           0 :         DiscardLsb(pabyData, cc, iBand);
     737             :     }
     738             : 
     739       46258 :     if (m_bStreamingOut)
     740             :     {
     741          17 :         if (tile != static_cast<uint32_t>(m_nLastWrittenBlockId + 1))
     742             :         {
     743           1 :             ReportError(CE_Failure, CPLE_NotSupported,
     744             :                         "Attempt to write block %d whereas %d was expected",
     745           1 :                         tile, m_nLastWrittenBlockId + 1);
     746           1 :             return false;
     747             :         }
     748          16 :         if (static_cast<GPtrDiff_t>(VSIFWriteL(pabyData, 1, cc, m_fpToWrite)) !=
     749             :             cc)
     750             :         {
     751           0 :             ReportError(CE_Failure, CPLE_FileIO,
     752             :                         "Could not write " CPL_FRMT_GUIB " bytes",
     753             :                         static_cast<GUIntBig>(cc));
     754           0 :             return false;
     755             :         }
     756          16 :         m_nLastWrittenBlockId = tile;
     757          16 :         return true;
     758             :     }
     759             : 
     760             :     /* -------------------------------------------------------------------- */
     761             :     /*      Should we do compression in a worker thread ?                   */
     762             :     /* -------------------------------------------------------------------- */
     763       46241 :     if (SubmitCompressionJob(tile, pabyData, cc, m_nBlockYSize))
     764       19746 :         return true;
     765             : 
     766       26493 :     return TIFFWriteEncodedTile(m_hTIFF, tile, pabyData, cc) == cc;
     767             : }
     768             : 
     769             : /************************************************************************/
     770             : /*                        WriteEncodedStrip()                           */
     771             : /************************************************************************/
     772             : 
     773      161742 : bool GTiffDataset::WriteEncodedStrip(uint32_t strip, GByte *pabyData,
     774             :                                      int bPreserveDataBuffer)
     775             : {
     776      161742 :     GPtrDiff_t cc = static_cast<GPtrDiff_t>(TIFFStripSize(m_hTIFF));
     777      161744 :     const auto ccFull = cc;
     778             : 
     779             :     /* -------------------------------------------------------------------- */
     780             :     /*      If this is the last strip in the image, and is partial, then    */
     781             :     /*      we need to trim the number of scanlines written to the          */
     782             :     /*      amount of valid data we have. (#2748)                           */
     783             :     /* -------------------------------------------------------------------- */
     784      161744 :     const int nStripWithinBand = strip % m_nBlocksPerBand;
     785      161744 :     int nStripHeight = m_nRowsPerStrip;
     786             : 
     787      161744 :     if (nStripWithinBand * nStripHeight > GetRasterYSize() - nStripHeight)
     788             :     {
     789        1120 :         nStripHeight = GetRasterYSize() - nStripWithinBand * m_nRowsPerStrip;
     790        1120 :         cc = (cc / m_nRowsPerStrip) * nStripHeight;
     791        2240 :         CPLDebug("GTiff",
     792             :                  "Adjusted bytes to write from " CPL_FRMT_GUIB
     793             :                  " to " CPL_FRMT_GUIB ".",
     794        1120 :                  static_cast<GUIntBig>(TIFFStripSize(m_hTIFF)),
     795             :                  static_cast<GUIntBig>(cc));
     796             :     }
     797             : 
     798             :     /* -------------------------------------------------------------------- */
     799             :     /*      Don't write empty blocks in some cases.                         */
     800             :     /* -------------------------------------------------------------------- */
     801      161748 :     if (!m_bWriteEmptyTiles && IsFirstPixelEqualToNoData(pabyData))
     802             :     {
     803       36235 :         if (!IsBlockAvailable(strip, nullptr, nullptr, nullptr))
     804             :         {
     805       36065 :             const int nComponents =
     806       36065 :                 m_nPlanarConfig == PLANARCONFIG_CONTIG ? nBands : 1;
     807             : 
     808       36065 :             if (HasOnlyNoData(pabyData, m_nBlockXSize, nStripHeight,
     809             :                               m_nBlockXSize, nComponents))
     810             :             {
     811       24646 :                 return true;
     812             :             }
     813             :         }
     814             :     }
     815             : 
     816             :     /* -------------------------------------------------------------------- */
     817             :     /*      TIFFWriteEncodedStrip can alter the passed buffer if            */
     818             :     /*      byte-swapping is necessary so we use a temporary buffer         */
     819             :     /*      before calling it.                                              */
     820             :     /* -------------------------------------------------------------------- */
     821      225714 :     if (bPreserveDataBuffer &&
     822       88620 :         (TIFFIsByteSwapped(m_hTIFF) || m_panMaskOffsetLsb))
     823             :     {
     824         294 :         if (m_pabyTempWriteBuffer == nullptr)
     825             :         {
     826         126 :             m_pabyTempWriteBuffer = CPLMalloc(ccFull);
     827             :         }
     828         294 :         memcpy(m_pabyTempWriteBuffer, pabyData, cc);
     829         294 :         pabyData = static_cast<GByte *>(m_pabyTempWriteBuffer);
     830             :     }
     831             : 
     832             : #if !defined(LIBTIFF_MULTIBAND_LERC_NAN_OK)
     833             :     const bool bIsLercFloatingPoint =
     834             :         m_nCompression == COMPRESSION_LERC &&
     835             :         (GetRasterBand(1)->GetRasterDataType() == GDT_Float32 ||
     836             :          GetRasterBand(1)->GetRasterDataType() == GDT_Float64);
     837             :     if (bIsLercFloatingPoint &&
     838             :         /* libtiff < 4.6.1 doesn't generate a LERC mask for multi-band contig configuration */
     839             :         m_nPlanarConfig == PLANARCONFIG_CONTIG && nBands > 1)
     840             :     {
     841             :         if (GetRasterBand(1)->GetRasterDataType() == GDT_Float32)
     842             :             WriteDealWithLercAndNan(reinterpret_cast<float *>(pabyData),
     843             :                                     m_nBlockXSize, nStripHeight, nStripHeight);
     844             :         else
     845             :             WriteDealWithLercAndNan(reinterpret_cast<double *>(pabyData),
     846             :                                     m_nBlockXSize, nStripHeight, nStripHeight);
     847             :     }
     848             : #endif
     849             : 
     850      137094 :     if (m_panMaskOffsetLsb)
     851             :     {
     852         366 :         int iBand = m_nPlanarConfig == PLANARCONFIG_SEPARATE
     853         183 :                         ? static_cast<int>(strip) / m_nBlocksPerBand
     854             :                         : -1;
     855         183 :         DiscardLsb(pabyData, cc, iBand);
     856             :     }
     857             : 
     858      137095 :     if (m_bStreamingOut)
     859             :     {
     860        1408 :         if (strip != static_cast<uint32_t>(m_nLastWrittenBlockId + 1))
     861             :         {
     862           1 :             ReportError(CE_Failure, CPLE_NotSupported,
     863             :                         "Attempt to write block %d whereas %d was expected",
     864           1 :                         strip, m_nLastWrittenBlockId + 1);
     865           1 :             return false;
     866             :         }
     867        1407 :         if (static_cast<GPtrDiff_t>(VSIFWriteL(pabyData, 1, cc, m_fpToWrite)) !=
     868             :             cc)
     869             :         {
     870           0 :             ReportError(CE_Failure, CPLE_FileIO,
     871             :                         "Could not write " CPL_FRMT_GUIB " bytes",
     872             :                         static_cast<GUIntBig>(cc));
     873           0 :             return false;
     874             :         }
     875        1407 :         m_nLastWrittenBlockId = strip;
     876        1407 :         return true;
     877             :     }
     878             : 
     879             :     /* -------------------------------------------------------------------- */
     880             :     /*      Should we do compression in a worker thread ?                   */
     881             :     /* -------------------------------------------------------------------- */
     882      135687 :     if (SubmitCompressionJob(strip, pabyData, cc, nStripHeight))
     883        6730 :         return true;
     884             : 
     885      128960 :     return TIFFWriteEncodedStrip(m_hTIFF, strip, pabyData, cc) == cc;
     886             : }
     887             : 
     888             : /************************************************************************/
     889             : /*                        InitCompressionThreads()                      */
     890             : /************************************************************************/
     891             : 
     892       25137 : void GTiffDataset::InitCompressionThreads(bool bUpdateMode,
     893             :                                           CSLConstList papszOptions)
     894             : {
     895             :     // Raster == tile, then no need for threads
     896       25137 :     if (m_nBlockXSize == nRasterXSize && m_nBlockYSize == nRasterYSize)
     897       17323 :         return;
     898             : 
     899        7814 :     const char *pszValue = CSLFetchNameValue(papszOptions, "NUM_THREADS");
     900        7765 :     if (pszValue == nullptr)
     901        7701 :         pszValue = CPLGetConfigOption("GDAL_NUM_THREADS", nullptr);
     902        7768 :     if (pszValue)
     903             :     {
     904             :         int nThreads =
     905          79 :             EQUAL(pszValue, "ALL_CPUS") ? CPLGetNumCPUs() : atoi(pszValue);
     906          79 :         if (nThreads > 1024)
     907           0 :             nThreads = 1024;  // to please Coverity
     908          79 :         if (nThreads > 1)
     909             :         {
     910          87 :             if ((bUpdateMode && m_nCompression != COMPRESSION_NONE) ||
     911          15 :                 (nBands >= 1 && IsMultiThreadedReadCompatible()))
     912             :             {
     913          66 :                 CPLDebug("GTiff",
     914             :                          "Using up to %d threads for compression/decompression",
     915             :                          nThreads);
     916             : 
     917          66 :                 m_poThreadPool = GDALGetGlobalThreadPool(nThreads);
     918          66 :                 if (bUpdateMode && m_poThreadPool)
     919          57 :                     m_poCompressQueue = m_poThreadPool->CreateJobQueue();
     920             : 
     921          66 :                 if (m_poCompressQueue != nullptr)
     922             :                 {
     923             :                     // Add a margin of an extra job w.r.t thread number
     924             :                     // so as to optimize compression time (enables the main
     925             :                     // thread to do boring I/O while all CPUs are working).
     926          57 :                     m_asCompressionJobs.resize(nThreads + 1);
     927          57 :                     memset(&m_asCompressionJobs[0], 0,
     928          57 :                            m_asCompressionJobs.size() *
     929             :                                sizeof(GTiffCompressionJob));
     930          57 :                     for (int i = 0;
     931         276 :                          i < static_cast<int>(m_asCompressionJobs.size()); ++i)
     932             :                     {
     933         438 :                         m_asCompressionJobs[i].pszTmpFilename =
     934         219 :                             CPLStrdup(VSIMemGenerateHiddenFilename(
     935             :                                 CPLSPrintf("thread_job_%d.tif", i)));
     936         219 :                         m_asCompressionJobs[i].nStripOrTile = -1;
     937             :                     }
     938             : 
     939             :                     // This is kind of a hack, but basically using
     940             :                     // TIFFWriteRawStrip/Tile and then TIFFReadEncodedStrip/Tile
     941             :                     // does not work on a newly created file, because
     942             :                     // TIFF_MYBUFFER is not set in tif_flags
     943             :                     // (if using TIFFWriteEncodedStrip/Tile first,
     944             :                     // TIFFWriteBufferSetup() is automatically called).
     945             :                     // This should likely rather fixed in libtiff itself.
     946          57 :                     CPL_IGNORE_RET_VAL(
     947          57 :                         TIFFWriteBufferSetup(m_hTIFF, nullptr, -1));
     948             :                 }
     949             :             }
     950             :         }
     951           7 :         else if (nThreads < 0 ||
     952           7 :                  (!EQUAL(pszValue, "0") && !EQUAL(pszValue, "1") &&
     953           3 :                   !EQUAL(pszValue, "ALL_CPUS")))
     954             :         {
     955           3 :             ReportError(CE_Warning, CPLE_AppDefined,
     956             :                         "Invalid value for NUM_THREADS: %s", pszValue);
     957             :         }
     958             :     }
     959             : }
     960             : 
     961             : /************************************************************************/
     962             : /*                      ThreadCompressionFunc()                         */
     963             : /************************************************************************/
     964             : 
     965       26488 : void GTiffDataset::ThreadCompressionFunc(void *pData)
     966             : {
     967       26488 :     GTiffCompressionJob *psJob = static_cast<GTiffCompressionJob *>(pData);
     968       26488 :     GTiffDataset *poDS = psJob->poDS;
     969             : 
     970       26488 :     VSILFILE *fpTmp = VSIFOpenL(psJob->pszTmpFilename, "wb+");
     971       26488 :     TIFF *hTIFFTmp = VSI_TIFFOpen(
     972       52976 :         psJob->pszTmpFilename, psJob->bTIFFIsBigEndian ? "wb+" : "wl+", fpTmp);
     973       26487 :     CPLAssert(hTIFFTmp != nullptr);
     974       26487 :     TIFFSetField(hTIFFTmp, TIFFTAG_IMAGEWIDTH, poDS->m_nBlockXSize);
     975       26488 :     TIFFSetField(hTIFFTmp, TIFFTAG_IMAGELENGTH, psJob->nHeight);
     976       26488 :     TIFFSetField(hTIFFTmp, TIFFTAG_BITSPERSAMPLE, poDS->m_nBitsPerSample);
     977       26488 :     TIFFSetField(hTIFFTmp, TIFFTAG_COMPRESSION, poDS->m_nCompression);
     978       26488 :     TIFFSetField(hTIFFTmp, TIFFTAG_PHOTOMETRIC, poDS->m_nPhotometric);
     979       26488 :     TIFFSetField(hTIFFTmp, TIFFTAG_SAMPLEFORMAT, poDS->m_nSampleFormat);
     980       26488 :     TIFFSetField(hTIFFTmp, TIFFTAG_SAMPLESPERPIXEL, poDS->m_nSamplesPerPixel);
     981       26488 :     TIFFSetField(hTIFFTmp, TIFFTAG_ROWSPERSTRIP, poDS->m_nBlockYSize);
     982       26488 :     TIFFSetField(hTIFFTmp, TIFFTAG_PLANARCONFIG, poDS->m_nPlanarConfig);
     983       26488 :     if (psJob->nPredictor != PREDICTOR_NONE)
     984         262 :         TIFFSetField(hTIFFTmp, TIFFTAG_PREDICTOR, psJob->nPredictor);
     985       26488 :     if (poDS->m_nCompression == COMPRESSION_LERC)
     986             :     {
     987          24 :         TIFFSetField(hTIFFTmp, TIFFTAG_LERC_PARAMETERS, 2,
     988          24 :                      poDS->m_anLercAddCompressionAndVersion);
     989             :     }
     990       26488 :     if (psJob->nExtraSampleCount)
     991             :     {
     992         325 :         TIFFSetField(hTIFFTmp, TIFFTAG_EXTRASAMPLES, psJob->nExtraSampleCount,
     993             :                      psJob->pExtraSamples);
     994             :     }
     995             : 
     996       26488 :     poDS->RestoreVolatileParameters(hTIFFTmp);
     997             : 
     998       52969 :     bool bOK = TIFFWriteEncodedStrip(hTIFFTmp, 0, psJob->pabyBuffer,
     999       26488 :                                      psJob->nBufferSize) == psJob->nBufferSize;
    1000             : 
    1001       26481 :     toff_t nOffset = 0;
    1002       26481 :     if (bOK)
    1003             :     {
    1004       26481 :         toff_t *panOffsets = nullptr;
    1005       26481 :         toff_t *panByteCounts = nullptr;
    1006       26481 :         TIFFGetField(hTIFFTmp, TIFFTAG_STRIPOFFSETS, &panOffsets);
    1007       26483 :         TIFFGetField(hTIFFTmp, TIFFTAG_STRIPBYTECOUNTS, &panByteCounts);
    1008             : 
    1009       26485 :         nOffset = panOffsets[0];
    1010       26485 :         psJob->nCompressedBufferSize =
    1011       26485 :             static_cast<GPtrDiff_t>(panByteCounts[0]);
    1012             :     }
    1013             :     else
    1014             :     {
    1015           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1016             :                  "Error when compressing strip/tile %d", psJob->nStripOrTile);
    1017             :     }
    1018             : 
    1019       26485 :     XTIFFClose(hTIFFTmp);
    1020       26483 :     if (VSIFCloseL(fpTmp) != 0)
    1021             :     {
    1022           0 :         if (bOK)
    1023             :         {
    1024           0 :             bOK = false;
    1025           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    1026             :                      "Error when compressing strip/tile %d",
    1027             :                      psJob->nStripOrTile);
    1028             :         }
    1029             :     }
    1030             : 
    1031       26483 :     if (bOK)
    1032             :     {
    1033       26483 :         vsi_l_offset nFileSize = 0;
    1034             :         GByte *pabyCompressedBuffer =
    1035       26483 :             VSIGetMemFileBuffer(psJob->pszTmpFilename, &nFileSize, FALSE);
    1036       26488 :         CPLAssert(static_cast<vsi_l_offset>(
    1037             :                       nOffset + psJob->nCompressedBufferSize) <= nFileSize);
    1038       26488 :         psJob->pabyCompressedBuffer = pabyCompressedBuffer + nOffset;
    1039             :     }
    1040             :     else
    1041             :     {
    1042           0 :         psJob->pabyCompressedBuffer = nullptr;
    1043           0 :         psJob->nCompressedBufferSize = 0;
    1044             :     }
    1045             : 
    1046       26488 :     auto poMainDS = poDS->m_poBaseDS ? poDS->m_poBaseDS : poDS;
    1047       26488 :     if (poMainDS->m_poCompressQueue)
    1048             :     {
    1049        1575 :         std::lock_guard oLock(poMainDS->m_oCompressThreadPoolMutex);
    1050        1575 :         psJob->bReady = true;
    1051             :     }
    1052       26488 : }
    1053             : 
    1054             : /************************************************************************/
    1055             : /*                        WriteRawStripOrTile()                         */
    1056             : /************************************************************************/
    1057             : 
    1058       33766 : void GTiffDataset::WriteRawStripOrTile(int nStripOrTile,
    1059             :                                        GByte *pabyCompressedBuffer,
    1060             :                                        GPtrDiff_t nCompressedBufferSize)
    1061             : {
    1062             : #ifdef DEBUG_VERBOSE
    1063             :     CPLDebug("GTIFF", "Writing raw strip/tile %d, size " CPL_FRMT_GUIB,
    1064             :              nStripOrTile, static_cast<GUIntBig>(nCompressedBufferSize));
    1065             : #endif
    1066       33766 :     toff_t *panOffsets = nullptr;
    1067       33766 :     toff_t *panByteCounts = nullptr;
    1068       33766 :     bool bWriteAtEnd = true;
    1069       33766 :     bool bWriteLeader = m_bLeaderSizeAsUInt4;
    1070       33766 :     bool bWriteTrailer = m_bTrailerRepeatedLast4BytesRepeated;
    1071       33766 :     if (TIFFGetField(m_hTIFF,
    1072       33766 :                      TIFFIsTiled(m_hTIFF) ? TIFFTAG_TILEOFFSETS
    1073             :                                           : TIFFTAG_STRIPOFFSETS,
    1074       33766 :                      &panOffsets) &&
    1075       33766 :         panOffsets != nullptr && panOffsets[nStripOrTile] != 0)
    1076             :     {
    1077             :         // Forces TIFFAppendStrip() to consider if the location of the
    1078             :         // tile/strip can be reused or if the strile should be written at end of
    1079             :         // file.
    1080         360 :         TIFFSetWriteOffset(m_hTIFF, 0);
    1081             : 
    1082         360 :         if (m_bBlockOrderRowMajor)
    1083             :         {
    1084         264 :             if (TIFFGetField(m_hTIFF,
    1085         264 :                              TIFFIsTiled(m_hTIFF) ? TIFFTAG_TILEBYTECOUNTS
    1086             :                                                   : TIFFTAG_STRIPBYTECOUNTS,
    1087         528 :                              &panByteCounts) &&
    1088         264 :                 panByteCounts != nullptr)
    1089             :             {
    1090         264 :                 if (static_cast<GUIntBig>(nCompressedBufferSize) >
    1091         264 :                     panByteCounts[nStripOrTile])
    1092             :                 {
    1093           8 :                     GTiffDataset *poRootDS = m_poBaseDS ? m_poBaseDS : this;
    1094           8 :                     if (!poRootDS->m_bKnownIncompatibleEdition &&
    1095           8 :                         !poRootDS->m_bWriteKnownIncompatibleEdition)
    1096             :                     {
    1097           8 :                         ReportError(
    1098             :                             CE_Warning, CPLE_AppDefined,
    1099             :                             "A strile cannot be rewritten in place, which "
    1100             :                             "invalidates the BLOCK_ORDER optimization.");
    1101           8 :                         poRootDS->m_bKnownIncompatibleEdition = true;
    1102           8 :                         poRootDS->m_bWriteKnownIncompatibleEdition = true;
    1103             :                     }
    1104             :                 }
    1105             :                 // For mask interleaving, if the size is not exactly the same,
    1106             :                 // completely give up (we could potentially move the mask in
    1107             :                 // case the imagery is smaller)
    1108         256 :                 else if (m_poMaskDS && m_bMaskInterleavedWithImagery &&
    1109           0 :                          static_cast<GUIntBig>(nCompressedBufferSize) !=
    1110           0 :                              panByteCounts[nStripOrTile])
    1111             :                 {
    1112           0 :                     GTiffDataset *poRootDS = m_poBaseDS ? m_poBaseDS : this;
    1113           0 :                     if (!poRootDS->m_bKnownIncompatibleEdition &&
    1114           0 :                         !poRootDS->m_bWriteKnownIncompatibleEdition)
    1115             :                     {
    1116           0 :                         ReportError(
    1117             :                             CE_Warning, CPLE_AppDefined,
    1118             :                             "A strile cannot be rewritten in place, which "
    1119             :                             "invalidates the MASK_INTERLEAVED_WITH_IMAGERY "
    1120             :                             "optimization.");
    1121           0 :                         poRootDS->m_bKnownIncompatibleEdition = true;
    1122           0 :                         poRootDS->m_bWriteKnownIncompatibleEdition = true;
    1123             :                     }
    1124           0 :                     bWriteLeader = false;
    1125           0 :                     bWriteTrailer = false;
    1126           0 :                     if (m_bLeaderSizeAsUInt4)
    1127             :                     {
    1128             :                         // If there was a valid leader, invalidat it
    1129           0 :                         VSI_TIFFSeek(m_hTIFF, panOffsets[nStripOrTile] - 4,
    1130             :                                      SEEK_SET);
    1131             :                         uint32_t nOldSize;
    1132           0 :                         VSIFReadL(&nOldSize, 1, 4,
    1133             :                                   VSI_TIFFGetVSILFile(TIFFClientdata(m_hTIFF)));
    1134           0 :                         CPL_LSBPTR32(&nOldSize);
    1135           0 :                         if (nOldSize == panByteCounts[nStripOrTile])
    1136             :                         {
    1137           0 :                             uint32_t nInvalidatedSize = 0;
    1138           0 :                             VSI_TIFFSeek(m_hTIFF, panOffsets[nStripOrTile] - 4,
    1139             :                                          SEEK_SET);
    1140           0 :                             VSI_TIFFWrite(m_hTIFF, &nInvalidatedSize,
    1141             :                                           sizeof(nInvalidatedSize));
    1142             :                         }
    1143           0 :                     }
    1144             :                 }
    1145             :                 else
    1146             :                 {
    1147         256 :                     bWriteAtEnd = false;
    1148             :                 }
    1149             :             }
    1150             :         }
    1151             :     }
    1152       33766 :     if (bWriteLeader &&
    1153       24918 :         static_cast<GUIntBig>(nCompressedBufferSize) <= 0xFFFFFFFFU)
    1154             :     {
    1155             :         // cppcheck-suppress knownConditionTrueFalse
    1156       24918 :         if (bWriteAtEnd)
    1157             :         {
    1158       24662 :             VSI_TIFFSeek(m_hTIFF, 0, SEEK_END);
    1159             :         }
    1160             :         else
    1161             :         {
    1162             :             // If we rewrite an existing strile in place with an existing
    1163             :             // leader, check that the leader is valid, before rewriting it. And
    1164             :             // if it is not valid, then do not write the trailer, as we could
    1165             :             // corrupt other data.
    1166         256 :             VSI_TIFFSeek(m_hTIFF, panOffsets[nStripOrTile] - 4, SEEK_SET);
    1167             :             uint32_t nOldSize;
    1168         256 :             VSIFReadL(&nOldSize, 1, 4,
    1169             :                       VSI_TIFFGetVSILFile(TIFFClientdata(m_hTIFF)));
    1170         256 :             CPL_LSBPTR32(&nOldSize);
    1171         256 :             bWriteLeader =
    1172         256 :                 panByteCounts && nOldSize == panByteCounts[nStripOrTile];
    1173         256 :             bWriteTrailer = bWriteLeader;
    1174         256 :             VSI_TIFFSeek(m_hTIFF, panOffsets[nStripOrTile] - 4, SEEK_SET);
    1175             :         }
    1176             :         // cppcheck-suppress knownConditionTrueFalse
    1177       24918 :         if (bWriteLeader)
    1178             :         {
    1179       24918 :             uint32_t nSize = static_cast<uint32_t>(nCompressedBufferSize);
    1180       24918 :             CPL_LSBPTR32(&nSize);
    1181       24918 :             if (!VSI_TIFFWrite(m_hTIFF, &nSize, sizeof(nSize)))
    1182           0 :                 m_bWriteError = true;
    1183             :         }
    1184             :     }
    1185             :     tmsize_t written;
    1186       33766 :     if (TIFFIsTiled(m_hTIFF))
    1187       26135 :         written = TIFFWriteRawTile(m_hTIFF, nStripOrTile, pabyCompressedBuffer,
    1188             :                                    nCompressedBufferSize);
    1189             :     else
    1190        7631 :         written = TIFFWriteRawStrip(m_hTIFF, nStripOrTile, pabyCompressedBuffer,
    1191             :                                     nCompressedBufferSize);
    1192       33766 :     if (written != nCompressedBufferSize)
    1193          12 :         m_bWriteError = true;
    1194       33766 :     if (bWriteTrailer &&
    1195       24918 :         static_cast<GUIntBig>(nCompressedBufferSize) <= 0xFFFFFFFFU)
    1196             :     {
    1197       24918 :         GByte abyLastBytes[4] = {};
    1198       24918 :         if (nCompressedBufferSize >= 4)
    1199       24918 :             memcpy(abyLastBytes,
    1200       24918 :                    pabyCompressedBuffer + nCompressedBufferSize - 4, 4);
    1201             :         else
    1202           0 :             memcpy(abyLastBytes, pabyCompressedBuffer, nCompressedBufferSize);
    1203       24918 :         if (!VSI_TIFFWrite(m_hTIFF, abyLastBytes, 4))
    1204           0 :             m_bWriteError = true;
    1205             :     }
    1206       33766 : }
    1207             : 
    1208             : /************************************************************************/
    1209             : /*                        WaitCompletionForJobIdx()                     */
    1210             : /************************************************************************/
    1211             : 
    1212        1575 : void GTiffDataset::WaitCompletionForJobIdx(int i)
    1213             : {
    1214        1575 :     auto poMainDS = m_poBaseDS ? m_poBaseDS : this;
    1215        1575 :     auto poQueue = poMainDS->m_poCompressQueue.get();
    1216        1575 :     auto &oQueue = poMainDS->m_asQueueJobIdx;
    1217        1575 :     auto &asJobs = poMainDS->m_asCompressionJobs;
    1218        1575 :     auto &mutex = poMainDS->m_oCompressThreadPoolMutex;
    1219             : 
    1220        1575 :     CPLAssert(i >= 0 && static_cast<size_t>(i) < asJobs.size());
    1221        1575 :     CPLAssert(asJobs[i].nStripOrTile >= 0);
    1222        1575 :     CPLAssert(!oQueue.empty());
    1223             : 
    1224        1575 :     bool bHasWarned = false;
    1225             :     while (true)
    1226             :     {
    1227             :         bool bReady;
    1228             :         {
    1229        2161 :             std::lock_guard oLock(mutex);
    1230        2161 :             bReady = asJobs[i].bReady;
    1231             :         }
    1232        2161 :         if (!bReady)
    1233             :         {
    1234         586 :             if (!bHasWarned)
    1235             :             {
    1236         317 :                 CPLDebug("GTIFF",
    1237             :                          "Waiting for worker job to finish handling block %d",
    1238         317 :                          asJobs[i].nStripOrTile);
    1239         317 :                 bHasWarned = true;
    1240             :             }
    1241         586 :             poQueue->GetPool()->WaitEvent();
    1242             :         }
    1243             :         else
    1244             :         {
    1245        1575 :             break;
    1246             :         }
    1247         586 :     }
    1248             : 
    1249        1575 :     if (asJobs[i].nCompressedBufferSize)
    1250             :     {
    1251        3150 :         asJobs[i].poDS->WriteRawStripOrTile(asJobs[i].nStripOrTile,
    1252        1575 :                                             asJobs[i].pabyCompressedBuffer,
    1253        1575 :                                             asJobs[i].nCompressedBufferSize);
    1254             :     }
    1255        1575 :     asJobs[i].pabyCompressedBuffer = nullptr;
    1256        1575 :     asJobs[i].nBufferSize = 0;
    1257             :     {
    1258             :         // Likely useless, but makes Coverity happy
    1259        1575 :         std::lock_guard oLock(mutex);
    1260        1575 :         asJobs[i].bReady = false;
    1261             :     }
    1262        1575 :     asJobs[i].nStripOrTile = -1;
    1263        1575 :     oQueue.pop();
    1264        1575 : }
    1265             : 
    1266             : /************************************************************************/
    1267             : /*                        WaitCompletionForBlock()                      */
    1268             : /************************************************************************/
    1269             : 
    1270     2301310 : void GTiffDataset::WaitCompletionForBlock(int nBlockId)
    1271             : {
    1272     2301310 :     auto poQueue = m_poBaseDS ? m_poBaseDS->m_poCompressQueue.get()
    1273     2282180 :                               : m_poCompressQueue.get();
    1274             :     // cppcheck-suppress constVariableReference
    1275     2301290 :     auto &oQueue = m_poBaseDS ? m_poBaseDS->m_asQueueJobIdx : m_asQueueJobIdx;
    1276             :     // cppcheck-suppress constVariableReference
    1277     2282150 :     auto &asJobs =
    1278     2301290 :         m_poBaseDS ? m_poBaseDS->m_asCompressionJobs : m_asCompressionJobs;
    1279             : 
    1280     2301290 :     if (poQueue != nullptr && !oQueue.empty())
    1281             :     {
    1282        1062 :         for (int i = 0; i < static_cast<int>(asJobs.size()); ++i)
    1283             :         {
    1284         885 :             if (asJobs[i].poDS == this && asJobs[i].nStripOrTile == nBlockId)
    1285             :             {
    1286         126 :                 while (!oQueue.empty() &&
    1287          63 :                        !(asJobs[oQueue.front()].poDS == this &&
    1288          63 :                          asJobs[oQueue.front()].nStripOrTile == nBlockId))
    1289             :                 {
    1290           0 :                     WaitCompletionForJobIdx(oQueue.front());
    1291             :                 }
    1292          63 :                 CPLAssert(!oQueue.empty() &&
    1293             :                           asJobs[oQueue.front()].poDS == this &&
    1294             :                           asJobs[oQueue.front()].nStripOrTile == nBlockId);
    1295          63 :                 WaitCompletionForJobIdx(oQueue.front());
    1296             :             }
    1297             :         }
    1298             :     }
    1299     2301290 : }
    1300             : 
    1301             : /************************************************************************/
    1302             : /*                      SubmitCompressionJob()                          */
    1303             : /************************************************************************/
    1304             : 
    1305      181928 : bool GTiffDataset::SubmitCompressionJob(int nStripOrTile, GByte *pabyData,
    1306             :                                         GPtrDiff_t cc, int nHeight)
    1307             : {
    1308             :     /* -------------------------------------------------------------------- */
    1309             :     /*      Should we do compression in a worker thread ?                   */
    1310             :     /* -------------------------------------------------------------------- */
    1311      181928 :     auto poQueue = m_poBaseDS ? m_poBaseDS->m_poCompressQueue.get()
    1312      168110 :                               : m_poCompressQueue.get();
    1313             : 
    1314      181918 :     if (poQueue && m_nCompression == COMPRESSION_NONE)
    1315             :     {
    1316             :         // We don't do multi-threaded compression for uncompressed...
    1317             :         // but we must wait for other related compression tasks (e.g mask)
    1318             :         // to be completed
    1319           0 :         poQueue->WaitCompletion();
    1320             : 
    1321             :         // Flush remaining data
    1322             :         // cppcheck-suppress constVariableReference
    1323           0 :         auto &oQueue =
    1324           0 :             m_poBaseDS ? m_poBaseDS->m_asQueueJobIdx : m_asQueueJobIdx;
    1325           0 :         while (!oQueue.empty())
    1326             :         {
    1327           0 :             WaitCompletionForJobIdx(oQueue.front());
    1328             :         }
    1329             :     }
    1330             : 
    1331             :     const auto SetupJob =
    1332      122604 :         [this, pabyData, cc, nHeight, nStripOrTile](GTiffCompressionJob &sJob)
    1333             :     {
    1334       26488 :         sJob.poDS = this;
    1335       26488 :         sJob.bTIFFIsBigEndian = CPL_TO_BOOL(TIFFIsBigEndian(m_hTIFF));
    1336       26488 :         sJob.pabyBuffer = static_cast<GByte *>(CPLRealloc(sJob.pabyBuffer, cc));
    1337       26488 :         memcpy(sJob.pabyBuffer, pabyData, cc);
    1338       26488 :         sJob.nBufferSize = cc;
    1339       26488 :         sJob.nHeight = nHeight;
    1340       26488 :         sJob.nStripOrTile = nStripOrTile;
    1341       26488 :         sJob.nPredictor = PREDICTOR_NONE;
    1342       26488 :         if (GTIFFSupportsPredictor(m_nCompression))
    1343             :         {
    1344       16652 :             TIFFGetField(m_hTIFF, TIFFTAG_PREDICTOR, &sJob.nPredictor);
    1345             :         }
    1346             : 
    1347       26488 :         sJob.pExtraSamples = nullptr;
    1348       26488 :         sJob.nExtraSampleCount = 0;
    1349       26488 :         TIFFGetField(m_hTIFF, TIFFTAG_EXTRASAMPLES, &sJob.nExtraSampleCount,
    1350             :                      &sJob.pExtraSamples);
    1351      208406 :     };
    1352             : 
    1353      181918 :     if (poQueue == nullptr || !(m_nCompression == COMPRESSION_ADOBE_DEFLATE ||
    1354         806 :                                 m_nCompression == COMPRESSION_LZW ||
    1355          78 :                                 m_nCompression == COMPRESSION_PACKBITS ||
    1356          72 :                                 m_nCompression == COMPRESSION_LZMA ||
    1357          62 :                                 m_nCompression == COMPRESSION_ZSTD ||
    1358          52 :                                 m_nCompression == COMPRESSION_LERC ||
    1359          46 :                                 m_nCompression == COMPRESSION_JXL ||
    1360          46 :                                 m_nCompression == COMPRESSION_JXL_DNG_1_7 ||
    1361          28 :                                 m_nCompression == COMPRESSION_WEBP ||
    1362          18 :                                 m_nCompression == COMPRESSION_JPEG))
    1363             :     {
    1364      180343 :         if (m_bBlockOrderRowMajor || m_bLeaderSizeAsUInt4 ||
    1365      155439 :             m_bTrailerRepeatedLast4BytesRepeated)
    1366             :         {
    1367             :             GTiffCompressionJob sJob;
    1368       24919 :             memset(&sJob, 0, sizeof(sJob));
    1369       24919 :             SetupJob(sJob);
    1370       24913 :             sJob.pszTmpFilename =
    1371       24913 :                 CPLStrdup(VSIMemGenerateHiddenFilename("temp.tif"));
    1372             : 
    1373       24913 :             ThreadCompressionFunc(&sJob);
    1374             : 
    1375       24913 :             if (sJob.nCompressedBufferSize)
    1376             :             {
    1377       24913 :                 sJob.poDS->WriteRawStripOrTile(sJob.nStripOrTile,
    1378             :                                                sJob.pabyCompressedBuffer,
    1379             :                                                sJob.nCompressedBufferSize);
    1380             :             }
    1381             : 
    1382       24913 :             CPLFree(sJob.pabyBuffer);
    1383       24913 :             VSIUnlink(sJob.pszTmpFilename);
    1384       24913 :             CPLFree(sJob.pszTmpFilename);
    1385       24913 :             return sJob.nCompressedBufferSize > 0 && !m_bWriteError;
    1386             :         }
    1387             : 
    1388      155424 :         return false;
    1389             :     }
    1390             : 
    1391        1575 :     auto poMainDS = m_poBaseDS ? m_poBaseDS : this;
    1392        1575 :     auto &oQueue = poMainDS->m_asQueueJobIdx;
    1393        1575 :     auto &asJobs = poMainDS->m_asCompressionJobs;
    1394             : 
    1395        1575 :     int nNextCompressionJobAvail = -1;
    1396             : 
    1397        1575 :     if (oQueue.size() == asJobs.size())
    1398             :     {
    1399        1443 :         CPLAssert(!oQueue.empty());
    1400        1443 :         nNextCompressionJobAvail = oQueue.front();
    1401        1443 :         WaitCompletionForJobIdx(nNextCompressionJobAvail);
    1402             :     }
    1403             :     else
    1404             :     {
    1405         132 :         const int nJobs = static_cast<int>(asJobs.size());
    1406         323 :         for (int i = 0; i < nJobs; ++i)
    1407             :         {
    1408         323 :             if (asJobs[i].nBufferSize == 0)
    1409             :             {
    1410         132 :                 nNextCompressionJobAvail = i;
    1411         132 :                 break;
    1412             :             }
    1413             :         }
    1414             :     }
    1415        1575 :     CPLAssert(nNextCompressionJobAvail >= 0);
    1416             : 
    1417        1575 :     GTiffCompressionJob *psJob = &asJobs[nNextCompressionJobAvail];
    1418        1575 :     SetupJob(*psJob);
    1419        1575 :     poQueue->SubmitJob(ThreadCompressionFunc, psJob);
    1420        1575 :     oQueue.push(nNextCompressionJobAvail);
    1421             : 
    1422        1575 :     return true;
    1423             : }
    1424             : 
    1425             : /************************************************************************/
    1426             : /*                          DiscardLsb()                                */
    1427             : /************************************************************************/
    1428             : 
    1429         272 : template <class T> bool MustNotDiscardLsb(T value, bool bHasNoData, T nodata)
    1430             : {
    1431         272 :     return bHasNoData && value == nodata;
    1432             : }
    1433             : 
    1434             : template <>
    1435          44 : bool MustNotDiscardLsb<float>(float value, bool bHasNoData, float nodata)
    1436             : {
    1437          44 :     return (bHasNoData && value == nodata) || !std::isfinite(value);
    1438             : }
    1439             : 
    1440             : template <>
    1441          44 : bool MustNotDiscardLsb<double>(double value, bool bHasNoData, double nodata)
    1442             : {
    1443          44 :     return (bHasNoData && value == nodata) || !std::isfinite(value);
    1444             : }
    1445             : 
    1446             : template <class T> T AdjustValue(T value, uint64_t nRoundUpBitTest);
    1447             : 
    1448          10 : template <class T> T AdjustValueInt(T value, uint64_t nRoundUpBitTest)
    1449             : {
    1450          10 :     if (value >=
    1451          10 :         static_cast<T>(std::numeric_limits<T>::max() - (nRoundUpBitTest << 1)))
    1452           0 :         return static_cast<T>(value - (nRoundUpBitTest << 1));
    1453          10 :     return static_cast<T>(value + (nRoundUpBitTest << 1));
    1454             : }
    1455             : 
    1456           0 : template <> int8_t AdjustValue<int8_t>(int8_t value, uint64_t nRoundUpBitTest)
    1457             : {
    1458           0 :     return AdjustValueInt(value, nRoundUpBitTest);
    1459             : }
    1460             : 
    1461             : template <>
    1462           2 : uint8_t AdjustValue<uint8_t>(uint8_t value, uint64_t nRoundUpBitTest)
    1463             : {
    1464           2 :     return AdjustValueInt(value, nRoundUpBitTest);
    1465             : }
    1466             : 
    1467             : template <>
    1468           2 : int16_t AdjustValue<int16_t>(int16_t value, uint64_t nRoundUpBitTest)
    1469             : {
    1470           2 :     return AdjustValueInt(value, nRoundUpBitTest);
    1471             : }
    1472             : 
    1473             : template <>
    1474           2 : uint16_t AdjustValue<uint16_t>(uint16_t value, uint64_t nRoundUpBitTest)
    1475             : {
    1476           2 :     return AdjustValueInt(value, nRoundUpBitTest);
    1477             : }
    1478             : 
    1479             : template <>
    1480           2 : int32_t AdjustValue<int32_t>(int32_t value, uint64_t nRoundUpBitTest)
    1481             : {
    1482           2 :     return AdjustValueInt(value, nRoundUpBitTest);
    1483             : }
    1484             : 
    1485             : template <>
    1486           2 : uint32_t AdjustValue<uint32_t>(uint32_t value, uint64_t nRoundUpBitTest)
    1487             : {
    1488           2 :     return AdjustValueInt(value, nRoundUpBitTest);
    1489             : }
    1490             : 
    1491             : template <>
    1492           0 : int64_t AdjustValue<int64_t>(int64_t value, uint64_t nRoundUpBitTest)
    1493             : {
    1494           0 :     return AdjustValueInt(value, nRoundUpBitTest);
    1495             : }
    1496             : 
    1497             : template <>
    1498           0 : uint64_t AdjustValue<uint64_t>(uint64_t value, uint64_t nRoundUpBitTest)
    1499             : {
    1500           0 :     return AdjustValueInt(value, nRoundUpBitTest);
    1501             : }
    1502             : 
    1503           0 : template <> float AdjustValue<float>(float value, uint64_t)
    1504             : {
    1505           0 :     return std::nextafter(value, std::numeric_limits<float>::max());
    1506             : }
    1507             : 
    1508           0 : template <> double AdjustValue<double>(double value, uint64_t)
    1509             : {
    1510           0 :     return std::nextafter(value, std::numeric_limits<double>::max());
    1511             : }
    1512             : 
    1513             : template <class Teffective, class T>
    1514             : T RoundValueDiscardLsb(const void *ptr, uint64_t nMask,
    1515             :                        uint64_t nRoundUpBitTest);
    1516             : 
    1517             : template <class T>
    1518          16 : T RoundValueDiscardLsbUnsigned(const void *ptr, uint64_t nMask,
    1519             :                                uint64_t nRoundUpBitTest)
    1520             : {
    1521          32 :     if ((*reinterpret_cast<const T *>(ptr) & nMask) >
    1522          16 :         static_cast<uint64_t>(std::numeric_limits<T>::max()) -
    1523          16 :             (nRoundUpBitTest << 1U))
    1524             :     {
    1525           4 :         return static_cast<T>(std::numeric_limits<T>::max() & nMask);
    1526             :     }
    1527          12 :     const uint64_t newval =
    1528          12 :         (*reinterpret_cast<const T *>(ptr) & nMask) + (nRoundUpBitTest << 1U);
    1529          12 :     return static_cast<T>(newval);
    1530             : }
    1531             : 
    1532             : template <class T>
    1533          18 : T RoundValueDiscardLsbSigned(const void *ptr, uint64_t nMask,
    1534             :                              uint64_t nRoundUpBitTest)
    1535             : {
    1536          18 :     T oldval = *reinterpret_cast<const T *>(ptr);
    1537          18 :     if (oldval < 0)
    1538             :     {
    1539           4 :         return static_cast<T>(oldval & nMask);
    1540             :     }
    1541          14 :     const uint64_t newval =
    1542          14 :         (*reinterpret_cast<const T *>(ptr) & nMask) + (nRoundUpBitTest << 1U);
    1543          14 :     if (newval > static_cast<uint64_t>(std::numeric_limits<T>::max()))
    1544           4 :         return static_cast<T>(std::numeric_limits<T>::max() & nMask);
    1545          10 :     return static_cast<T>(newval);
    1546             : }
    1547             : 
    1548             : template <>
    1549          11 : uint16_t RoundValueDiscardLsb<uint16_t, uint16_t>(const void *ptr,
    1550             :                                                   uint64_t nMask,
    1551             :                                                   uint64_t nRoundUpBitTest)
    1552             : {
    1553          11 :     return RoundValueDiscardLsbUnsigned<uint16_t>(ptr, nMask, nRoundUpBitTest);
    1554             : }
    1555             : 
    1556             : template <>
    1557           5 : uint32_t RoundValueDiscardLsb<uint32_t, uint32_t>(const void *ptr,
    1558             :                                                   uint64_t nMask,
    1559             :                                                   uint64_t nRoundUpBitTest)
    1560             : {
    1561           5 :     return RoundValueDiscardLsbUnsigned<uint32_t>(ptr, nMask, nRoundUpBitTest);
    1562             : }
    1563             : 
    1564             : template <>
    1565           0 : uint64_t RoundValueDiscardLsb<uint64_t, uint64_t>(const void *ptr,
    1566             :                                                   uint64_t nMask,
    1567             :                                                   uint64_t nRoundUpBitTest)
    1568             : {
    1569           0 :     return RoundValueDiscardLsbUnsigned<uint64_t>(ptr, nMask, nRoundUpBitTest);
    1570             : }
    1571             : 
    1572             : template <>
    1573           0 : int8_t RoundValueDiscardLsb<int8_t, int8_t>(const void *ptr, uint64_t nMask,
    1574             :                                             uint64_t nRoundUpBitTest)
    1575             : {
    1576           0 :     return RoundValueDiscardLsbSigned<int8_t>(ptr, nMask, nRoundUpBitTest);
    1577             : }
    1578             : 
    1579             : template <>
    1580          13 : int16_t RoundValueDiscardLsb<int16_t, int16_t>(const void *ptr, uint64_t nMask,
    1581             :                                                uint64_t nRoundUpBitTest)
    1582             : {
    1583          13 :     return RoundValueDiscardLsbSigned<int16_t>(ptr, nMask, nRoundUpBitTest);
    1584             : }
    1585             : 
    1586             : template <>
    1587           5 : int32_t RoundValueDiscardLsb<int32_t, int32_t>(const void *ptr, uint64_t nMask,
    1588             :                                                uint64_t nRoundUpBitTest)
    1589             : {
    1590           5 :     return RoundValueDiscardLsbSigned<int32_t>(ptr, nMask, nRoundUpBitTest);
    1591             : }
    1592             : 
    1593             : template <>
    1594           0 : int64_t RoundValueDiscardLsb<int64_t, int64_t>(const void *ptr, uint64_t nMask,
    1595             :                                                uint64_t nRoundUpBitTest)
    1596             : {
    1597           0 :     return RoundValueDiscardLsbSigned<int64_t>(ptr, nMask, nRoundUpBitTest);
    1598             : }
    1599             : 
    1600             : template <>
    1601           0 : uint32_t RoundValueDiscardLsb<float, uint32_t>(const void *ptr, uint64_t nMask,
    1602             :                                                uint64_t nRoundUpBitTest)
    1603             : {
    1604           0 :     return RoundValueDiscardLsbUnsigned<uint32_t>(ptr, nMask, nRoundUpBitTest);
    1605             : }
    1606             : 
    1607             : template <>
    1608           0 : uint64_t RoundValueDiscardLsb<double, uint64_t>(const void *ptr, uint64_t nMask,
    1609             :                                                 uint64_t nRoundUpBitTest)
    1610             : {
    1611           0 :     return RoundValueDiscardLsbUnsigned<uint64_t>(ptr, nMask, nRoundUpBitTest);
    1612             : }
    1613             : 
    1614             : template <class Teffective, class T>
    1615         145 : static void DiscardLsbT(GByte *pabyBuffer, size_t nBytes, int iBand, int nBands,
    1616             :                         uint16_t nPlanarConfig,
    1617             :                         const GTiffDataset::MaskOffset *panMaskOffsetLsb,
    1618             :                         bool bHasNoData, Teffective nNoDataValue)
    1619             : {
    1620             :     static_assert(sizeof(Teffective) == sizeof(T),
    1621             :                   "sizeof(Teffective) == sizeof(T)");
    1622         145 :     if (nPlanarConfig == PLANARCONFIG_SEPARATE)
    1623             :     {
    1624          98 :         const auto nMask = panMaskOffsetLsb[iBand].nMask;
    1625          98 :         const auto nRoundUpBitTest = panMaskOffsetLsb[iBand].nRoundUpBitTest;
    1626         196 :         for (size_t i = 0; i < nBytes / sizeof(T); ++i)
    1627             :         {
    1628          98 :             if (MustNotDiscardLsb(reinterpret_cast<Teffective *>(pabyBuffer)[i],
    1629             :                                   bHasNoData, nNoDataValue))
    1630             :             {
    1631          22 :                 continue;
    1632             :             }
    1633             : 
    1634          76 :             if (reinterpret_cast<T *>(pabyBuffer)[i] & nRoundUpBitTest)
    1635             :             {
    1636          30 :                 reinterpret_cast<T *>(pabyBuffer)[i] =
    1637          15 :                     RoundValueDiscardLsb<Teffective, T>(
    1638          15 :                         &(reinterpret_cast<T *>(pabyBuffer)[i]), nMask,
    1639             :                         nRoundUpBitTest);
    1640             :             }
    1641             :             else
    1642             :             {
    1643          61 :                 reinterpret_cast<T *>(pabyBuffer)[i] = static_cast<T>(
    1644          61 :                     reinterpret_cast<T *>(pabyBuffer)[i] & nMask);
    1645             :             }
    1646             : 
    1647             :             // Make sure that by discarding LSB we don't end up to a value
    1648             :             // that is no the nodata value
    1649          76 :             if (MustNotDiscardLsb(reinterpret_cast<Teffective *>(pabyBuffer)[i],
    1650             :                                   bHasNoData, nNoDataValue))
    1651             :             {
    1652           8 :                 reinterpret_cast<Teffective *>(pabyBuffer)[i] =
    1653           4 :                     AdjustValue(nNoDataValue, nRoundUpBitTest);
    1654             :             }
    1655             :         }
    1656             :     }
    1657             :     else
    1658             :     {
    1659          94 :         for (size_t i = 0; i < nBytes / sizeof(T); i += nBands)
    1660             :         {
    1661         147 :             for (int j = 0; j < nBands; ++j)
    1662             :             {
    1663         100 :                 if (MustNotDiscardLsb(
    1664         100 :                         reinterpret_cast<Teffective *>(pabyBuffer)[i + j],
    1665             :                         bHasNoData, nNoDataValue))
    1666             :                 {
    1667          14 :                     continue;
    1668             :                 }
    1669             : 
    1670          86 :                 if (reinterpret_cast<T *>(pabyBuffer)[i + j] &
    1671          86 :                     panMaskOffsetLsb[j].nRoundUpBitTest)
    1672             :                 {
    1673          38 :                     reinterpret_cast<T *>(pabyBuffer)[i + j] =
    1674          19 :                         RoundValueDiscardLsb<Teffective, T>(
    1675          19 :                             &(reinterpret_cast<T *>(pabyBuffer)[i + j]),
    1676          19 :                             panMaskOffsetLsb[j].nMask,
    1677          19 :                             panMaskOffsetLsb[j].nRoundUpBitTest);
    1678             :                 }
    1679             :                 else
    1680             :                 {
    1681          67 :                     reinterpret_cast<T *>(pabyBuffer)[i + j] = static_cast<T>(
    1682          67 :                         (reinterpret_cast<T *>(pabyBuffer)[i + j] &
    1683          67 :                          panMaskOffsetLsb[j].nMask));
    1684             :                 }
    1685             : 
    1686             :                 // Make sure that by discarding LSB we don't end up to a value
    1687             :                 // that is no the nodata value
    1688          86 :                 if (MustNotDiscardLsb(
    1689          86 :                         reinterpret_cast<Teffective *>(pabyBuffer)[i + j],
    1690             :                         bHasNoData, nNoDataValue))
    1691             :                 {
    1692           8 :                     reinterpret_cast<Teffective *>(pabyBuffer)[i + j] =
    1693           4 :                         AdjustValue(nNoDataValue,
    1694           4 :                                     panMaskOffsetLsb[j].nRoundUpBitTest);
    1695             :                 }
    1696             :             }
    1697             :         }
    1698             :     }
    1699         145 : }
    1700             : 
    1701         183 : static void DiscardLsb(GByte *pabyBuffer, GPtrDiff_t nBytes, int iBand,
    1702             :                        int nBands, uint16_t nSampleFormat,
    1703             :                        uint16_t nBitsPerSample, uint16_t nPlanarConfig,
    1704             :                        const GTiffDataset::MaskOffset *panMaskOffsetLsb,
    1705             :                        bool bHasNoData, double dfNoDataValue)
    1706             : {
    1707         183 :     if (nBitsPerSample == 8 && nSampleFormat == SAMPLEFORMAT_UINT)
    1708             :     {
    1709          38 :         uint8_t nNoDataValue = 0;
    1710          38 :         if (bHasNoData && GDALIsValueExactAs<uint8_t>(dfNoDataValue))
    1711             :         {
    1712           6 :             nNoDataValue = static_cast<uint8_t>(dfNoDataValue);
    1713             :         }
    1714             :         else
    1715             :         {
    1716          32 :             bHasNoData = false;
    1717             :         }
    1718          38 :         if (nPlanarConfig == PLANARCONFIG_SEPARATE)
    1719             :         {
    1720          25 :             const auto nMask =
    1721          25 :                 static_cast<unsigned>(panMaskOffsetLsb[iBand].nMask);
    1722          25 :             const auto nRoundUpBitTest =
    1723          25 :                 static_cast<unsigned>(panMaskOffsetLsb[iBand].nRoundUpBitTest);
    1724          50 :             for (decltype(nBytes) i = 0; i < nBytes; ++i)
    1725             :             {
    1726          25 :                 if (bHasNoData && pabyBuffer[i] == nNoDataValue)
    1727           3 :                     continue;
    1728             : 
    1729             :                 // Keep 255 in case it is alpha.
    1730          22 :                 if (pabyBuffer[i] != 255)
    1731             :                 {
    1732          21 :                     if (pabyBuffer[i] & nRoundUpBitTest)
    1733           5 :                         pabyBuffer[i] = static_cast<GByte>(
    1734           5 :                             std::min(255U, (pabyBuffer[i] & nMask) +
    1735           5 :                                                (nRoundUpBitTest << 1U)));
    1736             :                     else
    1737          16 :                         pabyBuffer[i] =
    1738          16 :                             static_cast<GByte>(pabyBuffer[i] & nMask);
    1739             : 
    1740             :                     // Make sure that by discarding LSB we don't end up to a
    1741             :                     // value that is no the nodata value
    1742          21 :                     if (bHasNoData && pabyBuffer[i] == nNoDataValue)
    1743           2 :                         pabyBuffer[i] =
    1744           1 :                             AdjustValue(nNoDataValue, nRoundUpBitTest);
    1745             :                 }
    1746             :             }
    1747             :         }
    1748             :         else
    1749             :         {
    1750          26 :             for (decltype(nBytes) i = 0; i < nBytes; i += nBands)
    1751             :             {
    1752          42 :                 for (int j = 0; j < nBands; ++j)
    1753             :                 {
    1754          29 :                     if (bHasNoData && pabyBuffer[i + j] == nNoDataValue)
    1755           2 :                         continue;
    1756             : 
    1757             :                     // Keep 255 in case it is alpha.
    1758          27 :                     if (pabyBuffer[i + j] != 255)
    1759             :                     {
    1760          25 :                         if (pabyBuffer[i + j] &
    1761          25 :                             panMaskOffsetLsb[j].nRoundUpBitTest)
    1762             :                         {
    1763           6 :                             pabyBuffer[i + j] = static_cast<GByte>(std::min(
    1764          12 :                                 255U,
    1765           6 :                                 (pabyBuffer[i + j] &
    1766             :                                  static_cast<unsigned>(
    1767           6 :                                      panMaskOffsetLsb[j].nMask)) +
    1768             :                                     (static_cast<unsigned>(
    1769           6 :                                          panMaskOffsetLsb[j].nRoundUpBitTest)
    1770           6 :                                      << 1U)));
    1771             :                         }
    1772             :                         else
    1773             :                         {
    1774          19 :                             pabyBuffer[i + j] = static_cast<GByte>(
    1775          19 :                                 pabyBuffer[i + j] & panMaskOffsetLsb[j].nMask);
    1776             :                         }
    1777             : 
    1778             :                         // Make sure that by discarding LSB we don't end up to a
    1779             :                         // value that is no the nodata value
    1780          25 :                         if (bHasNoData && pabyBuffer[i + j] == nNoDataValue)
    1781           1 :                             pabyBuffer[i + j] = AdjustValue(
    1782             :                                 nNoDataValue,
    1783           1 :                                 panMaskOffsetLsb[j].nRoundUpBitTest);
    1784             :                     }
    1785             :                 }
    1786             :             }
    1787          38 :         }
    1788             :     }
    1789         145 :     else if (nBitsPerSample == 8 && nSampleFormat == SAMPLEFORMAT_INT)
    1790             :     {
    1791           0 :         int8_t nNoDataValue = 0;
    1792           0 :         if (bHasNoData && GDALIsValueExactAs<int8_t>(dfNoDataValue))
    1793             :         {
    1794           0 :             nNoDataValue = static_cast<int8_t>(dfNoDataValue);
    1795             :         }
    1796             :         else
    1797             :         {
    1798           0 :             bHasNoData = false;
    1799             :         }
    1800           0 :         DiscardLsbT<int8_t, int8_t>(pabyBuffer, nBytes, iBand, nBands,
    1801             :                                     nPlanarConfig, panMaskOffsetLsb, bHasNoData,
    1802           0 :                                     nNoDataValue);
    1803             :     }
    1804         145 :     else if (nBitsPerSample == 16 && nSampleFormat == SAMPLEFORMAT_INT)
    1805             :     {
    1806          48 :         int16_t nNoDataValue = 0;
    1807          48 :         if (bHasNoData && GDALIsValueExactAs<int16_t>(dfNoDataValue))
    1808             :         {
    1809           6 :             nNoDataValue = static_cast<int16_t>(dfNoDataValue);
    1810             :         }
    1811             :         else
    1812             :         {
    1813          42 :             bHasNoData = false;
    1814             :         }
    1815          48 :         DiscardLsbT<int16_t, int16_t>(pabyBuffer, nBytes, iBand, nBands,
    1816             :                                       nPlanarConfig, panMaskOffsetLsb,
    1817          48 :                                       bHasNoData, nNoDataValue);
    1818             :     }
    1819          97 :     else if (nBitsPerSample == 16 && nSampleFormat == SAMPLEFORMAT_UINT)
    1820             :     {
    1821          33 :         uint16_t nNoDataValue = 0;
    1822          33 :         if (bHasNoData && GDALIsValueExactAs<uint16_t>(dfNoDataValue))
    1823             :         {
    1824           6 :             nNoDataValue = static_cast<uint16_t>(dfNoDataValue);
    1825             :         }
    1826             :         else
    1827             :         {
    1828          27 :             bHasNoData = false;
    1829             :         }
    1830          33 :         DiscardLsbT<uint16_t, uint16_t>(pabyBuffer, nBytes, iBand, nBands,
    1831             :                                         nPlanarConfig, panMaskOffsetLsb,
    1832          33 :                                         bHasNoData, nNoDataValue);
    1833             :     }
    1834          64 :     else if (nBitsPerSample == 32 && nSampleFormat == SAMPLEFORMAT_INT)
    1835             :     {
    1836          13 :         int32_t nNoDataValue = 0;
    1837          13 :         if (bHasNoData && GDALIsValueExactAs<int32_t>(dfNoDataValue))
    1838             :         {
    1839           6 :             nNoDataValue = static_cast<int32_t>(dfNoDataValue);
    1840             :         }
    1841             :         else
    1842             :         {
    1843           7 :             bHasNoData = false;
    1844             :         }
    1845          13 :         DiscardLsbT<int32_t, int32_t>(pabyBuffer, nBytes, iBand, nBands,
    1846             :                                       nPlanarConfig, panMaskOffsetLsb,
    1847          13 :                                       bHasNoData, nNoDataValue);
    1848             :     }
    1849          51 :     else if (nBitsPerSample == 32 && nSampleFormat == SAMPLEFORMAT_UINT)
    1850             :     {
    1851          13 :         uint32_t nNoDataValue = 0;
    1852          13 :         if (bHasNoData && GDALIsValueExactAs<uint32_t>(dfNoDataValue))
    1853             :         {
    1854           6 :             nNoDataValue = static_cast<uint32_t>(dfNoDataValue);
    1855             :         }
    1856             :         else
    1857             :         {
    1858           7 :             bHasNoData = false;
    1859             :         }
    1860          13 :         DiscardLsbT<uint32_t, uint32_t>(pabyBuffer, nBytes, iBand, nBands,
    1861             :                                         nPlanarConfig, panMaskOffsetLsb,
    1862          13 :                                         bHasNoData, nNoDataValue);
    1863             :     }
    1864          38 :     else if (nBitsPerSample == 64 && nSampleFormat == SAMPLEFORMAT_INT)
    1865             :     {
    1866             :         // FIXME: we should not rely on dfNoDataValue when we support native
    1867             :         // data type for nodata
    1868           0 :         int64_t nNoDataValue = 0;
    1869           0 :         if (bHasNoData && GDALIsValueExactAs<int64_t>(dfNoDataValue))
    1870             :         {
    1871           0 :             nNoDataValue = static_cast<int64_t>(dfNoDataValue);
    1872             :         }
    1873             :         else
    1874             :         {
    1875           0 :             bHasNoData = false;
    1876             :         }
    1877           0 :         DiscardLsbT<int64_t, int64_t>(pabyBuffer, nBytes, iBand, nBands,
    1878             :                                       nPlanarConfig, panMaskOffsetLsb,
    1879           0 :                                       bHasNoData, nNoDataValue);
    1880             :     }
    1881          38 :     else if (nBitsPerSample == 64 && nSampleFormat == SAMPLEFORMAT_UINT)
    1882             :     {
    1883             :         // FIXME: we should not rely on dfNoDataValue when we support native
    1884             :         // data type for nodata
    1885           0 :         uint64_t nNoDataValue = 0;
    1886           0 :         if (bHasNoData && GDALIsValueExactAs<uint64_t>(dfNoDataValue))
    1887             :         {
    1888           0 :             nNoDataValue = static_cast<uint64_t>(dfNoDataValue);
    1889             :         }
    1890             :         else
    1891             :         {
    1892           0 :             bHasNoData = false;
    1893             :         }
    1894           0 :         DiscardLsbT<uint64_t, uint64_t>(pabyBuffer, nBytes, iBand, nBands,
    1895             :                                         nPlanarConfig, panMaskOffsetLsb,
    1896           0 :                                         bHasNoData, nNoDataValue);
    1897             :     }
    1898          38 :     else if (nBitsPerSample == 32 && nSampleFormat == SAMPLEFORMAT_IEEEFP)
    1899             :     {
    1900          19 :         float fNoDataValue = static_cast<float>(dfNoDataValue);
    1901          19 :         DiscardLsbT<float, uint32_t>(pabyBuffer, nBytes, iBand, nBands,
    1902             :                                      nPlanarConfig, panMaskOffsetLsb,
    1903          19 :                                      bHasNoData, fNoDataValue);
    1904             :     }
    1905          19 :     else if (nBitsPerSample == 64 && nSampleFormat == SAMPLEFORMAT_IEEEFP)
    1906             :     {
    1907          19 :         DiscardLsbT<double, uint64_t>(pabyBuffer, nBytes, iBand, nBands,
    1908             :                                       nPlanarConfig, panMaskOffsetLsb,
    1909             :                                       bHasNoData, dfNoDataValue);
    1910             :     }
    1911         183 : }
    1912             : 
    1913         183 : void GTiffDataset::DiscardLsb(GByte *pabyBuffer, GPtrDiff_t nBytes,
    1914             :                               int iBand) const
    1915             : {
    1916         183 :     ::DiscardLsb(pabyBuffer, nBytes, iBand, nBands, m_nSampleFormat,
    1917         183 :                  m_nBitsPerSample, m_nPlanarConfig, m_panMaskOffsetLsb,
    1918         183 :                  m_bNoDataSet, m_dfNoDataValue);
    1919         183 : }
    1920             : 
    1921             : /************************************************************************/
    1922             : /*                  WriteEncodedTileOrStrip()                           */
    1923             : /************************************************************************/
    1924             : 
    1925      209161 : CPLErr GTiffDataset::WriteEncodedTileOrStrip(uint32_t tile_or_strip, void *data,
    1926             :                                              int bPreserveDataBuffer)
    1927             : {
    1928      209161 :     CPLErr eErr = CE_None;
    1929             : 
    1930      209161 :     if (TIFFIsTiled(m_hTIFF))
    1931             :     {
    1932       47416 :         if (!(WriteEncodedTile(tile_or_strip, static_cast<GByte *>(data),
    1933             :                                bPreserveDataBuffer)))
    1934             :         {
    1935          14 :             eErr = CE_Failure;
    1936             :         }
    1937             :     }
    1938             :     else
    1939             :     {
    1940      161746 :         if (!(WriteEncodedStrip(tile_or_strip, static_cast<GByte *>(data),
    1941             :                                 bPreserveDataBuffer)))
    1942             :         {
    1943           8 :             eErr = CE_Failure;
    1944             :         }
    1945             :     }
    1946             : 
    1947      209159 :     return eErr;
    1948             : }
    1949             : 
    1950             : /************************************************************************/
    1951             : /*                           FlushBlockBuf()                            */
    1952             : /************************************************************************/
    1953             : 
    1954        9659 : CPLErr GTiffDataset::FlushBlockBuf()
    1955             : 
    1956             : {
    1957        9659 :     if (m_nLoadedBlock < 0 || !m_bLoadedBlockDirty)
    1958           0 :         return CE_None;
    1959             : 
    1960        9659 :     m_bLoadedBlockDirty = false;
    1961             : 
    1962             :     const CPLErr eErr =
    1963        9659 :         WriteEncodedTileOrStrip(m_nLoadedBlock, m_pabyBlockBuf, true);
    1964        9659 :     if (eErr != CE_None)
    1965             :     {
    1966           0 :         ReportError(CE_Failure, CPLE_AppDefined,
    1967             :                     "WriteEncodedTile/Strip() failed.");
    1968           0 :         m_bWriteError = true;
    1969             :     }
    1970             : 
    1971        9659 :     return eErr;
    1972             : }
    1973             : 
    1974             : /************************************************************************/
    1975             : /*                   GTiffFillStreamableOffsetAndCount()                */
    1976             : /************************************************************************/
    1977             : 
    1978           8 : static void GTiffFillStreamableOffsetAndCount(TIFF *hTIFF, int nSize)
    1979             : {
    1980           8 :     uint32_t nXSize = 0;
    1981           8 :     uint32_t nYSize = 0;
    1982           8 :     TIFFGetField(hTIFF, TIFFTAG_IMAGEWIDTH, &nXSize);
    1983           8 :     TIFFGetField(hTIFF, TIFFTAG_IMAGELENGTH, &nYSize);
    1984           8 :     const bool bIsTiled = CPL_TO_BOOL(TIFFIsTiled(hTIFF));
    1985             :     const int nBlockCount =
    1986           8 :         bIsTiled ? TIFFNumberOfTiles(hTIFF) : TIFFNumberOfStrips(hTIFF);
    1987             : 
    1988           8 :     toff_t *panOffset = nullptr;
    1989           8 :     TIFFGetField(hTIFF, bIsTiled ? TIFFTAG_TILEOFFSETS : TIFFTAG_STRIPOFFSETS,
    1990             :                  &panOffset);
    1991           8 :     toff_t *panSize = nullptr;
    1992           8 :     TIFFGetField(hTIFF,
    1993             :                  bIsTiled ? TIFFTAG_TILEBYTECOUNTS : TIFFTAG_STRIPBYTECOUNTS,
    1994             :                  &panSize);
    1995           8 :     toff_t nOffset = nSize;
    1996             :     // Trick to avoid clang static analyzer raising false positive about
    1997             :     // divide by zero later.
    1998           8 :     int nBlocksPerBand = 1;
    1999           8 :     uint32_t nRowsPerStrip = 0;
    2000           8 :     if (!bIsTiled)
    2001             :     {
    2002           6 :         TIFFGetField(hTIFF, TIFFTAG_ROWSPERSTRIP, &nRowsPerStrip);
    2003           6 :         if (nRowsPerStrip > static_cast<uint32_t>(nYSize))
    2004           0 :             nRowsPerStrip = nYSize;
    2005           6 :         nBlocksPerBand = DIV_ROUND_UP(nYSize, nRowsPerStrip);
    2006             :     }
    2007        2947 :     for (int i = 0; i < nBlockCount; ++i)
    2008             :     {
    2009             :         GPtrDiff_t cc = bIsTiled
    2010        2939 :                             ? static_cast<GPtrDiff_t>(TIFFTileSize(hTIFF))
    2011        2907 :                             : static_cast<GPtrDiff_t>(TIFFStripSize(hTIFF));
    2012        2939 :         if (!bIsTiled)
    2013             :         {
    2014             :             /* --------------------------------------------------------------------
    2015             :              */
    2016             :             /*      If this is the last strip in the image, and is partial, then
    2017             :              */
    2018             :             /*      we need to trim the number of scanlines written to the */
    2019             :             /*      amount of valid data we have. (#2748) */
    2020             :             /* --------------------------------------------------------------------
    2021             :              */
    2022        2907 :             int nStripWithinBand = i % nBlocksPerBand;
    2023        2907 :             if (nStripWithinBand * nRowsPerStrip > nYSize - nRowsPerStrip)
    2024             :             {
    2025           1 :                 cc = (cc / nRowsPerStrip) *
    2026           1 :                      (nYSize - nStripWithinBand * nRowsPerStrip);
    2027             :             }
    2028             :         }
    2029        2939 :         panOffset[i] = nOffset;
    2030        2939 :         panSize[i] = cc;
    2031        2939 :         nOffset += cc;
    2032             :     }
    2033           8 : }
    2034             : 
    2035             : /************************************************************************/
    2036             : /*                             Crystalize()                             */
    2037             : /*                                                                      */
    2038             : /*      Make sure that the directory information is written out for     */
    2039             : /*      a new file, require before writing any imagery data.            */
    2040             : /************************************************************************/
    2041             : 
    2042     2517220 : void GTiffDataset::Crystalize()
    2043             : 
    2044             : {
    2045     2517220 :     if (m_bCrystalized)
    2046     2513980 :         return;
    2047             : 
    2048             :     // TODO: libtiff writes extended tags in the order they are specified
    2049             :     // and not in increasing order.
    2050        3243 :     WriteMetadata(this, m_hTIFF, true, m_eProfile, m_pszFilename,
    2051        3243 :                   m_papszCreationOptions);
    2052        3203 :     WriteGeoTIFFInfo();
    2053        3203 :     if (m_bNoDataSet)
    2054         267 :         WriteNoDataValue(m_hTIFF, m_dfNoDataValue);
    2055        2936 :     else if (m_bNoDataSetAsInt64)
    2056           1 :         WriteNoDataValue(m_hTIFF, m_nNoDataValueInt64);
    2057        2935 :     else if (m_bNoDataSetAsUInt64)
    2058           1 :         WriteNoDataValue(m_hTIFF, m_nNoDataValueUInt64);
    2059             : 
    2060        3203 :     m_bMetadataChanged = false;
    2061        3203 :     m_bGeoTIFFInfoChanged = false;
    2062        3203 :     m_bNoDataChanged = false;
    2063        3203 :     m_bNeedsRewrite = false;
    2064             : 
    2065        3203 :     m_bCrystalized = true;
    2066             : 
    2067        3203 :     TIFFWriteCheck(m_hTIFF, TIFFIsTiled(m_hTIFF), "GTiffDataset::Crystalize");
    2068             : 
    2069        3203 :     TIFFWriteDirectory(m_hTIFF);
    2070        3203 :     if (m_bStreamingOut)
    2071             :     {
    2072             :         // We need to write twice the directory to be sure that custom
    2073             :         // TIFF tags are correctly sorted and that padding bytes have been
    2074             :         // added.
    2075           3 :         TIFFSetDirectory(m_hTIFF, 0);
    2076           3 :         TIFFWriteDirectory(m_hTIFF);
    2077             : 
    2078           3 :         if (VSIFSeekL(m_fpL, 0, SEEK_END) != 0)
    2079             :         {
    2080           0 :             ReportError(CE_Failure, CPLE_FileIO, "Could not seek");
    2081             :         }
    2082           3 :         const int nSize = static_cast<int>(VSIFTellL(m_fpL));
    2083             : 
    2084           3 :         TIFFSetDirectory(m_hTIFF, 0);
    2085           3 :         GTiffFillStreamableOffsetAndCount(m_hTIFF, nSize);
    2086           3 :         TIFFWriteDirectory(m_hTIFF);
    2087             : 
    2088           3 :         vsi_l_offset nDataLength = 0;
    2089             :         void *pabyBuffer =
    2090           3 :             VSIGetMemFileBuffer(m_pszTmpFilename, &nDataLength, FALSE);
    2091           3 :         if (static_cast<int>(VSIFWriteL(
    2092           3 :                 pabyBuffer, 1, static_cast<int>(nDataLength), m_fpToWrite)) !=
    2093             :             static_cast<int>(nDataLength))
    2094             :         {
    2095           0 :             ReportError(CE_Failure, CPLE_FileIO, "Could not write %d bytes",
    2096             :                         static_cast<int>(nDataLength));
    2097             :         }
    2098             :         // In case of single strip file, there's a libtiff check that would
    2099             :         // issue a warning since the file hasn't the required size.
    2100           3 :         CPLPushErrorHandler(CPLQuietErrorHandler);
    2101           3 :         TIFFSetDirectory(m_hTIFF, 0);
    2102           3 :         CPLPopErrorHandler();
    2103             :     }
    2104             :     else
    2105             :     {
    2106        3200 :         const tdir_t nNumberOfDirs = TIFFNumberOfDirectories(m_hTIFF);
    2107        3200 :         if (nNumberOfDirs > 0)
    2108             :         {
    2109        3200 :             TIFFSetDirectory(m_hTIFF, static_cast<tdir_t>(nNumberOfDirs - 1));
    2110             :         }
    2111             :     }
    2112             : 
    2113        3203 :     RestoreVolatileParameters(m_hTIFF);
    2114             : 
    2115        3203 :     m_nDirOffset = TIFFCurrentDirOffset(m_hTIFF);
    2116             : }
    2117             : 
    2118             : /************************************************************************/
    2119             : /*                             FlushCache()                             */
    2120             : /*                                                                      */
    2121             : /*      We override this so we can also flush out local tiff strip      */
    2122             : /*      cache if need be.                                               */
    2123             : /************************************************************************/
    2124             : 
    2125        4220 : CPLErr GTiffDataset::FlushCache(bool bAtClosing)
    2126             : 
    2127             : {
    2128        4220 :     return FlushCacheInternal(bAtClosing, true);
    2129             : }
    2130             : 
    2131       36589 : CPLErr GTiffDataset::FlushCacheInternal(bool bAtClosing, bool bFlushDirectory)
    2132             : {
    2133       36589 :     if (m_bIsFinalized)
    2134           2 :         return CE_None;
    2135             : 
    2136       36587 :     CPLErr eErr = GDALPamDataset::FlushCache(bAtClosing);
    2137             : 
    2138       36586 :     if (m_bLoadedBlockDirty && m_nLoadedBlock != -1)
    2139             :     {
    2140         255 :         if (FlushBlockBuf() != CE_None)
    2141           0 :             eErr = CE_Failure;
    2142             :     }
    2143             : 
    2144       36586 :     CPLFree(m_pabyBlockBuf);
    2145       36587 :     m_pabyBlockBuf = nullptr;
    2146       36587 :     m_nLoadedBlock = -1;
    2147       36587 :     m_bLoadedBlockDirty = false;
    2148             : 
    2149             :     // Finish compression
    2150       36587 :     auto poQueue = m_poBaseDS ? m_poBaseDS->m_poCompressQueue.get()
    2151       34334 :                               : m_poCompressQueue.get();
    2152       36586 :     if (poQueue)
    2153             :     {
    2154         159 :         poQueue->WaitCompletion();
    2155             : 
    2156             :         // Flush remaining data
    2157             :         // cppcheck-suppress constVariableReference
    2158             : 
    2159         159 :         auto &oQueue =
    2160         159 :             m_poBaseDS ? m_poBaseDS->m_asQueueJobIdx : m_asQueueJobIdx;
    2161         228 :         while (!oQueue.empty())
    2162             :         {
    2163          69 :             WaitCompletionForJobIdx(oQueue.front());
    2164             :         }
    2165             :     }
    2166             : 
    2167       36586 :     if (bFlushDirectory && GetAccess() == GA_Update)
    2168             :     {
    2169       10715 :         if (FlushDirectory() != CE_None)
    2170          12 :             eErr = CE_Failure;
    2171             :     }
    2172       36583 :     return eErr;
    2173             : }
    2174             : 
    2175             : /************************************************************************/
    2176             : /*                           FlushDirectory()                           */
    2177             : /************************************************************************/
    2178             : 
    2179       17360 : CPLErr GTiffDataset::FlushDirectory()
    2180             : 
    2181             : {
    2182       17360 :     CPLErr eErr = CE_None;
    2183             : 
    2184         487 :     const auto ReloadAllOtherDirectories = [this]()
    2185             :     {
    2186         239 :         const auto poBaseDS = m_poBaseDS ? m_poBaseDS : this;
    2187         239 :         if (poBaseDS->m_papoOverviewDS)
    2188             :         {
    2189          12 :             for (int i = 0; i < poBaseDS->m_nOverviewCount; ++i)
    2190             :             {
    2191           3 :                 if (poBaseDS->m_papoOverviewDS[i]->m_bCrystalized &&
    2192           3 :                     poBaseDS->m_papoOverviewDS[i] != this)
    2193             :                 {
    2194           3 :                     poBaseDS->m_papoOverviewDS[i]->ReloadDirectory(true);
    2195             :                 }
    2196             : 
    2197           3 :                 if (poBaseDS->m_papoOverviewDS[i]->m_poMaskDS &&
    2198           0 :                     poBaseDS->m_papoOverviewDS[i]->m_poMaskDS != this &&
    2199           0 :                     poBaseDS->m_papoOverviewDS[i]->m_poMaskDS->m_bCrystalized)
    2200             :                 {
    2201           0 :                     poBaseDS->m_papoOverviewDS[i]->m_poMaskDS->ReloadDirectory(
    2202             :                         true);
    2203             :                 }
    2204             :             }
    2205             :         }
    2206         239 :         if (poBaseDS->m_poMaskDS && poBaseDS->m_poMaskDS != this &&
    2207           0 :             poBaseDS->m_poMaskDS->m_bCrystalized)
    2208             :         {
    2209           0 :             poBaseDS->m_poMaskDS->ReloadDirectory(true);
    2210             :         }
    2211         239 :         if (poBaseDS->m_bCrystalized && poBaseDS != this)
    2212             :         {
    2213           6 :             poBaseDS->ReloadDirectory(true);
    2214             :         }
    2215       17599 :     };
    2216             : 
    2217       17360 :     if (eAccess == GA_Update)
    2218             :     {
    2219       12218 :         if (m_bMetadataChanged)
    2220             :         {
    2221         135 :             m_bNeedsRewrite =
    2222         270 :                 WriteMetadata(this, m_hTIFF, true, m_eProfile, m_pszFilename,
    2223         135 :                               m_papszCreationOptions);
    2224         135 :             m_bMetadataChanged = false;
    2225             : 
    2226         135 :             if (m_bForceUnsetRPC)
    2227             :             {
    2228           5 :                 double *padfRPCTag = nullptr;
    2229             :                 uint16_t nCount;
    2230           5 :                 if (TIFFGetField(m_hTIFF, TIFFTAG_RPCCOEFFICIENT, &nCount,
    2231           5 :                                  &padfRPCTag))
    2232             :                 {
    2233           3 :                     std::vector<double> zeroes(92);
    2234           3 :                     TIFFSetField(m_hTIFF, TIFFTAG_RPCCOEFFICIENT, 92,
    2235             :                                  zeroes.data());
    2236           3 :                     TIFFUnsetField(m_hTIFF, TIFFTAG_RPCCOEFFICIENT);
    2237           3 :                     m_bNeedsRewrite = true;
    2238             :                 }
    2239             : 
    2240           5 :                 GDALWriteRPCTXTFile(m_pszFilename, nullptr);
    2241           5 :                 GDALWriteRPBFile(m_pszFilename, nullptr);
    2242             :             }
    2243             :         }
    2244             : 
    2245       12218 :         if (m_bGeoTIFFInfoChanged)
    2246             :         {
    2247         121 :             WriteGeoTIFFInfo();
    2248         121 :             m_bGeoTIFFInfoChanged = false;
    2249             :         }
    2250             : 
    2251       12218 :         if (m_bNoDataChanged)
    2252             :         {
    2253          31 :             if (m_bNoDataSet)
    2254             :             {
    2255          30 :                 WriteNoDataValue(m_hTIFF, m_dfNoDataValue);
    2256             :             }
    2257           1 :             else if (m_bNoDataSetAsInt64)
    2258             :             {
    2259           0 :                 WriteNoDataValue(m_hTIFF, m_nNoDataValueInt64);
    2260             :             }
    2261           1 :             else if (m_bNoDataSetAsUInt64)
    2262             :             {
    2263           0 :                 WriteNoDataValue(m_hTIFF, m_nNoDataValueUInt64);
    2264             :             }
    2265             :             else
    2266             :             {
    2267           1 :                 UnsetNoDataValue(m_hTIFF);
    2268             :             }
    2269          31 :             m_bNeedsRewrite = true;
    2270          31 :             m_bNoDataChanged = false;
    2271             :         }
    2272             : 
    2273       12218 :         if (m_bNeedsRewrite)
    2274             :         {
    2275         261 :             if (!m_bCrystalized)
    2276             :             {
    2277          25 :                 Crystalize();
    2278             :             }
    2279             :             else
    2280             :             {
    2281         236 :                 const TIFFSizeProc pfnSizeProc = TIFFGetSizeProc(m_hTIFF);
    2282             : 
    2283         236 :                 m_nDirOffset = pfnSizeProc(TIFFClientdata(m_hTIFF));
    2284         236 :                 if ((m_nDirOffset % 2) == 1)
    2285          50 :                     ++m_nDirOffset;
    2286             : 
    2287         236 :                 if (TIFFRewriteDirectory(m_hTIFF) == 0)
    2288           0 :                     eErr = CE_Failure;
    2289             : 
    2290         236 :                 TIFFSetSubDirectory(m_hTIFF, m_nDirOffset);
    2291             : 
    2292         236 :                 ReloadAllOtherDirectories();
    2293             : 
    2294         236 :                 if (m_bLayoutIFDSBeforeData && m_bBlockOrderRowMajor &&
    2295           1 :                     m_bLeaderSizeAsUInt4 &&
    2296           1 :                     m_bTrailerRepeatedLast4BytesRepeated &&
    2297           1 :                     !m_bKnownIncompatibleEdition &&
    2298           1 :                     !m_bWriteKnownIncompatibleEdition)
    2299             :                 {
    2300           1 :                     ReportError(CE_Warning, CPLE_AppDefined,
    2301             :                                 "The IFD has been rewritten at the end of "
    2302             :                                 "the file, which breaks COG layout.");
    2303           1 :                     m_bKnownIncompatibleEdition = true;
    2304           1 :                     m_bWriteKnownIncompatibleEdition = true;
    2305             :                 }
    2306             :             }
    2307             : 
    2308         261 :             m_bNeedsRewrite = false;
    2309             :         }
    2310             :     }
    2311             : 
    2312             :     // There are some circumstances in which we can reach this point
    2313             :     // without having made this our directory (SetDirectory()) in which
    2314             :     // case we should not risk a flush.
    2315       29578 :     if (GetAccess() == GA_Update &&
    2316       12218 :         TIFFCurrentDirOffset(m_hTIFF) == m_nDirOffset)
    2317             :     {
    2318       12218 :         const TIFFSizeProc pfnSizeProc = TIFFGetSizeProc(m_hTIFF);
    2319             : 
    2320       12218 :         toff_t nNewDirOffset = pfnSizeProc(TIFFClientdata(m_hTIFF));
    2321       12218 :         if ((nNewDirOffset % 2) == 1)
    2322        3068 :             ++nNewDirOffset;
    2323             : 
    2324       12218 :         if (TIFFFlush(m_hTIFF) == 0)
    2325          12 :             eErr = CE_Failure;
    2326             : 
    2327       12218 :         if (m_nDirOffset != TIFFCurrentDirOffset(m_hTIFF))
    2328             :         {
    2329           3 :             m_nDirOffset = nNewDirOffset;
    2330           3 :             ReloadAllOtherDirectories();
    2331           3 :             CPLDebug("GTiff",
    2332             :                      "directory moved during flush in FlushDirectory()");
    2333             :         }
    2334             :     }
    2335             : 
    2336       17360 :     SetDirectory();
    2337       17360 :     return eErr;
    2338             : }
    2339             : 
    2340             : /************************************************************************/
    2341             : /*                           CleanOverviews()                           */
    2342             : /************************************************************************/
    2343             : 
    2344           3 : CPLErr GTiffDataset::CleanOverviews()
    2345             : 
    2346             : {
    2347           3 :     CPLAssert(!m_poBaseDS);
    2348             : 
    2349           3 :     ScanDirectories();
    2350             : 
    2351           3 :     FlushDirectory();
    2352             : 
    2353             :     /* -------------------------------------------------------------------- */
    2354             :     /*      Cleanup overviews objects, and get offsets to all overview      */
    2355             :     /*      directories.                                                    */
    2356             :     /* -------------------------------------------------------------------- */
    2357           6 :     std::vector<toff_t> anOvDirOffsets;
    2358             : 
    2359           6 :     for (int i = 0; i < m_nOverviewCount; ++i)
    2360             :     {
    2361           3 :         anOvDirOffsets.push_back(m_papoOverviewDS[i]->m_nDirOffset);
    2362           3 :         if (m_papoOverviewDS[i]->m_poMaskDS)
    2363           1 :             anOvDirOffsets.push_back(
    2364           1 :                 m_papoOverviewDS[i]->m_poMaskDS->m_nDirOffset);
    2365           3 :         delete m_papoOverviewDS[i];
    2366             :     }
    2367             : 
    2368             :     /* -------------------------------------------------------------------- */
    2369             :     /*      Loop through all the directories, translating the offsets       */
    2370             :     /*      into indexes we can use with TIFFUnlinkDirectory().             */
    2371             :     /* -------------------------------------------------------------------- */
    2372           6 :     std::vector<uint16_t> anOvDirIndexes;
    2373           3 :     int iThisOffset = 1;
    2374             : 
    2375           3 :     TIFFSetDirectory(m_hTIFF, 0);
    2376             : 
    2377             :     while (true)
    2378             :     {
    2379          20 :         for (toff_t nOffset : anOvDirOffsets)
    2380             :         {
    2381          12 :             if (nOffset == TIFFCurrentDirOffset(m_hTIFF))
    2382             :             {
    2383           4 :                 anOvDirIndexes.push_back(static_cast<uint16_t>(iThisOffset));
    2384             :             }
    2385             :         }
    2386             : 
    2387           8 :         if (TIFFLastDirectory(m_hTIFF))
    2388           3 :             break;
    2389             : 
    2390           5 :         TIFFReadDirectory(m_hTIFF);
    2391           5 :         ++iThisOffset;
    2392           5 :     }
    2393             : 
    2394             :     /* -------------------------------------------------------------------- */
    2395             :     /*      Actually unlink the target directories.  Note that we do        */
    2396             :     /*      this from last to first so as to avoid renumbering any of       */
    2397             :     /*      the earlier directories we need to remove.                      */
    2398             :     /* -------------------------------------------------------------------- */
    2399           7 :     while (!anOvDirIndexes.empty())
    2400             :     {
    2401           4 :         TIFFUnlinkDirectory(m_hTIFF, anOvDirIndexes.back());
    2402           4 :         anOvDirIndexes.pop_back();
    2403             :     }
    2404             : 
    2405           3 :     CPLFree(m_papoOverviewDS);
    2406           3 :     m_nOverviewCount = 0;
    2407           3 :     m_papoOverviewDS = nullptr;
    2408             : 
    2409           3 :     if (m_poMaskDS)
    2410             :     {
    2411           1 :         CPLFree(m_poMaskDS->m_papoOverviewDS);
    2412           1 :         m_poMaskDS->m_nOverviewCount = 0;
    2413           1 :         m_poMaskDS->m_papoOverviewDS = nullptr;
    2414             :     }
    2415             : 
    2416           3 :     if (!SetDirectory())
    2417           0 :         return CE_Failure;
    2418             : 
    2419           3 :     return CE_None;
    2420             : }
    2421             : 
    2422             : /************************************************************************/
    2423             : /*                   RegisterNewOverviewDataset()                       */
    2424             : /************************************************************************/
    2425             : 
    2426         484 : CPLErr GTiffDataset::RegisterNewOverviewDataset(toff_t nOverviewOffset,
    2427             :                                                 int l_nJpegQuality,
    2428             :                                                 CSLConstList papszOptions)
    2429             : {
    2430         484 :     if (m_nOverviewCount == 127)
    2431           0 :         return CE_Failure;
    2432             : 
    2433             :     const auto GetOptionValue =
    2434        2904 :         [papszOptions](const char *pszOptionKey, const char *pszConfigOptionKey,
    2435        5807 :                        const char **ppszKeyUsed = nullptr)
    2436             :     {
    2437        2904 :         const char *pszVal = CSLFetchNameValue(papszOptions, pszOptionKey);
    2438        2904 :         if (pszVal)
    2439             :         {
    2440           1 :             if (ppszKeyUsed)
    2441           1 :                 *ppszKeyUsed = pszOptionKey;
    2442           1 :             return pszVal;
    2443             :         }
    2444        2903 :         pszVal = CSLFetchNameValue(papszOptions, pszConfigOptionKey);
    2445        2903 :         if (pszVal)
    2446             :         {
    2447           0 :             if (ppszKeyUsed)
    2448           0 :                 *ppszKeyUsed = pszConfigOptionKey;
    2449           0 :             return pszVal;
    2450             :         }
    2451        2903 :         pszVal = CPLGetConfigOption(pszConfigOptionKey, nullptr);
    2452        2903 :         if (pszVal && ppszKeyUsed)
    2453          13 :             *ppszKeyUsed = pszConfigOptionKey;
    2454        2903 :         return pszVal;
    2455         484 :     };
    2456             : 
    2457         484 :     int nZLevel = m_nZLevel;
    2458         484 :     if (const char *opt = GetOptionValue("ZLEVEL", "ZLEVEL_OVERVIEW"))
    2459             :     {
    2460           4 :         nZLevel = atoi(opt);
    2461             :     }
    2462             : 
    2463         484 :     int nZSTDLevel = m_nZSTDLevel;
    2464         484 :     if (const char *opt = GetOptionValue("ZSTD_LEVEL", "ZSTD_LEVEL_OVERVIEW"))
    2465             :     {
    2466           4 :         nZSTDLevel = atoi(opt);
    2467             :     }
    2468             : 
    2469         484 :     bool bWebpLossless = m_bWebPLossless;
    2470             :     const char *pszWebPLosslessOverview =
    2471         484 :         GetOptionValue("WEBP_LOSSLESS", "WEBP_LOSSLESS_OVERVIEW");
    2472         484 :     if (pszWebPLosslessOverview)
    2473             :     {
    2474           2 :         bWebpLossless = CPLTestBool(pszWebPLosslessOverview);
    2475             :     }
    2476             : 
    2477         484 :     int nWebpLevel = m_nWebPLevel;
    2478         484 :     const char *pszKeyWebpLevel = "";
    2479         484 :     if (const char *opt = GetOptionValue("WEBP_LEVEL", "WEBP_LEVEL_OVERVIEW",
    2480             :                                          &pszKeyWebpLevel))
    2481             :     {
    2482          14 :         if (pszWebPLosslessOverview == nullptr && m_bWebPLossless)
    2483             :         {
    2484           1 :             CPLDebug("GTiff",
    2485             :                      "%s specified, but not WEBP_LOSSLESS_OVERVIEW. "
    2486             :                      "Assuming WEBP_LOSSLESS_OVERVIEW=NO",
    2487             :                      pszKeyWebpLevel);
    2488           1 :             bWebpLossless = false;
    2489             :         }
    2490          13 :         else if (bWebpLossless)
    2491             :         {
    2492           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2493             :                      "%s is specified, but WEBP_LOSSLESS_OVERVIEW=YES. "
    2494             :                      "%s will be ignored.",
    2495             :                      pszKeyWebpLevel, pszKeyWebpLevel);
    2496             :         }
    2497          14 :         nWebpLevel = atoi(opt);
    2498             :     }
    2499             : 
    2500         484 :     double dfMaxZError = m_dfMaxZErrorOverview;
    2501         484 :     if (const char *opt = GetOptionValue("MAX_Z_ERROR", "MAX_Z_ERROR_OVERVIEW"))
    2502             :     {
    2503          20 :         dfMaxZError = CPLAtof(opt);
    2504             :     }
    2505             : 
    2506         484 :     GTiffDataset *poODS = new GTiffDataset();
    2507         484 :     poODS->ShareLockWithParentDataset(this);
    2508         484 :     poODS->m_pszFilename = CPLStrdup(m_pszFilename);
    2509         484 :     const char *pszSparseOK = GetOptionValue("SPARSE_OK", "SPARSE_OK_OVERVIEW");
    2510         484 :     if (pszSparseOK && CPLTestBool(pszSparseOK))
    2511             :     {
    2512           1 :         poODS->m_bWriteEmptyTiles = false;
    2513           1 :         poODS->m_bFillEmptyTilesAtClosing = false;
    2514             :     }
    2515             :     else
    2516             :     {
    2517         483 :         poODS->m_bWriteEmptyTiles = m_bWriteEmptyTiles;
    2518         483 :         poODS->m_bFillEmptyTilesAtClosing = m_bFillEmptyTilesAtClosing;
    2519             :     }
    2520         484 :     poODS->m_nJpegQuality = static_cast<signed char>(l_nJpegQuality);
    2521         484 :     poODS->m_nWebPLevel = static_cast<signed char>(nWebpLevel);
    2522         484 :     poODS->m_nZLevel = static_cast<signed char>(nZLevel);
    2523         484 :     poODS->m_nLZMAPreset = m_nLZMAPreset;
    2524         484 :     poODS->m_nZSTDLevel = static_cast<signed char>(nZSTDLevel);
    2525         484 :     poODS->m_bWebPLossless = bWebpLossless;
    2526         484 :     poODS->m_nJpegTablesMode = m_nJpegTablesMode;
    2527         484 :     poODS->m_dfMaxZError = dfMaxZError;
    2528         484 :     poODS->m_dfMaxZErrorOverview = dfMaxZError;
    2529         484 :     memcpy(poODS->m_anLercAddCompressionAndVersion,
    2530         484 :            m_anLercAddCompressionAndVersion,
    2531             :            sizeof(m_anLercAddCompressionAndVersion));
    2532             : #ifdef HAVE_JXL
    2533         484 :     poODS->m_bJXLLossless = m_bJXLLossless;
    2534         484 :     poODS->m_fJXLDistance = m_fJXLDistance;
    2535         484 :     poODS->m_fJXLAlphaDistance = m_fJXLAlphaDistance;
    2536         484 :     poODS->m_nJXLEffort = m_nJXLEffort;
    2537             : #endif
    2538             : 
    2539         484 :     if (poODS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF), nOverviewOffset,
    2540         484 :                           GA_Update) != CE_None)
    2541             :     {
    2542           0 :         delete poODS;
    2543           0 :         return CE_Failure;
    2544             :     }
    2545             : 
    2546             :     // Assign color interpretation from main dataset
    2547         484 :     const int l_nBands = GetRasterCount();
    2548        1454 :     for (int i = 1; i <= l_nBands; i++)
    2549             :     {
    2550         970 :         auto poBand = dynamic_cast<GTiffRasterBand *>(poODS->GetRasterBand(i));
    2551         970 :         if (poBand)
    2552         970 :             poBand->m_eBandInterp = GetRasterBand(i)->GetColorInterpretation();
    2553             :     }
    2554             : 
    2555             :     // Do that now that m_nCompression is set
    2556         484 :     poODS->RestoreVolatileParameters(poODS->m_hTIFF);
    2557             : 
    2558         484 :     ++m_nOverviewCount;
    2559         484 :     m_papoOverviewDS = static_cast<GTiffDataset **>(
    2560         484 :         CPLRealloc(m_papoOverviewDS, m_nOverviewCount * (sizeof(void *))));
    2561         484 :     m_papoOverviewDS[m_nOverviewCount - 1] = poODS;
    2562         484 :     poODS->m_poBaseDS = this;
    2563         484 :     poODS->m_bIsOverview = true;
    2564         484 :     return CE_None;
    2565             : }
    2566             : 
    2567             : /************************************************************************/
    2568             : /*                     CreateTIFFColorTable()                           */
    2569             : /************************************************************************/
    2570             : 
    2571          12 : static void CreateTIFFColorTable(
    2572             :     GDALColorTable *poColorTable, int nBits, int nColorTableMultiplier,
    2573             :     std::vector<unsigned short> &anTRed, std::vector<unsigned short> &anTGreen,
    2574             :     std::vector<unsigned short> &anTBlue, unsigned short *&panRed,
    2575             :     unsigned short *&panGreen, unsigned short *&panBlue)
    2576             : {
    2577             :     int nColors;
    2578             : 
    2579          12 :     if (nBits == 8)
    2580          12 :         nColors = 256;
    2581           0 :     else if (nBits < 8)
    2582           0 :         nColors = 1 << nBits;
    2583             :     else
    2584           0 :         nColors = 65536;
    2585             : 
    2586          12 :     anTRed.resize(nColors, 0);
    2587          12 :     anTGreen.resize(nColors, 0);
    2588          12 :     anTBlue.resize(nColors, 0);
    2589             : 
    2590        3084 :     for (int iColor = 0; iColor < nColors; ++iColor)
    2591             :     {
    2592        3072 :         if (iColor < poColorTable->GetColorEntryCount())
    2593             :         {
    2594             :             GDALColorEntry sRGB;
    2595             : 
    2596        3072 :             poColorTable->GetColorEntryAsRGB(iColor, &sRGB);
    2597             : 
    2598        3072 :             anTRed[iColor] = GTiffDataset::ClampCTEntry(iColor, 1, sRGB.c1,
    2599             :                                                         nColorTableMultiplier);
    2600        3072 :             anTGreen[iColor] = GTiffDataset::ClampCTEntry(
    2601        3072 :                 iColor, 2, sRGB.c2, nColorTableMultiplier);
    2602        3072 :             anTBlue[iColor] = GTiffDataset::ClampCTEntry(iColor, 3, sRGB.c3,
    2603             :                                                          nColorTableMultiplier);
    2604             :         }
    2605             :         else
    2606             :         {
    2607           0 :             anTRed[iColor] = 0;
    2608           0 :             anTGreen[iColor] = 0;
    2609           0 :             anTBlue[iColor] = 0;
    2610             :         }
    2611             :     }
    2612             : 
    2613          12 :     panRed = &(anTRed[0]);
    2614          12 :     panGreen = &(anTGreen[0]);
    2615          12 :     panBlue = &(anTBlue[0]);
    2616          12 : }
    2617             : 
    2618             : /************************************************************************/
    2619             : /*                        GetOverviewParameters()                       */
    2620             : /************************************************************************/
    2621             : 
    2622         304 : bool GTiffDataset::GetOverviewParameters(
    2623             :     int &nCompression, uint16_t &nPlanarConfig, uint16_t &nPredictor,
    2624             :     uint16_t &nPhotometric, int &nOvrJpegQuality, std::string &osNoData,
    2625             :     uint16_t *&panExtraSampleValues, uint16_t &nExtraSamples,
    2626             :     CSLConstList papszOptions) const
    2627             : {
    2628             :     const auto GetOptionValue =
    2629        1005 :         [papszOptions](const char *pszOptionKey, const char *pszConfigOptionKey,
    2630        2006 :                        const char **ppszKeyUsed = nullptr)
    2631             :     {
    2632        1005 :         const char *pszVal = CSLFetchNameValue(papszOptions, pszOptionKey);
    2633        1005 :         if (pszVal)
    2634             :         {
    2635           4 :             if (ppszKeyUsed)
    2636           4 :                 *ppszKeyUsed = pszOptionKey;
    2637           4 :             return pszVal;
    2638             :         }
    2639        1001 :         pszVal = CSLFetchNameValue(papszOptions, pszConfigOptionKey);
    2640        1001 :         if (pszVal)
    2641             :         {
    2642           4 :             if (ppszKeyUsed)
    2643           4 :                 *ppszKeyUsed = pszConfigOptionKey;
    2644           4 :             return pszVal;
    2645             :         }
    2646         997 :         pszVal = CPLGetConfigOption(pszConfigOptionKey, nullptr);
    2647         997 :         if (pszVal && ppszKeyUsed)
    2648          54 :             *ppszKeyUsed = pszConfigOptionKey;
    2649         997 :         return pszVal;
    2650         304 :     };
    2651             : 
    2652             :     /* -------------------------------------------------------------------- */
    2653             :     /*      Determine compression method.                                   */
    2654             :     /* -------------------------------------------------------------------- */
    2655         304 :     nCompression = m_nCompression;
    2656         304 :     const char *pszOptionKey = "";
    2657             :     const char *pszCompressValue =
    2658         304 :         GetOptionValue("COMPRESS", "COMPRESS_OVERVIEW", &pszOptionKey);
    2659         304 :     if (pszCompressValue != nullptr)
    2660             :     {
    2661          52 :         nCompression =
    2662          52 :             GTIFFGetCompressionMethod(pszCompressValue, pszOptionKey);
    2663          52 :         if (nCompression < 0)
    2664             :         {
    2665           0 :             nCompression = m_nCompression;
    2666             :         }
    2667             :     }
    2668             : 
    2669             :     /* -------------------------------------------------------------------- */
    2670             :     /*      Determine planar configuration.                                 */
    2671             :     /* -------------------------------------------------------------------- */
    2672         304 :     nPlanarConfig = m_nPlanarConfig;
    2673         304 :     if (nCompression == COMPRESSION_WEBP)
    2674             :     {
    2675          11 :         nPlanarConfig = PLANARCONFIG_CONTIG;
    2676             :     }
    2677             :     const char *pszInterleave =
    2678         304 :         GetOptionValue("INTERLEAVE", "INTERLEAVE_OVERVIEW", &pszOptionKey);
    2679         304 :     if (pszInterleave != nullptr && pszInterleave[0] != '\0')
    2680             :     {
    2681           2 :         if (EQUAL(pszInterleave, "PIXEL"))
    2682           1 :             nPlanarConfig = PLANARCONFIG_CONTIG;
    2683           1 :         else if (EQUAL(pszInterleave, "BAND"))
    2684           1 :             nPlanarConfig = PLANARCONFIG_SEPARATE;
    2685             :         else
    2686             :         {
    2687           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2688             :                      "%s=%s unsupported, "
    2689             :                      "value must be PIXEL or BAND. ignoring",
    2690             :                      pszOptionKey, pszInterleave);
    2691             :         }
    2692             :     }
    2693             : 
    2694             :     /* -------------------------------------------------------------------- */
    2695             :     /*      Determine predictor tag                                         */
    2696             :     /* -------------------------------------------------------------------- */
    2697         304 :     nPredictor = PREDICTOR_NONE;
    2698         304 :     if (GTIFFSupportsPredictor(nCompression))
    2699             :     {
    2700             :         const char *pszPredictor =
    2701          66 :             GetOptionValue("PREDICTOR", "PREDICTOR_OVERVIEW");
    2702          66 :         if (pszPredictor != nullptr)
    2703             :         {
    2704           1 :             nPredictor = static_cast<uint16_t>(atoi(pszPredictor));
    2705             :         }
    2706          65 :         else if (GTIFFSupportsPredictor(m_nCompression))
    2707          64 :             TIFFGetField(m_hTIFF, TIFFTAG_PREDICTOR, &nPredictor);
    2708             :     }
    2709             : 
    2710             :     /* -------------------------------------------------------------------- */
    2711             :     /*      Determine photometric tag                                       */
    2712             :     /* -------------------------------------------------------------------- */
    2713         304 :     if (m_nPhotometric == PHOTOMETRIC_YCBCR && nCompression != COMPRESSION_JPEG)
    2714           1 :         nPhotometric = PHOTOMETRIC_RGB;
    2715             :     else
    2716         303 :         nPhotometric = m_nPhotometric;
    2717             :     const char *pszPhotometric =
    2718         304 :         GetOptionValue("PHOTOMETRIC", "PHOTOMETRIC_OVERVIEW", &pszOptionKey);
    2719         304 :     if (!GTIFFUpdatePhotometric(pszPhotometric, pszOptionKey, nCompression,
    2720         304 :                                 pszInterleave, nBands, nPhotometric,
    2721             :                                 nPlanarConfig))
    2722             :     {
    2723           0 :         return false;
    2724             :     }
    2725             : 
    2726             :     /* -------------------------------------------------------------------- */
    2727             :     /*      Determine JPEG quality                                          */
    2728             :     /* -------------------------------------------------------------------- */
    2729         304 :     nOvrJpegQuality = m_nJpegQuality;
    2730         304 :     if (nCompression == COMPRESSION_JPEG)
    2731             :     {
    2732             :         const char *pszJPEGQuality =
    2733          27 :             GetOptionValue("JPEG_QUALITY", "JPEG_QUALITY_OVERVIEW");
    2734          27 :         if (pszJPEGQuality != nullptr)
    2735             :         {
    2736           9 :             nOvrJpegQuality = atoi(pszJPEGQuality);
    2737             :         }
    2738             :     }
    2739             : 
    2740             :     /* -------------------------------------------------------------------- */
    2741             :     /*      Set nodata.                                                     */
    2742             :     /* -------------------------------------------------------------------- */
    2743         304 :     if (m_bNoDataSet)
    2744             :     {
    2745          16 :         osNoData = GTiffFormatGDALNoDataTagValue(m_dfNoDataValue);
    2746             :     }
    2747             : 
    2748             :     /* -------------------------------------------------------------------- */
    2749             :     /*      Fetch extra sample tag                                          */
    2750             :     /* -------------------------------------------------------------------- */
    2751         304 :     panExtraSampleValues = nullptr;
    2752         304 :     nExtraSamples = 0;
    2753         304 :     if (TIFFGetField(m_hTIFF, TIFFTAG_EXTRASAMPLES, &nExtraSamples,
    2754         304 :                      &panExtraSampleValues))
    2755             :     {
    2756             :         uint16_t *panExtraSampleValuesNew = static_cast<uint16_t *>(
    2757          39 :             CPLMalloc(nExtraSamples * sizeof(uint16_t)));
    2758          39 :         memcpy(panExtraSampleValuesNew, panExtraSampleValues,
    2759          39 :                nExtraSamples * sizeof(uint16_t));
    2760          39 :         panExtraSampleValues = panExtraSampleValuesNew;
    2761             :     }
    2762             :     else
    2763             :     {
    2764         265 :         panExtraSampleValues = nullptr;
    2765         265 :         nExtraSamples = 0;
    2766             :     }
    2767             : 
    2768         304 :     return true;
    2769             : }
    2770             : 
    2771             : /************************************************************************/
    2772             : /*                  CreateOverviewsFromSrcOverviews()                   */
    2773             : /************************************************************************/
    2774             : 
    2775             : // If poOvrDS is not null, it is used and poSrcDS is ignored.
    2776             : 
    2777          64 : CPLErr GTiffDataset::CreateOverviewsFromSrcOverviews(GDALDataset *poSrcDS,
    2778             :                                                      GDALDataset *poOvrDS,
    2779             :                                                      int nOverviews)
    2780             : {
    2781          64 :     CPLAssert(poSrcDS->GetRasterCount() != 0);
    2782          64 :     CPLAssert(m_nOverviewCount == 0);
    2783             : 
    2784          64 :     ScanDirectories();
    2785             : 
    2786          64 :     FlushDirectory();
    2787             : 
    2788          64 :     int nOvBitsPerSample = m_nBitsPerSample;
    2789             : 
    2790             :     /* -------------------------------------------------------------------- */
    2791             :     /*      Do we need some metadata for the overviews?                     */
    2792             :     /* -------------------------------------------------------------------- */
    2793         128 :     CPLString osMetadata;
    2794             : 
    2795          64 :     GTIFFBuildOverviewMetadata("NONE", this, false, osMetadata);
    2796             : 
    2797             :     int nCompression;
    2798             :     uint16_t nPlanarConfig;
    2799             :     uint16_t nPredictor;
    2800             :     uint16_t nPhotometric;
    2801             :     int nOvrJpegQuality;
    2802         128 :     std::string osNoData;
    2803          64 :     uint16_t *panExtraSampleValues = nullptr;
    2804          64 :     uint16_t nExtraSamples = 0;
    2805          64 :     if (!GetOverviewParameters(nCompression, nPlanarConfig, nPredictor,
    2806             :                                nPhotometric, nOvrJpegQuality, osNoData,
    2807             :                                panExtraSampleValues, nExtraSamples,
    2808             :                                /*papszOptions=*/nullptr))
    2809             :     {
    2810           0 :         return CE_Failure;
    2811             :     }
    2812             : 
    2813             :     /* -------------------------------------------------------------------- */
    2814             :     /*      Do we have a palette?  If so, create a TIFF compatible version. */
    2815             :     /* -------------------------------------------------------------------- */
    2816         128 :     std::vector<unsigned short> anTRed;
    2817         128 :     std::vector<unsigned short> anTGreen;
    2818          64 :     std::vector<unsigned short> anTBlue;
    2819          64 :     unsigned short *panRed = nullptr;
    2820          64 :     unsigned short *panGreen = nullptr;
    2821          64 :     unsigned short *panBlue = nullptr;
    2822             : 
    2823          64 :     if (nPhotometric == PHOTOMETRIC_PALETTE && m_poColorTable != nullptr)
    2824             :     {
    2825           0 :         if (m_nColorTableMultiplier == 0)
    2826           0 :             m_nColorTableMultiplier = DEFAULT_COLOR_TABLE_MULTIPLIER_257;
    2827             : 
    2828           0 :         CreateTIFFColorTable(m_poColorTable.get(), nOvBitsPerSample,
    2829             :                              m_nColorTableMultiplier, anTRed, anTGreen, anTBlue,
    2830             :                              panRed, panGreen, panBlue);
    2831             :     }
    2832             : 
    2833          64 :     int nOvrBlockXSize = 0;
    2834          64 :     int nOvrBlockYSize = 0;
    2835          64 :     GTIFFGetOverviewBlockSize(GDALRasterBand::ToHandle(GetRasterBand(1)),
    2836             :                               &nOvrBlockXSize, &nOvrBlockYSize);
    2837             : 
    2838          64 :     CPLErr eErr = CE_None;
    2839             : 
    2840         187 :     for (int i = 0; i < nOverviews && eErr == CE_None; ++i)
    2841             :     {
    2842             :         GDALRasterBand *poOvrBand =
    2843         164 :             poOvrDS ? ((i == 0) ? poOvrDS->GetRasterBand(1)
    2844          41 :                                 : poOvrDS->GetRasterBand(1)->GetOverview(i - 1))
    2845          47 :                     : poSrcDS->GetRasterBand(1)->GetOverview(i);
    2846             : 
    2847         123 :         int nOXSize = poOvrBand->GetXSize();
    2848         123 :         int nOYSize = poOvrBand->GetYSize();
    2849             : 
    2850         246 :         toff_t nOverviewOffset = GTIFFWriteDirectory(
    2851             :             m_hTIFF, FILETYPE_REDUCEDIMAGE, nOXSize, nOYSize, nOvBitsPerSample,
    2852         123 :             nPlanarConfig, m_nSamplesPerPixel, nOvrBlockXSize, nOvrBlockYSize,
    2853         123 :             TRUE, nCompression, nPhotometric, m_nSampleFormat, nPredictor,
    2854             :             panRed, panGreen, panBlue, nExtraSamples, panExtraSampleValues,
    2855             :             osMetadata,
    2856         123 :             nOvrJpegQuality >= 0 ? CPLSPrintf("%d", nOvrJpegQuality) : nullptr,
    2857         123 :             CPLSPrintf("%d", m_nJpegTablesMode),
    2858           2 :             osNoData.empty() ? nullptr : osNoData.c_str(),
    2859         123 :             m_anLercAddCompressionAndVersion, m_bWriteCOGLayout);
    2860             : 
    2861         123 :         if (nOverviewOffset == 0)
    2862           0 :             eErr = CE_Failure;
    2863             :         else
    2864         123 :             eErr = RegisterNewOverviewDataset(nOverviewOffset, nOvrJpegQuality,
    2865             :                                               nullptr);
    2866             :     }
    2867             : 
    2868             :     // For directory reloading, so that the chaining to the next directory is
    2869             :     // reloaded, as well as compression parameters.
    2870          64 :     ReloadDirectory();
    2871             : 
    2872          64 :     CPLFree(panExtraSampleValues);
    2873          64 :     panExtraSampleValues = nullptr;
    2874             : 
    2875          64 :     return eErr;
    2876             : }
    2877             : 
    2878             : /************************************************************************/
    2879             : /*                       CreateInternalMaskOverviews()                  */
    2880             : /************************************************************************/
    2881             : 
    2882         259 : CPLErr GTiffDataset::CreateInternalMaskOverviews(int nOvrBlockXSize,
    2883             :                                                  int nOvrBlockYSize)
    2884             : {
    2885         259 :     ScanDirectories();
    2886             : 
    2887             :     /* -------------------------------------------------------------------- */
    2888             :     /*      Create overviews for the mask.                                  */
    2889             :     /* -------------------------------------------------------------------- */
    2890         259 :     CPLErr eErr = CE_None;
    2891             : 
    2892         259 :     if (m_poMaskDS != nullptr && m_poMaskDS->GetRasterCount() == 1)
    2893             :     {
    2894             :         int nMaskOvrCompression;
    2895          41 :         if (strstr(GDALGetMetadataItem(GDALGetDriverByName("GTiff"),
    2896             :                                        GDAL_DMD_CREATIONOPTIONLIST, nullptr),
    2897          41 :                    "<Value>DEFLATE</Value>") != nullptr)
    2898          41 :             nMaskOvrCompression = COMPRESSION_ADOBE_DEFLATE;
    2899             :         else
    2900           0 :             nMaskOvrCompression = COMPRESSION_PACKBITS;
    2901             : 
    2902         115 :         for (int i = 0; i < m_nOverviewCount; ++i)
    2903             :         {
    2904          74 :             if (m_papoOverviewDS[i]->m_poMaskDS == nullptr)
    2905             :             {
    2906         124 :                 const toff_t nOverviewOffset = GTIFFWriteDirectory(
    2907             :                     m_hTIFF, FILETYPE_REDUCEDIMAGE | FILETYPE_MASK,
    2908          62 :                     m_papoOverviewDS[i]->nRasterXSize,
    2909          62 :                     m_papoOverviewDS[i]->nRasterYSize, 1, PLANARCONFIG_CONTIG,
    2910             :                     1, nOvrBlockXSize, nOvrBlockYSize, TRUE,
    2911             :                     nMaskOvrCompression, PHOTOMETRIC_MASK, SAMPLEFORMAT_UINT,
    2912             :                     PREDICTOR_NONE, nullptr, nullptr, nullptr, 0, nullptr, "",
    2913          62 :                     nullptr, nullptr, nullptr, nullptr, m_bWriteCOGLayout);
    2914             : 
    2915          62 :                 if (nOverviewOffset == 0)
    2916             :                 {
    2917           0 :                     eErr = CE_Failure;
    2918           0 :                     continue;
    2919             :                 }
    2920             : 
    2921          62 :                 GTiffDataset *poODS = new GTiffDataset();
    2922          62 :                 poODS->ShareLockWithParentDataset(this);
    2923          62 :                 poODS->m_pszFilename = CPLStrdup(m_pszFilename);
    2924          62 :                 if (poODS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF),
    2925          62 :                                       nOverviewOffset, GA_Update) != CE_None)
    2926             :                 {
    2927           0 :                     delete poODS;
    2928           0 :                     eErr = CE_Failure;
    2929             :                 }
    2930             :                 else
    2931             :                 {
    2932          62 :                     poODS->m_bPromoteTo8Bits = CPLTestBool(CPLGetConfigOption(
    2933             :                         "GDAL_TIFF_INTERNAL_MASK_TO_8BIT", "YES"));
    2934          62 :                     poODS->m_poBaseDS = this;
    2935          62 :                     poODS->m_poImageryDS = m_papoOverviewDS[i];
    2936          62 :                     m_papoOverviewDS[i]->m_poMaskDS = poODS;
    2937          62 :                     ++m_poMaskDS->m_nOverviewCount;
    2938         124 :                     m_poMaskDS->m_papoOverviewDS =
    2939         124 :                         static_cast<GTiffDataset **>(CPLRealloc(
    2940          62 :                             m_poMaskDS->m_papoOverviewDS,
    2941          62 :                             m_poMaskDS->m_nOverviewCount * (sizeof(void *))));
    2942          62 :                     m_poMaskDS
    2943          62 :                         ->m_papoOverviewDS[m_poMaskDS->m_nOverviewCount - 1] =
    2944             :                         poODS;
    2945             :                 }
    2946             :             }
    2947             :         }
    2948             :     }
    2949             : 
    2950         259 :     ReloadDirectory();
    2951             : 
    2952         259 :     return eErr;
    2953             : }
    2954             : 
    2955             : /************************************************************************/
    2956             : /*                          IBuildOverviews()                           */
    2957             : /************************************************************************/
    2958             : 
    2959         388 : CPLErr GTiffDataset::IBuildOverviews(const char *pszResampling, int nOverviews,
    2960             :                                      const int *panOverviewList, int nBandsIn,
    2961             :                                      const int *panBandList,
    2962             :                                      GDALProgressFunc pfnProgress,
    2963             :                                      void *pProgressData,
    2964             :                                      CSLConstList papszOptions)
    2965             : 
    2966             : {
    2967         388 :     ScanDirectories();
    2968             : 
    2969             :     // Make implicit JPEG overviews invisible, but do not destroy
    2970             :     // them in case they are already used (not sure that the client
    2971             :     // has the right to do that.  Behavior maybe undefined in GDAL API.
    2972         388 :     m_nJPEGOverviewCount = 0;
    2973             : 
    2974             :     /* -------------------------------------------------------------------- */
    2975             :     /*      If RRD or external OVR overviews requested, then invoke         */
    2976             :     /*      generic handling.                                               */
    2977             :     /* -------------------------------------------------------------------- */
    2978         388 :     bool bUseGenericHandling = false;
    2979             : 
    2980         388 :     if (CPLTestBool(CSLFetchNameValueDef(
    2981         774 :             papszOptions, "USE_RRD", CPLGetConfigOption("USE_RRD", "NO"))) ||
    2982         386 :         CPLTestBool(
    2983             :             CSLFetchNameValueDef(papszOptions, "TIFF_USE_OVR",
    2984             :                                  CPLGetConfigOption("TIFF_USE_OVR", "NO"))))
    2985             :     {
    2986           2 :         bUseGenericHandling = true;
    2987             :     }
    2988             : 
    2989             :     /* -------------------------------------------------------------------- */
    2990             :     /*      If we don't have read access, then create the overviews         */
    2991             :     /*      externally.                                                     */
    2992             :     /* -------------------------------------------------------------------- */
    2993         388 :     if (GetAccess() != GA_Update)
    2994             :     {
    2995         140 :         CPLDebug("GTiff", "File open for read-only accessing, "
    2996             :                           "creating overviews externally.");
    2997             : 
    2998         140 :         bUseGenericHandling = true;
    2999             :     }
    3000             : 
    3001         388 :     if (bUseGenericHandling)
    3002             :     {
    3003         142 :         if (m_nOverviewCount != 0)
    3004             :         {
    3005           0 :             ReportError(CE_Failure, CPLE_NotSupported,
    3006             :                         "Cannot add external overviews when there are already "
    3007             :                         "internal overviews");
    3008           0 :             return CE_Failure;
    3009             :         }
    3010             : 
    3011         142 :         CPLStringList aosOptions(papszOptions);
    3012         142 :         if (!m_bWriteEmptyTiles)
    3013             :         {
    3014           1 :             aosOptions.SetNameValue("SPARSE_OK", "YES");
    3015             :         }
    3016             : 
    3017         142 :         CPLErr eErr = GDALDataset::IBuildOverviews(
    3018             :             pszResampling, nOverviews, panOverviewList, nBandsIn, panBandList,
    3019         142 :             pfnProgress, pProgressData, aosOptions);
    3020         142 :         if (eErr == CE_None && m_poMaskDS)
    3021             :         {
    3022           1 :             ReportError(
    3023             :                 CE_Warning, CPLE_NotSupported,
    3024             :                 "Building external overviews whereas there is an internal "
    3025             :                 "mask is not fully supported. "
    3026             :                 "The overviews of the non-mask bands will be created, "
    3027             :                 "but not the overviews of the mask band.");
    3028             :         }
    3029         142 :         return eErr;
    3030             :     }
    3031             : 
    3032             :     /* -------------------------------------------------------------------- */
    3033             :     /*      Our TIFF overview support currently only works safely if all    */
    3034             :     /*      bands are handled at the same time.                             */
    3035             :     /* -------------------------------------------------------------------- */
    3036         246 :     if (nBandsIn != GetRasterCount())
    3037             :     {
    3038           0 :         ReportError(CE_Failure, CPLE_NotSupported,
    3039             :                     "Generation of overviews in TIFF currently only "
    3040             :                     "supported when operating on all bands.  "
    3041             :                     "Operation failed.");
    3042           0 :         return CE_Failure;
    3043             :     }
    3044             : 
    3045             :     /* -------------------------------------------------------------------- */
    3046             :     /*      If zero overviews were requested, we need to clear all          */
    3047             :     /*      existing overviews.                                             */
    3048             :     /* -------------------------------------------------------------------- */
    3049         246 :     if (nOverviews == 0)
    3050             :     {
    3051           6 :         if (m_nOverviewCount == 0)
    3052           3 :             return GDALDataset::IBuildOverviews(
    3053             :                 pszResampling, nOverviews, panOverviewList, nBandsIn,
    3054           3 :                 panBandList, pfnProgress, pProgressData, papszOptions);
    3055             : 
    3056           3 :         return CleanOverviews();
    3057             :     }
    3058             : 
    3059         240 :     CPLErr eErr = CE_None;
    3060             : 
    3061             :     /* -------------------------------------------------------------------- */
    3062             :     /*      Initialize progress counter.                                    */
    3063             :     /* -------------------------------------------------------------------- */
    3064         240 :     if (!pfnProgress(0.0, nullptr, pProgressData))
    3065             :     {
    3066           0 :         ReportError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    3067           0 :         return CE_Failure;
    3068             :     }
    3069             : 
    3070         240 :     FlushDirectory();
    3071             : 
    3072             :     /* -------------------------------------------------------------------- */
    3073             :     /*      If we are averaging bit data to grayscale we need to create     */
    3074             :     /*      8bit overviews.                                                 */
    3075             :     /* -------------------------------------------------------------------- */
    3076         240 :     int nOvBitsPerSample = m_nBitsPerSample;
    3077             : 
    3078         240 :     if (STARTS_WITH_CI(pszResampling, "AVERAGE_BIT2"))
    3079           2 :         nOvBitsPerSample = 8;
    3080             : 
    3081             :     /* -------------------------------------------------------------------- */
    3082             :     /*      Do we need some metadata for the overviews?                     */
    3083             :     /* -------------------------------------------------------------------- */
    3084         480 :     CPLString osMetadata;
    3085             : 
    3086         240 :     const bool bIsForMaskBand = nBands == 1 && GetRasterBand(1)->IsMaskBand();
    3087         240 :     GTIFFBuildOverviewMetadata(pszResampling, this, bIsForMaskBand, osMetadata);
    3088             : 
    3089             :     int nCompression;
    3090             :     uint16_t nPlanarConfig;
    3091             :     uint16_t nPredictor;
    3092             :     uint16_t nPhotometric;
    3093             :     int nOvrJpegQuality;
    3094         480 :     std::string osNoData;
    3095         240 :     uint16_t *panExtraSampleValues = nullptr;
    3096         240 :     uint16_t nExtraSamples = 0;
    3097         240 :     if (!GetOverviewParameters(nCompression, nPlanarConfig, nPredictor,
    3098             :                                nPhotometric, nOvrJpegQuality, osNoData,
    3099             :                                panExtraSampleValues, nExtraSamples,
    3100             :                                papszOptions))
    3101             :     {
    3102           0 :         return CE_Failure;
    3103             :     }
    3104             : 
    3105             :     /* -------------------------------------------------------------------- */
    3106             :     /*      Do we have a palette?  If so, create a TIFF compatible version. */
    3107             :     /* -------------------------------------------------------------------- */
    3108         480 :     std::vector<unsigned short> anTRed;
    3109         480 :     std::vector<unsigned short> anTGreen;
    3110         480 :     std::vector<unsigned short> anTBlue;
    3111         240 :     unsigned short *panRed = nullptr;
    3112         240 :     unsigned short *panGreen = nullptr;
    3113         240 :     unsigned short *panBlue = nullptr;
    3114             : 
    3115         240 :     if (nPhotometric == PHOTOMETRIC_PALETTE && m_poColorTable != nullptr)
    3116             :     {
    3117          12 :         if (m_nColorTableMultiplier == 0)
    3118           0 :             m_nColorTableMultiplier = DEFAULT_COLOR_TABLE_MULTIPLIER_257;
    3119             : 
    3120          12 :         CreateTIFFColorTable(m_poColorTable.get(), nOvBitsPerSample,
    3121             :                              m_nColorTableMultiplier, anTRed, anTGreen, anTBlue,
    3122             :                              panRed, panGreen, panBlue);
    3123             :     }
    3124             : 
    3125             :     /* -------------------------------------------------------------------- */
    3126             :     /*      Establish which of the overview levels we already have, and     */
    3127             :     /*      which are new.  We assume that band 1 of the file is            */
    3128             :     /*      representative.                                                 */
    3129             :     /* -------------------------------------------------------------------- */
    3130         240 :     int nOvrBlockXSize = 0;
    3131         240 :     int nOvrBlockYSize = 0;
    3132         240 :     GTIFFGetOverviewBlockSize(GDALRasterBand::ToHandle(GetRasterBand(1)),
    3133             :                               &nOvrBlockXSize, &nOvrBlockYSize);
    3134         480 :     std::vector<bool> abRequireNewOverview(nOverviews, true);
    3135         656 :     for (int i = 0; i < nOverviews && eErr == CE_None; ++i)
    3136             :     {
    3137         738 :         for (int j = 0; j < m_nOverviewCount && eErr == CE_None; ++j)
    3138             :         {
    3139         377 :             GTiffDataset *poODS = m_papoOverviewDS[j];
    3140             : 
    3141             :             const int nOvFactor =
    3142         377 :                 GDALComputeOvFactor(poODS->GetRasterXSize(), GetRasterXSize(),
    3143             :                                     poODS->GetRasterYSize(), GetRasterYSize());
    3144             : 
    3145             :             // If we already have a 1x1 overview and this new one would result
    3146             :             // in it too, then don't create it.
    3147         416 :             if (poODS->GetRasterXSize() == 1 && poODS->GetRasterYSize() == 1 &&
    3148          21 :                 (GetRasterXSize() + panOverviewList[i] - 1) /
    3149          21 :                         panOverviewList[i] ==
    3150         416 :                     1 &&
    3151          21 :                 (GetRasterYSize() + panOverviewList[i] - 1) /
    3152          21 :                         panOverviewList[i] ==
    3153             :                     1)
    3154             :             {
    3155          21 :                 abRequireNewOverview[i] = false;
    3156          21 :                 break;
    3157             :             }
    3158             : 
    3159         680 :             if (nOvFactor == panOverviewList[i] ||
    3160         324 :                 nOvFactor == GDALOvLevelAdjust2(panOverviewList[i],
    3161             :                                                 GetRasterXSize(),
    3162             :                                                 GetRasterYSize()))
    3163             :             {
    3164          34 :                 abRequireNewOverview[i] = false;
    3165          34 :                 break;
    3166             :             }
    3167             :         }
    3168             : 
    3169         416 :         if (abRequireNewOverview[i])
    3170             :         {
    3171         361 :             if (m_bLayoutIFDSBeforeData && !m_bKnownIncompatibleEdition &&
    3172           0 :                 !m_bWriteKnownIncompatibleEdition)
    3173             :             {
    3174           0 :                 ReportError(CE_Warning, CPLE_AppDefined,
    3175             :                             "Adding new overviews invalidates the "
    3176             :                             "LAYOUT=IFDS_BEFORE_DATA property");
    3177           0 :                 m_bKnownIncompatibleEdition = true;
    3178           0 :                 m_bWriteKnownIncompatibleEdition = true;
    3179             :             }
    3180             : 
    3181         361 :             const int nOXSize = (GetRasterXSize() + panOverviewList[i] - 1) /
    3182         361 :                                 panOverviewList[i];
    3183         361 :             const int nOYSize = (GetRasterYSize() + panOverviewList[i] - 1) /
    3184         361 :                                 panOverviewList[i];
    3185             : 
    3186         722 :             const toff_t nOverviewOffset = GTIFFWriteDirectory(
    3187             :                 m_hTIFF, FILETYPE_REDUCEDIMAGE, nOXSize, nOYSize,
    3188         361 :                 nOvBitsPerSample, nPlanarConfig, m_nSamplesPerPixel,
    3189             :                 nOvrBlockXSize, nOvrBlockYSize, TRUE, nCompression,
    3190         361 :                 nPhotometric, m_nSampleFormat, nPredictor, panRed, panGreen,
    3191             :                 panBlue, nExtraSamples, panExtraSampleValues, osMetadata,
    3192         361 :                 nOvrJpegQuality >= 0 ? CPLSPrintf("%d", nOvrJpegQuality)
    3193             :                                      : nullptr,
    3194         361 :                 CPLSPrintf("%d", m_nJpegTablesMode),
    3195          24 :                 osNoData.empty() ? nullptr : osNoData.c_str(),
    3196         361 :                 m_anLercAddCompressionAndVersion, false);
    3197             : 
    3198         361 :             if (nOverviewOffset == 0)
    3199           0 :                 eErr = CE_Failure;
    3200             :             else
    3201         361 :                 eErr = RegisterNewOverviewDataset(
    3202             :                     nOverviewOffset, nOvrJpegQuality, papszOptions);
    3203             :         }
    3204             :     }
    3205             : 
    3206         240 :     CPLFree(panExtraSampleValues);
    3207         240 :     panExtraSampleValues = nullptr;
    3208             : 
    3209         240 :     ReloadDirectory();
    3210             : 
    3211             :     /* -------------------------------------------------------------------- */
    3212             :     /*      Create overviews for the mask.                                  */
    3213             :     /* -------------------------------------------------------------------- */
    3214         240 :     if (eErr != CE_None)
    3215           0 :         return eErr;
    3216             : 
    3217         240 :     eErr = CreateInternalMaskOverviews(nOvrBlockXSize, nOvrBlockYSize);
    3218             : 
    3219             :     /* -------------------------------------------------------------------- */
    3220             :     /*      Refresh overviews for the mask                                  */
    3221             :     /* -------------------------------------------------------------------- */
    3222             :     const bool bHasInternalMask =
    3223         240 :         m_poMaskDS != nullptr && m_poMaskDS->GetRasterCount() == 1;
    3224             :     const bool bHasExternalMask =
    3225         240 :         !bHasInternalMask && oOvManager.HaveMaskFile();
    3226         240 :     const bool bHasMask = bHasInternalMask || bHasExternalMask;
    3227             : 
    3228         240 :     if (bHasInternalMask)
    3229             :     {
    3230          22 :         int nMaskOverviews = 0;
    3231             : 
    3232             :         GDALRasterBand **papoOverviewBands = static_cast<GDALRasterBand **>(
    3233          22 :             CPLCalloc(sizeof(void *), m_nOverviewCount));
    3234          60 :         for (int i = 0; i < m_nOverviewCount; ++i)
    3235             :         {
    3236          38 :             if (m_papoOverviewDS[i]->m_poMaskDS != nullptr)
    3237             :             {
    3238          38 :                 papoOverviewBands[nMaskOverviews++] =
    3239          38 :                     m_papoOverviewDS[i]->m_poMaskDS->GetRasterBand(1);
    3240             :             }
    3241             :         }
    3242             : 
    3243          44 :         void *pScaledProgressData = GDALCreateScaledProgress(
    3244          22 :             0, 1.0 / (nBands + 1), pfnProgress, pProgressData);
    3245          44 :         eErr = GDALRegenerateOverviewsEx(
    3246          22 :             m_poMaskDS->GetRasterBand(1), nMaskOverviews,
    3247             :             reinterpret_cast<GDALRasterBandH *>(papoOverviewBands),
    3248             :             pszResampling, GDALScaledProgress, pScaledProgressData,
    3249             :             papszOptions);
    3250          22 :         GDALDestroyScaledProgress(pScaledProgressData);
    3251          22 :         CPLFree(papoOverviewBands);
    3252             :     }
    3253         218 :     else if (bHasExternalMask)
    3254             :     {
    3255           4 :         void *pScaledProgressData = GDALCreateScaledProgress(
    3256           2 :             0, 1.0 / (nBands + 1), pfnProgress, pProgressData);
    3257           2 :         eErr = oOvManager.BuildOverviewsMask(
    3258             :             pszResampling, nOverviews, panOverviewList, GDALScaledProgress,
    3259             :             pScaledProgressData, papszOptions);
    3260           2 :         GDALDestroyScaledProgress(pScaledProgressData);
    3261             :     }
    3262             : 
    3263             :     // If we have an alpha band, we want it to be generated before downsampling
    3264             :     // other bands
    3265         240 :     bool bHasAlphaBand = false;
    3266         679 :     for (int iBand = 0; iBand < nBands; iBand++)
    3267             :     {
    3268         439 :         if (papoBands[iBand]->GetColorInterpretation() == GCI_AlphaBand)
    3269          18 :             bHasAlphaBand = true;
    3270             :     }
    3271             : 
    3272             :     /* -------------------------------------------------------------------- */
    3273             :     /*      Refresh old overviews that were listed.                         */
    3274             :     /* -------------------------------------------------------------------- */
    3275         240 :     const auto poColorTable = GetRasterBand(panBandList[0])->GetColorTable();
    3276          15 :     if ((m_nPlanarConfig == PLANARCONFIG_CONTIG || bHasAlphaBand) &&
    3277         227 :         GDALDataTypeIsComplex(
    3278         227 :             GetRasterBand(panBandList[0])->GetRasterDataType()) == FALSE &&
    3279          12 :         (poColorTable == nullptr || STARTS_WITH_CI(pszResampling, "NEAR") ||
    3280         481 :          poColorTable->IsIdentity()) &&
    3281         219 :         (STARTS_WITH_CI(pszResampling, "NEAR") ||
    3282         114 :          EQUAL(pszResampling, "AVERAGE") || EQUAL(pszResampling, "RMS") ||
    3283          48 :          EQUAL(pszResampling, "GAUSS") || EQUAL(pszResampling, "CUBIC") ||
    3284          29 :          EQUAL(pszResampling, "CUBICSPLINE") ||
    3285          28 :          EQUAL(pszResampling, "LANCZOS") || EQUAL(pszResampling, "BILINEAR") ||
    3286          24 :          EQUAL(pszResampling, "MODE")))
    3287             :     {
    3288             :         // In the case of pixel interleaved compressed overviews, we want to
    3289             :         // generate the overviews for all the bands block by block, and not
    3290             :         // band after band, in order to write the block once and not loose
    3291             :         // space in the TIFF file.  We also use that logic for uncompressed
    3292             :         // overviews, since GDALRegenerateOverviewsMultiBand() will be able to
    3293             :         // trigger cascading overview regeneration even in the presence
    3294             :         // of an alpha band.
    3295             : 
    3296         198 :         int nNewOverviews = 0;
    3297             : 
    3298             :         GDALRasterBand ***papapoOverviewBands = static_cast<GDALRasterBand ***>(
    3299         198 :             CPLCalloc(sizeof(void *), nBandsIn));
    3300             :         GDALRasterBand **papoBandList =
    3301         198 :             static_cast<GDALRasterBand **>(CPLCalloc(sizeof(void *), nBandsIn));
    3302         559 :         for (int iBand = 0; iBand < nBandsIn; ++iBand)
    3303             :         {
    3304         361 :             GDALRasterBand *poBand = GetRasterBand(panBandList[iBand]);
    3305             : 
    3306         361 :             papoBandList[iBand] = poBand;
    3307         722 :             papapoOverviewBands[iBand] = static_cast<GDALRasterBand **>(
    3308         361 :                 CPLCalloc(sizeof(void *), poBand->GetOverviewCount()));
    3309             : 
    3310         361 :             int iCurOverview = 0;
    3311             :             std::vector<bool> abAlreadyUsedOverviewBand(
    3312         361 :                 poBand->GetOverviewCount(), false);
    3313             : 
    3314        1024 :             for (int i = 0; i < nOverviews; ++i)
    3315             :             {
    3316        1156 :                 for (int j = 0; j < poBand->GetOverviewCount(); ++j)
    3317             :                 {
    3318        1142 :                     if (abAlreadyUsedOverviewBand[j])
    3319         493 :                         continue;
    3320             : 
    3321             :                     int nOvFactor;
    3322         649 :                     GDALRasterBand *poOverview = poBand->GetOverview(j);
    3323             : 
    3324         649 :                     nOvFactor = GDALComputeOvFactor(
    3325             :                         poOverview->GetXSize(), poBand->GetXSize(),
    3326             :                         poOverview->GetYSize(), poBand->GetYSize());
    3327             : 
    3328         649 :                     GDALCopyNoDataValue(poOverview, poBand);
    3329             : 
    3330         658 :                     if (nOvFactor == panOverviewList[i] ||
    3331           9 :                         nOvFactor == GDALOvLevelAdjust2(panOverviewList[i],
    3332             :                                                         poBand->GetXSize(),
    3333             :                                                         poBand->GetYSize()))
    3334             :                     {
    3335         649 :                         if (iBand == 0)
    3336             :                         {
    3337             :                             const auto osNewResampling =
    3338         660 :                                 GDALGetNormalizedOvrResampling(pszResampling);
    3339             :                             const char *pszExistingResampling =
    3340         330 :                                 poOverview->GetMetadataItem("RESAMPLING");
    3341         660 :                             if (pszExistingResampling &&
    3342         330 :                                 pszExistingResampling != osNewResampling)
    3343             :                             {
    3344           2 :                                 poOverview->SetMetadataItem(
    3345           2 :                                     "RESAMPLING", osNewResampling.c_str());
    3346             :                             }
    3347             :                         }
    3348             : 
    3349         649 :                         abAlreadyUsedOverviewBand[j] = true;
    3350         649 :                         CPLAssert(iCurOverview < poBand->GetOverviewCount());
    3351         649 :                         papapoOverviewBands[iBand][iCurOverview] = poOverview;
    3352         649 :                         ++iCurOverview;
    3353         649 :                         break;
    3354             :                     }
    3355             :                 }
    3356             :             }
    3357             : 
    3358         361 :             if (nNewOverviews == 0)
    3359             :             {
    3360         198 :                 nNewOverviews = iCurOverview;
    3361             :             }
    3362         163 :             else if (nNewOverviews != iCurOverview)
    3363             :             {
    3364           0 :                 CPLAssert(false);
    3365             :                 return CE_Failure;
    3366             :             }
    3367             :         }
    3368             : 
    3369             :         void *pScaledProgressData =
    3370         198 :             bHasMask ? GDALCreateScaledProgress(1.0 / (nBands + 1), 1.0,
    3371             :                                                 pfnProgress, pProgressData)
    3372         174 :                      : GDALCreateScaledProgress(0.0, 1.0, pfnProgress,
    3373         198 :                                                 pProgressData);
    3374         198 :         GDALRegenerateOverviewsMultiBand(nBandsIn, papoBandList, nNewOverviews,
    3375             :                                          papapoOverviewBands, pszResampling,
    3376             :                                          GDALScaledProgress,
    3377             :                                          pScaledProgressData, papszOptions);
    3378         198 :         GDALDestroyScaledProgress(pScaledProgressData);
    3379             : 
    3380         559 :         for (int iBand = 0; iBand < nBandsIn; ++iBand)
    3381             :         {
    3382         361 :             CPLFree(papapoOverviewBands[iBand]);
    3383             :         }
    3384         198 :         CPLFree(papapoOverviewBands);
    3385         198 :         CPLFree(papoBandList);
    3386             :     }
    3387             :     else
    3388             :     {
    3389             :         GDALRasterBand **papoOverviewBands = static_cast<GDALRasterBand **>(
    3390          42 :             CPLCalloc(sizeof(void *), nOverviews));
    3391             : 
    3392          42 :         const int iBandOffset = bHasMask ? 1 : 0;
    3393             : 
    3394         120 :         for (int iBand = 0; iBand < nBandsIn && eErr == CE_None; ++iBand)
    3395             :         {
    3396          78 :             GDALRasterBand *poBand = GetRasterBand(panBandList[iBand]);
    3397          78 :             if (poBand == nullptr)
    3398             :             {
    3399           0 :                 eErr = CE_Failure;
    3400           0 :                 break;
    3401             :             }
    3402             : 
    3403             :             std::vector<bool> abAlreadyUsedOverviewBand(
    3404         156 :                 poBand->GetOverviewCount(), false);
    3405             : 
    3406          78 :             int nNewOverviews = 0;
    3407         216 :             for (int i = 0; i < nOverviews; ++i)
    3408             :             {
    3409         336 :                 for (int j = 0; j < poBand->GetOverviewCount(); ++j)
    3410             :                 {
    3411         315 :                     if (abAlreadyUsedOverviewBand[j])
    3412         176 :                         continue;
    3413             : 
    3414         139 :                     GDALRasterBand *poOverview = poBand->GetOverview(j);
    3415             : 
    3416         139 :                     GDALCopyNoDataValue(poOverview, poBand);
    3417             : 
    3418         139 :                     const int nOvFactor = GDALComputeOvFactor(
    3419             :                         poOverview->GetXSize(), poBand->GetXSize(),
    3420             :                         poOverview->GetYSize(), poBand->GetYSize());
    3421             : 
    3422         171 :                     if (nOvFactor == panOverviewList[i] ||
    3423          32 :                         nOvFactor == GDALOvLevelAdjust2(panOverviewList[i],
    3424             :                                                         poBand->GetXSize(),
    3425             :                                                         poBand->GetYSize()))
    3426             :                     {
    3427         117 :                         if (iBand == 0)
    3428             :                         {
    3429             :                             const auto osNewResampling =
    3430         130 :                                 GDALGetNormalizedOvrResampling(pszResampling);
    3431             :                             const char *pszExistingResampling =
    3432          65 :                                 poOverview->GetMetadataItem("RESAMPLING");
    3433          98 :                             if (pszExistingResampling &&
    3434          33 :                                 pszExistingResampling != osNewResampling)
    3435             :                             {
    3436           1 :                                 poOverview->SetMetadataItem(
    3437           1 :                                     "RESAMPLING", osNewResampling.c_str());
    3438             :                             }
    3439             :                         }
    3440             : 
    3441         117 :                         abAlreadyUsedOverviewBand[j] = true;
    3442         117 :                         CPLAssert(nNewOverviews < poBand->GetOverviewCount());
    3443         117 :                         papoOverviewBands[nNewOverviews++] = poOverview;
    3444         117 :                         break;
    3445             :                     }
    3446             :                 }
    3447             :             }
    3448             : 
    3449         156 :             void *pScaledProgressData = GDALCreateScaledProgress(
    3450          78 :                 (iBand + iBandOffset) /
    3451          78 :                     static_cast<double>(nBandsIn + iBandOffset),
    3452          78 :                 (iBand + iBandOffset + 1) /
    3453          78 :                     static_cast<double>(nBandsIn + iBandOffset),
    3454             :                 pfnProgress, pProgressData);
    3455             : 
    3456          78 :             eErr = GDALRegenerateOverviewsEx(
    3457             :                 poBand, nNewOverviews,
    3458             :                 reinterpret_cast<GDALRasterBandH *>(papoOverviewBands),
    3459             :                 pszResampling, GDALScaledProgress, pScaledProgressData,
    3460             :                 papszOptions);
    3461             : 
    3462          78 :             GDALDestroyScaledProgress(pScaledProgressData);
    3463             :         }
    3464             : 
    3465             :         /* --------------------------------------------------------------------
    3466             :          */
    3467             :         /*      Cleanup */
    3468             :         /* --------------------------------------------------------------------
    3469             :          */
    3470          42 :         CPLFree(papoOverviewBands);
    3471             :     }
    3472             : 
    3473         240 :     pfnProgress(1.0, nullptr, pProgressData);
    3474             : 
    3475         240 :     return eErr;
    3476             : }
    3477             : 
    3478             : /************************************************************************/
    3479             : /*                      GTiffWriteDummyGeokeyDirectory()                */
    3480             : /************************************************************************/
    3481             : 
    3482        1358 : static void GTiffWriteDummyGeokeyDirectory(TIFF *hTIFF)
    3483             : {
    3484             :     // If we have existing geokeys, try to wipe them
    3485             :     // by writing a dummy geokey directory. (#2546)
    3486        1358 :     uint16_t *panVI = nullptr;
    3487        1358 :     uint16_t nKeyCount = 0;
    3488             : 
    3489        1358 :     if (TIFFGetField(hTIFF, TIFFTAG_GEOKEYDIRECTORY, &nKeyCount, &panVI))
    3490             :     {
    3491          21 :         GUInt16 anGKVersionInfo[4] = {1, 1, 0, 0};
    3492          21 :         double adfDummyDoubleParams[1] = {0.0};
    3493          21 :         TIFFSetField(hTIFF, TIFFTAG_GEOKEYDIRECTORY, 4, anGKVersionInfo);
    3494          21 :         TIFFSetField(hTIFF, TIFFTAG_GEODOUBLEPARAMS, 1, adfDummyDoubleParams);
    3495          21 :         TIFFSetField(hTIFF, TIFFTAG_GEOASCIIPARAMS, "");
    3496             :     }
    3497        1358 : }
    3498             : 
    3499             : /************************************************************************/
    3500             : /*                    IsSRSCompatibleOfGeoTIFF()                        */
    3501             : /************************************************************************/
    3502             : 
    3503        2826 : static bool IsSRSCompatibleOfGeoTIFF(const OGRSpatialReference *poSRS,
    3504             :                                      GTIFFKeysFlavorEnum eGeoTIFFKeysFlavor)
    3505             : {
    3506        2826 :     char *pszWKT = nullptr;
    3507        2826 :     if ((poSRS->IsGeographic() || poSRS->IsProjected()) && !poSRS->IsCompound())
    3508             :     {
    3509        2808 :         const char *pszAuthName = poSRS->GetAuthorityName(nullptr);
    3510        2808 :         const char *pszAuthCode = poSRS->GetAuthorityCode(nullptr);
    3511        2808 :         if (pszAuthName && pszAuthCode && EQUAL(pszAuthName, "EPSG"))
    3512        2288 :             return true;
    3513             :     }
    3514             :     OGRErr eErr;
    3515             :     {
    3516        1076 :         CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
    3517        1076 :         if (poSRS->IsDerivedGeographic() ||
    3518         538 :             (poSRS->IsProjected() && !poSRS->IsCompound() &&
    3519          70 :              poSRS->GetAxesCount() == 3))
    3520             :         {
    3521           0 :             eErr = OGRERR_FAILURE;
    3522             :         }
    3523             :         else
    3524             :         {
    3525             :             // Geographic3D CRS can't be exported to WKT1, but are
    3526             :             // valid GeoTIFF 1.1
    3527         538 :             const char *const apszOptions[] = {
    3528         538 :                 poSRS->IsGeographic() ? nullptr : "FORMAT=WKT1", nullptr};
    3529         538 :             eErr = poSRS->exportToWkt(&pszWKT, apszOptions);
    3530         538 :             if (eErr == OGRERR_FAILURE && poSRS->IsProjected() &&
    3531             :                 eGeoTIFFKeysFlavor == GEOTIFF_KEYS_ESRI_PE)
    3532             :             {
    3533           0 :                 CPLFree(pszWKT);
    3534           0 :                 const char *const apszOptionsESRIWKT[] = {"FORMAT=WKT1_ESRI",
    3535             :                                                           nullptr};
    3536           0 :                 eErr = poSRS->exportToWkt(&pszWKT, apszOptionsESRIWKT);
    3537             :             }
    3538             :         }
    3539             :     }
    3540         538 :     const bool bCompatibleOfGeoTIFF =
    3541        1075 :         (eErr == OGRERR_NONE && pszWKT != nullptr &&
    3542         537 :          strstr(pszWKT, "custom_proj4") == nullptr);
    3543         538 :     CPLFree(pszWKT);
    3544         538 :     return bCompatibleOfGeoTIFF;
    3545             : }
    3546             : 
    3547             : /************************************************************************/
    3548             : /*                          WriteGeoTIFFInfo()                          */
    3549             : /************************************************************************/
    3550             : 
    3551        3324 : void GTiffDataset::WriteGeoTIFFInfo()
    3552             : 
    3553             : {
    3554        3324 :     bool bPixelIsPoint = false;
    3555        3324 :     bool bPointGeoIgnore = false;
    3556             : 
    3557             :     const char *pszAreaOrPoint =
    3558        3324 :         GTiffDataset::GetMetadataItem(GDALMD_AREA_OR_POINT);
    3559        3324 :     if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_POINT))
    3560             :     {
    3561          17 :         bPixelIsPoint = true;
    3562             :         bPointGeoIgnore =
    3563          17 :             CPLTestBool(CPLGetConfigOption("GTIFF_POINT_GEO_IGNORE", "FALSE"));
    3564             :     }
    3565             : 
    3566        3324 :     if (m_bForceUnsetGTOrGCPs)
    3567             :     {
    3568          11 :         m_bNeedsRewrite = true;
    3569          11 :         m_bForceUnsetGTOrGCPs = false;
    3570             : 
    3571          11 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOPIXELSCALE);
    3572          11 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOTIEPOINTS);
    3573          11 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOTRANSMATRIX);
    3574             :     }
    3575             : 
    3576        3324 :     if (m_bForceUnsetProjection)
    3577             :     {
    3578           8 :         m_bNeedsRewrite = true;
    3579           8 :         m_bForceUnsetProjection = false;
    3580             : 
    3581           8 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOKEYDIRECTORY);
    3582           8 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEODOUBLEPARAMS);
    3583           8 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOASCIIPARAMS);
    3584             :     }
    3585             : 
    3586             :     /* -------------------------------------------------------------------- */
    3587             :     /*      Write geotransform if valid.                                    */
    3588             :     /* -------------------------------------------------------------------- */
    3589        3324 :     if (m_bGeoTransformValid)
    3590             :     {
    3591        1578 :         m_bNeedsRewrite = true;
    3592             : 
    3593             :         /* --------------------------------------------------------------------
    3594             :          */
    3595             :         /*      Clear old tags to ensure we don't end up with conflicting */
    3596             :         /*      information. (#2625) */
    3597             :         /* --------------------------------------------------------------------
    3598             :          */
    3599        1578 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOPIXELSCALE);
    3600        1578 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOTIEPOINTS);
    3601        1578 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOTRANSMATRIX);
    3602             : 
    3603             :         /* --------------------------------------------------------------------
    3604             :          */
    3605             :         /*      Write the transform.  If we have a normal north-up image we */
    3606             :         /*      use the tiepoint plus pixelscale otherwise we use a matrix. */
    3607             :         /* --------------------------------------------------------------------
    3608             :          */
    3609        1578 :         if (m_adfGeoTransform[2] == 0.0 && m_adfGeoTransform[4] == 0.0 &&
    3610        1560 :             m_adfGeoTransform[5] < 0.0)
    3611             :         {
    3612        1522 :             double dfOffset = 0.0;
    3613        1522 :             if (m_eProfile != GTiffProfile::BASELINE)
    3614             :             {
    3615             :                 // In the case the SRS has a vertical component and we have
    3616             :                 // a single band, encode its scale/offset in the GeoTIFF tags
    3617        1516 :                 int bHasScale = FALSE;
    3618        1516 :                 double dfScale = GetRasterBand(1)->GetScale(&bHasScale);
    3619        1516 :                 int bHasOffset = FALSE;
    3620        1516 :                 dfOffset = GetRasterBand(1)->GetOffset(&bHasOffset);
    3621             :                 const bool bApplyScaleOffset =
    3622        1516 :                     m_oSRS.IsVertical() && GetRasterCount() == 1;
    3623        1516 :                 if (bApplyScaleOffset && !bHasScale)
    3624           0 :                     dfScale = 1.0;
    3625        1516 :                 if (!bApplyScaleOffset || !bHasOffset)
    3626        1513 :                     dfOffset = 0.0;
    3627             :                 const double adfPixelScale[3] = {
    3628        1516 :                     m_adfGeoTransform[1], fabs(m_adfGeoTransform[5]),
    3629        1516 :                     bApplyScaleOffset ? dfScale : 0.0};
    3630        1516 :                 TIFFSetField(m_hTIFF, TIFFTAG_GEOPIXELSCALE, 3, adfPixelScale);
    3631             :             }
    3632             : 
    3633        1522 :             double adfTiePoints[6] = {
    3634        1522 :                 0.0,     0.0, 0.0, m_adfGeoTransform[0], m_adfGeoTransform[3],
    3635        1522 :                 dfOffset};
    3636             : 
    3637        1522 :             if (bPixelIsPoint && !bPointGeoIgnore)
    3638             :             {
    3639          13 :                 adfTiePoints[3] +=
    3640          13 :                     m_adfGeoTransform[1] * 0.5 + m_adfGeoTransform[2] * 0.5;
    3641          13 :                 adfTiePoints[4] +=
    3642          13 :                     m_adfGeoTransform[4] * 0.5 + m_adfGeoTransform[5] * 0.5;
    3643             :             }
    3644             : 
    3645        1522 :             if (m_eProfile != GTiffProfile::BASELINE)
    3646        1522 :                 TIFFSetField(m_hTIFF, TIFFTAG_GEOTIEPOINTS, 6, adfTiePoints);
    3647             :         }
    3648             :         else
    3649             :         {
    3650          56 :             double adfMatrix[16] = {};
    3651             : 
    3652          56 :             adfMatrix[0] = m_adfGeoTransform[1];
    3653          56 :             adfMatrix[1] = m_adfGeoTransform[2];
    3654          56 :             adfMatrix[3] = m_adfGeoTransform[0];
    3655          56 :             adfMatrix[4] = m_adfGeoTransform[4];
    3656          56 :             adfMatrix[5] = m_adfGeoTransform[5];
    3657          56 :             adfMatrix[7] = m_adfGeoTransform[3];
    3658          56 :             adfMatrix[15] = 1.0;
    3659             : 
    3660          56 :             if (bPixelIsPoint && !bPointGeoIgnore)
    3661             :             {
    3662           0 :                 adfMatrix[3] +=
    3663           0 :                     m_adfGeoTransform[1] * 0.5 + m_adfGeoTransform[2] * 0.5;
    3664           0 :                 adfMatrix[7] +=
    3665           0 :                     m_adfGeoTransform[4] * 0.5 + m_adfGeoTransform[5] * 0.5;
    3666             :             }
    3667             : 
    3668          56 :             if (m_eProfile != GTiffProfile::BASELINE)
    3669          56 :                 TIFFSetField(m_hTIFF, TIFFTAG_GEOTRANSMATRIX, 16, adfMatrix);
    3670             :         }
    3671             : 
    3672             :         // Do we need a world file?
    3673        1578 :         if (CPLFetchBool(m_papszCreationOptions, "TFW", false))
    3674           7 :             GDALWriteWorldFile(m_pszFilename, "tfw", m_adfGeoTransform);
    3675        1571 :         else if (CPLFetchBool(m_papszCreationOptions, "WORLDFILE", false))
    3676           2 :             GDALWriteWorldFile(m_pszFilename, "wld", m_adfGeoTransform);
    3677             :     }
    3678        1759 :     else if (GetGCPCount() > 0 && GetGCPCount() <= knMAX_GCP_COUNT &&
    3679          13 :              m_eProfile != GTiffProfile::BASELINE)
    3680             :     {
    3681          13 :         m_bNeedsRewrite = true;
    3682             : 
    3683             :         double *padfTiePoints = static_cast<double *>(
    3684          13 :             CPLMalloc(6 * sizeof(double) * GetGCPCount()));
    3685             : 
    3686          68 :         for (size_t iGCP = 0; iGCP < m_aoGCPs.size(); ++iGCP)
    3687             :         {
    3688             : 
    3689          55 :             padfTiePoints[iGCP * 6 + 0] = m_aoGCPs[iGCP].Pixel();
    3690          55 :             padfTiePoints[iGCP * 6 + 1] = m_aoGCPs[iGCP].Line();
    3691          55 :             padfTiePoints[iGCP * 6 + 2] = 0;
    3692          55 :             padfTiePoints[iGCP * 6 + 3] = m_aoGCPs[iGCP].X();
    3693          55 :             padfTiePoints[iGCP * 6 + 4] = m_aoGCPs[iGCP].Y();
    3694          55 :             padfTiePoints[iGCP * 6 + 5] = m_aoGCPs[iGCP].Z();
    3695             : 
    3696          55 :             if (bPixelIsPoint && !bPointGeoIgnore)
    3697             :             {
    3698           0 :                 padfTiePoints[iGCP * 6 + 0] += 0.5;
    3699           0 :                 padfTiePoints[iGCP * 6 + 1] += 0.5;
    3700             :             }
    3701             :         }
    3702             : 
    3703          13 :         TIFFSetField(m_hTIFF, TIFFTAG_GEOTIEPOINTS, 6 * GetGCPCount(),
    3704             :                      padfTiePoints);
    3705          13 :         CPLFree(padfTiePoints);
    3706             :     }
    3707             : 
    3708             :     /* -------------------------------------------------------------------- */
    3709             :     /*      Write out projection definition.                                */
    3710             :     /* -------------------------------------------------------------------- */
    3711        3324 :     const bool bHasProjection = !m_oSRS.IsEmpty();
    3712        3324 :     if ((bHasProjection || bPixelIsPoint) &&
    3713        1362 :         m_eProfile != GTiffProfile::BASELINE)
    3714             :     {
    3715        1358 :         m_bNeedsRewrite = true;
    3716             : 
    3717             :         // If we have existing geokeys, try to wipe them
    3718             :         // by writing a dummy geokey directory. (#2546)
    3719        1358 :         GTiffWriteDummyGeokeyDirectory(m_hTIFF);
    3720             : 
    3721        1358 :         GTIF *psGTIF = GTiffDataset::GTIFNew(m_hTIFF);
    3722             : 
    3723             :         // Set according to coordinate system.
    3724        1358 :         if (bHasProjection)
    3725             :         {
    3726        1357 :             if (IsSRSCompatibleOfGeoTIFF(&m_oSRS, m_eGeoTIFFKeysFlavor))
    3727             :             {
    3728        1355 :                 GTIFSetFromOGISDefnEx(psGTIF,
    3729             :                                       OGRSpatialReference::ToHandle(&m_oSRS),
    3730             :                                       m_eGeoTIFFKeysFlavor, m_eGeoTIFFVersion);
    3731             :             }
    3732             :             else
    3733             :             {
    3734           2 :                 GDALPamDataset::SetSpatialRef(&m_oSRS);
    3735             :             }
    3736             :         }
    3737             : 
    3738        1358 :         if (bPixelIsPoint)
    3739             :         {
    3740          17 :             GTIFKeySet(psGTIF, GTRasterTypeGeoKey, TYPE_SHORT, 1,
    3741             :                        RasterPixelIsPoint);
    3742             :         }
    3743             : 
    3744        1358 :         GTIFWriteKeys(psGTIF);
    3745        1358 :         GTIFFree(psGTIF);
    3746             :     }
    3747        3324 : }
    3748             : 
    3749             : /************************************************************************/
    3750             : /*                         AppendMetadataItem()                         */
    3751             : /************************************************************************/
    3752             : 
    3753        3466 : static void AppendMetadataItem(CPLXMLNode **ppsRoot, CPLXMLNode **ppsTail,
    3754             :                                const char *pszKey, const char *pszValue,
    3755             :                                int nBand, const char *pszRole,
    3756             :                                const char *pszDomain)
    3757             : 
    3758             : {
    3759             :     /* -------------------------------------------------------------------- */
    3760             :     /*      Create the Item element, and subcomponents.                     */
    3761             :     /* -------------------------------------------------------------------- */
    3762        3466 :     CPLXMLNode *psItem = CPLCreateXMLNode(nullptr, CXT_Element, "Item");
    3763        3466 :     CPLCreateXMLNode(CPLCreateXMLNode(psItem, CXT_Attribute, "name"), CXT_Text,
    3764             :                      pszKey);
    3765             : 
    3766        3466 :     if (nBand > 0)
    3767             :     {
    3768         817 :         char szBandId[32] = {};
    3769         817 :         snprintf(szBandId, sizeof(szBandId), "%d", nBand - 1);
    3770         817 :         CPLCreateXMLNode(CPLCreateXMLNode(psItem, CXT_Attribute, "sample"),
    3771             :                          CXT_Text, szBandId);
    3772             :     }
    3773             : 
    3774        3466 :     if (pszRole != nullptr)
    3775         336 :         CPLCreateXMLNode(CPLCreateXMLNode(psItem, CXT_Attribute, "role"),
    3776             :                          CXT_Text, pszRole);
    3777             : 
    3778        3466 :     if (pszDomain != nullptr && strlen(pszDomain) > 0)
    3779         954 :         CPLCreateXMLNode(CPLCreateXMLNode(psItem, CXT_Attribute, "domain"),
    3780             :                          CXT_Text, pszDomain);
    3781             : 
    3782             :     // Note: this escaping should not normally be done, as the serialization
    3783             :     // of the tree to XML also does it, so we end up width double XML escaping,
    3784             :     // but keep it for backward compatibility.
    3785        3466 :     char *pszEscapedItemValue = CPLEscapeString(pszValue, -1, CPLES_XML);
    3786        3466 :     CPLCreateXMLNode(psItem, CXT_Text, pszEscapedItemValue);
    3787        3466 :     CPLFree(pszEscapedItemValue);
    3788             : 
    3789             :     /* -------------------------------------------------------------------- */
    3790             :     /*      Create root, if missing.                                        */
    3791             :     /* -------------------------------------------------------------------- */
    3792        3466 :     if (*ppsRoot == nullptr)
    3793         607 :         *ppsRoot = CPLCreateXMLNode(nullptr, CXT_Element, "GDALMetadata");
    3794             : 
    3795             :     /* -------------------------------------------------------------------- */
    3796             :     /*      Append item to tail.  We keep track of the tail to avoid        */
    3797             :     /*      O(nsquared) time as the list gets longer.                       */
    3798             :     /* -------------------------------------------------------------------- */
    3799        3466 :     if (*ppsTail == nullptr)
    3800         607 :         CPLAddXMLChild(*ppsRoot, psItem);
    3801             :     else
    3802        2859 :         CPLAddXMLSibling(*ppsTail, psItem);
    3803             : 
    3804        3466 :     *ppsTail = psItem;
    3805        3466 : }
    3806             : 
    3807             : /************************************************************************/
    3808             : /*                         WriteMDMetadata()                            */
    3809             : /************************************************************************/
    3810             : 
    3811      206720 : static void WriteMDMetadata(GDALMultiDomainMetadata *poMDMD, TIFF *hTIFF,
    3812             :                             CPLXMLNode **ppsRoot, CPLXMLNode **ppsTail,
    3813             :                             int nBand, GTiffProfile eProfile)
    3814             : 
    3815             : {
    3816             : 
    3817             :     /* ==================================================================== */
    3818             :     /*      Process each domain.                                            */
    3819             :     /* ==================================================================== */
    3820      206720 :     CSLConstList papszDomainList = poMDMD->GetDomainList();
    3821      212359 :     for (int iDomain = 0; papszDomainList && papszDomainList[iDomain];
    3822             :          ++iDomain)
    3823             :     {
    3824        5639 :         CSLConstList papszMD = poMDMD->GetMetadata(papszDomainList[iDomain]);
    3825        5639 :         bool bIsXML = false;
    3826             : 
    3827        5639 :         if (EQUAL(papszDomainList[iDomain], "IMAGE_STRUCTURE") ||
    3828        2220 :             EQUAL(papszDomainList[iDomain], "DERIVED_SUBDATASETS"))
    3829        3422 :             continue;  // Ignored.
    3830        2217 :         if (EQUAL(papszDomainList[iDomain], "COLOR_PROFILE"))
    3831           3 :             continue;  // Handled elsewhere.
    3832        2214 :         if (EQUAL(papszDomainList[iDomain], MD_DOMAIN_RPC))
    3833           7 :             continue;  // Handled elsewhere.
    3834        2208 :         if (EQUAL(papszDomainList[iDomain], "xml:ESRI") &&
    3835           1 :             CPLTestBool(CPLGetConfigOption("ESRI_XML_PAM", "NO")))
    3836           1 :             continue;  // Handled elsewhere.
    3837        2206 :         if (EQUAL(papszDomainList[iDomain], "xml:XMP"))
    3838           2 :             continue;  // Handled in SetMetadata.
    3839             : 
    3840        2204 :         if (STARTS_WITH_CI(papszDomainList[iDomain], "xml:"))
    3841           2 :             bIsXML = true;
    3842             : 
    3843             :         /* --------------------------------------------------------------------
    3844             :          */
    3845             :         /*      Process each item in this domain. */
    3846             :         /* --------------------------------------------------------------------
    3847             :          */
    3848        6806 :         for (int iItem = 0; papszMD && papszMD[iItem]; ++iItem)
    3849             :         {
    3850        4602 :             const char *pszItemValue = nullptr;
    3851        4602 :             char *pszItemName = nullptr;
    3852             : 
    3853        4602 :             if (bIsXML)
    3854             :             {
    3855           2 :                 pszItemName = CPLStrdup("doc");
    3856           2 :                 pszItemValue = papszMD[iItem];
    3857             :             }
    3858             :             else
    3859             :             {
    3860        4600 :                 pszItemValue = CPLParseNameValue(papszMD[iItem], &pszItemName);
    3861        4600 :                 if (pszItemName == nullptr)
    3862             :                 {
    3863          49 :                     CPLDebug("GTiff", "Invalid metadata item : %s",
    3864          49 :                              papszMD[iItem]);
    3865          49 :                     continue;
    3866             :                 }
    3867             :             }
    3868             : 
    3869             :             /* --------------------------------------------------------------------
    3870             :              */
    3871             :             /*      Convert into XML item or handle as a special TIFF tag. */
    3872             :             /* --------------------------------------------------------------------
    3873             :              */
    3874        4553 :             if (strlen(papszDomainList[iDomain]) == 0 && nBand == 0 &&
    3875        3508 :                 (STARTS_WITH_CI(pszItemName, "TIFFTAG_") ||
    3876        3447 :                  (EQUAL(pszItemName, "GEO_METADATA") &&
    3877        3446 :                   eProfile == GTiffProfile::GDALGEOTIFF) ||
    3878        3446 :                  (EQUAL(pszItemName, "TIFF_RSID") &&
    3879             :                   eProfile == GTiffProfile::GDALGEOTIFF)))
    3880             :             {
    3881          63 :                 if (EQUAL(pszItemName, "TIFFTAG_RESOLUTIONUNIT"))
    3882             :                 {
    3883             :                     // ResolutionUnit can't be 0, which is the default if
    3884             :                     // atoi() fails.  Set to 1=Unknown.
    3885           9 :                     int v = atoi(pszItemValue);
    3886           9 :                     if (!v)
    3887           1 :                         v = RESUNIT_NONE;
    3888           9 :                     TIFFSetField(hTIFF, TIFFTAG_RESOLUTIONUNIT, v);
    3889             :                 }
    3890             :                 else
    3891             :                 {
    3892          54 :                     bool bFoundTag = false;
    3893          54 :                     size_t iTag = 0;  // Used after for.
    3894          54 :                     const auto *pasTIFFTags = GTiffDataset::GetTIFFTags();
    3895         286 :                     for (; pasTIFFTags[iTag].pszTagName; ++iTag)
    3896             :                     {
    3897         286 :                         if (EQUAL(pszItemName, pasTIFFTags[iTag].pszTagName))
    3898             :                         {
    3899          54 :                             bFoundTag = true;
    3900          54 :                             break;
    3901             :                         }
    3902             :                     }
    3903             : 
    3904          54 :                     if (bFoundTag &&
    3905          54 :                         pasTIFFTags[iTag].eType == GTIFFTAGTYPE_STRING)
    3906          33 :                         TIFFSetField(hTIFF, pasTIFFTags[iTag].nTagVal,
    3907             :                                      pszItemValue);
    3908          21 :                     else if (bFoundTag &&
    3909          21 :                              pasTIFFTags[iTag].eType == GTIFFTAGTYPE_FLOAT)
    3910          16 :                         TIFFSetField(hTIFF, pasTIFFTags[iTag].nTagVal,
    3911             :                                      CPLAtof(pszItemValue));
    3912           5 :                     else if (bFoundTag &&
    3913           5 :                              pasTIFFTags[iTag].eType == GTIFFTAGTYPE_SHORT)
    3914           4 :                         TIFFSetField(hTIFF, pasTIFFTags[iTag].nTagVal,
    3915             :                                      atoi(pszItemValue));
    3916           1 :                     else if (bFoundTag && pasTIFFTags[iTag].eType ==
    3917             :                                               GTIFFTAGTYPE_BYTE_STRING)
    3918             :                     {
    3919           1 :                         uint32_t nLen =
    3920           1 :                             static_cast<uint32_t>(strlen(pszItemValue));
    3921           1 :                         if (nLen)
    3922             :                         {
    3923           1 :                             TIFFSetField(hTIFF, pasTIFFTags[iTag].nTagVal, nLen,
    3924             :                                          pszItemValue);
    3925           1 :                         }
    3926             :                     }
    3927             :                     else
    3928           0 :                         CPLError(CE_Warning, CPLE_NotSupported,
    3929             :                                  "%s metadata item is unhandled and "
    3930             :                                  "will not be written",
    3931             :                                  pszItemName);
    3932          63 :                 }
    3933             :             }
    3934        4490 :             else if (nBand == 0 && EQUAL(pszItemName, GDALMD_AREA_OR_POINT))
    3935             :             {
    3936             :                 /* Do nothing, handled elsewhere. */;
    3937             :             }
    3938             :             else
    3939             :             {
    3940        2744 :                 AppendMetadataItem(ppsRoot, ppsTail, pszItemName, pszItemValue,
    3941        2744 :                                    nBand, nullptr, papszDomainList[iDomain]);
    3942             :             }
    3943             : 
    3944        4553 :             CPLFree(pszItemName);
    3945             :         }
    3946             : 
    3947             :         /* --------------------------------------------------------------------
    3948             :          */
    3949             :         /*      Remove TIFFTAG_xxxxxx that are already set but no longer in */
    3950             :         /*      the metadata list (#5619) */
    3951             :         /* --------------------------------------------------------------------
    3952             :          */
    3953        2204 :         if (strlen(papszDomainList[iDomain]) == 0 && nBand == 0)
    3954             :         {
    3955        2010 :             const auto *pasTIFFTags = GTiffDataset::GetTIFFTags();
    3956       30150 :             for (size_t iTag = 0; pasTIFFTags[iTag].pszTagName; ++iTag)
    3957             :             {
    3958       28140 :                 uint32_t nCount = 0;
    3959       28140 :                 char *pszText = nullptr;
    3960       28140 :                 int16_t nVal = 0;
    3961       28140 :                 float fVal = 0.0f;
    3962             :                 const char *pszVal =
    3963       28140 :                     CSLFetchNameValue(papszMD, pasTIFFTags[iTag].pszTagName);
    3964       56217 :                 if (pszVal == nullptr &&
    3965       28077 :                     ((pasTIFFTags[iTag].eType == GTIFFTAGTYPE_STRING &&
    3966       16047 :                       TIFFGetField(hTIFF, pasTIFFTags[iTag].nTagVal,
    3967       28069 :                                    &pszText)) ||
    3968       28069 :                      (pasTIFFTags[iTag].eType == GTIFFTAGTYPE_SHORT &&
    3969        6017 :                       TIFFGetField(hTIFF, pasTIFFTags[iTag].nTagVal, &nVal)) ||
    3970       28066 :                      (pasTIFFTags[iTag].eType == GTIFFTAGTYPE_FLOAT &&
    3971        4004 :                       TIFFGetField(hTIFF, pasTIFFTags[iTag].nTagVal, &fVal)) ||
    3972       28065 :                      (pasTIFFTags[iTag].eType == GTIFFTAGTYPE_BYTE_STRING &&
    3973        2009 :                       TIFFGetField(hTIFF, pasTIFFTags[iTag].nTagVal, &nCount,
    3974             :                                    &pszText))))
    3975             :                 {
    3976          13 :                     TIFFUnsetField(hTIFF, pasTIFFTags[iTag].nTagVal);
    3977             :                 }
    3978             :             }
    3979             :         }
    3980             :     }
    3981      206720 : }
    3982             : 
    3983             : /************************************************************************/
    3984             : /*                           WriteRPC()                                 */
    3985             : /************************************************************************/
    3986             : 
    3987        7186 : void GTiffDataset::WriteRPC(GDALDataset *poSrcDS, TIFF *l_hTIFF,
    3988             :                             int bSrcIsGeoTIFF, GTiffProfile eProfile,
    3989             :                             const char *pszTIFFFilename,
    3990             :                             CSLConstList papszCreationOptions,
    3991             :                             bool bWriteOnlyInPAMIfNeeded)
    3992             : {
    3993             :     /* -------------------------------------------------------------------- */
    3994             :     /*      Handle RPC data written to TIFF RPCCoefficient tag, RPB file,   */
    3995             :     /*      RPCTEXT file or PAM.                                            */
    3996             :     /* -------------------------------------------------------------------- */
    3997        7186 :     char **papszRPCMD = poSrcDS->GetMetadata(MD_DOMAIN_RPC);
    3998        7186 :     if (papszRPCMD != nullptr)
    3999             :     {
    4000          32 :         bool bRPCSerializedOtherWay = false;
    4001             : 
    4002          32 :         if (eProfile == GTiffProfile::GDALGEOTIFF)
    4003             :         {
    4004          20 :             if (!bWriteOnlyInPAMIfNeeded)
    4005          11 :                 GTiffDatasetWriteRPCTag(l_hTIFF, papszRPCMD);
    4006          20 :             bRPCSerializedOtherWay = true;
    4007             :         }
    4008             : 
    4009             :         // Write RPB file if explicitly asked, or if a non GDAL specific
    4010             :         // profile is selected and RPCTXT is not asked.
    4011             :         bool bRPBExplicitlyAsked =
    4012          32 :             CPLFetchBool(papszCreationOptions, "RPB", false);
    4013             :         bool bRPBExplicitlyDenied =
    4014          32 :             !CPLFetchBool(papszCreationOptions, "RPB", true);
    4015          44 :         if ((eProfile != GTiffProfile::GDALGEOTIFF &&
    4016          12 :              !CPLFetchBool(papszCreationOptions, "RPCTXT", false) &&
    4017          44 :              !bRPBExplicitlyDenied) ||
    4018             :             bRPBExplicitlyAsked)
    4019             :         {
    4020           8 :             if (!bWriteOnlyInPAMIfNeeded)
    4021           4 :                 GDALWriteRPBFile(pszTIFFFilename, papszRPCMD);
    4022           8 :             bRPCSerializedOtherWay = true;
    4023             :         }
    4024             : 
    4025          32 :         if (CPLFetchBool(papszCreationOptions, "RPCTXT", false))
    4026             :         {
    4027           2 :             if (!bWriteOnlyInPAMIfNeeded)
    4028           1 :                 GDALWriteRPCTXTFile(pszTIFFFilename, papszRPCMD);
    4029           2 :             bRPCSerializedOtherWay = true;
    4030             :         }
    4031             : 
    4032          32 :         if (!bRPCSerializedOtherWay && bWriteOnlyInPAMIfNeeded && bSrcIsGeoTIFF)
    4033           1 :             cpl::down_cast<GTiffDataset *>(poSrcDS)
    4034           1 :                 ->GDALPamDataset::SetMetadata(papszRPCMD, MD_DOMAIN_RPC);
    4035             :     }
    4036        7186 : }
    4037             : 
    4038             : /************************************************************************/
    4039             : /*                           WriteMetadata()                            */
    4040             : /************************************************************************/
    4041             : 
    4042        5276 : bool GTiffDataset::WriteMetadata(GDALDataset *poSrcDS, TIFF *l_hTIFF,
    4043             :                                  bool bSrcIsGeoTIFF, GTiffProfile eProfile,
    4044             :                                  const char *pszTIFFFilename,
    4045             :                                  CSLConstList papszCreationOptions,
    4046             :                                  bool bExcludeRPBandIMGFileWriting)
    4047             : 
    4048             : {
    4049             :     /* -------------------------------------------------------------------- */
    4050             :     /*      Convert all the remaining metadata into a simple XML            */
    4051             :     /*      format.                                                         */
    4052             :     /* -------------------------------------------------------------------- */
    4053        5276 :     CPLXMLNode *psRoot = nullptr;
    4054        5276 :     CPLXMLNode *psTail = nullptr;
    4055             : 
    4056             :     const char *pszCopySrcMDD =
    4057        5276 :         CSLFetchNameValueDef(papszCreationOptions, "COPY_SRC_MDD", "AUTO");
    4058             :     char **papszSrcMDD =
    4059        5276 :         CSLFetchNameValueMultiple(papszCreationOptions, "SRC_MDD");
    4060             : 
    4061        5276 :     if (bSrcIsGeoTIFF)
    4062             :     {
    4063        3344 :         GTiffDataset *poSrcDSGTiff = cpl::down_cast<GTiffDataset *>(poSrcDS);
    4064        3344 :         assert(poSrcDSGTiff);
    4065        3344 :         WriteMDMetadata(&poSrcDSGTiff->m_oGTiffMDMD, l_hTIFF, &psRoot, &psTail,
    4066             :                         0, eProfile);
    4067             :     }
    4068             :     else
    4069             :     {
    4070        1932 :         if (EQUAL(pszCopySrcMDD, "AUTO") || CPLTestBool(pszCopySrcMDD) ||
    4071             :             papszSrcMDD)
    4072             :         {
    4073        3858 :             GDALMultiDomainMetadata l_oMDMD;
    4074        1929 :             CSLConstList papszMD = poSrcDS->GetMetadata();
    4075        1933 :             if (CSLCount(papszMD) > 0 &&
    4076           4 :                 (!papszSrcMDD || CSLFindString(papszSrcMDD, "") >= 0 ||
    4077           2 :                  CSLFindString(papszSrcMDD, "_DEFAULT_") >= 0))
    4078             :             {
    4079        1489 :                 l_oMDMD.SetMetadata(papszMD);
    4080             :             }
    4081             : 
    4082        1929 :             if ((!EQUAL(pszCopySrcMDD, "AUTO") && CPLTestBool(pszCopySrcMDD)) ||
    4083             :                 papszSrcMDD)
    4084             :             {
    4085           9 :                 char **papszDomainList = poSrcDS->GetMetadataDomainList();
    4086          39 :                 for (CSLConstList papszIter = papszDomainList;
    4087          39 :                      papszIter && *papszIter; ++papszIter)
    4088             :                 {
    4089          30 :                     const char *pszDomain = *papszIter;
    4090          46 :                     if (pszDomain[0] != 0 &&
    4091          16 :                         (!papszSrcMDD ||
    4092          16 :                          CSLFindString(papszSrcMDD, pszDomain) >= 0))
    4093             :                     {
    4094          12 :                         l_oMDMD.SetMetadata(poSrcDS->GetMetadata(pszDomain),
    4095             :                                             pszDomain);
    4096             :                     }
    4097             :                 }
    4098           9 :                 CSLDestroy(papszDomainList);
    4099             :             }
    4100             : 
    4101        1929 :             WriteMDMetadata(&l_oMDMD, l_hTIFF, &psRoot, &psTail, 0, eProfile);
    4102             :         }
    4103             :     }
    4104             : 
    4105        5276 :     if (!bExcludeRPBandIMGFileWriting)
    4106             :     {
    4107        5270 :         WriteRPC(poSrcDS, l_hTIFF, bSrcIsGeoTIFF, eProfile, pszTIFFFilename,
    4108             :                  papszCreationOptions);
    4109             : 
    4110             :         /* --------------------------------------------------------------------
    4111             :          */
    4112             :         /*      Handle metadata data written to an IMD file. */
    4113             :         /* --------------------------------------------------------------------
    4114             :          */
    4115        5270 :         char **papszIMDMD = poSrcDS->GetMetadata(MD_DOMAIN_IMD);
    4116        5270 :         if (papszIMDMD != nullptr)
    4117             :         {
    4118          20 :             GDALWriteIMDFile(pszTIFFFilename, papszIMDMD);
    4119             :         }
    4120             :     }
    4121             : 
    4122        5276 :     uint16_t nPhotometric = 0;
    4123        5276 :     if (!TIFFGetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, &(nPhotometric)))
    4124           1 :         nPhotometric = PHOTOMETRIC_MINISBLACK;
    4125             : 
    4126        5276 :     const bool bStandardColorInterp = GTIFFIsStandardColorInterpretation(
    4127             :         GDALDataset::ToHandle(poSrcDS), nPhotometric, papszCreationOptions);
    4128             : 
    4129             :     /* -------------------------------------------------------------------- */
    4130             :     /*      We also need to address band specific metadata, and special     */
    4131             :     /*      "role" metadata.                                                */
    4132             :     /* -------------------------------------------------------------------- */
    4133      211398 :     for (int nBand = 1; nBand <= poSrcDS->GetRasterCount(); ++nBand)
    4134             :     {
    4135      206122 :         GDALRasterBand *poBand = poSrcDS->GetRasterBand(nBand);
    4136             : 
    4137      206122 :         if (bSrcIsGeoTIFF)
    4138             :         {
    4139             :             GTiffRasterBand *poSrcBandGTiff =
    4140      201359 :                 cpl::down_cast<GTiffRasterBand *>(poBand);
    4141      201359 :             assert(poSrcBandGTiff);
    4142      201359 :             WriteMDMetadata(&poSrcBandGTiff->m_oGTiffMDMD, l_hTIFF, &psRoot,
    4143             :                             &psTail, nBand, eProfile);
    4144             :         }
    4145             :         else
    4146             :         {
    4147        9526 :             GDALMultiDomainMetadata l_oMDMD;
    4148        4763 :             bool bOMDMDSet = false;
    4149             : 
    4150        4763 :             if (EQUAL(pszCopySrcMDD, "AUTO") && !papszSrcMDD)
    4151             :             {
    4152       14253 :                 for (const char *pszDomain : {"", "IMAGERY"})
    4153             :                 {
    4154        9502 :                     if (CSLConstList papszMD = poBand->GetMetadata(pszDomain))
    4155             :                     {
    4156          86 :                         if (papszMD[0])
    4157             :                         {
    4158          86 :                             bOMDMDSet = true;
    4159          86 :                             l_oMDMD.SetMetadata(papszMD, pszDomain);
    4160             :                         }
    4161             :                     }
    4162        4751 :                 }
    4163             :             }
    4164          12 :             else if (CPLTestBool(pszCopySrcMDD) || papszSrcMDD)
    4165             :             {
    4166           9 :                 char **papszDomainList = poBand->GetMetadataDomainList();
    4167           3 :                 for (const char *pszDomain :
    4168          15 :                      cpl::Iterate(CSLConstList(papszDomainList)))
    4169             :                 {
    4170           9 :                     if (pszDomain[0] != 0 &&
    4171           5 :                         !EQUAL(pszDomain, "IMAGE_STRUCTURE") &&
    4172           2 :                         (!papszSrcMDD ||
    4173           2 :                          CSLFindString(papszSrcMDD, pszDomain) >= 0))
    4174             :                     {
    4175           2 :                         bOMDMDSet = true;
    4176           2 :                         l_oMDMD.SetMetadata(poBand->GetMetadata(pszDomain),
    4177             :                                             pszDomain);
    4178             :                     }
    4179             :                 }
    4180           9 :                 CSLDestroy(papszDomainList);
    4181             :             }
    4182             : 
    4183        4763 :             if (bOMDMDSet)
    4184             :             {
    4185          88 :                 WriteMDMetadata(&l_oMDMD, l_hTIFF, &psRoot, &psTail, nBand,
    4186             :                                 eProfile);
    4187             :             }
    4188             :         }
    4189             : 
    4190      206122 :         const double dfOffset = poBand->GetOffset();
    4191      206122 :         const double dfScale = poBand->GetScale();
    4192      206122 :         bool bGeoTIFFScaleOffsetInZ = false;
    4193             :         double adfGeoTransform[6];
    4194             :         // Check if we have already encoded scale/offset in the GeoTIFF tags
    4195      206122 :         if (poSrcDS->GetGeoTransform(adfGeoTransform) == CE_None &&
    4196        5443 :             adfGeoTransform[2] == 0.0 && adfGeoTransform[4] == 0.0 &&
    4197        5431 :             adfGeoTransform[5] < 0.0 && poSrcDS->GetSpatialRef() &&
    4198      211572 :             poSrcDS->GetSpatialRef()->IsVertical() &&
    4199           7 :             poSrcDS->GetRasterCount() == 1)
    4200             :         {
    4201           7 :             bGeoTIFFScaleOffsetInZ = true;
    4202             :         }
    4203             : 
    4204      206122 :         if ((dfOffset != 0.0 || dfScale != 1.0) && !bGeoTIFFScaleOffsetInZ)
    4205             :         {
    4206          25 :             char szValue[128] = {};
    4207             : 
    4208          25 :             CPLsnprintf(szValue, sizeof(szValue), "%.17g", dfOffset);
    4209          25 :             AppendMetadataItem(&psRoot, &psTail, "OFFSET", szValue, nBand,
    4210             :                                "offset", "");
    4211          25 :             CPLsnprintf(szValue, sizeof(szValue), "%.17g", dfScale);
    4212          25 :             AppendMetadataItem(&psRoot, &psTail, "SCALE", szValue, nBand,
    4213             :                                "scale", "");
    4214             :         }
    4215             : 
    4216      206122 :         const char *pszUnitType = poBand->GetUnitType();
    4217      206122 :         if (pszUnitType != nullptr && pszUnitType[0] != '\0')
    4218             :         {
    4219          39 :             bool bWriteUnit = true;
    4220          39 :             auto poSRS = poSrcDS->GetSpatialRef();
    4221          39 :             if (poSRS && poSRS->IsCompound())
    4222             :             {
    4223           2 :                 const char *pszVertUnit = nullptr;
    4224           2 :                 poSRS->GetTargetLinearUnits("COMPD_CS|VERT_CS", &pszVertUnit);
    4225           2 :                 if (pszVertUnit && EQUAL(pszVertUnit, pszUnitType))
    4226             :                 {
    4227           2 :                     bWriteUnit = false;
    4228             :                 }
    4229             :             }
    4230          39 :             if (bWriteUnit)
    4231             :             {
    4232          37 :                 AppendMetadataItem(&psRoot, &psTail, "UNITTYPE", pszUnitType,
    4233             :                                    nBand, "unittype", "");
    4234             :             }
    4235             :         }
    4236             : 
    4237      206122 :         if (strlen(poBand->GetDescription()) > 0)
    4238             :         {
    4239          15 :             AppendMetadataItem(&psRoot, &psTail, "DESCRIPTION",
    4240          15 :                                poBand->GetDescription(), nBand, "description",
    4241             :                                "");
    4242             :         }
    4243             : 
    4244      206324 :         if (!bStandardColorInterp &&
    4245         202 :             !(nBand <= 3 && EQUAL(CSLFetchNameValueDef(papszCreationOptions,
    4246             :                                                        "PHOTOMETRIC", ""),
    4247             :                                   "RGB")))
    4248             :         {
    4249         234 :             AppendMetadataItem(&psRoot, &psTail, "COLORINTERP",
    4250             :                                GDALGetColorInterpretationName(
    4251         234 :                                    poBand->GetColorInterpretation()),
    4252             :                                nBand, "colorinterp", "");
    4253             :         }
    4254             :     }
    4255             : 
    4256        5276 :     CSLDestroy(papszSrcMDD);
    4257             : 
    4258             :     const char *pszTilingSchemeName =
    4259        5276 :         CSLFetchNameValue(papszCreationOptions, "@TILING_SCHEME_NAME");
    4260        5276 :     if (pszTilingSchemeName)
    4261             :     {
    4262          23 :         AppendMetadataItem(&psRoot, &psTail, "NAME", pszTilingSchemeName, 0,
    4263             :                            nullptr, "TILING_SCHEME");
    4264             : 
    4265          23 :         const char *pszZoomLevel = CSLFetchNameValue(
    4266             :             papszCreationOptions, "@TILING_SCHEME_ZOOM_LEVEL");
    4267          23 :         if (pszZoomLevel)
    4268             :         {
    4269          23 :             AppendMetadataItem(&psRoot, &psTail, "ZOOM_LEVEL", pszZoomLevel, 0,
    4270             :                                nullptr, "TILING_SCHEME");
    4271             :         }
    4272             : 
    4273          23 :         const char *pszAlignedLevels = CSLFetchNameValue(
    4274             :             papszCreationOptions, "@TILING_SCHEME_ALIGNED_LEVELS");
    4275          23 :         if (pszAlignedLevels)
    4276             :         {
    4277           4 :             AppendMetadataItem(&psRoot, &psTail, "ALIGNED_LEVELS",
    4278             :                                pszAlignedLevels, 0, nullptr, "TILING_SCHEME");
    4279             :         }
    4280             :     }
    4281             : 
    4282             :     /* -------------------------------------------------------------------- */
    4283             :     /*      Write information about some codecs.                            */
    4284             :     /* -------------------------------------------------------------------- */
    4285        5276 :     if (CPLTestBool(
    4286             :             CPLGetConfigOption("GTIFF_WRITE_IMAGE_STRUCTURE_METADATA", "YES")))
    4287             :     {
    4288             :         const char *pszTileInterleave =
    4289        5271 :             CSLFetchNameValue(papszCreationOptions, "@TILE_INTERLEAVE");
    4290        5271 :         if (pszTileInterleave && CPLTestBool(pszTileInterleave))
    4291             :         {
    4292           7 :             AppendMetadataItem(&psRoot, &psTail, "INTERLEAVE", "TILE", 0,
    4293             :                                nullptr, "IMAGE_STRUCTURE");
    4294             :         }
    4295             : 
    4296             :         const char *pszCompress =
    4297        5271 :             CSLFetchNameValue(papszCreationOptions, "COMPRESS");
    4298        5271 :         if (pszCompress && EQUAL(pszCompress, "WEBP"))
    4299             :         {
    4300          31 :             if (GTiffGetWebPLossless(papszCreationOptions))
    4301             :             {
    4302           6 :                 AppendMetadataItem(&psRoot, &psTail,
    4303             :                                    "COMPRESSION_REVERSIBILITY", "LOSSLESS", 0,
    4304             :                                    nullptr, "IMAGE_STRUCTURE");
    4305             :             }
    4306             :             else
    4307             :             {
    4308          25 :                 AppendMetadataItem(
    4309             :                     &psRoot, &psTail, "WEBP_LEVEL",
    4310          25 :                     CPLSPrintf("%d", GTiffGetWebPLevel(papszCreationOptions)),
    4311             :                     0, nullptr, "IMAGE_STRUCTURE");
    4312             :             }
    4313             :         }
    4314        5240 :         else if (pszCompress && STARTS_WITH_CI(pszCompress, "LERC"))
    4315             :         {
    4316             :             const double dfMaxZError =
    4317          97 :                 GTiffGetLERCMaxZError(papszCreationOptions);
    4318             :             const double dfMaxZErrorOverview =
    4319          97 :                 GTiffGetLERCMaxZErrorOverview(papszCreationOptions);
    4320          97 :             if (dfMaxZError == 0.0 && dfMaxZErrorOverview == 0.0)
    4321             :             {
    4322          83 :                 AppendMetadataItem(&psRoot, &psTail,
    4323             :                                    "COMPRESSION_REVERSIBILITY", "LOSSLESS", 0,
    4324             :                                    nullptr, "IMAGE_STRUCTURE");
    4325             :             }
    4326             :             else
    4327             :             {
    4328          14 :                 AppendMetadataItem(&psRoot, &psTail, "MAX_Z_ERROR",
    4329             :                                    CSLFetchNameValueDef(papszCreationOptions,
    4330             :                                                         "MAX_Z_ERROR", ""),
    4331             :                                    0, nullptr, "IMAGE_STRUCTURE");
    4332          14 :                 if (dfMaxZError != dfMaxZErrorOverview)
    4333             :                 {
    4334           3 :                     AppendMetadataItem(
    4335             :                         &psRoot, &psTail, "MAX_Z_ERROR_OVERVIEW",
    4336             :                         CSLFetchNameValueDef(papszCreationOptions,
    4337             :                                              "MAX_Z_ERROR_OVERVIEW", ""),
    4338             :                         0, nullptr, "IMAGE_STRUCTURE");
    4339             :                 }
    4340          97 :             }
    4341             :         }
    4342             : #if HAVE_JXL
    4343        5143 :         else if (pszCompress && EQUAL(pszCompress, "JXL"))
    4344             :         {
    4345          98 :             float fDistance = 0.0f;
    4346          98 :             if (GTiffGetJXLLossless(papszCreationOptions))
    4347             :             {
    4348          80 :                 AppendMetadataItem(&psRoot, &psTail,
    4349             :                                    "COMPRESSION_REVERSIBILITY", "LOSSLESS", 0,
    4350             :                                    nullptr, "IMAGE_STRUCTURE");
    4351             :             }
    4352             :             else
    4353             :             {
    4354          18 :                 fDistance = GTiffGetJXLDistance(papszCreationOptions);
    4355          18 :                 AppendMetadataItem(&psRoot, &psTail, "JXL_DISTANCE",
    4356             :                                    CPLSPrintf("%f", fDistance), 0, nullptr,
    4357             :                                    "IMAGE_STRUCTURE");
    4358             :             }
    4359             :             const float fAlphaDistance =
    4360          98 :                 GTiffGetJXLAlphaDistance(papszCreationOptions);
    4361          98 :             if (fAlphaDistance >= 0.0f && fAlphaDistance != fDistance)
    4362             :             {
    4363           2 :                 AppendMetadataItem(&psRoot, &psTail, "JXL_ALPHA_DISTANCE",
    4364             :                                    CPLSPrintf("%f", fAlphaDistance), 0, nullptr,
    4365             :                                    "IMAGE_STRUCTURE");
    4366             :             }
    4367          98 :             AppendMetadataItem(
    4368             :                 &psRoot, &psTail, "JXL_EFFORT",
    4369             :                 CPLSPrintf("%d", GTiffGetJXLEffort(papszCreationOptions)), 0,
    4370             :                 nullptr, "IMAGE_STRUCTURE");
    4371             :         }
    4372             : #endif
    4373             :     }
    4374             : 
    4375             :     /* -------------------------------------------------------------------- */
    4376             :     /*      Write out the generic XML metadata if there is any.             */
    4377             :     /* -------------------------------------------------------------------- */
    4378        5276 :     if (psRoot != nullptr)
    4379             :     {
    4380         607 :         bool bRet = true;
    4381             : 
    4382         607 :         if (eProfile == GTiffProfile::GDALGEOTIFF)
    4383             :         {
    4384         590 :             char *pszXML_MD = CPLSerializeXMLTree(psRoot);
    4385         590 :             TIFFSetField(l_hTIFF, TIFFTAG_GDAL_METADATA, pszXML_MD);
    4386         590 :             CPLFree(pszXML_MD);
    4387             :         }
    4388             :         else
    4389             :         {
    4390          17 :             if (bSrcIsGeoTIFF)
    4391          11 :                 cpl::down_cast<GTiffDataset *>(poSrcDS)->PushMetadataToPam();
    4392             :             else
    4393           6 :                 bRet = false;
    4394             :         }
    4395             : 
    4396         607 :         CPLDestroyXMLNode(psRoot);
    4397             : 
    4398         607 :         return bRet;
    4399             :     }
    4400             : 
    4401             :     // If we have no more metadata but it existed before,
    4402             :     // remove the GDAL_METADATA tag.
    4403        4669 :     if (eProfile == GTiffProfile::GDALGEOTIFF)
    4404             :     {
    4405        4645 :         char *pszText = nullptr;
    4406        4645 :         if (TIFFGetField(l_hTIFF, TIFFTAG_GDAL_METADATA, &pszText))
    4407             :         {
    4408           6 :             TIFFUnsetField(l_hTIFF, TIFFTAG_GDAL_METADATA);
    4409             :         }
    4410             :     }
    4411             : 
    4412        4669 :     return true;
    4413             : }
    4414             : 
    4415             : /************************************************************************/
    4416             : /*                         PushMetadataToPam()                          */
    4417             : /*                                                                      */
    4418             : /*      When producing a strict profile TIFF or if our aggregate        */
    4419             : /*      metadata is too big for a single tiff tag we may end up         */
    4420             : /*      needing to write it via the PAM mechanisms.  This method        */
    4421             : /*      copies all the appropriate metadata into the PAM level          */
    4422             : /*      metadata object but with special care to avoid copying          */
    4423             : /*      metadata handled in other ways in TIFF format.                  */
    4424             : /************************************************************************/
    4425             : 
    4426          20 : void GTiffDataset::PushMetadataToPam()
    4427             : 
    4428             : {
    4429          20 :     if (GetPamFlags() & GPF_DISABLED)
    4430           0 :         return;
    4431             : 
    4432          20 :     const bool bStandardColorInterp = GTIFFIsStandardColorInterpretation(
    4433          20 :         GDALDataset::ToHandle(this), m_nPhotometric, m_papszCreationOptions);
    4434             : 
    4435          66 :     for (int nBand = 0; nBand <= GetRasterCount(); ++nBand)
    4436             :     {
    4437          46 :         GDALMultiDomainMetadata *poSrcMDMD = nullptr;
    4438          46 :         GTiffRasterBand *poBand = nullptr;
    4439             : 
    4440          46 :         if (nBand == 0)
    4441             :         {
    4442          20 :             poSrcMDMD = &(this->m_oGTiffMDMD);
    4443             :         }
    4444             :         else
    4445             :         {
    4446          26 :             poBand = cpl::down_cast<GTiffRasterBand *>(GetRasterBand(nBand));
    4447          26 :             poSrcMDMD = &(poBand->m_oGTiffMDMD);
    4448             :         }
    4449             : 
    4450             :         /* --------------------------------------------------------------------
    4451             :          */
    4452             :         /*      Loop over the available domains. */
    4453             :         /* --------------------------------------------------------------------
    4454             :          */
    4455          46 :         CSLConstList papszDomainList = poSrcMDMD->GetDomainList();
    4456          96 :         for (int iDomain = 0; papszDomainList && papszDomainList[iDomain];
    4457             :              ++iDomain)
    4458             :         {
    4459          50 :             char **papszMD = poSrcMDMD->GetMetadata(papszDomainList[iDomain]);
    4460             : 
    4461          50 :             if (EQUAL(papszDomainList[iDomain], MD_DOMAIN_RPC) ||
    4462          50 :                 EQUAL(papszDomainList[iDomain], MD_DOMAIN_IMD) ||
    4463          50 :                 EQUAL(papszDomainList[iDomain], "_temporary_") ||
    4464          50 :                 EQUAL(papszDomainList[iDomain], "IMAGE_STRUCTURE") ||
    4465          30 :                 EQUAL(papszDomainList[iDomain], "COLOR_PROFILE"))
    4466          20 :                 continue;
    4467             : 
    4468          30 :             papszMD = CSLDuplicate(papszMD);
    4469             : 
    4470         105 :             for (int i = CSLCount(papszMD) - 1; i >= 0; --i)
    4471             :             {
    4472          75 :                 if (STARTS_WITH_CI(papszMD[i], "TIFFTAG_") ||
    4473          75 :                     EQUALN(papszMD[i], GDALMD_AREA_OR_POINT,
    4474             :                            strlen(GDALMD_AREA_OR_POINT)))
    4475           4 :                     papszMD = CSLRemoveStrings(papszMD, i, 1, nullptr);
    4476             :             }
    4477             : 
    4478          30 :             if (nBand == 0)
    4479          16 :                 GDALPamDataset::SetMetadata(papszMD, papszDomainList[iDomain]);
    4480             :             else
    4481          14 :                 poBand->GDALPamRasterBand::SetMetadata(
    4482          14 :                     papszMD, papszDomainList[iDomain]);
    4483             : 
    4484          30 :             CSLDestroy(papszMD);
    4485             :         }
    4486             : 
    4487             :         /* --------------------------------------------------------------------
    4488             :          */
    4489             :         /*      Handle some "special domain" stuff. */
    4490             :         /* --------------------------------------------------------------------
    4491             :          */
    4492          46 :         if (poBand != nullptr)
    4493             :         {
    4494          26 :             poBand->GDALPamRasterBand::SetOffset(poBand->GetOffset());
    4495          26 :             poBand->GDALPamRasterBand::SetScale(poBand->GetScale());
    4496          26 :             poBand->GDALPamRasterBand::SetUnitType(poBand->GetUnitType());
    4497          26 :             poBand->GDALPamRasterBand::SetDescription(poBand->GetDescription());
    4498          26 :             if (!bStandardColorInterp)
    4499             :             {
    4500           3 :                 poBand->GDALPamRasterBand::SetColorInterpretation(
    4501           3 :                     poBand->GetColorInterpretation());
    4502             :             }
    4503             :         }
    4504             :     }
    4505          20 :     MarkPamDirty();
    4506             : }
    4507             : 
    4508             : /************************************************************************/
    4509             : /*                         WriteNoDataValue()                           */
    4510             : /************************************************************************/
    4511             : 
    4512         386 : void GTiffDataset::WriteNoDataValue(TIFF *hTIFF, double dfNoData)
    4513             : 
    4514             : {
    4515         772 :     CPLString osVal(GTiffFormatGDALNoDataTagValue(dfNoData));
    4516         386 :     TIFFSetField(hTIFF, TIFFTAG_GDAL_NODATA, osVal.c_str());
    4517         386 : }
    4518             : 
    4519           2 : void GTiffDataset::WriteNoDataValue(TIFF *hTIFF, int64_t nNoData)
    4520             : 
    4521             : {
    4522           2 :     TIFFSetField(hTIFF, TIFFTAG_GDAL_NODATA,
    4523             :                  CPLSPrintf(CPL_FRMT_GIB, static_cast<GIntBig>(nNoData)));
    4524           2 : }
    4525             : 
    4526           2 : void GTiffDataset::WriteNoDataValue(TIFF *hTIFF, uint64_t nNoData)
    4527             : 
    4528             : {
    4529           2 :     TIFFSetField(hTIFF, TIFFTAG_GDAL_NODATA,
    4530             :                  CPLSPrintf(CPL_FRMT_GUIB, static_cast<GUIntBig>(nNoData)));
    4531           2 : }
    4532             : 
    4533             : /************************************************************************/
    4534             : /*                         UnsetNoDataValue()                           */
    4535             : /************************************************************************/
    4536             : 
    4537           1 : void GTiffDataset::UnsetNoDataValue(TIFF *l_hTIFF)
    4538             : 
    4539             : {
    4540           1 :     TIFFUnsetField(l_hTIFF, TIFFTAG_GDAL_NODATA);
    4541           1 : }
    4542             : 
    4543             : /************************************************************************/
    4544             : /*                             SaveICCProfile()                         */
    4545             : /*                                                                      */
    4546             : /*      Save ICC Profile or colorimetric data into file                 */
    4547             : /* pDS:                                                                 */
    4548             : /*      Dataset that contains the metadata with the ICC or colorimetric */
    4549             : /*      data. If this argument is specified, all other arguments are    */
    4550             : /*      ignored. Set them to NULL or 0.                                 */
    4551             : /* hTIFF:                                                               */
    4552             : /*      Pointer to TIFF handle. Only needed if pDS is NULL or           */
    4553             : /*      pDS->m_hTIFF is NULL.                                             */
    4554             : /* papszParamList:                                                       */
    4555             : /*      Options containing the ICC profile or colorimetric metadata.    */
    4556             : /*      Ignored if pDS is not NULL.                                     */
    4557             : /* nBitsPerSample:                                                      */
    4558             : /*      Bits per sample. Ignored if pDS is not NULL.                    */
    4559             : /************************************************************************/
    4560             : 
    4561        7092 : void GTiffDataset::SaveICCProfile(GTiffDataset *pDS, TIFF *l_hTIFF,
    4562             :                                   char **papszParamList,
    4563             :                                   uint32_t l_nBitsPerSample)
    4564             : {
    4565        7092 :     if ((pDS != nullptr) && (pDS->eAccess != GA_Update))
    4566           0 :         return;
    4567             : 
    4568        7092 :     if (l_hTIFF == nullptr)
    4569             :     {
    4570           2 :         if (pDS == nullptr)
    4571           0 :             return;
    4572             : 
    4573           2 :         l_hTIFF = pDS->m_hTIFF;
    4574           2 :         if (l_hTIFF == nullptr)
    4575           0 :             return;
    4576             :     }
    4577             : 
    4578        7092 :     if ((papszParamList == nullptr) && (pDS == nullptr))
    4579        2483 :         return;
    4580             : 
    4581        4609 :     const char *pszValue = nullptr;
    4582        4609 :     if (pDS != nullptr)
    4583           2 :         pszValue = pDS->GetMetadataItem("SOURCE_ICC_PROFILE", "COLOR_PROFILE");
    4584             :     else
    4585        4607 :         pszValue = CSLFetchNameValue(papszParamList, "SOURCE_ICC_PROFILE");
    4586        4609 :     if (pszValue != nullptr)
    4587             :     {
    4588           8 :         char *pEmbedBuffer = CPLStrdup(pszValue);
    4589             :         int32_t nEmbedLen =
    4590           8 :             CPLBase64DecodeInPlace(reinterpret_cast<GByte *>(pEmbedBuffer));
    4591             : 
    4592           8 :         TIFFSetField(l_hTIFF, TIFFTAG_ICCPROFILE, nEmbedLen, pEmbedBuffer);
    4593             : 
    4594           8 :         CPLFree(pEmbedBuffer);
    4595             :     }
    4596             :     else
    4597             :     {
    4598             :         // Output colorimetric data.
    4599        4601 :         float pCHR[6] = {};     // Primaries.
    4600        4601 :         uint16_t pTXR[6] = {};  // Transfer range.
    4601        4601 :         const char *pszCHRNames[] = {"SOURCE_PRIMARIES_RED",
    4602             :                                      "SOURCE_PRIMARIES_GREEN",
    4603             :                                      "SOURCE_PRIMARIES_BLUE"};
    4604        4601 :         const char *pszTXRNames[] = {"TIFFTAG_TRANSFERRANGE_BLACK",
    4605             :                                      "TIFFTAG_TRANSFERRANGE_WHITE"};
    4606             : 
    4607             :         // Output chromacities.
    4608        4601 :         bool bOutputCHR = true;
    4609        4616 :         for (int i = 0; i < 3 && bOutputCHR; ++i)
    4610             :         {
    4611        4611 :             if (pDS != nullptr)
    4612             :                 pszValue =
    4613           3 :                     pDS->GetMetadataItem(pszCHRNames[i], "COLOR_PROFILE");
    4614             :             else
    4615        4608 :                 pszValue = CSLFetchNameValue(papszParamList, pszCHRNames[i]);
    4616        4611 :             if (pszValue == nullptr)
    4617             :             {
    4618        4596 :                 bOutputCHR = false;
    4619        4596 :                 break;
    4620             :             }
    4621             : 
    4622          15 :             char **papszTokens = CSLTokenizeString2(pszValue, ",",
    4623             :                                                     CSLT_ALLOWEMPTYTOKENS |
    4624             :                                                         CSLT_STRIPLEADSPACES |
    4625             :                                                         CSLT_STRIPENDSPACES);
    4626             : 
    4627          15 :             if (CSLCount(papszTokens) != 3)
    4628             :             {
    4629           0 :                 bOutputCHR = false;
    4630           0 :                 CSLDestroy(papszTokens);
    4631           0 :                 break;
    4632             :             }
    4633             : 
    4634          60 :             for (int j = 0; j < 3; ++j)
    4635             :             {
    4636          45 :                 float v = static_cast<float>(CPLAtof(papszTokens[j]));
    4637             : 
    4638          45 :                 if (j == 2)
    4639             :                 {
    4640             :                     // Last term of xyY color must be 1.0.
    4641          15 :                     if (v != 1.0)
    4642             :                     {
    4643           0 :                         bOutputCHR = false;
    4644           0 :                         break;
    4645             :                     }
    4646             :                 }
    4647             :                 else
    4648             :                 {
    4649          30 :                     pCHR[i * 2 + j] = v;
    4650             :                 }
    4651             :             }
    4652             : 
    4653          15 :             CSLDestroy(papszTokens);
    4654             :         }
    4655             : 
    4656        4601 :         if (bOutputCHR)
    4657             :         {
    4658           5 :             TIFFSetField(l_hTIFF, TIFFTAG_PRIMARYCHROMATICITIES, pCHR);
    4659             :         }
    4660             : 
    4661             :         // Output whitepoint.
    4662        4601 :         if (pDS != nullptr)
    4663             :             pszValue =
    4664           1 :                 pDS->GetMetadataItem("SOURCE_WHITEPOINT", "COLOR_PROFILE");
    4665             :         else
    4666        4600 :             pszValue = CSLFetchNameValue(papszParamList, "SOURCE_WHITEPOINT");
    4667        4601 :         if (pszValue != nullptr)
    4668             :         {
    4669           5 :             char **papszTokens = CSLTokenizeString2(pszValue, ",",
    4670             :                                                     CSLT_ALLOWEMPTYTOKENS |
    4671             :                                                         CSLT_STRIPLEADSPACES |
    4672             :                                                         CSLT_STRIPENDSPACES);
    4673             : 
    4674           5 :             bool bOutputWhitepoint = true;
    4675           5 :             float pWP[2] = {0.0f, 0.0f};  // Whitepoint
    4676           5 :             if (CSLCount(papszTokens) != 3)
    4677             :             {
    4678           0 :                 bOutputWhitepoint = false;
    4679             :             }
    4680             :             else
    4681             :             {
    4682          20 :                 for (int j = 0; j < 3; ++j)
    4683             :                 {
    4684          15 :                     const float v = static_cast<float>(CPLAtof(papszTokens[j]));
    4685             : 
    4686          15 :                     if (j == 2)
    4687             :                     {
    4688             :                         // Last term of xyY color must be 1.0.
    4689           5 :                         if (v != 1.0)
    4690             :                         {
    4691           0 :                             bOutputWhitepoint = false;
    4692           0 :                             break;
    4693             :                         }
    4694             :                     }
    4695             :                     else
    4696             :                     {
    4697          10 :                         pWP[j] = v;
    4698             :                     }
    4699             :                 }
    4700             :             }
    4701           5 :             CSLDestroy(papszTokens);
    4702             : 
    4703           5 :             if (bOutputWhitepoint)
    4704             :             {
    4705           5 :                 TIFFSetField(l_hTIFF, TIFFTAG_WHITEPOINT, pWP);
    4706             :             }
    4707             :         }
    4708             : 
    4709             :         // Set transfer function metadata.
    4710        4601 :         char const *pszTFRed = nullptr;
    4711        4601 :         if (pDS != nullptr)
    4712           1 :             pszTFRed = pDS->GetMetadataItem("TIFFTAG_TRANSFERFUNCTION_RED",
    4713             :                                             "COLOR_PROFILE");
    4714             :         else
    4715        4600 :             pszTFRed = CSLFetchNameValue(papszParamList,
    4716             :                                          "TIFFTAG_TRANSFERFUNCTION_RED");
    4717             : 
    4718        4601 :         char const *pszTFGreen = nullptr;
    4719        4601 :         if (pDS != nullptr)
    4720           1 :             pszTFGreen = pDS->GetMetadataItem("TIFFTAG_TRANSFERFUNCTION_GREEN",
    4721             :                                               "COLOR_PROFILE");
    4722             :         else
    4723        4600 :             pszTFGreen = CSLFetchNameValue(papszParamList,
    4724             :                                            "TIFFTAG_TRANSFERFUNCTION_GREEN");
    4725             : 
    4726        4601 :         char const *pszTFBlue = nullptr;
    4727        4601 :         if (pDS != nullptr)
    4728           1 :             pszTFBlue = pDS->GetMetadataItem("TIFFTAG_TRANSFERFUNCTION_BLUE",
    4729             :                                              "COLOR_PROFILE");
    4730             :         else
    4731        4600 :             pszTFBlue = CSLFetchNameValue(papszParamList,
    4732             :                                           "TIFFTAG_TRANSFERFUNCTION_BLUE");
    4733             : 
    4734        4601 :         if ((pszTFRed != nullptr) && (pszTFGreen != nullptr) &&
    4735             :             (pszTFBlue != nullptr))
    4736             :         {
    4737             :             // Get length of table.
    4738           4 :             const int nTransferFunctionLength =
    4739           4 :                 1 << ((pDS != nullptr) ? pDS->m_nBitsPerSample
    4740             :                                        : l_nBitsPerSample);
    4741             : 
    4742           4 :             char **papszTokensRed = CSLTokenizeString2(
    4743             :                 pszTFRed, ",",
    4744             :                 CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES |
    4745             :                     CSLT_STRIPENDSPACES);
    4746           4 :             char **papszTokensGreen = CSLTokenizeString2(
    4747             :                 pszTFGreen, ",",
    4748             :                 CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES |
    4749             :                     CSLT_STRIPENDSPACES);
    4750           4 :             char **papszTokensBlue = CSLTokenizeString2(
    4751             :                 pszTFBlue, ",",
    4752             :                 CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES |
    4753             :                     CSLT_STRIPENDSPACES);
    4754             : 
    4755           4 :             if ((CSLCount(papszTokensRed) == nTransferFunctionLength) &&
    4756           8 :                 (CSLCount(papszTokensGreen) == nTransferFunctionLength) &&
    4757           4 :                 (CSLCount(papszTokensBlue) == nTransferFunctionLength))
    4758             :             {
    4759             :                 uint16_t *pTransferFuncRed = static_cast<uint16_t *>(
    4760           4 :                     CPLMalloc(sizeof(uint16_t) * nTransferFunctionLength));
    4761             :                 uint16_t *pTransferFuncGreen = static_cast<uint16_t *>(
    4762           4 :                     CPLMalloc(sizeof(uint16_t) * nTransferFunctionLength));
    4763             :                 uint16_t *pTransferFuncBlue = static_cast<uint16_t *>(
    4764           4 :                     CPLMalloc(sizeof(uint16_t) * nTransferFunctionLength));
    4765             : 
    4766             :                 // Convert our table in string format into int16_t format.
    4767        1028 :                 for (int i = 0; i < nTransferFunctionLength; ++i)
    4768             :                 {
    4769        1024 :                     pTransferFuncRed[i] =
    4770        1024 :                         static_cast<uint16_t>(atoi(papszTokensRed[i]));
    4771        1024 :                     pTransferFuncGreen[i] =
    4772        1024 :                         static_cast<uint16_t>(atoi(papszTokensGreen[i]));
    4773        1024 :                     pTransferFuncBlue[i] =
    4774        1024 :                         static_cast<uint16_t>(atoi(papszTokensBlue[i]));
    4775             :                 }
    4776             : 
    4777           4 :                 TIFFSetField(l_hTIFF, TIFFTAG_TRANSFERFUNCTION,
    4778             :                              pTransferFuncRed, pTransferFuncGreen,
    4779             :                              pTransferFuncBlue);
    4780             : 
    4781           4 :                 CPLFree(pTransferFuncRed);
    4782           4 :                 CPLFree(pTransferFuncGreen);
    4783           4 :                 CPLFree(pTransferFuncBlue);
    4784             :             }
    4785             : 
    4786           4 :             CSLDestroy(papszTokensRed);
    4787           4 :             CSLDestroy(papszTokensGreen);
    4788           4 :             CSLDestroy(papszTokensBlue);
    4789             :         }
    4790             : 
    4791             :         // Output transfer range.
    4792        4601 :         bool bOutputTransferRange = true;
    4793        4601 :         for (int i = 0; (i < 2) && bOutputTransferRange; ++i)
    4794             :         {
    4795        4601 :             if (pDS != nullptr)
    4796             :                 pszValue =
    4797           1 :                     pDS->GetMetadataItem(pszTXRNames[i], "COLOR_PROFILE");
    4798             :             else
    4799        4600 :                 pszValue = CSLFetchNameValue(papszParamList, pszTXRNames[i]);
    4800        4601 :             if (pszValue == nullptr)
    4801             :             {
    4802        4601 :                 bOutputTransferRange = false;
    4803        4601 :                 break;
    4804             :             }
    4805             : 
    4806           0 :             char **papszTokens = CSLTokenizeString2(pszValue, ",",
    4807             :                                                     CSLT_ALLOWEMPTYTOKENS |
    4808             :                                                         CSLT_STRIPLEADSPACES |
    4809             :                                                         CSLT_STRIPENDSPACES);
    4810             : 
    4811           0 :             if (CSLCount(papszTokens) != 3)
    4812             :             {
    4813           0 :                 bOutputTransferRange = false;
    4814           0 :                 CSLDestroy(papszTokens);
    4815           0 :                 break;
    4816             :             }
    4817             : 
    4818           0 :             for (int j = 0; j < 3; ++j)
    4819             :             {
    4820           0 :                 pTXR[i + j * 2] = static_cast<uint16_t>(atoi(papszTokens[j]));
    4821             :             }
    4822             : 
    4823           0 :             CSLDestroy(papszTokens);
    4824             :         }
    4825             : 
    4826        4601 :         if (bOutputTransferRange)
    4827             :         {
    4828           0 :             const int TIFFTAG_TRANSFERRANGE = 0x0156;
    4829           0 :             TIFFSetField(l_hTIFF, TIFFTAG_TRANSFERRANGE, pTXR);
    4830             :         }
    4831             :     }
    4832             : }
    4833             : 
    4834       12265 : static signed char GTiffGetLZMAPreset(char **papszOptions)
    4835             : {
    4836       12265 :     int nLZMAPreset = -1;
    4837       12265 :     const char *pszValue = CSLFetchNameValue(papszOptions, "LZMA_PRESET");
    4838       12265 :     if (pszValue != nullptr)
    4839             :     {
    4840          20 :         nLZMAPreset = atoi(pszValue);
    4841          20 :         if (!(nLZMAPreset >= 0 && nLZMAPreset <= 9))
    4842             :         {
    4843           0 :             CPLError(CE_Warning, CPLE_IllegalArg,
    4844             :                      "LZMA_PRESET=%s value not recognised, ignoring.",
    4845             :                      pszValue);
    4846           0 :             nLZMAPreset = -1;
    4847             :         }
    4848             :     }
    4849       12265 :     return static_cast<signed char>(nLZMAPreset);
    4850             : }
    4851             : 
    4852       12265 : static signed char GTiffGetZSTDPreset(char **papszOptions)
    4853             : {
    4854       12265 :     int nZSTDLevel = -1;
    4855       12265 :     const char *pszValue = CSLFetchNameValue(papszOptions, "ZSTD_LEVEL");
    4856       12265 :     if (pszValue != nullptr)
    4857             :     {
    4858          24 :         nZSTDLevel = atoi(pszValue);
    4859          24 :         if (!(nZSTDLevel >= 1 && nZSTDLevel <= 22))
    4860             :         {
    4861           0 :             CPLError(CE_Warning, CPLE_IllegalArg,
    4862             :                      "ZSTD_LEVEL=%s value not recognised, ignoring.", pszValue);
    4863           0 :             nZSTDLevel = -1;
    4864             :         }
    4865             :     }
    4866       12265 :     return static_cast<signed char>(nZSTDLevel);
    4867             : }
    4868             : 
    4869       12265 : static signed char GTiffGetZLevel(char **papszOptions)
    4870             : {
    4871       12265 :     int nZLevel = -1;
    4872       12265 :     const char *pszValue = CSLFetchNameValue(papszOptions, "ZLEVEL");
    4873       12265 :     if (pszValue != nullptr)
    4874             :     {
    4875          44 :         nZLevel = atoi(pszValue);
    4876             : #ifdef TIFFTAG_DEFLATE_SUBCODEC
    4877          44 :         constexpr int nMaxLevel = 12;
    4878             : #ifndef LIBDEFLATE_SUPPORT
    4879             :         if (nZLevel > 9 && nZLevel <= nMaxLevel)
    4880             :         {
    4881             :             CPLDebug("GTiff",
    4882             :                      "ZLEVEL=%d not supported in a non-libdeflate enabled "
    4883             :                      "libtiff build. Capping to 9",
    4884             :                      nZLevel);
    4885             :             nZLevel = 9;
    4886             :         }
    4887             : #endif
    4888             : #else
    4889             :         constexpr int nMaxLevel = 9;
    4890             : #endif
    4891          44 :         if (nZLevel < 1 || nZLevel > nMaxLevel)
    4892             :         {
    4893           0 :             CPLError(CE_Warning, CPLE_IllegalArg,
    4894             :                      "ZLEVEL=%s value not recognised, ignoring.", pszValue);
    4895           0 :             nZLevel = -1;
    4896             :         }
    4897             :     }
    4898       12265 :     return static_cast<signed char>(nZLevel);
    4899             : }
    4900             : 
    4901       12265 : static signed char GTiffGetJpegQuality(char **papszOptions)
    4902             : {
    4903       12265 :     int nJpegQuality = -1;
    4904       12265 :     const char *pszValue = CSLFetchNameValue(papszOptions, "JPEG_QUALITY");
    4905       12265 :     if (pszValue != nullptr)
    4906             :     {
    4907        1939 :         nJpegQuality = atoi(pszValue);
    4908        1939 :         if (nJpegQuality < 1 || nJpegQuality > 100)
    4909             :         {
    4910           0 :             CPLError(CE_Warning, CPLE_IllegalArg,
    4911             :                      "JPEG_QUALITY=%s value not recognised, ignoring.",
    4912             :                      pszValue);
    4913           0 :             nJpegQuality = -1;
    4914             :         }
    4915             :     }
    4916       12265 :     return static_cast<signed char>(nJpegQuality);
    4917             : }
    4918             : 
    4919       12265 : static signed char GTiffGetJpegTablesMode(char **papszOptions)
    4920             : {
    4921       12265 :     return static_cast<signed char>(atoi(
    4922             :         CSLFetchNameValueDef(papszOptions, "JPEGTABLESMODE",
    4923       12265 :                              CPLSPrintf("%d", knGTIFFJpegTablesModeDefault))));
    4924             : }
    4925             : 
    4926             : /************************************************************************/
    4927             : /*                        GetDiscardLsbOption()                         */
    4928             : /************************************************************************/
    4929             : 
    4930        5123 : static GTiffDataset::MaskOffset *GetDiscardLsbOption(TIFF *hTIFF,
    4931             :                                                      char **papszOptions)
    4932             : {
    4933        5123 :     const char *pszBits = CSLFetchNameValue(papszOptions, "DISCARD_LSB");
    4934        5123 :     if (pszBits == nullptr)
    4935        5001 :         return nullptr;
    4936             : 
    4937         122 :     uint16_t nPhotometric = 0;
    4938         122 :     TIFFGetFieldDefaulted(hTIFF, TIFFTAG_PHOTOMETRIC, &nPhotometric);
    4939             : 
    4940         122 :     uint16_t nBitsPerSample = 0;
    4941         122 :     if (!TIFFGetField(hTIFF, TIFFTAG_BITSPERSAMPLE, &nBitsPerSample))
    4942           0 :         nBitsPerSample = 1;
    4943             : 
    4944         122 :     uint16_t nSamplesPerPixel = 0;
    4945         122 :     if (!TIFFGetField(hTIFF, TIFFTAG_SAMPLESPERPIXEL, &nSamplesPerPixel))
    4946           0 :         nSamplesPerPixel = 1;
    4947             : 
    4948         122 :     uint16_t nSampleFormat = 0;
    4949         122 :     if (!TIFFGetField(hTIFF, TIFFTAG_SAMPLEFORMAT, &nSampleFormat))
    4950           0 :         nSampleFormat = SAMPLEFORMAT_UINT;
    4951             : 
    4952         122 :     if (nPhotometric == PHOTOMETRIC_PALETTE)
    4953             :     {
    4954           1 :         CPLError(CE_Warning, CPLE_AppDefined,
    4955             :                  "DISCARD_LSB ignored on a paletted image");
    4956           1 :         return nullptr;
    4957             :     }
    4958         121 :     if (!(nBitsPerSample == 8 || nBitsPerSample == 16 || nBitsPerSample == 32 ||
    4959          13 :           nBitsPerSample == 64))
    4960             :     {
    4961           1 :         CPLError(CE_Warning, CPLE_AppDefined,
    4962             :                  "DISCARD_LSB ignored on non 8, 16, 32 or 64 bits images");
    4963           1 :         return nullptr;
    4964             :     }
    4965             : 
    4966         240 :     const CPLStringList aosTokens(CSLTokenizeString2(pszBits, ",", 0));
    4967         120 :     const int nTokens = aosTokens.size();
    4968         120 :     GTiffDataset::MaskOffset *panMaskOffsetLsb = nullptr;
    4969         120 :     if (nTokens == 1 || nTokens == nSamplesPerPixel)
    4970             :     {
    4971             :         panMaskOffsetLsb = static_cast<GTiffDataset::MaskOffset *>(
    4972         119 :             CPLCalloc(nSamplesPerPixel, sizeof(GTiffDataset::MaskOffset)));
    4973         374 :         for (int i = 0; i < nSamplesPerPixel; ++i)
    4974             :         {
    4975         255 :             const int nBits = atoi(aosTokens[nTokens == 1 ? 0 : i]);
    4976         510 :             const int nMaxBits = (nSampleFormat == SAMPLEFORMAT_IEEEFP)
    4977         484 :                                      ? ((nBitsPerSample == 32)   ? 23 - 1
    4978          26 :                                         : (nBitsPerSample == 64) ? 53 - 1
    4979             :                                                                  : 0)
    4980         203 :                                  : nSampleFormat == SAMPLEFORMAT_INT
    4981         203 :                                      ? nBitsPerSample - 2
    4982         119 :                                      : nBitsPerSample - 1;
    4983             : 
    4984         255 :             if (nBits < 0 || nBits > nMaxBits)
    4985             :             {
    4986           0 :                 CPLError(
    4987             :                     CE_Warning, CPLE_AppDefined,
    4988             :                     "DISCARD_LSB ignored: values should be in [0,%d] range",
    4989             :                     nMaxBits);
    4990           0 :                 VSIFree(panMaskOffsetLsb);
    4991           0 :                 return nullptr;
    4992             :             }
    4993         255 :             panMaskOffsetLsb[i].nMask =
    4994         255 :                 ~((static_cast<uint64_t>(1) << nBits) - 1);
    4995         255 :             if (nBits > 1)
    4996             :             {
    4997         249 :                 panMaskOffsetLsb[i].nRoundUpBitTest = static_cast<uint64_t>(1)
    4998         249 :                                                       << (nBits - 1);
    4999             :             }
    5000         119 :         }
    5001             :     }
    5002             :     else
    5003             :     {
    5004           1 :         CPLError(CE_Warning, CPLE_AppDefined,
    5005             :                  "DISCARD_LSB ignored: wrong number of components");
    5006             :     }
    5007         120 :     return panMaskOffsetLsb;
    5008             : }
    5009             : 
    5010        5123 : void GTiffDataset::GetDiscardLsbOption(char **papszOptions)
    5011             : {
    5012        5123 :     m_panMaskOffsetLsb = ::GetDiscardLsbOption(m_hTIFF, papszOptions);
    5013        5123 : }
    5014             : 
    5015             : /************************************************************************/
    5016             : /*                             GetProfile()                             */
    5017             : /************************************************************************/
    5018             : 
    5019       12309 : static GTiffProfile GetProfile(const char *pszProfile)
    5020             : {
    5021       12309 :     GTiffProfile eProfile = GTiffProfile::GDALGEOTIFF;
    5022       12309 :     if (pszProfile != nullptr)
    5023             :     {
    5024          70 :         if (EQUAL(pszProfile, szPROFILE_BASELINE))
    5025          50 :             eProfile = GTiffProfile::BASELINE;
    5026          20 :         else if (EQUAL(pszProfile, szPROFILE_GeoTIFF))
    5027          18 :             eProfile = GTiffProfile::GEOTIFF;
    5028           2 :         else if (!EQUAL(pszProfile, szPROFILE_GDALGeoTIFF))
    5029             :         {
    5030           0 :             CPLError(CE_Warning, CPLE_NotSupported,
    5031             :                      "Unsupported value for PROFILE: %s", pszProfile);
    5032             :         }
    5033             :     }
    5034       12309 :     return eProfile;
    5035             : }
    5036             : 
    5037             : /************************************************************************/
    5038             : /*                            GTiffCreate()                             */
    5039             : /*                                                                      */
    5040             : /*      Shared functionality between GTiffDataset::Create() and         */
    5041             : /*      GTiffCreateCopy() for creating TIFF file based on a set of      */
    5042             : /*      options and a configuration.                                    */
    5043             : /************************************************************************/
    5044             : 
    5045        7158 : TIFF *GTiffDataset::CreateLL(const char *pszFilename, int nXSize, int nYSize,
    5046             :                              int l_nBands, GDALDataType eType,
    5047             :                              double dfExtraSpaceForOverviews,
    5048             :                              int nColorTableMultiplier, char **papszParamList,
    5049             :                              VSILFILE **pfpL, CPLString &l_osTmpFilename,
    5050             :                              bool bCreateCopy, bool &bTileInterleavingOut)
    5051             : 
    5052             : {
    5053        7158 :     bTileInterleavingOut = false;
    5054             : 
    5055        7158 :     GTiffOneTimeInit();
    5056             : 
    5057             :     /* -------------------------------------------------------------------- */
    5058             :     /*      Blow on a few errors.                                           */
    5059             :     /* -------------------------------------------------------------------- */
    5060        7158 :     if (nXSize < 1 || nYSize < 1 || l_nBands < 1)
    5061             :     {
    5062           1 :         ReportError(
    5063             :             pszFilename, CE_Failure, CPLE_AppDefined,
    5064             :             "Attempt to create %dx%dx%d TIFF file, but width, height and bands"
    5065             :             "must be positive.",
    5066             :             nXSize, nYSize, l_nBands);
    5067             : 
    5068           1 :         return nullptr;
    5069             :     }
    5070             : 
    5071        7157 :     if (l_nBands > 65535)
    5072             :     {
    5073           1 :         ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
    5074             :                     "Attempt to create %dx%dx%d TIFF file, but bands "
    5075             :                     "must be lesser or equal to 65535.",
    5076             :                     nXSize, nYSize, l_nBands);
    5077             : 
    5078           1 :         return nullptr;
    5079             :     }
    5080             : 
    5081             :     /* -------------------------------------------------------------------- */
    5082             :     /*      Setup values based on options.                                  */
    5083             :     /* -------------------------------------------------------------------- */
    5084             :     const GTiffProfile eProfile =
    5085        7156 :         GetProfile(CSLFetchNameValue(papszParamList, "PROFILE"));
    5086             : 
    5087        7156 :     const bool bTiled = CPLFetchBool(papszParamList, "TILED", false);
    5088             : 
    5089        7156 :     int l_nBlockXSize = 0;
    5090        7156 :     const char *pszValue = CSLFetchNameValue(papszParamList, "BLOCKXSIZE");
    5091        7156 :     if (pszValue != nullptr)
    5092             :     {
    5093         352 :         l_nBlockXSize = atoi(pszValue);
    5094         352 :         if (l_nBlockXSize < 0)
    5095             :         {
    5096           0 :             ReportError(pszFilename, CE_Failure, CPLE_IllegalArg,
    5097             :                         "Invalid value for BLOCKXSIZE");
    5098           0 :             return nullptr;
    5099             :         }
    5100             :     }
    5101             : 
    5102        7156 :     int l_nBlockYSize = 0;
    5103        7156 :     pszValue = CSLFetchNameValue(papszParamList, "BLOCKYSIZE");
    5104        7156 :     if (pszValue != nullptr)
    5105             :     {
    5106        2423 :         l_nBlockYSize = atoi(pszValue);
    5107        2423 :         if (l_nBlockYSize < 0)
    5108             :         {
    5109           0 :             ReportError(pszFilename, CE_Failure, CPLE_IllegalArg,
    5110             :                         "Invalid value for BLOCKYSIZE");
    5111           0 :             return nullptr;
    5112             :         }
    5113             :     }
    5114             : 
    5115        7156 :     if (bTiled)
    5116             :     {
    5117         647 :         if (l_nBlockXSize == 0)
    5118         304 :             l_nBlockXSize = 256;
    5119             : 
    5120         647 :         if (l_nBlockYSize == 0)
    5121         303 :             l_nBlockYSize = 256;
    5122             :     }
    5123             : 
    5124        7156 :     int nPlanar = 0;
    5125             : 
    5126             :     // Hidden @TILE_INTERLEAVE=YES parameter used by the COG driver
    5127        9103 :     if (bCreateCopy &&
    5128        7163 :         (pszValue = CSLFetchNameValue(papszParamList, "@TILE_INTERLEAVE")) &&
    5129           7 :         CPLTestBool(pszValue))
    5130             :     {
    5131           7 :         bTileInterleavingOut = true;
    5132           7 :         nPlanar = PLANARCONFIG_SEPARATE;
    5133             :     }
    5134             :     else
    5135             :     {
    5136        7149 :         pszValue = CSLFetchNameValue(papszParamList, "INTERLEAVE");
    5137        7149 :         if (pszValue != nullptr)
    5138             :         {
    5139         674 :             if (EQUAL(pszValue, "PIXEL"))
    5140         360 :                 nPlanar = PLANARCONFIG_CONTIG;
    5141         314 :             else if (EQUAL(pszValue, "BAND"))
    5142             :             {
    5143         313 :                 nPlanar = PLANARCONFIG_SEPARATE;
    5144             :             }
    5145           1 :             else if (EQUAL(pszValue, "BAND"))
    5146             :             {
    5147           0 :                 nPlanar = PLANARCONFIG_SEPARATE;
    5148             :             }
    5149             :             else
    5150             :             {
    5151           1 :                 ReportError(
    5152             :                     pszFilename, CE_Failure, CPLE_IllegalArg,
    5153             :                     "INTERLEAVE=%s unsupported, value must be PIXEL or BAND.",
    5154             :                     pszValue);
    5155           1 :                 return nullptr;
    5156             :             }
    5157             :         }
    5158             :         else
    5159             :         {
    5160        6475 :             nPlanar = PLANARCONFIG_CONTIG;
    5161             :         }
    5162             :     }
    5163             : 
    5164        7155 :     int l_nCompression = COMPRESSION_NONE;
    5165        7155 :     pszValue = CSLFetchNameValue(papszParamList, "COMPRESS");
    5166        7155 :     if (pszValue != nullptr)
    5167             :     {
    5168        3104 :         l_nCompression = GTIFFGetCompressionMethod(pszValue, "COMPRESS");
    5169        3104 :         if (l_nCompression < 0)
    5170           0 :             return nullptr;
    5171             :     }
    5172             : 
    5173        7155 :     constexpr int JPEG_MAX_DIMENSION = 65500;  // Defined in jpeglib.h
    5174        7155 :     constexpr int WEBP_MAX_DIMENSION = 16383;
    5175             : 
    5176             :     const struct
    5177             :     {
    5178             :         int nCodecID;
    5179             :         const char *pszCodecName;
    5180             :         int nMaxDim;
    5181        7155 :     } asLimitations[] = {
    5182             :         {COMPRESSION_JPEG, "JPEG", JPEG_MAX_DIMENSION},
    5183             :         {COMPRESSION_WEBP, "WEBP", WEBP_MAX_DIMENSION},
    5184             :     };
    5185             : 
    5186       21453 :     for (const auto &sLimitation : asLimitations)
    5187             :     {
    5188       14306 :         if (l_nCompression == sLimitation.nCodecID && !bTiled &&
    5189        2078 :             nXSize > sLimitation.nMaxDim)
    5190             :         {
    5191           2 :             ReportError(
    5192             :                 pszFilename, CE_Failure, CPLE_IllegalArg,
    5193             :                 "COMPRESS=%s is only compatible of un-tiled images whose "
    5194             :                 "width is lesser or equal to %d pixels. "
    5195             :                 "To overcome this limitation, set the TILED=YES creation "
    5196             :                 "option.",
    5197           2 :                 sLimitation.pszCodecName, sLimitation.nMaxDim);
    5198           2 :             return nullptr;
    5199             :         }
    5200       14304 :         else if (l_nCompression == sLimitation.nCodecID && bTiled &&
    5201          52 :                  l_nBlockXSize > sLimitation.nMaxDim)
    5202             :         {
    5203           2 :             ReportError(pszFilename, CE_Failure, CPLE_IllegalArg,
    5204             :                         "COMPRESS=%s is only compatible of tiled images whose "
    5205             :                         "BLOCKXSIZE is lesser or equal to %d pixels.",
    5206           2 :                         sLimitation.pszCodecName, sLimitation.nMaxDim);
    5207           2 :             return nullptr;
    5208             :         }
    5209       14302 :         else if (l_nCompression == sLimitation.nCodecID &&
    5210        2126 :                  l_nBlockYSize > sLimitation.nMaxDim)
    5211             :         {
    5212           4 :             ReportError(pszFilename, CE_Failure, CPLE_IllegalArg,
    5213             :                         "COMPRESS=%s is only compatible of images whose "
    5214             :                         "BLOCKYSIZE is lesser or equal to %d pixels. "
    5215             :                         "To overcome this limitation, set the TILED=YES "
    5216             :                         "creation option",
    5217           4 :                         sLimitation.pszCodecName, sLimitation.nMaxDim);
    5218           4 :             return nullptr;
    5219             :         }
    5220             :     }
    5221             : 
    5222             :     /* -------------------------------------------------------------------- */
    5223             :     /*      How many bits per sample?  We have a special case if NBITS      */
    5224             :     /*      specified for GDT_Byte, GDT_UInt16, GDT_UInt32.                 */
    5225             :     /* -------------------------------------------------------------------- */
    5226        7147 :     int l_nBitsPerSample = GDALGetDataTypeSizeBits(eType);
    5227        7147 :     if (CSLFetchNameValue(papszParamList, "NBITS") != nullptr)
    5228             :     {
    5229        1753 :         int nMinBits = 0;
    5230        1753 :         int nMaxBits = 0;
    5231        1753 :         l_nBitsPerSample = atoi(CSLFetchNameValue(papszParamList, "NBITS"));
    5232        1753 :         if (eType == GDT_Byte)
    5233             :         {
    5234         531 :             nMinBits = 1;
    5235         531 :             nMaxBits = 8;
    5236             :         }
    5237        1222 :         else if (eType == GDT_UInt16)
    5238             :         {
    5239        1202 :             nMinBits = 9;
    5240        1202 :             nMaxBits = 16;
    5241             :         }
    5242          20 :         else if (eType == GDT_UInt32)
    5243             :         {
    5244          14 :             nMinBits = 17;
    5245          14 :             nMaxBits = 32;
    5246             :         }
    5247           6 :         else if (eType == GDT_Float32)
    5248             :         {
    5249           6 :             if (l_nBitsPerSample != 16 && l_nBitsPerSample != 32)
    5250             :             {
    5251           1 :                 ReportError(pszFilename, CE_Warning, CPLE_NotSupported,
    5252             :                             "Only NBITS=16 is supported for data type Float32");
    5253           1 :                 l_nBitsPerSample = GDALGetDataTypeSizeBits(eType);
    5254             :             }
    5255             :         }
    5256             :         else
    5257             :         {
    5258           0 :             ReportError(pszFilename, CE_Warning, CPLE_NotSupported,
    5259             :                         "NBITS is not supported for data type %s",
    5260             :                         GDALGetDataTypeName(eType));
    5261           0 :             l_nBitsPerSample = GDALGetDataTypeSizeBits(eType);
    5262             :         }
    5263             : 
    5264        1753 :         if (nMinBits != 0)
    5265             :         {
    5266        1747 :             if (l_nBitsPerSample < nMinBits)
    5267             :             {
    5268           2 :                 ReportError(
    5269             :                     pszFilename, CE_Warning, CPLE_AppDefined,
    5270             :                     "NBITS=%d is invalid for data type %s. Using NBITS=%d",
    5271             :                     l_nBitsPerSample, GDALGetDataTypeName(eType), nMinBits);
    5272           2 :                 l_nBitsPerSample = nMinBits;
    5273             :             }
    5274        1745 :             else if (l_nBitsPerSample > nMaxBits)
    5275             :             {
    5276           3 :                 ReportError(
    5277             :                     pszFilename, CE_Warning, CPLE_AppDefined,
    5278             :                     "NBITS=%d is invalid for data type %s. Using NBITS=%d",
    5279             :                     l_nBitsPerSample, GDALGetDataTypeName(eType), nMaxBits);
    5280           3 :                 l_nBitsPerSample = nMaxBits;
    5281             :             }
    5282             :         }
    5283             :     }
    5284             : 
    5285             : #ifdef HAVE_JXL
    5286        7147 :     if ((l_nCompression == COMPRESSION_JXL ||
    5287         103 :          l_nCompression == COMPRESSION_JXL_DNG_1_7) &&
    5288             :         eType != GDT_Float32)
    5289             :     {
    5290             :         // Reflects tif_jxl's GetJXLDataType()
    5291          82 :         if (eType != GDT_Byte && eType != GDT_UInt16)
    5292             :         {
    5293           1 :             ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    5294             :                         "Data type %s not supported for JXL compression. Only "
    5295             :                         "Byte, UInt16, Float32 are supported",
    5296             :                         GDALGetDataTypeName(eType));
    5297           2 :             return nullptr;
    5298             :         }
    5299             : 
    5300             :         const struct
    5301             :         {
    5302             :             GDALDataType eDT;
    5303             :             int nBitsPerSample;
    5304          81 :         } asSupportedDTBitsPerSample[] = {
    5305             :             {GDT_Byte, 8},
    5306             :             {GDT_UInt16, 16},
    5307             :         };
    5308             : 
    5309         241 :         for (const auto &sSupportedDTBitsPerSample : asSupportedDTBitsPerSample)
    5310             :         {
    5311         161 :             if (eType == sSupportedDTBitsPerSample.eDT &&
    5312          81 :                 l_nBitsPerSample != sSupportedDTBitsPerSample.nBitsPerSample)
    5313             :             {
    5314           1 :                 ReportError(
    5315             :                     pszFilename, CE_Failure, CPLE_NotSupported,
    5316             :                     "Bits per sample=%d not supported for JXL compression. "
    5317             :                     "Only %d is supported for %s data type.",
    5318           1 :                     l_nBitsPerSample, sSupportedDTBitsPerSample.nBitsPerSample,
    5319             :                     GDALGetDataTypeName(eType));
    5320           1 :                 return nullptr;
    5321             :             }
    5322             :         }
    5323             :     }
    5324             : #endif
    5325             : 
    5326        7145 :     int nPredictor = PREDICTOR_NONE;
    5327        7145 :     pszValue = CSLFetchNameValue(papszParamList, "PREDICTOR");
    5328        7145 :     if (pszValue != nullptr)
    5329             :     {
    5330          27 :         nPredictor = atoi(pszValue);
    5331             :     }
    5332             : 
    5333        7145 :     if (nPredictor != PREDICTOR_NONE &&
    5334          14 :         l_nCompression != COMPRESSION_ADOBE_DEFLATE &&
    5335           2 :         l_nCompression != COMPRESSION_LZW &&
    5336           2 :         l_nCompression != COMPRESSION_LZMA &&
    5337             :         l_nCompression != COMPRESSION_ZSTD)
    5338             :     {
    5339           1 :         ReportError(pszFilename, CE_Warning, CPLE_NotSupported,
    5340             :                     "PREDICTOR option is ignored for COMPRESS=%s. "
    5341             :                     "Only valid for DEFLATE, LZW, LZMA or ZSTD",
    5342             :                     CSLFetchNameValueDef(papszParamList, "COMPRESS", "NONE"));
    5343             :     }
    5344             : 
    5345             :     // Do early checks as libtiff will only error out when starting to write.
    5346        7170 :     else if (nPredictor != PREDICTOR_NONE &&
    5347          26 :              CPLTestBool(
    5348             :                  CPLGetConfigOption("GDAL_GTIFF_PREDICTOR_CHECKS", "YES")))
    5349             :     {
    5350             : #if (TIFFLIB_VERSION > 20210416) || defined(INTERNAL_LIBTIFF)
    5351             : #define HAVE_PREDICTOR_2_FOR_64BIT
    5352             : #endif
    5353          26 :         if (nPredictor == 2)
    5354             :         {
    5355          22 :             if (l_nBitsPerSample != 8 && l_nBitsPerSample != 16 &&
    5356             :                 l_nBitsPerSample != 32
    5357             : #ifdef HAVE_PREDICTOR_2_FOR_64BIT
    5358           2 :                 && l_nBitsPerSample != 64
    5359             : #endif
    5360             :             )
    5361             :             {
    5362             : #if !defined(HAVE_PREDICTOR_2_FOR_64BIT)
    5363             :                 if (l_nBitsPerSample == 64)
    5364             :                 {
    5365             :                     ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
    5366             :                                 "PREDICTOR=2 is supported on 64 bit samples "
    5367             :                                 "starting with libtiff > 4.3.0.");
    5368             :                 }
    5369             :                 else
    5370             : #endif
    5371             :                 {
    5372           2 :                     const int nBITSHint = (l_nBitsPerSample < 8)    ? 8
    5373           1 :                                           : (l_nBitsPerSample < 16) ? 16
    5374           0 :                                           : (l_nBitsPerSample < 32) ? 32
    5375             :                                                                     : 64;
    5376           1 :                     ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
    5377             : #ifdef HAVE_PREDICTOR_2_FOR_64BIT
    5378             :                                 "PREDICTOR=2 is only supported with 8/16/32/64 "
    5379             :                                 "bit samples. You can specify the NBITS=%d "
    5380             :                                 "creation option to promote to the closest "
    5381             :                                 "supported bits per sample value.",
    5382             : #else
    5383             :                                 "PREDICTOR=2 is only supported with 8/16/32 "
    5384             :                                 "bit samples. You can specify the NBITS=%d "
    5385             :                                 "creation option to promote to the closest "
    5386             :                                 "supported bits per sample value.",
    5387             : #endif
    5388             :                                 nBITSHint);
    5389             :                 }
    5390           1 :                 return nullptr;
    5391             :             }
    5392             :         }
    5393           4 :         else if (nPredictor == 3)
    5394             :         {
    5395           3 :             if (eType != GDT_Float32 && eType != GDT_Float64)
    5396             :             {
    5397           1 :                 ReportError(
    5398             :                     pszFilename, CE_Failure, CPLE_AppDefined,
    5399             :                     "PREDICTOR=3 is only supported with Float32 or Float64.");
    5400           1 :                 return nullptr;
    5401             :             }
    5402             :         }
    5403             :         else
    5404             :         {
    5405           1 :             ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
    5406             :                         "PREDICTOR=%s is not supported.", pszValue);
    5407           1 :             return nullptr;
    5408             :         }
    5409             :     }
    5410             : 
    5411        7142 :     const int l_nZLevel = GTiffGetZLevel(papszParamList);
    5412        7142 :     const int l_nLZMAPreset = GTiffGetLZMAPreset(papszParamList);
    5413        7142 :     const int l_nZSTDLevel = GTiffGetZSTDPreset(papszParamList);
    5414        7142 :     const int l_nWebPLevel = GTiffGetWebPLevel(papszParamList);
    5415        7142 :     const bool l_bWebPLossless = GTiffGetWebPLossless(papszParamList);
    5416        7142 :     const int l_nJpegQuality = GTiffGetJpegQuality(papszParamList);
    5417        7142 :     const int l_nJpegTablesMode = GTiffGetJpegTablesMode(papszParamList);
    5418        7142 :     const double l_dfMaxZError = GTiffGetLERCMaxZError(papszParamList);
    5419             : #if HAVE_JXL
    5420        7142 :     const bool l_bJXLLossless = GTiffGetJXLLossless(papszParamList);
    5421        7142 :     const uint32_t l_nJXLEffort = GTiffGetJXLEffort(papszParamList);
    5422        7142 :     const float l_fJXLDistance = GTiffGetJXLDistance(papszParamList);
    5423        7142 :     const float l_fJXLAlphaDistance = GTiffGetJXLAlphaDistance(papszParamList);
    5424             : #endif
    5425             :     /* -------------------------------------------------------------------- */
    5426             :     /*      Streaming related code                                          */
    5427             :     /* -------------------------------------------------------------------- */
    5428       14284 :     const CPLString osOriFilename(pszFilename);
    5429       14284 :     bool bStreaming = strcmp(pszFilename, "/vsistdout/") == 0 ||
    5430        7142 :                       CPLFetchBool(papszParamList, "STREAMABLE_OUTPUT", false);
    5431             : #ifdef S_ISFIFO
    5432        7142 :     if (!bStreaming)
    5433             :     {
    5434             :         VSIStatBufL sStat;
    5435        7130 :         if (VSIStatExL(pszFilename, &sStat,
    5436        8008 :                        VSI_STAT_EXISTS_FLAG | VSI_STAT_NATURE_FLAG) == 0 &&
    5437         878 :             S_ISFIFO(sStat.st_mode))
    5438             :         {
    5439           0 :             bStreaming = true;
    5440             :         }
    5441             :     }
    5442             : #endif
    5443        7142 :     if (bStreaming && !EQUAL("NONE", CSLFetchNameValueDef(papszParamList,
    5444             :                                                           "COMPRESS", "NONE")))
    5445             :     {
    5446           1 :         ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    5447             :                     "Streaming only supported to uncompressed TIFF");
    5448           1 :         return nullptr;
    5449             :     }
    5450        7141 :     if (bStreaming && CPLFetchBool(papszParamList, "SPARSE_OK", false))
    5451             :     {
    5452           1 :         ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    5453             :                     "Streaming not supported with SPARSE_OK");
    5454           1 :         return nullptr;
    5455             :     }
    5456             :     const bool bCopySrcOverviews =
    5457        7140 :         CPLFetchBool(papszParamList, "COPY_SRC_OVERVIEWS", false);
    5458        7140 :     if (bStreaming && bCopySrcOverviews)
    5459             :     {
    5460           1 :         ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    5461             :                     "Streaming not supported with COPY_SRC_OVERVIEWS");
    5462           1 :         return nullptr;
    5463             :     }
    5464        7139 :     if (bStreaming)
    5465             :     {
    5466           9 :         l_osTmpFilename = VSIMemGenerateHiddenFilename("vsistdout.tif");
    5467           9 :         pszFilename = l_osTmpFilename.c_str();
    5468             :     }
    5469             : 
    5470             :     /* -------------------------------------------------------------------- */
    5471             :     /*      Compute the uncompressed size.                                  */
    5472             :     /* -------------------------------------------------------------------- */
    5473        7139 :     const unsigned nTileXCount =
    5474        7139 :         bTiled ? DIV_ROUND_UP(nXSize, l_nBlockXSize) : 0;
    5475        7139 :     const unsigned nTileYCount =
    5476        7139 :         bTiled ? DIV_ROUND_UP(nYSize, l_nBlockYSize) : 0;
    5477             :     const double dfUncompressedImageSize =
    5478        7139 :         (bTiled ? (static_cast<double>(nTileXCount) * nTileYCount *
    5479         643 :                    l_nBlockXSize * l_nBlockYSize)
    5480        6496 :                 : (nXSize * static_cast<double>(nYSize))) *
    5481        7139 :             l_nBands * GDALGetDataTypeSizeBytes(eType) +
    5482        7139 :         dfExtraSpaceForOverviews;
    5483             : 
    5484             :     /* -------------------------------------------------------------------- */
    5485             :     /*      Should the file be created as a bigtiff file?                   */
    5486             :     /* -------------------------------------------------------------------- */
    5487        7139 :     const char *pszBIGTIFF = CSLFetchNameValue(papszParamList, "BIGTIFF");
    5488             : 
    5489        7139 :     if (pszBIGTIFF == nullptr)
    5490        6765 :         pszBIGTIFF = "IF_NEEDED";
    5491             : 
    5492        7139 :     bool bCreateBigTIFF = false;
    5493        7139 :     if (EQUAL(pszBIGTIFF, "IF_NEEDED"))
    5494             :     {
    5495        6766 :         if (l_nCompression == COMPRESSION_NONE &&
    5496             :             dfUncompressedImageSize > 4200000000.0)
    5497          16 :             bCreateBigTIFF = true;
    5498             :     }
    5499         373 :     else if (EQUAL(pszBIGTIFF, "IF_SAFER"))
    5500             :     {
    5501         355 :         if (dfUncompressedImageSize > 2000000000.0)
    5502           1 :             bCreateBigTIFF = true;
    5503             :     }
    5504             :     else
    5505             :     {
    5506          18 :         bCreateBigTIFF = CPLTestBool(pszBIGTIFF);
    5507          18 :         if (!bCreateBigTIFF && l_nCompression == COMPRESSION_NONE &&
    5508             :             dfUncompressedImageSize > 4200000000.0)
    5509             :         {
    5510           2 :             ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    5511             :                         "The TIFF file will be larger than 4GB, so BigTIFF is "
    5512             :                         "necessary.  Creation failed.");
    5513           2 :             return nullptr;
    5514             :         }
    5515             :     }
    5516             : 
    5517        7137 :     if (bCreateBigTIFF)
    5518          31 :         CPLDebug("GTiff", "File being created as a BigTIFF.");
    5519             : 
    5520             :     /* -------------------------------------------------------------------- */
    5521             :     /*      Sanity check.                                                   */
    5522             :     /* -------------------------------------------------------------------- */
    5523        7137 :     if (bTiled)
    5524             :     {
    5525             :         // libtiff implementation limitation
    5526         643 :         if (nTileXCount > 0x80000000U / (bCreateBigTIFF ? 8 : 4) / nTileYCount)
    5527             :         {
    5528           1 :             ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    5529             :                         "File too large regarding tile size. This would result "
    5530             :                         "in a file with tile arrays larger than 2GB");
    5531           1 :             return nullptr;
    5532             :         }
    5533             :     }
    5534             : 
    5535             :     /* -------------------------------------------------------------------- */
    5536             :     /*      Check free space (only for big, non sparse, uncompressed)       */
    5537             :     /* -------------------------------------------------------------------- */
    5538        4050 :     if (l_nCompression == COMPRESSION_NONE && dfUncompressedImageSize >= 1e9 &&
    5539          18 :         !CPLFetchBool(papszParamList, "SPARSE_OK", false) &&
    5540           3 :         osOriFilename != "/vsistdout/" &&
    5541       11189 :         osOriFilename != "/vsistdout_redirect/" &&
    5542           3 :         CPLTestBool(CPLGetConfigOption("CHECK_DISK_FREE_SPACE", "TRUE")))
    5543             :     {
    5544             :         GIntBig nFreeDiskSpace =
    5545           2 :             VSIGetDiskFreeSpace(CPLGetDirnameSafe(pszFilename).c_str());
    5546           2 :         if (nFreeDiskSpace >= 0 && nFreeDiskSpace < dfUncompressedImageSize)
    5547             :         {
    5548           1 :             ReportError(pszFilename, CE_Failure, CPLE_FileIO,
    5549             :                         "Free disk space available is " CPL_FRMT_GIB " bytes, "
    5550             :                         "whereas " CPL_FRMT_GIB " are at least necessary. "
    5551             :                         "You can disable this check by defining the "
    5552             :                         "CHECK_DISK_FREE_SPACE configuration option to FALSE.",
    5553             :                         nFreeDiskSpace,
    5554             :                         static_cast<GIntBig>(dfUncompressedImageSize));
    5555           1 :             return nullptr;
    5556             :         }
    5557             :     }
    5558             : 
    5559             :     /* -------------------------------------------------------------------- */
    5560             :     /*      Check if the user wishes a particular endianness                */
    5561             :     /* -------------------------------------------------------------------- */
    5562             : 
    5563        7135 :     int eEndianness = ENDIANNESS_NATIVE;
    5564        7135 :     pszValue = CSLFetchNameValue(papszParamList, "ENDIANNESS");
    5565        7135 :     if (pszValue == nullptr)
    5566        7072 :         pszValue = CPLGetConfigOption("GDAL_TIFF_ENDIANNESS", nullptr);
    5567        7135 :     if (pszValue != nullptr)
    5568             :     {
    5569         123 :         if (EQUAL(pszValue, "LITTLE"))
    5570             :         {
    5571          36 :             eEndianness = ENDIANNESS_LITTLE;
    5572             :         }
    5573          87 :         else if (EQUAL(pszValue, "BIG"))
    5574             :         {
    5575           1 :             eEndianness = ENDIANNESS_BIG;
    5576             :         }
    5577          86 :         else if (EQUAL(pszValue, "INVERTED"))
    5578             :         {
    5579             : #ifdef CPL_LSB
    5580          82 :             eEndianness = ENDIANNESS_BIG;
    5581             : #else
    5582             :             eEndianness = ENDIANNESS_LITTLE;
    5583             : #endif
    5584             :         }
    5585           4 :         else if (!EQUAL(pszValue, "NATIVE"))
    5586             :         {
    5587           1 :             ReportError(pszFilename, CE_Warning, CPLE_NotSupported,
    5588             :                         "ENDIANNESS=%s not supported. Defaulting to NATIVE",
    5589             :                         pszValue);
    5590             :         }
    5591             :     }
    5592             : 
    5593             :     /* -------------------------------------------------------------------- */
    5594             :     /*      Try opening the dataset.                                        */
    5595             :     /* -------------------------------------------------------------------- */
    5596             : 
    5597             :     const bool bAppend =
    5598        7135 :         CPLFetchBool(papszParamList, "APPEND_SUBDATASET", false);
    5599             : 
    5600        7135 :     char szOpeningFlag[5] = {};
    5601        7135 :     strcpy(szOpeningFlag, bAppend ? "r+" : "w+");
    5602        7135 :     if (bCreateBigTIFF)
    5603          29 :         strcat(szOpeningFlag, "8");
    5604        7135 :     if (eEndianness == ENDIANNESS_BIG)
    5605          83 :         strcat(szOpeningFlag, "b");
    5606        7052 :     else if (eEndianness == ENDIANNESS_LITTLE)
    5607          36 :         strcat(szOpeningFlag, "l");
    5608             : 
    5609        7135 :     VSIErrorReset();
    5610        7135 :     VSILFILE *l_fpL = VSIFOpenExL(pszFilename, bAppend ? "r+b" : "w+b", true);
    5611        7135 :     if (l_fpL == nullptr)
    5612             :     {
    5613          15 :         VSIToCPLErrorWithMsg(CE_Failure, CPLE_OpenFailed,
    5614          30 :                              std::string("Attempt to create new tiff file `")
    5615          15 :                                  .append(pszFilename)
    5616          15 :                                  .append("' failed")
    5617             :                                  .c_str());
    5618          15 :         return nullptr;
    5619             :     }
    5620        7120 :     TIFF *l_hTIFF = VSI_TIFFOpen(pszFilename, szOpeningFlag, l_fpL);
    5621        7120 :     if (l_hTIFF == nullptr)
    5622             :     {
    5623           2 :         if (CPLGetLastErrorNo() == 0)
    5624           0 :             CPLError(CE_Failure, CPLE_OpenFailed,
    5625             :                      "Attempt to create new tiff file `%s' "
    5626             :                      "failed in XTIFFOpen().",
    5627             :                      pszFilename);
    5628           2 :         CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    5629           2 :         return nullptr;
    5630             :     }
    5631             : 
    5632        7118 :     if (bAppend)
    5633             :     {
    5634             :         // This is a bit of a hack to cause (*tif->tif_cleanup)(tif); to be
    5635             :         // called. See https://trac.osgeo.org/gdal/ticket/2055
    5636           5 :         TIFFSetField(l_hTIFF, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
    5637           5 :         TIFFFreeDirectory(l_hTIFF);
    5638           5 :         TIFFCreateDirectory(l_hTIFF);
    5639             :     }
    5640             : 
    5641             :     /* -------------------------------------------------------------------- */
    5642             :     /*      Do we have a custom pixel type (just used for signed byte now). */
    5643             :     /* -------------------------------------------------------------------- */
    5644        7118 :     const char *pszPixelType = CSLFetchNameValue(papszParamList, "PIXELTYPE");
    5645        7118 :     if (pszPixelType == nullptr)
    5646        7110 :         pszPixelType = "";
    5647        7118 :     if (eType == GDT_Byte && EQUAL(pszPixelType, "SIGNEDBYTE"))
    5648             :     {
    5649           8 :         CPLError(CE_Warning, CPLE_AppDefined,
    5650             :                  "Using PIXELTYPE=SIGNEDBYTE with Byte data type is deprecated "
    5651             :                  "(but still works). "
    5652             :                  "Using Int8 data type instead is now recommended.");
    5653             :     }
    5654             : 
    5655             :     /* -------------------------------------------------------------------- */
    5656             :     /*      Setup some standard flags.                                      */
    5657             :     /* -------------------------------------------------------------------- */
    5658        7118 :     TIFFSetField(l_hTIFF, TIFFTAG_IMAGEWIDTH, nXSize);
    5659        7118 :     TIFFSetField(l_hTIFF, TIFFTAG_IMAGELENGTH, nYSize);
    5660        7118 :     TIFFSetField(l_hTIFF, TIFFTAG_BITSPERSAMPLE, l_nBitsPerSample);
    5661             : 
    5662        7118 :     uint16_t l_nSampleFormat = 0;
    5663        7118 :     if ((eType == GDT_Byte && EQUAL(pszPixelType, "SIGNEDBYTE")) ||
    5664        7088 :         eType == GDT_Int8 || eType == GDT_Int16 || eType == GDT_Int32 ||
    5665             :         eType == GDT_Int64)
    5666         303 :         l_nSampleFormat = SAMPLEFORMAT_INT;
    5667        6815 :     else if (eType == GDT_CInt16 || eType == GDT_CInt32)
    5668         133 :         l_nSampleFormat = SAMPLEFORMAT_COMPLEXINT;
    5669        6682 :     else if (eType == GDT_Float32 || eType == GDT_Float64)
    5670         545 :         l_nSampleFormat = SAMPLEFORMAT_IEEEFP;
    5671        6137 :     else if (eType == GDT_CFloat32 || eType == GDT_CFloat64)
    5672         128 :         l_nSampleFormat = SAMPLEFORMAT_COMPLEXIEEEFP;
    5673             :     else
    5674        6009 :         l_nSampleFormat = SAMPLEFORMAT_UINT;
    5675             : 
    5676        7118 :     TIFFSetField(l_hTIFF, TIFFTAG_SAMPLEFORMAT, l_nSampleFormat);
    5677        7118 :     TIFFSetField(l_hTIFF, TIFFTAG_SAMPLESPERPIXEL, l_nBands);
    5678        7118 :     TIFFSetField(l_hTIFF, TIFFTAG_PLANARCONFIG, nPlanar);
    5679             : 
    5680             :     /* -------------------------------------------------------------------- */
    5681             :     /*      Setup Photometric Interpretation. Take this value from the user */
    5682             :     /*      passed option or guess correct value otherwise.                 */
    5683             :     /* -------------------------------------------------------------------- */
    5684        7118 :     int nSamplesAccountedFor = 1;
    5685        7118 :     bool bForceColorTable = false;
    5686             : 
    5687        7118 :     pszValue = CSLFetchNameValue(papszParamList, "PHOTOMETRIC");
    5688        7118 :     if (pszValue != nullptr)
    5689             :     {
    5690        1888 :         if (EQUAL(pszValue, "MINISBLACK"))
    5691          14 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
    5692        1874 :         else if (EQUAL(pszValue, "MINISWHITE"))
    5693             :         {
    5694           2 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISWHITE);
    5695             :         }
    5696        1872 :         else if (EQUAL(pszValue, "PALETTE"))
    5697             :         {
    5698           5 :             if (eType == GDT_Byte || eType == GDT_UInt16)
    5699             :             {
    5700           4 :                 TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
    5701           4 :                 nSamplesAccountedFor = 1;
    5702           4 :                 bForceColorTable = true;
    5703             :             }
    5704             :             else
    5705             :             {
    5706           1 :                 ReportError(
    5707             :                     pszFilename, CE_Warning, CPLE_AppDefined,
    5708             :                     "PHOTOMETRIC=PALETTE only compatible with Byte or UInt16");
    5709             :             }
    5710             :         }
    5711        1867 :         else if (EQUAL(pszValue, "RGB"))
    5712             :         {
    5713        1123 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
    5714        1123 :             nSamplesAccountedFor = 3;
    5715             :         }
    5716         744 :         else if (EQUAL(pszValue, "CMYK"))
    5717             :         {
    5718          10 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_SEPARATED);
    5719          10 :             nSamplesAccountedFor = 4;
    5720             :         }
    5721         734 :         else if (EQUAL(pszValue, "YCBCR"))
    5722             :         {
    5723             :             // Because of subsampling, setting YCBCR without JPEG compression
    5724             :             // leads to a crash currently. Would need to make
    5725             :             // GTiffRasterBand::IWriteBlock() aware of subsampling so that it
    5726             :             // doesn't overrun buffer size returned by libtiff.
    5727         733 :             if (l_nCompression != COMPRESSION_JPEG)
    5728             :             {
    5729           1 :                 ReportError(
    5730             :                     pszFilename, CE_Failure, CPLE_NotSupported,
    5731             :                     "Currently, PHOTOMETRIC=YCBCR requires COMPRESS=JPEG");
    5732           1 :                 XTIFFClose(l_hTIFF);
    5733           1 :                 CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    5734           1 :                 return nullptr;
    5735             :             }
    5736             : 
    5737         732 :             if (nPlanar == PLANARCONFIG_SEPARATE)
    5738             :             {
    5739           1 :                 ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    5740             :                             "PHOTOMETRIC=YCBCR requires INTERLEAVE=PIXEL");
    5741           1 :                 XTIFFClose(l_hTIFF);
    5742           1 :                 CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    5743           1 :                 return nullptr;
    5744             :             }
    5745             : 
    5746             :             // YCBCR strictly requires 3 bands. Not less, not more Issue an
    5747             :             // explicit error message as libtiff one is a bit cryptic:
    5748             :             // TIFFVStripSize64:Invalid td_samplesperpixel value.
    5749         731 :             if (l_nBands != 3)
    5750             :             {
    5751           1 :                 ReportError(
    5752             :                     pszFilename, CE_Failure, CPLE_NotSupported,
    5753             :                     "PHOTOMETRIC=YCBCR not supported on a %d-band raster: "
    5754             :                     "only compatible of a 3-band (RGB) raster",
    5755             :                     l_nBands);
    5756           1 :                 XTIFFClose(l_hTIFF);
    5757           1 :                 CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    5758           1 :                 return nullptr;
    5759             :             }
    5760             : 
    5761         730 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
    5762         730 :             nSamplesAccountedFor = 3;
    5763             : 
    5764             :             // Explicitly register the subsampling so that JPEGFixupTags
    5765             :             // is a no-op (helps for cloud optimized geotiffs)
    5766         730 :             TIFFSetField(l_hTIFF, TIFFTAG_YCBCRSUBSAMPLING, 2, 2);
    5767             :         }
    5768           1 :         else if (EQUAL(pszValue, "CIELAB"))
    5769             :         {
    5770           0 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_CIELAB);
    5771           0 :             nSamplesAccountedFor = 3;
    5772             :         }
    5773           1 :         else if (EQUAL(pszValue, "ICCLAB"))
    5774             :         {
    5775           0 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_ICCLAB);
    5776           0 :             nSamplesAccountedFor = 3;
    5777             :         }
    5778           1 :         else if (EQUAL(pszValue, "ITULAB"))
    5779             :         {
    5780           0 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_ITULAB);
    5781           0 :             nSamplesAccountedFor = 3;
    5782             :         }
    5783             :         else
    5784             :         {
    5785           1 :             ReportError(pszFilename, CE_Warning, CPLE_IllegalArg,
    5786             :                         "PHOTOMETRIC=%s value not recognised, ignoring.  "
    5787             :                         "Set the Photometric Interpretation as MINISBLACK.",
    5788             :                         pszValue);
    5789           1 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
    5790             :         }
    5791             : 
    5792        1885 :         if (l_nBands < nSamplesAccountedFor)
    5793             :         {
    5794           1 :             ReportError(pszFilename, CE_Warning, CPLE_IllegalArg,
    5795             :                         "PHOTOMETRIC=%s value does not correspond to number "
    5796             :                         "of bands (%d), ignoring.  "
    5797             :                         "Set the Photometric Interpretation as MINISBLACK.",
    5798             :                         pszValue, l_nBands);
    5799           1 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
    5800             :         }
    5801             :     }
    5802             :     else
    5803             :     {
    5804             :         // If image contains 3 or 4 bands and datatype is Byte then we will
    5805             :         // assume it is RGB. In all other cases assume it is MINISBLACK.
    5806        5230 :         if (l_nBands == 3 && eType == GDT_Byte)
    5807             :         {
    5808         255 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
    5809         255 :             nSamplesAccountedFor = 3;
    5810             :         }
    5811        4975 :         else if (l_nBands == 4 && eType == GDT_Byte)
    5812             :         {
    5813             :             uint16_t v[1] = {
    5814         718 :                 GTiffGetAlphaValue(CSLFetchNameValue(papszParamList, "ALPHA"),
    5815         718 :                                    DEFAULT_ALPHA_TYPE)};
    5816             : 
    5817         718 :             TIFFSetField(l_hTIFF, TIFFTAG_EXTRASAMPLES, 1, v);
    5818         718 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
    5819         718 :             nSamplesAccountedFor = 4;
    5820             :         }
    5821             :         else
    5822             :         {
    5823        4257 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
    5824        4257 :             nSamplesAccountedFor = 1;
    5825             :         }
    5826             :     }
    5827             : 
    5828             :     /* -------------------------------------------------------------------- */
    5829             :     /*      If there are extra samples, we need to mark them with an        */
    5830             :     /*      appropriate extrasamples definition here.                       */
    5831             :     /* -------------------------------------------------------------------- */
    5832        7115 :     if (l_nBands > nSamplesAccountedFor)
    5833             :     {
    5834        1158 :         const int nExtraSamples = l_nBands - nSamplesAccountedFor;
    5835             : 
    5836             :         uint16_t *v = static_cast<uint16_t *>(
    5837        1158 :             CPLMalloc(sizeof(uint16_t) * nExtraSamples));
    5838             : 
    5839        1158 :         v[0] = GTiffGetAlphaValue(CSLFetchNameValue(papszParamList, "ALPHA"),
    5840             :                                   EXTRASAMPLE_UNSPECIFIED);
    5841             : 
    5842      198838 :         for (int i = 1; i < nExtraSamples; ++i)
    5843      197680 :             v[i] = EXTRASAMPLE_UNSPECIFIED;
    5844             : 
    5845        1158 :         TIFFSetField(l_hTIFF, TIFFTAG_EXTRASAMPLES, nExtraSamples, v);
    5846             : 
    5847        1158 :         CPLFree(v);
    5848             :     }
    5849             : 
    5850             :     // Set the ICC color profile.
    5851        7115 :     if (eProfile != GTiffProfile::BASELINE)
    5852             :     {
    5853        7090 :         SaveICCProfile(nullptr, l_hTIFF, papszParamList, l_nBitsPerSample);
    5854             :     }
    5855             : 
    5856             :     // Set the compression method before asking the default strip size
    5857             :     // This is useful when translating to a JPEG-In-TIFF file where
    5858             :     // the default strip size is 8 or 16 depending on the photometric value.
    5859        7115 :     TIFFSetField(l_hTIFF, TIFFTAG_COMPRESSION, l_nCompression);
    5860             : 
    5861        7115 :     if (l_nCompression == COMPRESSION_LERC)
    5862             :     {
    5863             :         const char *pszCompress =
    5864          97 :             CSLFetchNameValueDef(papszParamList, "COMPRESS", "");
    5865          97 :         if (EQUAL(pszCompress, "LERC_DEFLATE"))
    5866             :         {
    5867          16 :             TIFFSetField(l_hTIFF, TIFFTAG_LERC_ADD_COMPRESSION,
    5868             :                          LERC_ADD_COMPRESSION_DEFLATE);
    5869             :         }
    5870          81 :         else if (EQUAL(pszCompress, "LERC_ZSTD"))
    5871             :         {
    5872          14 :             if (TIFFSetField(l_hTIFF, TIFFTAG_LERC_ADD_COMPRESSION,
    5873          14 :                              LERC_ADD_COMPRESSION_ZSTD) != 1)
    5874             :             {
    5875           0 :                 XTIFFClose(l_hTIFF);
    5876           0 :                 CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    5877           0 :                 return nullptr;
    5878             :             }
    5879             :         }
    5880             :     }
    5881             :     // TODO later: take into account LERC version
    5882             : 
    5883             :     /* -------------------------------------------------------------------- */
    5884             :     /*      Setup tiling/stripping flags.                                   */
    5885             :     /* -------------------------------------------------------------------- */
    5886        7115 :     if (bTiled)
    5887             :     {
    5888        1278 :         if (!TIFFSetField(l_hTIFF, TIFFTAG_TILEWIDTH, l_nBlockXSize) ||
    5889         639 :             !TIFFSetField(l_hTIFF, TIFFTAG_TILELENGTH, l_nBlockYSize))
    5890             :         {
    5891           1 :             XTIFFClose(l_hTIFF);
    5892           1 :             CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    5893           1 :             return nullptr;
    5894             :         }
    5895             :     }
    5896             :     else
    5897             :     {
    5898        6476 :         const uint32_t l_nRowsPerStrip = std::min(
    5899             :             nYSize, l_nBlockYSize == 0
    5900        6476 :                         ? static_cast<int>(TIFFDefaultStripSize(l_hTIFF, 0))
    5901        6476 :                         : l_nBlockYSize);
    5902             : 
    5903        6476 :         TIFFSetField(l_hTIFF, TIFFTAG_ROWSPERSTRIP, l_nRowsPerStrip);
    5904             :     }
    5905             : 
    5906             :     /* -------------------------------------------------------------------- */
    5907             :     /*      Set compression related tags.                                   */
    5908             :     /* -------------------------------------------------------------------- */
    5909        7114 :     if (GTIFFSupportsPredictor(l_nCompression))
    5910         729 :         TIFFSetField(l_hTIFF, TIFFTAG_PREDICTOR, nPredictor);
    5911        7114 :     if (l_nCompression == COMPRESSION_ADOBE_DEFLATE ||
    5912             :         l_nCompression == COMPRESSION_LERC)
    5913             :     {
    5914         259 :         GTiffSetDeflateSubCodec(l_hTIFF);
    5915             : 
    5916         259 :         if (l_nZLevel != -1)
    5917          22 :             TIFFSetField(l_hTIFF, TIFFTAG_ZIPQUALITY, l_nZLevel);
    5918             :     }
    5919        7114 :     if (l_nCompression == COMPRESSION_JPEG && l_nJpegQuality != -1)
    5920        1905 :         TIFFSetField(l_hTIFF, TIFFTAG_JPEGQUALITY, l_nJpegQuality);
    5921        7114 :     if (l_nCompression == COMPRESSION_LZMA && l_nLZMAPreset != -1)
    5922          10 :         TIFFSetField(l_hTIFF, TIFFTAG_LZMAPRESET, l_nLZMAPreset);
    5923        7114 :     if ((l_nCompression == COMPRESSION_ZSTD ||
    5924         134 :          l_nCompression == COMPRESSION_LERC) &&
    5925             :         l_nZSTDLevel != -1)
    5926          12 :         TIFFSetField(l_hTIFF, TIFFTAG_ZSTD_LEVEL, l_nZSTDLevel);
    5927        7114 :     if (l_nCompression == COMPRESSION_LERC)
    5928             :     {
    5929          97 :         TIFFSetField(l_hTIFF, TIFFTAG_LERC_MAXZERROR, l_dfMaxZError);
    5930             :     }
    5931             : #if HAVE_JXL
    5932        7114 :     if (l_nCompression == COMPRESSION_JXL ||
    5933             :         l_nCompression == COMPRESSION_JXL_DNG_1_7)
    5934             :     {
    5935         101 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_LOSSYNESS,
    5936             :                      l_bJXLLossless ? JXL_LOSSLESS : JXL_LOSSY);
    5937         101 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_EFFORT, l_nJXLEffort);
    5938         101 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_DISTANCE, l_fJXLDistance);
    5939         101 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_ALPHA_DISTANCE, l_fJXLAlphaDistance);
    5940             :     }
    5941             : #endif
    5942        7114 :     if (l_nCompression == COMPRESSION_WEBP)
    5943          33 :         TIFFSetField(l_hTIFF, TIFFTAG_WEBP_LEVEL, l_nWebPLevel);
    5944        7114 :     if (l_nCompression == COMPRESSION_WEBP && l_bWebPLossless)
    5945           7 :         TIFFSetField(l_hTIFF, TIFFTAG_WEBP_LOSSLESS, 1);
    5946             : 
    5947        7114 :     if (l_nCompression == COMPRESSION_JPEG)
    5948        2087 :         TIFFSetField(l_hTIFF, TIFFTAG_JPEGTABLESMODE, l_nJpegTablesMode);
    5949             : 
    5950             :     /* -------------------------------------------------------------------- */
    5951             :     /*      If we forced production of a file with photometric=palette,     */
    5952             :     /*      we need to push out a default color table.                      */
    5953             :     /* -------------------------------------------------------------------- */
    5954        7114 :     if (bForceColorTable)
    5955             :     {
    5956           4 :         const int nColors = eType == GDT_Byte ? 256 : 65536;
    5957             : 
    5958             :         unsigned short *panTRed = static_cast<unsigned short *>(
    5959           4 :             CPLMalloc(sizeof(unsigned short) * nColors));
    5960             :         unsigned short *panTGreen = static_cast<unsigned short *>(
    5961           4 :             CPLMalloc(sizeof(unsigned short) * nColors));
    5962             :         unsigned short *panTBlue = static_cast<unsigned short *>(
    5963           4 :             CPLMalloc(sizeof(unsigned short) * nColors));
    5964             : 
    5965        1028 :         for (int iColor = 0; iColor < nColors; ++iColor)
    5966             :         {
    5967        1024 :             if (eType == GDT_Byte)
    5968             :             {
    5969        1024 :                 panTRed[iColor] = GTiffDataset::ClampCTEntry(
    5970             :                     iColor, 1, iColor, nColorTableMultiplier);
    5971        1024 :                 panTGreen[iColor] = GTiffDataset::ClampCTEntry(
    5972             :                     iColor, 2, iColor, nColorTableMultiplier);
    5973        1024 :                 panTBlue[iColor] = GTiffDataset::ClampCTEntry(
    5974             :                     iColor, 3, iColor, nColorTableMultiplier);
    5975             :             }
    5976             :             else
    5977             :             {
    5978           0 :                 panTRed[iColor] = static_cast<unsigned short>(iColor);
    5979           0 :                 panTGreen[iColor] = static_cast<unsigned short>(iColor);
    5980           0 :                 panTBlue[iColor] = static_cast<unsigned short>(iColor);
    5981             :             }
    5982             :         }
    5983             : 
    5984           4 :         TIFFSetField(l_hTIFF, TIFFTAG_COLORMAP, panTRed, panTGreen, panTBlue);
    5985             : 
    5986           4 :         CPLFree(panTRed);
    5987           4 :         CPLFree(panTGreen);
    5988           4 :         CPLFree(panTBlue);
    5989             :     }
    5990             : 
    5991             :     // This trick
    5992             :     // creates a temporary in-memory file and fetches its JPEG tables so that
    5993             :     // we can directly set them, before tif_jpeg.c compute them at the first
    5994             :     // strip/tile writing, which is too late, since we have already crystalized
    5995             :     // the directory. This way we avoid a directory rewriting.
    5996        9201 :     if (l_nCompression == COMPRESSION_JPEG &&
    5997        2087 :         CPLTestBool(
    5998             :             CSLFetchNameValueDef(papszParamList, "WRITE_JPEGTABLE_TAG", "YES")))
    5999             :     {
    6000        1014 :         GTiffWriteJPEGTables(
    6001             :             l_hTIFF, CSLFetchNameValue(papszParamList, "PHOTOMETRIC"),
    6002             :             CSLFetchNameValue(papszParamList, "JPEG_QUALITY"),
    6003             :             CSLFetchNameValue(papszParamList, "JPEGTABLESMODE"));
    6004             :     }
    6005             : 
    6006        7114 :     *pfpL = l_fpL;
    6007             : 
    6008        7114 :     return l_hTIFF;
    6009             : }
    6010             : 
    6011             : /************************************************************************/
    6012             : /*                            GuessJPEGQuality()                        */
    6013             : /*                                                                      */
    6014             : /*      Guess JPEG quality from JPEGTABLES tag.                         */
    6015             : /************************************************************************/
    6016             : 
    6017        3915 : static const GByte *GTIFFFindNextTable(const GByte *paby, GByte byMarker,
    6018             :                                        int nLen, int *pnLenTable)
    6019             : {
    6020        8097 :     for (int i = 0; i + 1 < nLen;)
    6021             :     {
    6022        8097 :         if (paby[i] != 0xFF)
    6023           0 :             return nullptr;
    6024        8097 :         ++i;
    6025        8097 :         if (paby[i] == 0xD8)
    6026             :         {
    6027        3156 :             ++i;
    6028        3156 :             continue;
    6029             :         }
    6030        4941 :         if (i + 2 >= nLen)
    6031         859 :             return nullptr;
    6032        4082 :         int nMarkerLen = paby[i + 1] * 256 + paby[i + 2];
    6033        4082 :         if (i + 1 + nMarkerLen >= nLen)
    6034           0 :             return nullptr;
    6035        4082 :         if (paby[i] == byMarker)
    6036             :         {
    6037        3056 :             if (pnLenTable)
    6038        2499 :                 *pnLenTable = nMarkerLen;
    6039        3056 :             return paby + i + 1;
    6040             :         }
    6041        1026 :         i += 1 + nMarkerLen;
    6042             :     }
    6043           0 :     return nullptr;
    6044             : }
    6045             : 
    6046             : constexpr GByte MARKER_HUFFMAN_TABLE = 0xC4;
    6047             : constexpr GByte MARKER_QUANT_TABLE = 0xDB;
    6048             : 
    6049             : // We assume that if there are several quantization tables, they are
    6050             : // in the same order. Which is a reasonable assumption for updating
    6051             : // a file generated by ourselves.
    6052         904 : static bool GTIFFQuantizationTablesEqual(const GByte *paby1, int nLen1,
    6053             :                                          const GByte *paby2, int nLen2)
    6054             : {
    6055         904 :     bool bFound = false;
    6056             :     while (true)
    6057             :     {
    6058         945 :         int nLenTable1 = 0;
    6059         945 :         int nLenTable2 = 0;
    6060             :         const GByte *paby1New =
    6061         945 :             GTIFFFindNextTable(paby1, MARKER_QUANT_TABLE, nLen1, &nLenTable1);
    6062             :         const GByte *paby2New =
    6063         945 :             GTIFFFindNextTable(paby2, MARKER_QUANT_TABLE, nLen2, &nLenTable2);
    6064         945 :         if (paby1New == nullptr && paby2New == nullptr)
    6065         904 :             return bFound;
    6066         911 :         if (paby1New == nullptr || paby2New == nullptr)
    6067           0 :             return false;
    6068         911 :         if (nLenTable1 != nLenTable2)
    6069         207 :             return false;
    6070         704 :         if (memcmp(paby1New, paby2New, nLenTable1) != 0)
    6071         663 :             return false;
    6072          41 :         paby1New += nLenTable1;
    6073          41 :         paby2New += nLenTable2;
    6074          41 :         nLen1 -= static_cast<int>(paby1New - paby1);
    6075          41 :         nLen2 -= static_cast<int>(paby2New - paby2);
    6076          41 :         paby1 = paby1New;
    6077          41 :         paby2 = paby2New;
    6078          41 :         bFound = true;
    6079          41 :     }
    6080             : }
    6081             : 
    6082             : // Guess the JPEG quality by comparing against the MD5Sum of precomputed
    6083             : // quantization tables
    6084         422 : static int GuessJPEGQualityFromMD5(const uint8_t md5JPEGQuantTable[][16],
    6085             :                                    const GByte *const pabyJPEGTable,
    6086             :                                    int nJPEGTableSize)
    6087             : {
    6088         422 :     int nRemainingLen = nJPEGTableSize;
    6089         422 :     const GByte *pabyCur = pabyJPEGTable;
    6090             : 
    6091             :     struct CPLMD5Context context;
    6092         422 :     CPLMD5Init(&context);
    6093             : 
    6094             :     while (true)
    6095             :     {
    6096        1099 :         int nLenTable = 0;
    6097        1099 :         const GByte *pabyNew = GTIFFFindNextTable(pabyCur, MARKER_QUANT_TABLE,
    6098             :                                                   nRemainingLen, &nLenTable);
    6099        1099 :         if (pabyNew == nullptr)
    6100         422 :             break;
    6101         677 :         CPLMD5Update(&context, pabyNew, nLenTable);
    6102         677 :         pabyNew += nLenTable;
    6103         677 :         nRemainingLen -= static_cast<int>(pabyNew - pabyCur);
    6104         677 :         pabyCur = pabyNew;
    6105         677 :     }
    6106             : 
    6107             :     GByte digest[16];
    6108         422 :     CPLMD5Final(digest, &context);
    6109             : 
    6110       29821 :     for (int i = 0; i < 100; i++)
    6111             :     {
    6112       29818 :         if (memcmp(md5JPEGQuantTable[i], digest, 16) == 0)
    6113             :         {
    6114         419 :             return i + 1;
    6115             :         }
    6116             :     }
    6117           3 :     return -1;
    6118             : }
    6119             : 
    6120         477 : int GTiffDataset::GuessJPEGQuality(bool &bOutHasQuantizationTable,
    6121             :                                    bool &bOutHasHuffmanTable)
    6122             : {
    6123         477 :     CPLAssert(m_nCompression == COMPRESSION_JPEG);
    6124         477 :     uint32_t nJPEGTableSize = 0;
    6125         477 :     void *pJPEGTable = nullptr;
    6126         477 :     if (!TIFFGetField(m_hTIFF, TIFFTAG_JPEGTABLES, &nJPEGTableSize,
    6127             :                       &pJPEGTable))
    6128             :     {
    6129          14 :         bOutHasQuantizationTable = false;
    6130          14 :         bOutHasHuffmanTable = false;
    6131          14 :         return -1;
    6132             :     }
    6133             : 
    6134         463 :     bOutHasQuantizationTable =
    6135         463 :         GTIFFFindNextTable(static_cast<const GByte *>(pJPEGTable),
    6136             :                            MARKER_QUANT_TABLE, nJPEGTableSize,
    6137         463 :                            nullptr) != nullptr;
    6138         463 :     bOutHasHuffmanTable =
    6139         463 :         GTIFFFindNextTable(static_cast<const GByte *>(pJPEGTable),
    6140             :                            MARKER_HUFFMAN_TABLE, nJPEGTableSize,
    6141         463 :                            nullptr) != nullptr;
    6142         463 :     if (!bOutHasQuantizationTable)
    6143           7 :         return -1;
    6144             : 
    6145         456 :     if ((nBands == 1 && m_nBitsPerSample == 8) ||
    6146         395 :         (nBands == 3 && m_nBitsPerSample == 8 &&
    6147         349 :          m_nPhotometric == PHOTOMETRIC_RGB) ||
    6148         301 :         (nBands == 4 && m_nBitsPerSample == 8 &&
    6149          27 :          m_nPhotometric == PHOTOMETRIC_SEPARATED))
    6150             :     {
    6151         167 :         return GuessJPEGQualityFromMD5(md5JPEGQuantTable_generic_8bit,
    6152             :                                        static_cast<const GByte *>(pJPEGTable),
    6153         167 :                                        static_cast<int>(nJPEGTableSize));
    6154             :     }
    6155             : 
    6156         289 :     if (nBands == 3 && m_nBitsPerSample == 8 &&
    6157         255 :         m_nPhotometric == PHOTOMETRIC_YCBCR)
    6158             :     {
    6159             :         int nRet =
    6160         255 :             GuessJPEGQualityFromMD5(md5JPEGQuantTable_3_YCBCR_8bit,
    6161             :                                     static_cast<const GByte *>(pJPEGTable),
    6162             :                                     static_cast<int>(nJPEGTableSize));
    6163         255 :         if (nRet < 0)
    6164             :         {
    6165             :             // libjpeg 9e has modified the YCbCr quantization tables.
    6166             :             nRet =
    6167           0 :                 GuessJPEGQualityFromMD5(md5JPEGQuantTable_3_YCBCR_8bit_jpeg9e,
    6168             :                                         static_cast<const GByte *>(pJPEGTable),
    6169             :                                         static_cast<int>(nJPEGTableSize));
    6170             :         }
    6171         255 :         return nRet;
    6172             :     }
    6173             : 
    6174          34 :     char **papszLocalParameters = nullptr;
    6175             :     papszLocalParameters =
    6176          34 :         CSLSetNameValue(papszLocalParameters, "COMPRESS", "JPEG");
    6177          34 :     if (m_nPhotometric == PHOTOMETRIC_YCBCR)
    6178             :         papszLocalParameters =
    6179           7 :             CSLSetNameValue(papszLocalParameters, "PHOTOMETRIC", "YCBCR");
    6180          27 :     else if (m_nPhotometric == PHOTOMETRIC_SEPARATED)
    6181             :         papszLocalParameters =
    6182           0 :             CSLSetNameValue(papszLocalParameters, "PHOTOMETRIC", "CMYK");
    6183             :     papszLocalParameters =
    6184          34 :         CSLSetNameValue(papszLocalParameters, "BLOCKYSIZE", "16");
    6185          34 :     if (m_nBitsPerSample == 12)
    6186             :         papszLocalParameters =
    6187          16 :             CSLSetNameValue(papszLocalParameters, "NBITS", "12");
    6188             : 
    6189             :     const CPLString osTmpFilenameIn(
    6190          34 :         VSIMemGenerateHiddenFilename("gtiffdataset_guess_jpeg_quality_tmp"));
    6191             : 
    6192          34 :     int nRet = -1;
    6193         938 :     for (int nQuality = 0; nQuality <= 100 && nRet < 0; ++nQuality)
    6194             :     {
    6195         904 :         VSILFILE *fpTmp = nullptr;
    6196         904 :         if (nQuality == 0)
    6197             :             papszLocalParameters =
    6198          34 :                 CSLSetNameValue(papszLocalParameters, "JPEG_QUALITY", "75");
    6199             :         else
    6200             :             papszLocalParameters =
    6201         870 :                 CSLSetNameValue(papszLocalParameters, "JPEG_QUALITY",
    6202             :                                 CPLSPrintf("%d", nQuality));
    6203             : 
    6204         904 :         CPLPushErrorHandler(CPLQuietErrorHandler);
    6205         904 :         CPLString osTmp;
    6206             :         bool bTileInterleaving;
    6207        1808 :         TIFF *hTIFFTmp = CreateLL(
    6208         904 :             osTmpFilenameIn, 16, 16, (nBands <= 4) ? nBands : 1,
    6209             :             GetRasterBand(1)->GetRasterDataType(), 0.0, 0, papszLocalParameters,
    6210             :             &fpTmp, osTmp, /* bCreateCopy=*/false, bTileInterleaving);
    6211         904 :         CPLPopErrorHandler();
    6212         904 :         if (!hTIFFTmp)
    6213             :         {
    6214           0 :             break;
    6215             :         }
    6216             : 
    6217         904 :         TIFFWriteCheck(hTIFFTmp, FALSE, "CreateLL");
    6218         904 :         TIFFWriteDirectory(hTIFFTmp);
    6219         904 :         TIFFSetDirectory(hTIFFTmp, 0);
    6220             :         // Now reset jpegcolormode.
    6221        1196 :         if (m_nPhotometric == PHOTOMETRIC_YCBCR &&
    6222         292 :             CPLTestBool(CPLGetConfigOption("CONVERT_YCBCR_TO_RGB", "YES")))
    6223             :         {
    6224         292 :             TIFFSetField(hTIFFTmp, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
    6225             :         }
    6226             : 
    6227         904 :         GByte abyZeroData[(16 * 16 * 4 * 3) / 2] = {};
    6228         904 :         const int nBlockSize =
    6229         904 :             (16 * 16 * ((nBands <= 4) ? nBands : 1) * m_nBitsPerSample) / 8;
    6230         904 :         TIFFWriteEncodedStrip(hTIFFTmp, 0, abyZeroData, nBlockSize);
    6231             : 
    6232         904 :         uint32_t nJPEGTableSizeTry = 0;
    6233         904 :         void *pJPEGTableTry = nullptr;
    6234         904 :         if (TIFFGetField(hTIFFTmp, TIFFTAG_JPEGTABLES, &nJPEGTableSizeTry,
    6235         904 :                          &pJPEGTableTry))
    6236             :         {
    6237         904 :             if (GTIFFQuantizationTablesEqual(
    6238             :                     static_cast<GByte *>(pJPEGTable), nJPEGTableSize,
    6239             :                     static_cast<GByte *>(pJPEGTableTry), nJPEGTableSizeTry))
    6240             :             {
    6241          34 :                 nRet = (nQuality == 0) ? 75 : nQuality;
    6242             :             }
    6243             :         }
    6244             : 
    6245         904 :         XTIFFClose(hTIFFTmp);
    6246         904 :         CPL_IGNORE_RET_VAL(VSIFCloseL(fpTmp));
    6247             :     }
    6248             : 
    6249          34 :     CSLDestroy(papszLocalParameters);
    6250          34 :     VSIUnlink(osTmpFilenameIn);
    6251             : 
    6252          34 :     return nRet;
    6253             : }
    6254             : 
    6255             : /************************************************************************/
    6256             : /*               SetJPEGQualityAndTablesModeFromFile()                  */
    6257             : /************************************************************************/
    6258             : 
    6259         165 : void GTiffDataset::SetJPEGQualityAndTablesModeFromFile(
    6260             :     int nQuality, bool bHasQuantizationTable, bool bHasHuffmanTable)
    6261             : {
    6262         165 :     if (nQuality > 0)
    6263             :     {
    6264         158 :         CPLDebug("GTiff", "Guessed JPEG quality to be %d", nQuality);
    6265         158 :         m_nJpegQuality = static_cast<signed char>(nQuality);
    6266         158 :         TIFFSetField(m_hTIFF, TIFFTAG_JPEGQUALITY, nQuality);
    6267             : 
    6268             :         // This means we will use the quantization tables from the
    6269             :         // JpegTables tag.
    6270         158 :         m_nJpegTablesMode = JPEGTABLESMODE_QUANT;
    6271             :     }
    6272             :     else
    6273             :     {
    6274           7 :         uint32_t nJPEGTableSize = 0;
    6275           7 :         void *pJPEGTable = nullptr;
    6276           7 :         if (!TIFFGetField(m_hTIFF, TIFFTAG_JPEGTABLES, &nJPEGTableSize,
    6277             :                           &pJPEGTable))
    6278             :         {
    6279           4 :             toff_t *panByteCounts = nullptr;
    6280           8 :             const int nBlockCount = m_nPlanarConfig == PLANARCONFIG_SEPARATE
    6281           4 :                                         ? m_nBlocksPerBand * nBands
    6282             :                                         : m_nBlocksPerBand;
    6283           4 :             if (TIFFIsTiled(m_hTIFF))
    6284           1 :                 TIFFGetField(m_hTIFF, TIFFTAG_TILEBYTECOUNTS, &panByteCounts);
    6285             :             else
    6286           3 :                 TIFFGetField(m_hTIFF, TIFFTAG_STRIPBYTECOUNTS, &panByteCounts);
    6287             : 
    6288           4 :             bool bFoundNonEmptyBlock = false;
    6289           4 :             if (panByteCounts != nullptr)
    6290             :             {
    6291          56 :                 for (int iBlock = 0; iBlock < nBlockCount; ++iBlock)
    6292             :                 {
    6293          53 :                     if (panByteCounts[iBlock] != 0)
    6294             :                     {
    6295           1 :                         bFoundNonEmptyBlock = true;
    6296           1 :                         break;
    6297             :                     }
    6298             :                 }
    6299             :             }
    6300           4 :             if (bFoundNonEmptyBlock)
    6301             :             {
    6302           1 :                 CPLDebug("GTiff", "Could not guess JPEG quality. "
    6303             :                                   "JPEG tables are missing, so going in "
    6304             :                                   "TIFFTAG_JPEGTABLESMODE = 0/2 mode");
    6305             :                 // Write quantization tables in each strile.
    6306           1 :                 m_nJpegTablesMode = 0;
    6307             :             }
    6308             :         }
    6309             :         else
    6310             :         {
    6311           3 :             if (bHasQuantizationTable)
    6312             :             {
    6313             :                 // FIXME in libtiff: this is likely going to cause issues
    6314             :                 // since libtiff will reuse in each strile the number of
    6315             :                 // the global quantization table, which is invalid.
    6316           1 :                 CPLDebug("GTiff",
    6317             :                          "Could not guess JPEG quality although JPEG "
    6318             :                          "quantization tables are present, so going in "
    6319             :                          "TIFFTAG_JPEGTABLESMODE = 0/2 mode");
    6320             :             }
    6321             :             else
    6322             :             {
    6323           2 :                 CPLDebug("GTiff",
    6324             :                          "Could not guess JPEG quality since JPEG "
    6325             :                          "quantization tables are not present, so going in "
    6326             :                          "TIFFTAG_JPEGTABLESMODE = 0/2 mode");
    6327             :             }
    6328             : 
    6329             :             // Write quantization tables in each strile.
    6330           3 :             m_nJpegTablesMode = 0;
    6331             :         }
    6332             :     }
    6333         165 :     if (bHasHuffmanTable)
    6334             :     {
    6335             :         // If there are Huffman tables in header use them, otherwise
    6336             :         // if we use optimized tables, libtiff will currently reuse
    6337             :         // the number of the Huffman tables of the header for the
    6338             :         // optimized version of each strile, which is illegal.
    6339          23 :         m_nJpegTablesMode |= JPEGTABLESMODE_HUFF;
    6340             :     }
    6341         165 :     if (m_nJpegTablesMode >= 0)
    6342         163 :         TIFFSetField(m_hTIFF, TIFFTAG_JPEGTABLESMODE, m_nJpegTablesMode);
    6343         165 : }
    6344             : 
    6345             : /************************************************************************/
    6346             : /*                               Create()                               */
    6347             : /*                                                                      */
    6348             : /*      Create a new GeoTIFF or TIFF file.                              */
    6349             : /************************************************************************/
    6350             : 
    6351        3234 : GDALDataset *GTiffDataset::Create(const char *pszFilename, int nXSize,
    6352             :                                   int nYSize, int l_nBands, GDALDataType eType,
    6353             :                                   char **papszParamList)
    6354             : 
    6355             : {
    6356        3234 :     VSILFILE *l_fpL = nullptr;
    6357        6468 :     CPLString l_osTmpFilename;
    6358             : 
    6359             :     const int nColorTableMultiplier = std::max(
    6360        6468 :         1,
    6361        6468 :         std::min(257,
    6362        3234 :                  atoi(CSLFetchNameValueDef(
    6363             :                      papszParamList, "COLOR_TABLE_MULTIPLIER",
    6364        3234 :                      CPLSPrintf("%d", DEFAULT_COLOR_TABLE_MULTIPLIER_257)))));
    6365             : 
    6366             :     /* -------------------------------------------------------------------- */
    6367             :     /*      Create the underlying TIFF file.                                */
    6368             :     /* -------------------------------------------------------------------- */
    6369             :     bool bTileInterleaving;
    6370             :     TIFF *l_hTIFF =
    6371        3234 :         CreateLL(pszFilename, nXSize, nYSize, l_nBands, eType, 0,
    6372             :                  nColorTableMultiplier, papszParamList, &l_fpL, l_osTmpFilename,
    6373             :                  /* bCreateCopy=*/false, bTileInterleaving);
    6374        3234 :     const bool bStreaming = !l_osTmpFilename.empty();
    6375             : 
    6376        3234 :     if (l_hTIFF == nullptr)
    6377          30 :         return nullptr;
    6378             : 
    6379             :     /* -------------------------------------------------------------------- */
    6380             :     /*      Create the new GTiffDataset object.                             */
    6381             :     /* -------------------------------------------------------------------- */
    6382        3204 :     GTiffDataset *poDS = new GTiffDataset();
    6383        3204 :     poDS->m_hTIFF = l_hTIFF;
    6384        3204 :     poDS->m_fpL = l_fpL;
    6385        3204 :     if (bStreaming)
    6386             :     {
    6387           4 :         poDS->m_bStreamingOut = true;
    6388           4 :         poDS->m_pszTmpFilename = CPLStrdup(l_osTmpFilename);
    6389           4 :         poDS->m_fpToWrite = VSIFOpenL(pszFilename, "wb");
    6390           4 :         if (poDS->m_fpToWrite == nullptr)
    6391             :         {
    6392           1 :             VSIUnlink(l_osTmpFilename);
    6393           1 :             delete poDS;
    6394           1 :             return nullptr;
    6395             :         }
    6396             :     }
    6397        3203 :     poDS->nRasterXSize = nXSize;
    6398        3203 :     poDS->nRasterYSize = nYSize;
    6399        3203 :     poDS->eAccess = GA_Update;
    6400             : 
    6401        3203 :     poDS->m_nColorTableMultiplier = nColorTableMultiplier;
    6402             : 
    6403        3203 :     poDS->m_bCrystalized = false;
    6404        3203 :     poDS->m_nSamplesPerPixel = static_cast<uint16_t>(l_nBands);
    6405        3203 :     poDS->m_pszFilename = CPLStrdup(pszFilename);
    6406             : 
    6407             :     // Don't try to load external metadata files (#6597).
    6408        3203 :     poDS->m_bIMDRPCMetadataLoaded = true;
    6409             : 
    6410             :     // Avoid premature crystalization that will cause directory re-writing if
    6411             :     // GetProjectionRef() or GetGeoTransform() are called on the newly created
    6412             :     // GeoTIFF.
    6413        3203 :     poDS->m_bLookedForProjection = true;
    6414             : 
    6415        3203 :     TIFFGetField(l_hTIFF, TIFFTAG_SAMPLEFORMAT, &(poDS->m_nSampleFormat));
    6416        3203 :     TIFFGetField(l_hTIFF, TIFFTAG_PLANARCONFIG, &(poDS->m_nPlanarConfig));
    6417             :     // Weird that we need this, but otherwise we get a Valgrind warning on
    6418             :     // tiff_write_124.
    6419        3203 :     if (!TIFFGetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, &(poDS->m_nPhotometric)))
    6420           1 :         poDS->m_nPhotometric = PHOTOMETRIC_MINISBLACK;
    6421        3203 :     TIFFGetField(l_hTIFF, TIFFTAG_BITSPERSAMPLE, &(poDS->m_nBitsPerSample));
    6422        3203 :     TIFFGetField(l_hTIFF, TIFFTAG_COMPRESSION, &(poDS->m_nCompression));
    6423             : 
    6424        3203 :     if (TIFFIsTiled(l_hTIFF))
    6425             :     {
    6426         320 :         TIFFGetField(l_hTIFF, TIFFTAG_TILEWIDTH, &(poDS->m_nBlockXSize));
    6427         320 :         TIFFGetField(l_hTIFF, TIFFTAG_TILELENGTH, &(poDS->m_nBlockYSize));
    6428             :     }
    6429             :     else
    6430             :     {
    6431        2883 :         if (!TIFFGetField(l_hTIFF, TIFFTAG_ROWSPERSTRIP,
    6432             :                           &(poDS->m_nRowsPerStrip)))
    6433           0 :             poDS->m_nRowsPerStrip = 1;  // Dummy value.
    6434             : 
    6435        2883 :         poDS->m_nBlockXSize = nXSize;
    6436        2883 :         poDS->m_nBlockYSize =
    6437        2883 :             std::min(static_cast<int>(poDS->m_nRowsPerStrip), nYSize);
    6438             :     }
    6439             : 
    6440        3203 :     if (!poDS->ComputeBlocksPerColRowAndBand(l_nBands))
    6441             :     {
    6442           0 :         delete poDS;
    6443           0 :         return nullptr;
    6444             :     }
    6445             : 
    6446        3203 :     poDS->m_eProfile = GetProfile(CSLFetchNameValue(papszParamList, "PROFILE"));
    6447             : 
    6448             :     /* -------------------------------------------------------------------- */
    6449             :     /*      YCbCr JPEG compressed images should be translated on the fly    */
    6450             :     /*      to RGB by libtiff/libjpeg unless specifically requested         */
    6451             :     /*      otherwise.                                                      */
    6452             :     /* -------------------------------------------------------------------- */
    6453        6440 :     if (poDS->m_nCompression == COMPRESSION_JPEG &&
    6454        3224 :         poDS->m_nPhotometric == PHOTOMETRIC_YCBCR &&
    6455          21 :         CPLTestBool(CPLGetConfigOption("CONVERT_YCBCR_TO_RGB", "YES")))
    6456             :     {
    6457          21 :         int nColorMode = 0;
    6458             : 
    6459          21 :         poDS->SetMetadataItem("SOURCE_COLOR_SPACE", "YCbCr", "IMAGE_STRUCTURE");
    6460          42 :         if (!TIFFGetField(l_hTIFF, TIFFTAG_JPEGCOLORMODE, &nColorMode) ||
    6461          21 :             nColorMode != JPEGCOLORMODE_RGB)
    6462          21 :             TIFFSetField(l_hTIFF, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
    6463             :     }
    6464             : 
    6465        3203 :     if (poDS->m_nCompression == COMPRESSION_LERC)
    6466             :     {
    6467          26 :         uint32_t nLercParamCount = 0;
    6468          26 :         uint32_t *panLercParams = nullptr;
    6469          26 :         if (TIFFGetField(l_hTIFF, TIFFTAG_LERC_PARAMETERS, &nLercParamCount,
    6470          52 :                          &panLercParams) &&
    6471          26 :             nLercParamCount == 2)
    6472             :         {
    6473          26 :             memcpy(poDS->m_anLercAddCompressionAndVersion, panLercParams,
    6474             :                    sizeof(poDS->m_anLercAddCompressionAndVersion));
    6475             :         }
    6476             :     }
    6477             : 
    6478             :     /* -------------------------------------------------------------------- */
    6479             :     /*      Read palette back as a color table if it has one.               */
    6480             :     /* -------------------------------------------------------------------- */
    6481        3203 :     unsigned short *panRed = nullptr;
    6482        3203 :     unsigned short *panGreen = nullptr;
    6483        3203 :     unsigned short *panBlue = nullptr;
    6484             : 
    6485        3207 :     if (poDS->m_nPhotometric == PHOTOMETRIC_PALETTE &&
    6486           4 :         TIFFGetField(l_hTIFF, TIFFTAG_COLORMAP, &panRed, &panGreen, &panBlue))
    6487             :     {
    6488             : 
    6489           4 :         poDS->m_poColorTable = std::make_unique<GDALColorTable>();
    6490             : 
    6491           4 :         const int nColorCount = 1 << poDS->m_nBitsPerSample;
    6492             : 
    6493        1028 :         for (int iColor = nColorCount - 1; iColor >= 0; iColor--)
    6494             :         {
    6495        1024 :             const GDALColorEntry oEntry = {
    6496        1024 :                 static_cast<short>(panRed[iColor] / nColorTableMultiplier),
    6497        1024 :                 static_cast<short>(panGreen[iColor] / nColorTableMultiplier),
    6498        1024 :                 static_cast<short>(panBlue[iColor] / nColorTableMultiplier),
    6499        1024 :                 static_cast<short>(255)};
    6500             : 
    6501        1024 :             poDS->m_poColorTable->SetColorEntry(iColor, &oEntry);
    6502             :         }
    6503             :     }
    6504             : 
    6505             :     /* -------------------------------------------------------------------- */
    6506             :     /*      Do we want to ensure all blocks get written out on close to     */
    6507             :     /*      avoid sparse files?                                             */
    6508             :     /* -------------------------------------------------------------------- */
    6509        3203 :     if (!CPLFetchBool(papszParamList, "SPARSE_OK", false))
    6510        3097 :         poDS->m_bFillEmptyTilesAtClosing = true;
    6511             : 
    6512        3203 :     poDS->m_bWriteEmptyTiles =
    6513        3872 :         bStreaming || (poDS->m_nCompression != COMPRESSION_NONE &&
    6514         669 :                        poDS->m_bFillEmptyTilesAtClosing);
    6515             :     // Only required for people writing non-compressed striped files in the
    6516             :     // right order and wanting all tstrips to be written in the same order
    6517             :     // so that the end result can be memory mapped without knowledge of each
    6518             :     // strip offset.
    6519        3203 :     if (CPLTestBool(CSLFetchNameValueDef(
    6520        6406 :             papszParamList, "WRITE_EMPTY_TILES_SYNCHRONOUSLY", "FALSE")) ||
    6521        3203 :         CPLTestBool(CSLFetchNameValueDef(
    6522             :             papszParamList, "@WRITE_EMPTY_TILES_SYNCHRONOUSLY", "FALSE")))
    6523             :     {
    6524          19 :         poDS->m_bWriteEmptyTiles = true;
    6525             :     }
    6526             : 
    6527             :     /* -------------------------------------------------------------------- */
    6528             :     /*      Preserve creation options for consulting later (for instance    */
    6529             :     /*      to decide if a TFW file should be written).                     */
    6530             :     /* -------------------------------------------------------------------- */
    6531        3203 :     poDS->m_papszCreationOptions = CSLDuplicate(papszParamList);
    6532             : 
    6533        3203 :     poDS->m_nZLevel = GTiffGetZLevel(papszParamList);
    6534        3203 :     poDS->m_nLZMAPreset = GTiffGetLZMAPreset(papszParamList);
    6535        3203 :     poDS->m_nZSTDLevel = GTiffGetZSTDPreset(papszParamList);
    6536        3203 :     poDS->m_nWebPLevel = GTiffGetWebPLevel(papszParamList);
    6537        3203 :     poDS->m_bWebPLossless = GTiffGetWebPLossless(papszParamList);
    6538        3205 :     if (poDS->m_nWebPLevel != 100 && poDS->m_bWebPLossless &&
    6539           2 :         CSLFetchNameValue(papszParamList, "WEBP_LEVEL"))
    6540             :     {
    6541           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    6542             :                  "WEBP_LEVEL is specified, but WEBP_LOSSLESS=YES. "
    6543             :                  "WEBP_LEVEL will be ignored.");
    6544             :     }
    6545        3203 :     poDS->m_nJpegQuality = GTiffGetJpegQuality(papszParamList);
    6546        3203 :     poDS->m_nJpegTablesMode = GTiffGetJpegTablesMode(papszParamList);
    6547        3203 :     poDS->m_dfMaxZError = GTiffGetLERCMaxZError(papszParamList);
    6548        3203 :     poDS->m_dfMaxZErrorOverview = GTiffGetLERCMaxZErrorOverview(papszParamList);
    6549             : #if HAVE_JXL
    6550        3203 :     poDS->m_bJXLLossless = GTiffGetJXLLossless(papszParamList);
    6551        3203 :     poDS->m_nJXLEffort = GTiffGetJXLEffort(papszParamList);
    6552        3203 :     poDS->m_fJXLDistance = GTiffGetJXLDistance(papszParamList);
    6553        3203 :     poDS->m_fJXLAlphaDistance = GTiffGetJXLAlphaDistance(papszParamList);
    6554             : #endif
    6555        3203 :     poDS->InitCreationOrOpenOptions(true, papszParamList);
    6556             : 
    6557             :     /* -------------------------------------------------------------------- */
    6558             :     /*      Create band information objects.                                */
    6559             :     /* -------------------------------------------------------------------- */
    6560      204306 :     for (int iBand = 0; iBand < l_nBands; ++iBand)
    6561             :     {
    6562      201103 :         if (poDS->m_nBitsPerSample == 8 ||
    6563        1480 :             (poDS->m_nBitsPerSample == 16 && eType != GDT_Float32) ||
    6564         973 :             poDS->m_nBitsPerSample == 32 || poDS->m_nBitsPerSample == 64 ||
    6565         127 :             poDS->m_nBitsPerSample == 128)
    6566             :         {
    6567      201036 :             poDS->SetBand(iBand + 1, new GTiffRasterBand(poDS, iBand + 1));
    6568             :         }
    6569             :         else
    6570             :         {
    6571          67 :             poDS->SetBand(iBand + 1, new GTiffOddBitsBand(poDS, iBand + 1));
    6572         134 :             poDS->GetRasterBand(iBand + 1)->SetMetadataItem(
    6573         134 :                 "NBITS", CPLString().Printf("%d", poDS->m_nBitsPerSample),
    6574          67 :                 "IMAGE_STRUCTURE");
    6575             :         }
    6576             :     }
    6577             : 
    6578        3203 :     poDS->GetDiscardLsbOption(papszParamList);
    6579             : 
    6580        3203 :     if (poDS->m_nPlanarConfig == PLANARCONFIG_CONTIG && l_nBands != 1)
    6581         577 :         poDS->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
    6582             :     else
    6583        2626 :         poDS->SetMetadataItem("INTERLEAVE", "BAND", "IMAGE_STRUCTURE");
    6584             : 
    6585        3203 :     poDS->oOvManager.Initialize(poDS, pszFilename);
    6586             : 
    6587        3203 :     return poDS;
    6588             : }
    6589             : 
    6590             : /************************************************************************/
    6591             : /*                           CopyImageryAndMask()                       */
    6592             : /************************************************************************/
    6593             : 
    6594         294 : CPLErr GTiffDataset::CopyImageryAndMask(GTiffDataset *poDstDS,
    6595             :                                         GDALDataset *poSrcDS,
    6596             :                                         GDALRasterBand *poSrcMaskBand,
    6597             :                                         GDALProgressFunc pfnProgress,
    6598             :                                         void *pProgressData)
    6599             : {
    6600         294 :     CPLErr eErr = CE_None;
    6601             : 
    6602         294 :     const auto eType = poDstDS->GetRasterBand(1)->GetRasterDataType();
    6603         294 :     const int nDataTypeSize = GDALGetDataTypeSizeBytes(eType);
    6604         294 :     const int l_nBands = poDstDS->GetRasterCount();
    6605             :     GByte *pBlockBuffer = static_cast<GByte *>(
    6606         294 :         VSI_MALLOC3_VERBOSE(poDstDS->m_nBlockXSize, poDstDS->m_nBlockYSize,
    6607             :                             cpl::fits_on<int>(l_nBands * nDataTypeSize)));
    6608         294 :     if (pBlockBuffer == nullptr)
    6609             :     {
    6610           0 :         eErr = CE_Failure;
    6611             :     }
    6612         294 :     const int nYSize = poDstDS->nRasterYSize;
    6613         294 :     const int nXSize = poDstDS->nRasterXSize;
    6614             :     const bool bIsOddBand =
    6615         294 :         dynamic_cast<GTiffOddBitsBand *>(poDstDS->GetRasterBand(1)) != nullptr;
    6616             : 
    6617         294 :     if (poDstDS->m_poMaskDS)
    6618             :     {
    6619          63 :         CPLAssert(poDstDS->m_poMaskDS->m_nBlockXSize == poDstDS->m_nBlockXSize);
    6620          63 :         CPLAssert(poDstDS->m_poMaskDS->m_nBlockYSize == poDstDS->m_nBlockYSize);
    6621             :     }
    6622             : 
    6623         294 :     if (poDstDS->m_nPlanarConfig == PLANARCONFIG_SEPARATE &&
    6624          53 :         !poDstDS->m_bTileInterleave)
    6625             :     {
    6626          40 :         int iBlock = 0;
    6627          80 :         const int nBlocks = poDstDS->m_nBlocksPerBand *
    6628          40 :                             (l_nBands + (poDstDS->m_poMaskDS ? 1 : 0));
    6629         174 :         for (int i = 0; eErr == CE_None && i < l_nBands; i++)
    6630             :         {
    6631         313 :             for (int iY = 0, nYBlock = 0; iY < nYSize && eErr == CE_None;
    6632         179 :                  iY = ((nYSize - iY < poDstDS->m_nBlockYSize)
    6633         179 :                            ? nYSize
    6634          57 :                            : iY + poDstDS->m_nBlockYSize),
    6635             :                      nYBlock++)
    6636             :             {
    6637             :                 const int nReqYSize =
    6638         179 :                     std::min(nYSize - iY, poDstDS->m_nBlockYSize);
    6639         463 :                 for (int iX = 0, nXBlock = 0; iX < nXSize && eErr == CE_None;
    6640         284 :                      iX = ((nXSize - iX < poDstDS->m_nBlockXSize)
    6641         284 :                                ? nXSize
    6642         153 :                                : iX + poDstDS->m_nBlockXSize),
    6643             :                          nXBlock++)
    6644             :                 {
    6645             :                     const int nReqXSize =
    6646         284 :                         std::min(nXSize - iX, poDstDS->m_nBlockXSize);
    6647         284 :                     if (nReqXSize < poDstDS->m_nBlockXSize ||
    6648         153 :                         nReqYSize < poDstDS->m_nBlockYSize)
    6649             :                     {
    6650         176 :                         memset(pBlockBuffer, 0,
    6651         176 :                                static_cast<size_t>(poDstDS->m_nBlockXSize) *
    6652         176 :                                    poDstDS->m_nBlockYSize * nDataTypeSize);
    6653             :                     }
    6654         284 :                     eErr = poSrcDS->GetRasterBand(i + 1)->RasterIO(
    6655             :                         GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
    6656             :                         nReqXSize, nReqYSize, eType, nDataTypeSize,
    6657         284 :                         static_cast<GSpacing>(nDataTypeSize) *
    6658         284 :                             poDstDS->m_nBlockXSize,
    6659             :                         nullptr);
    6660         284 :                     if (eErr == CE_None)
    6661             :                     {
    6662         284 :                         eErr = poDstDS->WriteEncodedTileOrStrip(
    6663             :                             iBlock, pBlockBuffer, false);
    6664             :                     }
    6665             : 
    6666         284 :                     iBlock++;
    6667         568 :                     if (pfnProgress &&
    6668         284 :                         !pfnProgress(static_cast<double>(iBlock) / nBlocks,
    6669             :                                      nullptr, pProgressData))
    6670             :                     {
    6671           0 :                         eErr = CE_Failure;
    6672             :                     }
    6673             : 
    6674         284 :                     if (poDstDS->m_bWriteError)
    6675           0 :                         eErr = CE_Failure;
    6676             :                 }
    6677             :             }
    6678             :         }
    6679          40 :         if (poDstDS->m_poMaskDS && eErr == CE_None)
    6680             :         {
    6681           6 :             int iBlockMask = 0;
    6682          17 :             for (int iY = 0, nYBlock = 0; iY < nYSize && eErr == CE_None;
    6683          11 :                  iY = ((nYSize - iY < poDstDS->m_nBlockYSize)
    6684          11 :                            ? nYSize
    6685           5 :                            : iY + poDstDS->m_nBlockYSize),
    6686             :                      nYBlock++)
    6687             :             {
    6688             :                 const int nReqYSize =
    6689          11 :                     std::min(nYSize - iY, poDstDS->m_nBlockYSize);
    6690          49 :                 for (int iX = 0, nXBlock = 0; iX < nXSize && eErr == CE_None;
    6691          38 :                      iX = ((nXSize - iX < poDstDS->m_nBlockXSize)
    6692          38 :                                ? nXSize
    6693          30 :                                : iX + poDstDS->m_nBlockXSize),
    6694             :                          nXBlock++)
    6695             :                 {
    6696             :                     const int nReqXSize =
    6697          38 :                         std::min(nXSize - iX, poDstDS->m_nBlockXSize);
    6698          38 :                     if (nReqXSize < poDstDS->m_nBlockXSize ||
    6699          30 :                         nReqYSize < poDstDS->m_nBlockYSize)
    6700             :                     {
    6701          16 :                         memset(pBlockBuffer, 0,
    6702          16 :                                static_cast<size_t>(poDstDS->m_nBlockXSize) *
    6703          16 :                                    poDstDS->m_nBlockYSize);
    6704             :                     }
    6705          76 :                     eErr = poSrcMaskBand->RasterIO(
    6706             :                         GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
    6707             :                         nReqXSize, nReqYSize, GDT_Byte, 1,
    6708          38 :                         poDstDS->m_nBlockXSize, nullptr);
    6709          38 :                     if (eErr == CE_None)
    6710             :                     {
    6711             :                         // Avoid any attempt to load from disk
    6712          38 :                         poDstDS->m_poMaskDS->m_nLoadedBlock = iBlockMask;
    6713             :                         eErr =
    6714          38 :                             poDstDS->m_poMaskDS->GetRasterBand(1)->WriteBlock(
    6715             :                                 nXBlock, nYBlock, pBlockBuffer);
    6716          38 :                         if (eErr == CE_None)
    6717          38 :                             eErr = poDstDS->m_poMaskDS->FlushBlockBuf();
    6718             :                     }
    6719             : 
    6720          38 :                     iBlockMask++;
    6721          76 :                     if (pfnProgress &&
    6722          38 :                         !pfnProgress(static_cast<double>(iBlock + iBlockMask) /
    6723             :                                          nBlocks,
    6724             :                                      nullptr, pProgressData))
    6725             :                     {
    6726           0 :                         eErr = CE_Failure;
    6727             :                     }
    6728             : 
    6729          38 :                     if (poDstDS->m_poMaskDS->m_bWriteError)
    6730           0 :                         eErr = CE_Failure;
    6731             :                 }
    6732             :             }
    6733          40 :         }
    6734             :     }
    6735             :     else
    6736             :     {
    6737         254 :         int iBlock = 0;
    6738         254 :         const int nBlocks = poDstDS->m_nBlocksPerBand;
    6739        6997 :         for (int iY = 0, nYBlock = 0; iY < nYSize && eErr == CE_None;
    6740        6743 :              iY = ((nYSize - iY < poDstDS->m_nBlockYSize)
    6741        6743 :                        ? nYSize
    6742        6559 :                        : iY + poDstDS->m_nBlockYSize),
    6743             :                  nYBlock++)
    6744             :         {
    6745        6743 :             const int nReqYSize = std::min(nYSize - iY, poDstDS->m_nBlockYSize);
    6746       26391 :             for (int iX = 0, nXBlock = 0; iX < nXSize && eErr == CE_None;
    6747       19648 :                  iX = ((nXSize - iX < poDstDS->m_nBlockXSize)
    6748       19648 :                            ? nXSize
    6749       19393 :                            : iX + poDstDS->m_nBlockXSize),
    6750             :                      nXBlock++)
    6751             :             {
    6752             :                 const int nReqXSize =
    6753       19648 :                     std::min(nXSize - iX, poDstDS->m_nBlockXSize);
    6754       19648 :                 if (nReqXSize < poDstDS->m_nBlockXSize ||
    6755       19393 :                     nReqYSize < poDstDS->m_nBlockYSize)
    6756             :                 {
    6757         415 :                     memset(pBlockBuffer, 0,
    6758         415 :                            static_cast<size_t>(poDstDS->m_nBlockXSize) *
    6759         415 :                                poDstDS->m_nBlockYSize * l_nBands *
    6760         415 :                                nDataTypeSize);
    6761             :                 }
    6762             : 
    6763       19648 :                 if (poDstDS->m_bTileInterleave)
    6764             :                 {
    6765         114 :                     eErr = poSrcDS->RasterIO(
    6766             :                         GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
    6767             :                         nReqXSize, nReqYSize, eType, l_nBands, nullptr,
    6768             :                         nDataTypeSize,
    6769          57 :                         static_cast<GSpacing>(nDataTypeSize) *
    6770          57 :                             poDstDS->m_nBlockXSize,
    6771          57 :                         static_cast<GSpacing>(nDataTypeSize) *
    6772          57 :                             poDstDS->m_nBlockXSize * poDstDS->m_nBlockYSize,
    6773             :                         nullptr);
    6774          57 :                     if (eErr == CE_None)
    6775             :                     {
    6776         228 :                         for (int i = 0; eErr == CE_None && i < l_nBands; i++)
    6777             :                         {
    6778         171 :                             eErr = poDstDS->WriteEncodedTileOrStrip(
    6779         171 :                                 iBlock + i * poDstDS->m_nBlocksPerBand,
    6780         171 :                                 pBlockBuffer + static_cast<size_t>(i) *
    6781         171 :                                                    poDstDS->m_nBlockXSize *
    6782         171 :                                                    poDstDS->m_nBlockYSize *
    6783         171 :                                                    nDataTypeSize,
    6784             :                                 false);
    6785             :                         }
    6786             :                     }
    6787             :                 }
    6788       19591 :                 else if (!bIsOddBand)
    6789             :                 {
    6790       39060 :                     eErr = poSrcDS->RasterIO(
    6791             :                         GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
    6792             :                         nReqXSize, nReqYSize, eType, l_nBands, nullptr,
    6793       19530 :                         static_cast<GSpacing>(nDataTypeSize) * l_nBands,
    6794       19530 :                         static_cast<GSpacing>(nDataTypeSize) * l_nBands *
    6795       19530 :                             poDstDS->m_nBlockXSize,
    6796             :                         nDataTypeSize, nullptr);
    6797       19530 :                     if (eErr == CE_None)
    6798             :                     {
    6799       19529 :                         eErr = poDstDS->WriteEncodedTileOrStrip(
    6800             :                             iBlock, pBlockBuffer, false);
    6801             :                     }
    6802             :                 }
    6803             :                 else
    6804             :                 {
    6805             :                     // In the odd bit case, this is a bit messy to ensure
    6806             :                     // the strile gets written synchronously.
    6807             :                     // We load the content of the n-1 bands in the cache,
    6808             :                     // and for the last band we invoke WriteBlock() directly
    6809             :                     // We also force FlushBlockBuf()
    6810         122 :                     std::vector<GDALRasterBlock *> apoLockedBlocks;
    6811          91 :                     for (int i = 0; eErr == CE_None && i < l_nBands - 1; i++)
    6812             :                     {
    6813             :                         auto poBlock =
    6814          30 :                             poDstDS->GetRasterBand(i + 1)->GetLockedBlockRef(
    6815          30 :                                 nXBlock, nYBlock, TRUE);
    6816          30 :                         if (poBlock)
    6817             :                         {
    6818          60 :                             eErr = poSrcDS->GetRasterBand(i + 1)->RasterIO(
    6819             :                                 GF_Read, iX, iY, nReqXSize, nReqYSize,
    6820             :                                 poBlock->GetDataRef(), nReqXSize, nReqYSize,
    6821             :                                 eType, nDataTypeSize,
    6822          30 :                                 static_cast<GSpacing>(nDataTypeSize) *
    6823          30 :                                     poDstDS->m_nBlockXSize,
    6824             :                                 nullptr);
    6825          30 :                             poBlock->MarkDirty();
    6826          30 :                             apoLockedBlocks.emplace_back(poBlock);
    6827             :                         }
    6828             :                         else
    6829             :                         {
    6830           0 :                             eErr = CE_Failure;
    6831             :                         }
    6832             :                     }
    6833          61 :                     if (eErr == CE_None)
    6834             :                     {
    6835         122 :                         eErr = poSrcDS->GetRasterBand(l_nBands)->RasterIO(
    6836             :                             GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
    6837             :                             nReqXSize, nReqYSize, eType, nDataTypeSize,
    6838          61 :                             static_cast<GSpacing>(nDataTypeSize) *
    6839          61 :                                 poDstDS->m_nBlockXSize,
    6840             :                             nullptr);
    6841             :                     }
    6842          61 :                     if (eErr == CE_None)
    6843             :                     {
    6844             :                         // Avoid any attempt to load from disk
    6845          61 :                         poDstDS->m_nLoadedBlock = iBlock;
    6846          61 :                         eErr = poDstDS->GetRasterBand(l_nBands)->WriteBlock(
    6847             :                             nXBlock, nYBlock, pBlockBuffer);
    6848          61 :                         if (eErr == CE_None)
    6849          61 :                             eErr = poDstDS->FlushBlockBuf();
    6850             :                     }
    6851          91 :                     for (auto poBlock : apoLockedBlocks)
    6852             :                     {
    6853          30 :                         poBlock->MarkClean();
    6854          30 :                         poBlock->DropLock();
    6855             :                     }
    6856             :                 }
    6857             : 
    6858       19648 :                 if (eErr == CE_None && poDstDS->m_poMaskDS)
    6859             :                 {
    6860        4669 :                     if (nReqXSize < poDstDS->m_nBlockXSize ||
    6861        4627 :                         nReqYSize < poDstDS->m_nBlockYSize)
    6862             :                     {
    6863          81 :                         memset(pBlockBuffer, 0,
    6864          81 :                                static_cast<size_t>(poDstDS->m_nBlockXSize) *
    6865          81 :                                    poDstDS->m_nBlockYSize);
    6866             :                     }
    6867        9338 :                     eErr = poSrcMaskBand->RasterIO(
    6868             :                         GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
    6869             :                         nReqXSize, nReqYSize, GDT_Byte, 1,
    6870        4669 :                         poDstDS->m_nBlockXSize, nullptr);
    6871        4669 :                     if (eErr == CE_None)
    6872             :                     {
    6873             :                         // Avoid any attempt to load from disk
    6874        4669 :                         poDstDS->m_poMaskDS->m_nLoadedBlock = iBlock;
    6875             :                         eErr =
    6876        4669 :                             poDstDS->m_poMaskDS->GetRasterBand(1)->WriteBlock(
    6877             :                                 nXBlock, nYBlock, pBlockBuffer);
    6878        4669 :                         if (eErr == CE_None)
    6879        4669 :                             eErr = poDstDS->m_poMaskDS->FlushBlockBuf();
    6880             :                     }
    6881             :                 }
    6882       19648 :                 if (poDstDS->m_bWriteError)
    6883           6 :                     eErr = CE_Failure;
    6884             : 
    6885       19648 :                 iBlock++;
    6886       39296 :                 if (pfnProgress &&
    6887       19648 :                     !pfnProgress(static_cast<double>(iBlock) / nBlocks, nullptr,
    6888             :                                  pProgressData))
    6889             :                 {
    6890           0 :                     eErr = CE_Failure;
    6891             :                 }
    6892             :             }
    6893             :         }
    6894             :     }
    6895             : 
    6896         294 :     poDstDS->FlushCache(false);  // mostly to wait for thread completion
    6897         294 :     VSIFree(pBlockBuffer);
    6898             : 
    6899         294 :     return eErr;
    6900             : }
    6901             : 
    6902             : /************************************************************************/
    6903             : /*                             CreateCopy()                             */
    6904             : /************************************************************************/
    6905             : 
    6906        1952 : GDALDataset *GTiffDataset::CreateCopy(const char *pszFilename,
    6907             :                                       GDALDataset *poSrcDS, int bStrict,
    6908             :                                       char **papszOptions,
    6909             :                                       GDALProgressFunc pfnProgress,
    6910             :                                       void *pProgressData)
    6911             : 
    6912             : {
    6913        1952 :     if (poSrcDS->GetRasterCount() == 0)
    6914             :     {
    6915           2 :         ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
    6916             :                     "Unable to export GeoTIFF files with zero bands.");
    6917           2 :         return nullptr;
    6918             :     }
    6919             : 
    6920        1950 :     GDALRasterBand *const poPBand = poSrcDS->GetRasterBand(1);
    6921        1950 :     GDALDataType eType = poPBand->GetRasterDataType();
    6922             : 
    6923             :     /* -------------------------------------------------------------------- */
    6924             :     /*      Check, whether all bands in input dataset has the same type.    */
    6925             :     /* -------------------------------------------------------------------- */
    6926        1950 :     const int l_nBands = poSrcDS->GetRasterCount();
    6927        4785 :     for (int iBand = 2; iBand <= l_nBands; ++iBand)
    6928             :     {
    6929        2835 :         if (eType != poSrcDS->GetRasterBand(iBand)->GetRasterDataType())
    6930             :         {
    6931           0 :             if (bStrict)
    6932             :             {
    6933           0 :                 ReportError(
    6934             :                     pszFilename, CE_Failure, CPLE_AppDefined,
    6935             :                     "Unable to export GeoTIFF file with different datatypes "
    6936             :                     "per different bands. All bands should have the same "
    6937             :                     "types in TIFF.");
    6938           0 :                 return nullptr;
    6939             :             }
    6940             :             else
    6941             :             {
    6942           0 :                 ReportError(
    6943             :                     pszFilename, CE_Warning, CPLE_AppDefined,
    6944             :                     "Unable to export GeoTIFF file with different datatypes "
    6945             :                     "per different bands. All bands should have the same "
    6946             :                     "types in TIFF.");
    6947             :             }
    6948             :         }
    6949             :     }
    6950             : 
    6951             :     /* -------------------------------------------------------------------- */
    6952             :     /*      Capture the profile.                                            */
    6953             :     /* -------------------------------------------------------------------- */
    6954             :     const GTiffProfile eProfile =
    6955        1950 :         GetProfile(CSLFetchNameValue(papszOptions, "PROFILE"));
    6956             : 
    6957        1950 :     const bool bGeoTIFF = eProfile != GTiffProfile::BASELINE;
    6958             : 
    6959             :     /* -------------------------------------------------------------------- */
    6960             :     /*      Special handling for NBITS.  Copy from band metadata if found.  */
    6961             :     /* -------------------------------------------------------------------- */
    6962        1950 :     char **papszCreateOptions = CSLDuplicate(papszOptions);
    6963             : 
    6964        1950 :     if (poPBand->GetMetadataItem("NBITS", "IMAGE_STRUCTURE") != nullptr &&
    6965        1969 :         atoi(poPBand->GetMetadataItem("NBITS", "IMAGE_STRUCTURE")) > 0 &&
    6966          19 :         CSLFetchNameValue(papszCreateOptions, "NBITS") == nullptr)
    6967             :     {
    6968           5 :         papszCreateOptions = CSLSetNameValue(
    6969             :             papszCreateOptions, "NBITS",
    6970           5 :             poPBand->GetMetadataItem("NBITS", "IMAGE_STRUCTURE"));
    6971             :     }
    6972             : 
    6973        1950 :     if (CSLFetchNameValue(papszOptions, "PIXELTYPE") == nullptr &&
    6974             :         eType == GDT_Byte)
    6975             :     {
    6976        1636 :         poPBand->EnablePixelTypeSignedByteWarning(false);
    6977             :         const char *pszPixelType =
    6978        1636 :             poPBand->GetMetadataItem("PIXELTYPE", "IMAGE_STRUCTURE");
    6979        1636 :         poPBand->EnablePixelTypeSignedByteWarning(true);
    6980        1636 :         if (pszPixelType)
    6981             :         {
    6982           1 :             papszCreateOptions =
    6983           1 :                 CSLSetNameValue(papszCreateOptions, "PIXELTYPE", pszPixelType);
    6984             :         }
    6985             :     }
    6986             : 
    6987             :     /* -------------------------------------------------------------------- */
    6988             :     /*      Color profile.  Copy from band metadata if found.              */
    6989             :     /* -------------------------------------------------------------------- */
    6990        1950 :     if (bGeoTIFF)
    6991             :     {
    6992        1933 :         const char *pszOptionsMD[] = {"SOURCE_ICC_PROFILE",
    6993             :                                       "SOURCE_PRIMARIES_RED",
    6994             :                                       "SOURCE_PRIMARIES_GREEN",
    6995             :                                       "SOURCE_PRIMARIES_BLUE",
    6996             :                                       "SOURCE_WHITEPOINT",
    6997             :                                       "TIFFTAG_TRANSFERFUNCTION_RED",
    6998             :                                       "TIFFTAG_TRANSFERFUNCTION_GREEN",
    6999             :                                       "TIFFTAG_TRANSFERFUNCTION_BLUE",
    7000             :                                       "TIFFTAG_TRANSFERRANGE_BLACK",
    7001             :                                       "TIFFTAG_TRANSFERRANGE_WHITE",
    7002             :                                       nullptr};
    7003             : 
    7004             :         // Copy all the tags.  Options will override tags in the source.
    7005        1933 :         int i = 0;
    7006       21243 :         while (pszOptionsMD[i] != nullptr)
    7007             :         {
    7008             :             char const *pszMD =
    7009       19312 :                 CSLFetchNameValue(papszOptions, pszOptionsMD[i]);
    7010       19312 :             if (pszMD == nullptr)
    7011             :                 pszMD =
    7012       19304 :                     poSrcDS->GetMetadataItem(pszOptionsMD[i], "COLOR_PROFILE");
    7013             : 
    7014       19312 :             if ((pszMD != nullptr) && !EQUAL(pszMD, ""))
    7015             :             {
    7016          16 :                 papszCreateOptions =
    7017          16 :                     CSLSetNameValue(papszCreateOptions, pszOptionsMD[i], pszMD);
    7018             : 
    7019             :                 // If an ICC profile exists, other tags are not needed.
    7020          16 :                 if (EQUAL(pszOptionsMD[i], "SOURCE_ICC_PROFILE"))
    7021           2 :                     break;
    7022             :             }
    7023             : 
    7024       19310 :             ++i;
    7025             :         }
    7026             :     }
    7027             : 
    7028        1950 :     double dfExtraSpaceForOverviews = 0;
    7029             :     const bool bCopySrcOverviews =
    7030        1950 :         CPLFetchBool(papszCreateOptions, "COPY_SRC_OVERVIEWS", false);
    7031        1950 :     std::unique_ptr<GDALDataset> poOvrDS;
    7032        1950 :     int nSrcOverviews = 0;
    7033        1950 :     if (bCopySrcOverviews)
    7034             :     {
    7035             :         const char *pszOvrDS =
    7036         181 :             CSLFetchNameValue(papszCreateOptions, "@OVERVIEW_DATASET");
    7037         181 :         if (pszOvrDS)
    7038             :         {
    7039             :             // Empty string is used by COG driver to indicate that we want
    7040             :             // to ignore source overviews.
    7041          38 :             if (!EQUAL(pszOvrDS, ""))
    7042             :             {
    7043          36 :                 poOvrDS.reset(GDALDataset::Open(pszOvrDS));
    7044          36 :                 if (!poOvrDS)
    7045             :                 {
    7046           0 :                     CSLDestroy(papszCreateOptions);
    7047           0 :                     return nullptr;
    7048             :                 }
    7049          36 :                 if (poOvrDS->GetRasterCount() != l_nBands)
    7050             :                 {
    7051           0 :                     CSLDestroy(papszCreateOptions);
    7052           0 :                     return nullptr;
    7053             :                 }
    7054          36 :                 nSrcOverviews =
    7055          36 :                     poOvrDS->GetRasterBand(1)->GetOverviewCount() + 1;
    7056             :             }
    7057             :         }
    7058             :         else
    7059             :         {
    7060         143 :             nSrcOverviews = poSrcDS->GetRasterBand(1)->GetOverviewCount();
    7061             :         }
    7062             : 
    7063             :         // Limit number of overviews if specified
    7064             :         const char *pszOverviewCount =
    7065         181 :             CSLFetchNameValue(papszCreateOptions, "@OVERVIEW_COUNT");
    7066         181 :         if (pszOverviewCount)
    7067           8 :             nSrcOverviews =
    7068           8 :                 std::max(0, std::min(nSrcOverviews, atoi(pszOverviewCount)));
    7069             : 
    7070         181 :         if (nSrcOverviews)
    7071             :         {
    7072         194 :             for (int j = 1; j <= l_nBands; ++j)
    7073             :             {
    7074             :                 const int nOtherBandOverviewCount =
    7075         129 :                     poOvrDS ? poOvrDS->GetRasterBand(j)->GetOverviewCount() + 1
    7076         179 :                             : poSrcDS->GetRasterBand(j)->GetOverviewCount();
    7077         129 :                 if (nOtherBandOverviewCount < nSrcOverviews)
    7078             :                 {
    7079           1 :                     ReportError(
    7080             :                         pszFilename, CE_Failure, CPLE_NotSupported,
    7081             :                         "COPY_SRC_OVERVIEWS cannot be used when the bands have "
    7082             :                         "not the same number of overview levels.");
    7083           1 :                     CSLDestroy(papszCreateOptions);
    7084           1 :                     return nullptr;
    7085             :                 }
    7086         388 :                 for (int i = 0; i < nSrcOverviews; ++i)
    7087             :                 {
    7088             :                     GDALRasterBand *poOvrBand =
    7089             :                         poOvrDS
    7090         370 :                             ? (i == 0 ? poOvrDS->GetRasterBand(j)
    7091         216 :                                       : poOvrDS->GetRasterBand(j)->GetOverview(
    7092         108 :                                             i - 1))
    7093         337 :                             : poSrcDS->GetRasterBand(j)->GetOverview(i);
    7094         262 :                     if (poOvrBand == nullptr)
    7095             :                     {
    7096           1 :                         ReportError(
    7097             :                             pszFilename, CE_Failure, CPLE_NotSupported,
    7098             :                             "COPY_SRC_OVERVIEWS cannot be used when one "
    7099             :                             "overview band is NULL.");
    7100           1 :                         CSLDestroy(papszCreateOptions);
    7101           1 :                         return nullptr;
    7102             :                     }
    7103             :                     GDALRasterBand *poOvrFirstBand =
    7104             :                         poOvrDS
    7105         369 :                             ? (i == 0 ? poOvrDS->GetRasterBand(1)
    7106         216 :                                       : poOvrDS->GetRasterBand(1)->GetOverview(
    7107         108 :                                             i - 1))
    7108         335 :                             : poSrcDS->GetRasterBand(1)->GetOverview(i);
    7109         521 :                     if (poOvrBand->GetXSize() != poOvrFirstBand->GetXSize() ||
    7110         260 :                         poOvrBand->GetYSize() != poOvrFirstBand->GetYSize())
    7111             :                     {
    7112           1 :                         ReportError(
    7113             :                             pszFilename, CE_Failure, CPLE_NotSupported,
    7114             :                             "COPY_SRC_OVERVIEWS cannot be used when the "
    7115             :                             "overview bands have not the same dimensions "
    7116             :                             "among bands.");
    7117           1 :                         CSLDestroy(papszCreateOptions);
    7118           1 :                         return nullptr;
    7119             :                     }
    7120             :                 }
    7121             :             }
    7122             : 
    7123         190 :             for (int i = 0; i < nSrcOverviews; ++i)
    7124             :             {
    7125             :                 GDALRasterBand *poOvrFirstBand =
    7126             :                     poOvrDS
    7127         203 :                         ? (i == 0
    7128          78 :                                ? poOvrDS->GetRasterBand(1)
    7129          42 :                                : poOvrDS->GetRasterBand(1)->GetOverview(i - 1))
    7130         172 :                         : poSrcDS->GetRasterBand(1)->GetOverview(i);
    7131         125 :                 dfExtraSpaceForOverviews +=
    7132         125 :                     static_cast<double>(poOvrFirstBand->GetXSize()) *
    7133         125 :                     poOvrFirstBand->GetYSize();
    7134             :             }
    7135          65 :             dfExtraSpaceForOverviews *=
    7136          65 :                 l_nBands * GDALGetDataTypeSizeBytes(eType);
    7137             :         }
    7138             :         else
    7139             :         {
    7140         113 :             CPLDebug("GTiff", "No source overviews to copy");
    7141             :         }
    7142             :     }
    7143             : 
    7144             : /* -------------------------------------------------------------------- */
    7145             : /*      Should we use optimized way of copying from an input JPEG       */
    7146             : /*      dataset?                                                        */
    7147             : /* -------------------------------------------------------------------- */
    7148             : 
    7149             : // TODO(schwehr): Refactor bDirectCopyFromJPEG to be a const.
    7150             : #if defined(HAVE_LIBJPEG) || defined(JPEG_DIRECT_COPY)
    7151        1947 :     bool bDirectCopyFromJPEG = false;
    7152             : #endif
    7153             : 
    7154             :     // Note: JPEG_DIRECT_COPY is not defined by default, because it is mainly
    7155             :     // useful for debugging purposes.
    7156             : #ifdef JPEG_DIRECT_COPY
    7157             :     if (CPLFetchBool(papszCreateOptions, "JPEG_DIRECT_COPY", false) &&
    7158             :         GTIFF_CanDirectCopyFromJPEG(poSrcDS, papszCreateOptions))
    7159             :     {
    7160             :         CPLDebug("GTiff", "Using special direct copy mode from a JPEG dataset");
    7161             : 
    7162             :         bDirectCopyFromJPEG = true;
    7163             :     }
    7164             : #endif
    7165             : 
    7166             : #ifdef HAVE_LIBJPEG
    7167        1947 :     bool bCopyFromJPEG = false;
    7168             : 
    7169             :     // When CreateCopy'ing() from a JPEG dataset, and asking for COMPRESS=JPEG,
    7170             :     // use DCT coefficients (unless other options are incompatible, like
    7171             :     // strip/tile dimensions, specifying JPEG_QUALITY option, incompatible
    7172             :     // PHOTOMETRIC with the source colorspace, etc.) to avoid the lossy steps
    7173             :     // involved by decompression/recompression.
    7174        3894 :     if (!bDirectCopyFromJPEG &&
    7175        1947 :         GTIFF_CanCopyFromJPEG(poSrcDS, papszCreateOptions))
    7176             :     {
    7177          12 :         CPLDebug("GTiff", "Using special copy mode from a JPEG dataset");
    7178             : 
    7179          12 :         bCopyFromJPEG = true;
    7180             :     }
    7181             : #endif
    7182             : 
    7183             :     /* -------------------------------------------------------------------- */
    7184             :     /*      If the source is RGB, then set the PHOTOMETRIC=RGB value        */
    7185             :     /* -------------------------------------------------------------------- */
    7186             : 
    7187             :     const bool bForcePhotometric =
    7188        1947 :         CSLFetchNameValue(papszOptions, "PHOTOMETRIC") != nullptr;
    7189             : 
    7190        1188 :     if (l_nBands >= 3 && !bForcePhotometric &&
    7191             : #ifdef HAVE_LIBJPEG
    7192        1150 :         !bCopyFromJPEG &&
    7193             : #endif
    7194        1144 :         poSrcDS->GetRasterBand(1)->GetColorInterpretation() == GCI_RedBand &&
    7195        4183 :         poSrcDS->GetRasterBand(2)->GetColorInterpretation() == GCI_GreenBand &&
    7196        1048 :         poSrcDS->GetRasterBand(3)->GetColorInterpretation() == GCI_BlueBand)
    7197             :     {
    7198        1042 :         papszCreateOptions =
    7199        1042 :             CSLSetNameValue(papszCreateOptions, "PHOTOMETRIC", "RGB");
    7200             :     }
    7201             : 
    7202             :     /* -------------------------------------------------------------------- */
    7203             :     /*      Create the file.                                                */
    7204             :     /* -------------------------------------------------------------------- */
    7205        1947 :     VSILFILE *l_fpL = nullptr;
    7206        3894 :     CPLString l_osTmpFilename;
    7207             : 
    7208        1947 :     const int nXSize = poSrcDS->GetRasterXSize();
    7209        1947 :     const int nYSize = poSrcDS->GetRasterYSize();
    7210             : 
    7211             :     const int nColorTableMultiplier = std::max(
    7212        3894 :         1,
    7213        3894 :         std::min(257,
    7214        1947 :                  atoi(CSLFetchNameValueDef(
    7215             :                      papszOptions, "COLOR_TABLE_MULTIPLIER",
    7216        1947 :                      CPLSPrintf("%d", DEFAULT_COLOR_TABLE_MULTIPLIER_257)))));
    7217             : 
    7218        1947 :     bool bTileInterleaving = false;
    7219        1947 :     TIFF *l_hTIFF = CreateLL(pszFilename, nXSize, nYSize, l_nBands, eType,
    7220             :                              dfExtraSpaceForOverviews, nColorTableMultiplier,
    7221             :                              papszCreateOptions, &l_fpL, l_osTmpFilename,
    7222             :                              /* bCreateCopy = */ true, bTileInterleaving);
    7223        1947 :     const bool bStreaming = !l_osTmpFilename.empty();
    7224             : 
    7225        1947 :     CSLDestroy(papszCreateOptions);
    7226        1947 :     papszCreateOptions = nullptr;
    7227             : 
    7228        1947 :     if (l_hTIFF == nullptr)
    7229             :     {
    7230          14 :         if (bStreaming)
    7231           0 :             VSIUnlink(l_osTmpFilename);
    7232          14 :         return nullptr;
    7233             :     }
    7234             : 
    7235        1933 :     uint16_t l_nPlanarConfig = 0;
    7236        1933 :     TIFFGetField(l_hTIFF, TIFFTAG_PLANARCONFIG, &l_nPlanarConfig);
    7237             : 
    7238        1933 :     uint16_t l_nCompression = 0;
    7239             : 
    7240        1933 :     if (!TIFFGetField(l_hTIFF, TIFFTAG_COMPRESSION, &(l_nCompression)))
    7241           0 :         l_nCompression = COMPRESSION_NONE;
    7242             : 
    7243             :     /* -------------------------------------------------------------------- */
    7244             :     /*      Set the alpha channel if we find one.                           */
    7245             :     /* -------------------------------------------------------------------- */
    7246        1933 :     uint16_t *extraSamples = nullptr;
    7247        1933 :     uint16_t nExtraSamples = 0;
    7248        1933 :     if (TIFFGetField(l_hTIFF, TIFFTAG_EXTRASAMPLES, &nExtraSamples,
    7249        2173 :                      &extraSamples) &&
    7250         240 :         nExtraSamples > 0)
    7251             :     {
    7252             :         // We need to allocate a new array as (current) libtiff
    7253             :         // versions will not like that we reuse the array we got from
    7254             :         // TIFFGetField().
    7255             :         uint16_t *pasNewExtraSamples = static_cast<uint16_t *>(
    7256         240 :             CPLMalloc(nExtraSamples * sizeof(uint16_t)));
    7257         240 :         memcpy(pasNewExtraSamples, extraSamples,
    7258         240 :                nExtraSamples * sizeof(uint16_t));
    7259         240 :         const char *pszAlpha = CPLGetConfigOption(
    7260             :             "GTIFF_ALPHA", CSLFetchNameValue(papszOptions, "ALPHA"));
    7261             :         const uint16_t nAlpha =
    7262         240 :             GTiffGetAlphaValue(pszAlpha, DEFAULT_ALPHA_TYPE);
    7263         240 :         const int nBaseSamples = l_nBands - nExtraSamples;
    7264         832 :         for (int iExtraBand = nBaseSamples + 1; iExtraBand <= l_nBands;
    7265             :              iExtraBand++)
    7266             :         {
    7267         592 :             if (poSrcDS->GetRasterBand(iExtraBand)->GetColorInterpretation() ==
    7268             :                 GCI_AlphaBand)
    7269             :             {
    7270         132 :                 pasNewExtraSamples[iExtraBand - nBaseSamples - 1] = nAlpha;
    7271         132 :                 if (!pszAlpha)
    7272             :                 {
    7273             :                     // Use the ALPHA metadata item from the source band, when
    7274             :                     // present, if no explicit ALPHA creation option
    7275         260 :                     pasNewExtraSamples[iExtraBand - nBaseSamples - 1] =
    7276         130 :                         GTiffGetAlphaValue(
    7277         130 :                             poSrcDS->GetRasterBand(iExtraBand)
    7278         130 :                                 ->GetMetadataItem("ALPHA", "IMAGE_STRUCTURE"),
    7279             :                             nAlpha);
    7280             :                 }
    7281             :             }
    7282             :         }
    7283         240 :         TIFFSetField(l_hTIFF, TIFFTAG_EXTRASAMPLES, nExtraSamples,
    7284             :                      pasNewExtraSamples);
    7285             : 
    7286         240 :         CPLFree(pasNewExtraSamples);
    7287             :     }
    7288             : 
    7289             :     /* -------------------------------------------------------------------- */
    7290             :     /*      If the output is jpeg compressed, and the input is RGB make     */
    7291             :     /*      sure we note that.                                              */
    7292             :     /* -------------------------------------------------------------------- */
    7293             : 
    7294        1933 :     if (l_nCompression == COMPRESSION_JPEG)
    7295             :     {
    7296         134 :         if (l_nBands >= 3 &&
    7297          58 :             (poSrcDS->GetRasterBand(1)->GetColorInterpretation() ==
    7298           0 :              GCI_YCbCr_YBand) &&
    7299           0 :             (poSrcDS->GetRasterBand(2)->GetColorInterpretation() ==
    7300         134 :              GCI_YCbCr_CbBand) &&
    7301           0 :             (poSrcDS->GetRasterBand(3)->GetColorInterpretation() ==
    7302             :              GCI_YCbCr_CrBand))
    7303             :         {
    7304             :             // Do nothing.
    7305             :         }
    7306             :         else
    7307             :         {
    7308             :             // Assume RGB if it is not explicitly YCbCr.
    7309          76 :             CPLDebug("GTiff", "Setting JPEGCOLORMODE_RGB");
    7310          76 :             TIFFSetField(l_hTIFF, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
    7311             :         }
    7312             :     }
    7313             : 
    7314             :     /* -------------------------------------------------------------------- */
    7315             :     /*      Does the source image consist of one band, with a palette?      */
    7316             :     /*      If so, copy over.                                               */
    7317             :     /* -------------------------------------------------------------------- */
    7318        1264 :     if ((l_nBands == 1 || l_nBands == 2) &&
    7319        3197 :         poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
    7320             :         eType == GDT_Byte)
    7321             :     {
    7322          10 :         unsigned short anTRed[256] = {0};
    7323          10 :         unsigned short anTGreen[256] = {0};
    7324          10 :         unsigned short anTBlue[256] = {0};
    7325          10 :         GDALColorTable *poCT = poSrcDS->GetRasterBand(1)->GetColorTable();
    7326             : 
    7327        2570 :         for (int iColor = 0; iColor < 256; ++iColor)
    7328             :         {
    7329        2560 :             if (iColor < poCT->GetColorEntryCount())
    7330             :             {
    7331        1505 :                 GDALColorEntry sRGB = {0, 0, 0, 0};
    7332             : 
    7333        1505 :                 poCT->GetColorEntryAsRGB(iColor, &sRGB);
    7334             : 
    7335        3010 :                 anTRed[iColor] = GTiffDataset::ClampCTEntry(
    7336        1505 :                     iColor, 1, sRGB.c1, nColorTableMultiplier);
    7337        3010 :                 anTGreen[iColor] = GTiffDataset::ClampCTEntry(
    7338        1505 :                     iColor, 2, sRGB.c2, nColorTableMultiplier);
    7339        1505 :                 anTBlue[iColor] = GTiffDataset::ClampCTEntry(
    7340        1505 :                     iColor, 3, sRGB.c3, nColorTableMultiplier);
    7341             :             }
    7342             :             else
    7343             :             {
    7344        1055 :                 anTRed[iColor] = 0;
    7345        1055 :                 anTGreen[iColor] = 0;
    7346        1055 :                 anTBlue[iColor] = 0;
    7347             :             }
    7348             :         }
    7349             : 
    7350          10 :         if (!bForcePhotometric)
    7351          10 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
    7352          10 :         TIFFSetField(l_hTIFF, TIFFTAG_COLORMAP, anTRed, anTGreen, anTBlue);
    7353             :     }
    7354        1263 :     else if ((l_nBands == 1 || l_nBands == 2) &&
    7355        3186 :              poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
    7356             :              eType == GDT_UInt16)
    7357             :     {
    7358             :         unsigned short *panTRed = static_cast<unsigned short *>(
    7359           1 :             CPLMalloc(65536 * sizeof(unsigned short)));
    7360             :         unsigned short *panTGreen = static_cast<unsigned short *>(
    7361           1 :             CPLMalloc(65536 * sizeof(unsigned short)));
    7362             :         unsigned short *panTBlue = static_cast<unsigned short *>(
    7363           1 :             CPLMalloc(65536 * sizeof(unsigned short)));
    7364             : 
    7365           1 :         GDALColorTable *poCT = poSrcDS->GetRasterBand(1)->GetColorTable();
    7366             : 
    7367       65537 :         for (int iColor = 0; iColor < 65536; ++iColor)
    7368             :         {
    7369       65536 :             if (iColor < poCT->GetColorEntryCount())
    7370             :             {
    7371       65536 :                 GDALColorEntry sRGB = {0, 0, 0, 0};
    7372             : 
    7373       65536 :                 poCT->GetColorEntryAsRGB(iColor, &sRGB);
    7374             : 
    7375      131072 :                 panTRed[iColor] = GTiffDataset::ClampCTEntry(
    7376       65536 :                     iColor, 1, sRGB.c1, nColorTableMultiplier);
    7377      131072 :                 panTGreen[iColor] = GTiffDataset::ClampCTEntry(
    7378       65536 :                     iColor, 2, sRGB.c2, nColorTableMultiplier);
    7379       65536 :                 panTBlue[iColor] = GTiffDataset::ClampCTEntry(
    7380       65536 :                     iColor, 3, sRGB.c3, nColorTableMultiplier);
    7381             :             }
    7382             :             else
    7383             :             {
    7384           0 :                 panTRed[iColor] = 0;
    7385           0 :                 panTGreen[iColor] = 0;
    7386           0 :                 panTBlue[iColor] = 0;
    7387             :             }
    7388             :         }
    7389             : 
    7390           1 :         if (!bForcePhotometric)
    7391           1 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
    7392           1 :         TIFFSetField(l_hTIFF, TIFFTAG_COLORMAP, panTRed, panTGreen, panTBlue);
    7393             : 
    7394           1 :         CPLFree(panTRed);
    7395           1 :         CPLFree(panTGreen);
    7396           1 :         CPLFree(panTBlue);
    7397             :     }
    7398        1922 :     else if (poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr)
    7399           1 :         ReportError(
    7400             :             pszFilename, CE_Failure, CPLE_AppDefined,
    7401             :             "Unable to export color table to GeoTIFF file.  Color tables "
    7402             :             "can only be written to 1 band or 2 bands Byte or "
    7403             :             "UInt16 GeoTIFF files.");
    7404             : 
    7405        1933 :     if (l_nCompression == COMPRESSION_JPEG)
    7406             :     {
    7407          76 :         uint16_t l_nPhotometric = 0;
    7408          76 :         TIFFGetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, &l_nPhotometric);
    7409             :         // Check done in tif_jpeg.c later, but not with a very clear error
    7410             :         // message
    7411          76 :         if (l_nPhotometric == PHOTOMETRIC_PALETTE)
    7412             :         {
    7413           1 :             ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    7414             :                         "JPEG compression not supported with paletted image");
    7415           1 :             XTIFFClose(l_hTIFF);
    7416           1 :             VSIUnlink(l_osTmpFilename);
    7417           1 :             CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    7418           1 :             return nullptr;
    7419             :         }
    7420             :     }
    7421             : 
    7422        2009 :     if (l_nBands == 2 &&
    7423        1932 :         poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
    7424           0 :         (eType == GDT_Byte || eType == GDT_UInt16))
    7425             :     {
    7426           1 :         uint16_t v[1] = {EXTRASAMPLE_UNASSALPHA};
    7427             : 
    7428           1 :         TIFFSetField(l_hTIFF, TIFFTAG_EXTRASAMPLES, 1, v);
    7429             :     }
    7430             : 
    7431        1932 :     const int nMaskFlags = poSrcDS->GetRasterBand(1)->GetMaskFlags();
    7432        1932 :     bool bCreateMask = false;
    7433        3864 :     CPLString osHiddenStructuralMD;
    7434             :     const char *pszInterleave =
    7435        1932 :         CSLFetchNameValueDef(papszOptions, "INTERLEAVE", "PIXEL");
    7436        1932 :     if (bCopySrcOverviews)
    7437             :     {
    7438         175 :         osHiddenStructuralMD += "LAYOUT=IFDS_BEFORE_DATA\n";
    7439         175 :         osHiddenStructuralMD += "BLOCK_ORDER=ROW_MAJOR\n";
    7440         175 :         osHiddenStructuralMD += "BLOCK_LEADER=SIZE_AS_UINT4\n";
    7441         175 :         osHiddenStructuralMD += "BLOCK_TRAILER=LAST_4_BYTES_REPEATED\n";
    7442         175 :         if (l_nBands > 1 && !EQUAL(pszInterleave, "PIXEL"))
    7443             :         {
    7444          17 :             osHiddenStructuralMD += "INTERLEAVE=";
    7445          17 :             osHiddenStructuralMD += CPLString(pszInterleave).toupper();
    7446          17 :             osHiddenStructuralMD += "\n";
    7447             :         }
    7448             :         osHiddenStructuralMD +=
    7449         175 :             "KNOWN_INCOMPATIBLE_EDITION=NO\n ";  // Final space intended, so
    7450             :                                                  // this can be replaced by YES
    7451             :     }
    7452        1932 :     if (!(nMaskFlags & (GMF_ALL_VALID | GMF_ALPHA | GMF_NODATA)) &&
    7453          39 :         (nMaskFlags & GMF_PER_DATASET) && !bStreaming)
    7454             :     {
    7455          36 :         bCreateMask = true;
    7456          36 :         if (GTiffDataset::MustCreateInternalMask() &&
    7457          36 :             !osHiddenStructuralMD.empty() && EQUAL(pszInterleave, "PIXEL"))
    7458             :         {
    7459          22 :             osHiddenStructuralMD += "MASK_INTERLEAVED_WITH_IMAGERY=YES\n";
    7460             :         }
    7461             :     }
    7462        1932 :     if (!osHiddenStructuralMD.empty())
    7463             :     {
    7464         175 :         const int nHiddenMDSize = static_cast<int>(osHiddenStructuralMD.size());
    7465             :         osHiddenStructuralMD =
    7466         175 :             CPLOPrintf("GDAL_STRUCTURAL_METADATA_SIZE=%06d bytes\n",
    7467         350 :                        nHiddenMDSize) +
    7468         175 :             osHiddenStructuralMD;
    7469         175 :         VSI_TIFFWrite(l_hTIFF, osHiddenStructuralMD.c_str(),
    7470             :                       osHiddenStructuralMD.size());
    7471             :     }
    7472             : 
    7473             :     // FIXME? libtiff writes extended tags in the order they are specified
    7474             :     // and not in increasing order.
    7475             : 
    7476             :     /* -------------------------------------------------------------------- */
    7477             :     /*      Transfer some TIFF specific metadata, if available.             */
    7478             :     /*      The return value will tell us if we need to try again later with*/
    7479             :     /*      PAM because the profile doesn't allow to write some metadata    */
    7480             :     /*      as TIFF tag                                                     */
    7481             :     /* -------------------------------------------------------------------- */
    7482        1932 :     const bool bHasWrittenMDInGeotiffTAG = GTiffDataset::WriteMetadata(
    7483             :         poSrcDS, l_hTIFF, false, eProfile, pszFilename, papszOptions);
    7484             : 
    7485             :     /* -------------------------------------------------------------------- */
    7486             :     /*      Write NoData value, if exist.                                   */
    7487             :     /* -------------------------------------------------------------------- */
    7488        1932 :     if (eProfile == GTiffProfile::GDALGEOTIFF)
    7489             :     {
    7490        1911 :         int bSuccess = FALSE;
    7491        1911 :         GDALRasterBand *poFirstBand = poSrcDS->GetRasterBand(1);
    7492        1911 :         if (poFirstBand->GetRasterDataType() == GDT_Int64)
    7493             :         {
    7494           2 :             const auto nNoData = poFirstBand->GetNoDataValueAsInt64(&bSuccess);
    7495           2 :             if (bSuccess)
    7496           1 :                 GTiffDataset::WriteNoDataValue(l_hTIFF, nNoData);
    7497             :         }
    7498        1909 :         else if (poFirstBand->GetRasterDataType() == GDT_UInt64)
    7499             :         {
    7500           2 :             const auto nNoData = poFirstBand->GetNoDataValueAsUInt64(&bSuccess);
    7501           2 :             if (bSuccess)
    7502           1 :                 GTiffDataset::WriteNoDataValue(l_hTIFF, nNoData);
    7503             :         }
    7504             :         else
    7505             :         {
    7506        1907 :             const auto dfNoData = poFirstBand->GetNoDataValue(&bSuccess);
    7507        1907 :             if (bSuccess)
    7508          89 :                 GTiffDataset::WriteNoDataValue(l_hTIFF, dfNoData);
    7509             :         }
    7510             :     }
    7511             : 
    7512             :     /* -------------------------------------------------------------------- */
    7513             :     /*      Are we addressing PixelIsPoint mode?                            */
    7514             :     /* -------------------------------------------------------------------- */
    7515        1932 :     bool bPixelIsPoint = false;
    7516        1932 :     bool bPointGeoIgnore = false;
    7517             : 
    7518        3253 :     if (poSrcDS->GetMetadataItem(GDALMD_AREA_OR_POINT) &&
    7519        1321 :         EQUAL(poSrcDS->GetMetadataItem(GDALMD_AREA_OR_POINT), GDALMD_AOP_POINT))
    7520             :     {
    7521          12 :         bPixelIsPoint = true;
    7522             :         bPointGeoIgnore =
    7523          12 :             CPLTestBool(CPLGetConfigOption("GTIFF_POINT_GEO_IGNORE", "FALSE"));
    7524             :     }
    7525             : 
    7526             :     /* -------------------------------------------------------------------- */
    7527             :     /*      Write affine transform if it is meaningful.                     */
    7528             :     /* -------------------------------------------------------------------- */
    7529        1932 :     const OGRSpatialReference *l_poSRS = nullptr;
    7530        1932 :     double l_adfGeoTransform[6] = {0.0};
    7531             : 
    7532        1932 :     if (poSrcDS->GetGeoTransform(l_adfGeoTransform) == CE_None)
    7533             :     {
    7534        1486 :         if (bGeoTIFF)
    7535             :         {
    7536        1481 :             l_poSRS = poSrcDS->GetSpatialRef();
    7537             : 
    7538        1481 :             if (l_adfGeoTransform[2] == 0.0 && l_adfGeoTransform[4] == 0.0 &&
    7539        1478 :                 l_adfGeoTransform[5] < 0.0)
    7540             :             {
    7541        1468 :                 double dfOffset = 0.0;
    7542             :                 {
    7543             :                     // In the case the SRS has a vertical component and we have
    7544             :                     // a single band, encode its scale/offset in the GeoTIFF
    7545             :                     // tags
    7546        1468 :                     int bHasScale = FALSE;
    7547             :                     double dfScale =
    7548        1468 :                         poSrcDS->GetRasterBand(1)->GetScale(&bHasScale);
    7549        1468 :                     int bHasOffset = FALSE;
    7550             :                     dfOffset =
    7551        1468 :                         poSrcDS->GetRasterBand(1)->GetOffset(&bHasOffset);
    7552             :                     const bool bApplyScaleOffset =
    7553        1472 :                         l_poSRS && l_poSRS->IsVertical() &&
    7554           4 :                         poSrcDS->GetRasterCount() == 1;
    7555        1468 :                     if (bApplyScaleOffset && !bHasScale)
    7556           0 :                         dfScale = 1.0;
    7557        1468 :                     if (!bApplyScaleOffset || !bHasOffset)
    7558        1464 :                         dfOffset = 0.0;
    7559             :                     const double adfPixelScale[3] = {
    7560        1468 :                         l_adfGeoTransform[1], fabs(l_adfGeoTransform[5]),
    7561        1468 :                         bApplyScaleOffset ? dfScale : 0.0};
    7562             : 
    7563        1468 :                     TIFFSetField(l_hTIFF, TIFFTAG_GEOPIXELSCALE, 3,
    7564             :                                  adfPixelScale);
    7565             :                 }
    7566             : 
    7567        1468 :                 double adfTiePoints[6] = {0.0,
    7568             :                                           0.0,
    7569             :                                           0.0,
    7570        1468 :                                           l_adfGeoTransform[0],
    7571        1468 :                                           l_adfGeoTransform[3],
    7572        1468 :                                           dfOffset};
    7573             : 
    7574        1468 :                 if (bPixelIsPoint && !bPointGeoIgnore)
    7575             :                 {
    7576           8 :                     adfTiePoints[3] +=
    7577           8 :                         l_adfGeoTransform[1] * 0.5 + l_adfGeoTransform[2] * 0.5;
    7578           8 :                     adfTiePoints[4] +=
    7579           8 :                         l_adfGeoTransform[4] * 0.5 + l_adfGeoTransform[5] * 0.5;
    7580             :                 }
    7581             : 
    7582        1468 :                 TIFFSetField(l_hTIFF, TIFFTAG_GEOTIEPOINTS, 6, adfTiePoints);
    7583             :             }
    7584             :             else
    7585             :             {
    7586          13 :                 double adfMatrix[16] = {0.0};
    7587             : 
    7588          13 :                 adfMatrix[0] = l_adfGeoTransform[1];
    7589          13 :                 adfMatrix[1] = l_adfGeoTransform[2];
    7590          13 :                 adfMatrix[3] = l_adfGeoTransform[0];
    7591          13 :                 adfMatrix[4] = l_adfGeoTransform[4];
    7592          13 :                 adfMatrix[5] = l_adfGeoTransform[5];
    7593          13 :                 adfMatrix[7] = l_adfGeoTransform[3];
    7594          13 :                 adfMatrix[15] = 1.0;
    7595             : 
    7596          13 :                 if (bPixelIsPoint && !bPointGeoIgnore)
    7597             :                 {
    7598           0 :                     adfMatrix[3] +=
    7599           0 :                         l_adfGeoTransform[1] * 0.5 + l_adfGeoTransform[2] * 0.5;
    7600           0 :                     adfMatrix[7] +=
    7601           0 :                         l_adfGeoTransform[4] * 0.5 + l_adfGeoTransform[5] * 0.5;
    7602             :                 }
    7603             : 
    7604          13 :                 TIFFSetField(l_hTIFF, TIFFTAG_GEOTRANSMATRIX, 16, adfMatrix);
    7605             :             }
    7606             :         }
    7607             : 
    7608             :         /* --------------------------------------------------------------------
    7609             :          */
    7610             :         /*      Do we need a TFW file? */
    7611             :         /* --------------------------------------------------------------------
    7612             :          */
    7613        1486 :         if (CPLFetchBool(papszOptions, "TFW", false))
    7614           2 :             GDALWriteWorldFile(pszFilename, "tfw", l_adfGeoTransform);
    7615        1484 :         else if (CPLFetchBool(papszOptions, "WORLDFILE", false))
    7616           1 :             GDALWriteWorldFile(pszFilename, "wld", l_adfGeoTransform);
    7617             :     }
    7618             : 
    7619             :     /* -------------------------------------------------------------------- */
    7620             :     /*      Otherwise write tiepoints if they are available.                */
    7621             :     /* -------------------------------------------------------------------- */
    7622         446 :     else if (poSrcDS->GetGCPCount() > 0 && bGeoTIFF)
    7623             :     {
    7624          12 :         const GDAL_GCP *pasGCPs = poSrcDS->GetGCPs();
    7625             :         double *padfTiePoints = static_cast<double *>(
    7626          12 :             CPLMalloc(6 * sizeof(double) * poSrcDS->GetGCPCount()));
    7627             : 
    7628          60 :         for (int iGCP = 0; iGCP < poSrcDS->GetGCPCount(); ++iGCP)
    7629             :         {
    7630             : 
    7631          48 :             padfTiePoints[iGCP * 6 + 0] = pasGCPs[iGCP].dfGCPPixel;
    7632          48 :             padfTiePoints[iGCP * 6 + 1] = pasGCPs[iGCP].dfGCPLine;
    7633          48 :             padfTiePoints[iGCP * 6 + 2] = 0;
    7634          48 :             padfTiePoints[iGCP * 6 + 3] = pasGCPs[iGCP].dfGCPX;
    7635          48 :             padfTiePoints[iGCP * 6 + 4] = pasGCPs[iGCP].dfGCPY;
    7636          48 :             padfTiePoints[iGCP * 6 + 5] = pasGCPs[iGCP].dfGCPZ;
    7637             : 
    7638          48 :             if (bPixelIsPoint && !bPointGeoIgnore)
    7639             :             {
    7640           4 :                 padfTiePoints[iGCP * 6 + 0] -= 0.5;
    7641           4 :                 padfTiePoints[iGCP * 6 + 1] -= 0.5;
    7642             :             }
    7643             :         }
    7644             : 
    7645          12 :         TIFFSetField(l_hTIFF, TIFFTAG_GEOTIEPOINTS, 6 * poSrcDS->GetGCPCount(),
    7646             :                      padfTiePoints);
    7647          12 :         CPLFree(padfTiePoints);
    7648             : 
    7649          12 :         l_poSRS = poSrcDS->GetGCPSpatialRef();
    7650             : 
    7651          24 :         if (CPLFetchBool(papszOptions, "TFW", false) ||
    7652          12 :             CPLFetchBool(papszOptions, "WORLDFILE", false))
    7653             :         {
    7654           0 :             ReportError(
    7655             :                 pszFilename, CE_Warning, CPLE_AppDefined,
    7656             :                 "TFW=ON or WORLDFILE=ON creation options are ignored when "
    7657             :                 "GCPs are available");
    7658             :         }
    7659             :     }
    7660             :     else
    7661             :     {
    7662         434 :         l_poSRS = poSrcDS->GetSpatialRef();
    7663             :     }
    7664             : 
    7665             :     /* -------------------------------------------------------------------- */
    7666             :     /*      Copy xml:XMP data                                               */
    7667             :     /* -------------------------------------------------------------------- */
    7668        1932 :     char **papszXMP = poSrcDS->GetMetadata("xml:XMP");
    7669        1932 :     if (papszXMP != nullptr && *papszXMP != nullptr)
    7670             :     {
    7671           9 :         int nTagSize = static_cast<int>(strlen(*papszXMP));
    7672           9 :         TIFFSetField(l_hTIFF, TIFFTAG_XMLPACKET, nTagSize, *papszXMP);
    7673             :     }
    7674             : 
    7675             :     /* -------------------------------------------------------------------- */
    7676             :     /*      Write the projection information, if possible.                  */
    7677             :     /* -------------------------------------------------------------------- */
    7678        1932 :     const bool bHasProjection = l_poSRS != nullptr;
    7679        1932 :     bool bExportSRSToPAM = false;
    7680        1932 :     if ((bHasProjection || bPixelIsPoint) && bGeoTIFF)
    7681             :     {
    7682        1469 :         GTIF *psGTIF = GTiffDataset::GTIFNew(l_hTIFF);
    7683             : 
    7684        1469 :         if (bHasProjection)
    7685             :         {
    7686        1469 :             const auto eGeoTIFFKeysFlavor = GetGTIFFKeysFlavor(papszOptions);
    7687        1469 :             if (IsSRSCompatibleOfGeoTIFF(l_poSRS, eGeoTIFFKeysFlavor))
    7688             :             {
    7689        1469 :                 GTIFSetFromOGISDefnEx(
    7690             :                     psGTIF,
    7691             :                     OGRSpatialReference::ToHandle(
    7692             :                         const_cast<OGRSpatialReference *>(l_poSRS)),
    7693             :                     eGeoTIFFKeysFlavor, GetGeoTIFFVersion(papszOptions));
    7694             :             }
    7695             :             else
    7696             :             {
    7697           0 :                 bExportSRSToPAM = true;
    7698             :             }
    7699             :         }
    7700             : 
    7701        1469 :         if (bPixelIsPoint)
    7702             :         {
    7703          12 :             GTIFKeySet(psGTIF, GTRasterTypeGeoKey, TYPE_SHORT, 1,
    7704             :                        RasterPixelIsPoint);
    7705             :         }
    7706             : 
    7707        1469 :         GTIFWriteKeys(psGTIF);
    7708        1469 :         GTIFFree(psGTIF);
    7709             :     }
    7710             : 
    7711        1932 :     bool l_bDontReloadFirstBlock = false;
    7712             : 
    7713             : #ifdef HAVE_LIBJPEG
    7714        1932 :     if (bCopyFromJPEG)
    7715             :     {
    7716          12 :         GTIFF_CopyFromJPEG_WriteAdditionalTags(l_hTIFF, poSrcDS);
    7717             :     }
    7718             : #endif
    7719             : 
    7720             :     /* -------------------------------------------------------------------- */
    7721             :     /*      Cleanup                                                         */
    7722             :     /* -------------------------------------------------------------------- */
    7723        1932 :     if (bCopySrcOverviews)
    7724             :     {
    7725         175 :         TIFFDeferStrileArrayWriting(l_hTIFF);
    7726             :     }
    7727        1932 :     TIFFWriteCheck(l_hTIFF, TIFFIsTiled(l_hTIFF), "GTiffCreateCopy()");
    7728        1932 :     TIFFWriteDirectory(l_hTIFF);
    7729        1932 :     if (bStreaming)
    7730             :     {
    7731             :         // We need to write twice the directory to be sure that custom
    7732             :         // TIFF tags are correctly sorted and that padding bytes have been
    7733             :         // added.
    7734           5 :         TIFFSetDirectory(l_hTIFF, 0);
    7735           5 :         TIFFWriteDirectory(l_hTIFF);
    7736             : 
    7737           5 :         if (VSIFSeekL(l_fpL, 0, SEEK_END) != 0)
    7738           0 :             ReportError(pszFilename, CE_Failure, CPLE_FileIO, "Cannot seek");
    7739           5 :         const int nSize = static_cast<int>(VSIFTellL(l_fpL));
    7740             : 
    7741           5 :         vsi_l_offset nDataLength = 0;
    7742           5 :         VSIGetMemFileBuffer(l_osTmpFilename, &nDataLength, FALSE);
    7743           5 :         TIFFSetDirectory(l_hTIFF, 0);
    7744           5 :         GTiffFillStreamableOffsetAndCount(l_hTIFF, nSize);
    7745           5 :         TIFFWriteDirectory(l_hTIFF);
    7746             :     }
    7747        1932 :     const auto nDirCount = TIFFNumberOfDirectories(l_hTIFF);
    7748        1932 :     if (nDirCount >= 1)
    7749             :     {
    7750        1925 :         TIFFSetDirectory(l_hTIFF, static_cast<tdir_t>(nDirCount - 1));
    7751             :     }
    7752        1932 :     const toff_t l_nDirOffset = TIFFCurrentDirOffset(l_hTIFF);
    7753        1932 :     TIFFFlush(l_hTIFF);
    7754        1932 :     XTIFFClose(l_hTIFF);
    7755             : 
    7756        1932 :     VSIFSeekL(l_fpL, 0, SEEK_SET);
    7757             : 
    7758             :     // fpStreaming will assigned to the instance and not closed here.
    7759        1932 :     VSILFILE *fpStreaming = nullptr;
    7760        1932 :     if (bStreaming)
    7761             :     {
    7762           5 :         vsi_l_offset nDataLength = 0;
    7763             :         void *pabyBuffer =
    7764           5 :             VSIGetMemFileBuffer(l_osTmpFilename, &nDataLength, FALSE);
    7765           5 :         fpStreaming = VSIFOpenL(pszFilename, "wb");
    7766           5 :         if (fpStreaming == nullptr)
    7767             :         {
    7768           1 :             VSIUnlink(l_osTmpFilename);
    7769           1 :             CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    7770           1 :             return nullptr;
    7771             :         }
    7772           4 :         if (static_cast<vsi_l_offset>(VSIFWriteL(pabyBuffer, 1,
    7773             :                                                  static_cast<int>(nDataLength),
    7774           4 :                                                  fpStreaming)) != nDataLength)
    7775             :         {
    7776           0 :             ReportError(pszFilename, CE_Failure, CPLE_FileIO,
    7777             :                         "Could not write %d bytes",
    7778             :                         static_cast<int>(nDataLength));
    7779           0 :             CPL_IGNORE_RET_VAL(VSIFCloseL(fpStreaming));
    7780           0 :             VSIUnlink(l_osTmpFilename);
    7781           0 :             CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    7782           0 :             return nullptr;
    7783             :         }
    7784             :     }
    7785             : 
    7786             :     /* -------------------------------------------------------------------- */
    7787             :     /*      Re-open as a dataset and copy over missing metadata using       */
    7788             :     /*      PAM facilities.                                                 */
    7789             :     /* -------------------------------------------------------------------- */
    7790        1931 :     l_hTIFF = VSI_TIFFOpen(bStreaming ? l_osTmpFilename.c_str() : pszFilename,
    7791             :                            "r+", l_fpL);
    7792        1931 :     if (l_hTIFF == nullptr)
    7793             :     {
    7794          11 :         if (bStreaming)
    7795           0 :             VSIUnlink(l_osTmpFilename);
    7796          11 :         CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    7797          11 :         return nullptr;
    7798             :     }
    7799             : 
    7800             :     /* -------------------------------------------------------------------- */
    7801             :     /*      Create a corresponding GDALDataset.                             */
    7802             :     /* -------------------------------------------------------------------- */
    7803        1920 :     GTiffDataset *poDS = new GTiffDataset();
    7804        1920 :     poDS->SetDescription(pszFilename);
    7805        1920 :     poDS->eAccess = GA_Update;
    7806        1920 :     poDS->m_pszFilename = CPLStrdup(pszFilename);
    7807        1920 :     poDS->m_fpL = l_fpL;
    7808        1920 :     poDS->m_bIMDRPCMetadataLoaded = true;
    7809        1920 :     poDS->m_nColorTableMultiplier = nColorTableMultiplier;
    7810        1920 :     poDS->m_bTileInterleave = bTileInterleaving;
    7811             : 
    7812        1920 :     if (bTileInterleaving)
    7813             :     {
    7814           7 :         poDS->m_oGTiffMDMD.SetMetadataItem("INTERLEAVE", "TILE",
    7815             :                                            "IMAGE_STRUCTURE");
    7816             :     }
    7817             : 
    7818        1920 :     const bool bAppend = CPLFetchBool(papszOptions, "APPEND_SUBDATASET", false);
    7819        3839 :     if (poDS->OpenOffset(l_hTIFF,
    7820        1919 :                          bAppend ? l_nDirOffset : TIFFCurrentDirOffset(l_hTIFF),
    7821             :                          GA_Update,
    7822             :                          false,  // bAllowRGBAInterface
    7823             :                          true    // bReadGeoTransform
    7824        1920 :                          ) != CE_None)
    7825             :     {
    7826           0 :         delete poDS;
    7827           0 :         if (bStreaming)
    7828           0 :             VSIUnlink(l_osTmpFilename);
    7829           0 :         return nullptr;
    7830             :     }
    7831             : 
    7832             :     // Legacy... Patch back GDT_Int8 type to GDT_Byte if the user used
    7833             :     // PIXELTYPE=SIGNEDBYTE
    7834        1920 :     const char *pszPixelType = CSLFetchNameValue(papszOptions, "PIXELTYPE");
    7835        1920 :     if (pszPixelType == nullptr)
    7836        1915 :         pszPixelType = "";
    7837        1920 :     if (eType == GDT_Byte && EQUAL(pszPixelType, "SIGNEDBYTE"))
    7838             :     {
    7839          10 :         for (int i = 0; i < poDS->nBands; ++i)
    7840             :         {
    7841           5 :             auto poBand = static_cast<GTiffRasterBand *>(poDS->papoBands[i]);
    7842           5 :             poBand->eDataType = GDT_Byte;
    7843           5 :             poBand->EnablePixelTypeSignedByteWarning(false);
    7844           5 :             poBand->SetMetadataItem("PIXELTYPE", "SIGNEDBYTE",
    7845             :                                     "IMAGE_STRUCTURE");
    7846           5 :             poBand->EnablePixelTypeSignedByteWarning(true);
    7847             :         }
    7848             :     }
    7849             : 
    7850        1920 :     poDS->oOvManager.Initialize(poDS, pszFilename);
    7851             : 
    7852        1920 :     if (bStreaming)
    7853             :     {
    7854           4 :         VSIUnlink(l_osTmpFilename);
    7855           4 :         poDS->m_fpToWrite = fpStreaming;
    7856             :     }
    7857        1920 :     poDS->m_eProfile = eProfile;
    7858             : 
    7859        1920 :     int nCloneInfoFlags = GCIF_PAM_DEFAULT & ~GCIF_MASK;
    7860             : 
    7861             :     // If we explicitly asked not to tag the alpha band as such, do not
    7862             :     // reintroduce this alpha color interpretation in PAM.
    7863        1920 :     if (poSrcDS->GetRasterBand(l_nBands)->GetColorInterpretation() ==
    7864        2034 :             GCI_AlphaBand &&
    7865         114 :         GTiffGetAlphaValue(
    7866             :             CPLGetConfigOption("GTIFF_ALPHA",
    7867             :                                CSLFetchNameValue(papszOptions, "ALPHA")),
    7868             :             DEFAULT_ALPHA_TYPE) == EXTRASAMPLE_UNSPECIFIED)
    7869             :     {
    7870           1 :         nCloneInfoFlags &= ~GCIF_COLORINTERP;
    7871             :     }
    7872             :     // Ignore source band color interpretation if requesting PHOTOMETRIC=RGB
    7873        3104 :     else if (l_nBands >= 3 &&
    7874        1185 :              EQUAL(CSLFetchNameValueDef(papszOptions, "PHOTOMETRIC", ""),
    7875             :                    "RGB"))
    7876             :     {
    7877          28 :         for (int i = 1; i <= 3; i++)
    7878             :         {
    7879          21 :             poDS->GetRasterBand(i)->SetColorInterpretation(
    7880          21 :                 static_cast<GDALColorInterp>(GCI_RedBand + (i - 1)));
    7881             :         }
    7882           7 :         nCloneInfoFlags &= ~GCIF_COLORINTERP;
    7883           9 :         if (!(l_nBands == 4 &&
    7884           2 :               CSLFetchNameValue(papszOptions, "ALPHA") != nullptr))
    7885             :         {
    7886          15 :             for (int i = 4; i <= l_nBands; i++)
    7887             :             {
    7888          18 :                 poDS->GetRasterBand(i)->SetColorInterpretation(
    7889           9 :                     poSrcDS->GetRasterBand(i)->GetColorInterpretation());
    7890             :             }
    7891             :         }
    7892             :     }
    7893             : 
    7894             :     CPLString osOldGTIFF_REPORT_COMPD_CSVal(
    7895        3840 :         CPLGetConfigOption("GTIFF_REPORT_COMPD_CS", ""));
    7896        1920 :     CPLSetThreadLocalConfigOption("GTIFF_REPORT_COMPD_CS", "YES");
    7897        1920 :     poDS->CloneInfo(poSrcDS, nCloneInfoFlags);
    7898        1920 :     CPLSetThreadLocalConfigOption("GTIFF_REPORT_COMPD_CS",
    7899        1920 :                                   osOldGTIFF_REPORT_COMPD_CSVal.empty()
    7900             :                                       ? nullptr
    7901           0 :                                       : osOldGTIFF_REPORT_COMPD_CSVal.c_str());
    7902             : 
    7903        1937 :     if ((!bGeoTIFF || bExportSRSToPAM) &&
    7904          17 :         (poDS->GetPamFlags() & GPF_DISABLED) == 0)
    7905             :     {
    7906             :         // Copy georeferencing info to PAM if the profile is not GeoTIFF
    7907          16 :         poDS->GDALPamDataset::SetSpatialRef(poDS->GetSpatialRef());
    7908             :         double adfGeoTransform[6];
    7909          16 :         if (poDS->GetGeoTransform(adfGeoTransform) == CE_None)
    7910             :         {
    7911           5 :             poDS->GDALPamDataset::SetGeoTransform(adfGeoTransform);
    7912             :         }
    7913          16 :         poDS->GDALPamDataset::SetGCPs(poDS->GetGCPCount(), poDS->GetGCPs(),
    7914             :                                       poDS->GetGCPSpatialRef());
    7915             :     }
    7916             : 
    7917        1920 :     poDS->m_papszCreationOptions = CSLDuplicate(papszOptions);
    7918        1920 :     poDS->m_bDontReloadFirstBlock = l_bDontReloadFirstBlock;
    7919             : 
    7920             :     /* -------------------------------------------------------------------- */
    7921             :     /*      CloneInfo() does not merge metadata, it just replaces it        */
    7922             :     /*      totally.  So we have to merge it.                               */
    7923             :     /* -------------------------------------------------------------------- */
    7924             : 
    7925        1920 :     char **papszSRC_MD = poSrcDS->GetMetadata();
    7926        1920 :     char **papszDST_MD = CSLDuplicate(poDS->GetMetadata());
    7927             : 
    7928        1920 :     papszDST_MD = CSLMerge(papszDST_MD, papszSRC_MD);
    7929             : 
    7930        1920 :     poDS->SetMetadata(papszDST_MD);
    7931        1920 :     CSLDestroy(papszDST_MD);
    7932             : 
    7933             :     // Depending on the PHOTOMETRIC tag, the TIFF file may not have the same
    7934             :     // band count as the source. Will fail later in GDALDatasetCopyWholeRaster
    7935             :     // anyway.
    7936        6669 :     for (int nBand = 1;
    7937        6669 :          nBand <= std::min(poDS->GetRasterCount(), poSrcDS->GetRasterCount());
    7938             :          ++nBand)
    7939             :     {
    7940        4749 :         GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand(nBand);
    7941        4749 :         GDALRasterBand *poDstBand = poDS->GetRasterBand(nBand);
    7942        4749 :         papszSRC_MD = poSrcBand->GetMetadata();
    7943        4749 :         papszDST_MD = CSLDuplicate(poDstBand->GetMetadata());
    7944             : 
    7945        4749 :         papszDST_MD = CSLMerge(papszDST_MD, papszSRC_MD);
    7946             : 
    7947        4749 :         poDstBand->SetMetadata(papszDST_MD);
    7948        4749 :         CSLDestroy(papszDST_MD);
    7949             : 
    7950        4749 :         char **papszCatNames = poSrcBand->GetCategoryNames();
    7951        4749 :         if (nullptr != papszCatNames)
    7952           0 :             poDstBand->SetCategoryNames(papszCatNames);
    7953             :     }
    7954             : 
    7955        1920 :     l_hTIFF = static_cast<TIFF *>(poDS->GetInternalHandle(nullptr));
    7956             : 
    7957             :     /* -------------------------------------------------------------------- */
    7958             :     /*      Handle forcing xml:ESRI data to be written to PAM.              */
    7959             :     /* -------------------------------------------------------------------- */
    7960        1920 :     if (CPLTestBool(CPLGetConfigOption("ESRI_XML_PAM", "NO")))
    7961             :     {
    7962           1 :         char **papszESRIMD = poSrcDS->GetMetadata("xml:ESRI");
    7963           1 :         if (papszESRIMD)
    7964             :         {
    7965           1 :             poDS->SetMetadata(papszESRIMD, "xml:ESRI");
    7966             :         }
    7967             :     }
    7968             : 
    7969             :     /* -------------------------------------------------------------------- */
    7970             :     /*      Second chance: now that we have a PAM dataset, it is possible   */
    7971             :     /*      to write metadata that we could not write as a TIFF tag.        */
    7972             :     /* -------------------------------------------------------------------- */
    7973        1920 :     if (!bHasWrittenMDInGeotiffTAG && !bStreaming)
    7974             :     {
    7975           6 :         GTiffDataset::WriteMetadata(
    7976             :             poDS, l_hTIFF, true, eProfile, pszFilename, papszOptions,
    7977             :             true /* don't write RPC and IMD file again */);
    7978             :     }
    7979             : 
    7980        1920 :     if (!bStreaming)
    7981        1916 :         GTiffDataset::WriteRPC(poDS, l_hTIFF, true, eProfile, pszFilename,
    7982             :                                papszOptions,
    7983             :                                true /* write only in PAM AND if needed */);
    7984             : 
    7985             :     // Propagate ISIS3 or VICAR metadata, but only as PAM metadata.
    7986        5760 :     for (const char *pszMDD : {"json:ISIS3", "json:VICAR"})
    7987             :     {
    7988        3840 :         char **papszMD = poSrcDS->GetMetadata(pszMDD);
    7989        3840 :         if (papszMD)
    7990             :         {
    7991           3 :             poDS->SetMetadata(papszMD, pszMDD);
    7992           3 :             poDS->PushMetadataToPam();
    7993             :         }
    7994             :     }
    7995             : 
    7996        1920 :     poDS->m_bWriteCOGLayout = bCopySrcOverviews;
    7997             : 
    7998             :     // To avoid unnecessary directory rewriting.
    7999        1920 :     poDS->m_bMetadataChanged = false;
    8000        1920 :     poDS->m_bGeoTIFFInfoChanged = false;
    8001        1920 :     poDS->m_bNoDataChanged = false;
    8002        1920 :     poDS->m_bForceUnsetGTOrGCPs = false;
    8003        1920 :     poDS->m_bForceUnsetProjection = false;
    8004        1920 :     poDS->m_bStreamingOut = bStreaming;
    8005             : 
    8006             :     // Don't try to load external metadata files (#6597).
    8007        1920 :     poDS->m_bIMDRPCMetadataLoaded = true;
    8008             : 
    8009             :     // We must re-set the compression level at this point, since it has been
    8010             :     // lost a few lines above when closing the newly create TIFF file The
    8011             :     // TIFFTAG_ZIPQUALITY & TIFFTAG_JPEGQUALITY are not store in the TIFF file.
    8012             :     // They are just TIFF session parameters.
    8013             : 
    8014        1920 :     poDS->m_nZLevel = GTiffGetZLevel(papszOptions);
    8015        1920 :     poDS->m_nLZMAPreset = GTiffGetLZMAPreset(papszOptions);
    8016        1920 :     poDS->m_nZSTDLevel = GTiffGetZSTDPreset(papszOptions);
    8017        1920 :     poDS->m_nWebPLevel = GTiffGetWebPLevel(papszOptions);
    8018        1920 :     poDS->m_bWebPLossless = GTiffGetWebPLossless(papszOptions);
    8019        1923 :     if (poDS->m_nWebPLevel != 100 && poDS->m_bWebPLossless &&
    8020           3 :         CSLFetchNameValue(papszOptions, "WEBP_LEVEL"))
    8021             :     {
    8022           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    8023             :                  "WEBP_LEVEL is specified, but WEBP_LOSSLESS=YES. "
    8024             :                  "WEBP_LEVEL will be ignored.");
    8025             :     }
    8026        1920 :     poDS->m_nJpegQuality = GTiffGetJpegQuality(papszOptions);
    8027        1920 :     poDS->m_nJpegTablesMode = GTiffGetJpegTablesMode(papszOptions);
    8028        1920 :     poDS->GetDiscardLsbOption(papszOptions);
    8029        1920 :     poDS->m_dfMaxZError = GTiffGetLERCMaxZError(papszOptions);
    8030        1920 :     poDS->m_dfMaxZErrorOverview = GTiffGetLERCMaxZErrorOverview(papszOptions);
    8031             : #if HAVE_JXL
    8032        1920 :     poDS->m_bJXLLossless = GTiffGetJXLLossless(papszOptions);
    8033        1920 :     poDS->m_nJXLEffort = GTiffGetJXLEffort(papszOptions);
    8034        1920 :     poDS->m_fJXLDistance = GTiffGetJXLDistance(papszOptions);
    8035        1920 :     poDS->m_fJXLAlphaDistance = GTiffGetJXLAlphaDistance(papszOptions);
    8036             : #endif
    8037        1920 :     poDS->InitCreationOrOpenOptions(true, papszOptions);
    8038             : 
    8039        1920 :     if (l_nCompression == COMPRESSION_ADOBE_DEFLATE ||
    8040        1895 :         l_nCompression == COMPRESSION_LERC)
    8041             :     {
    8042          96 :         GTiffSetDeflateSubCodec(l_hTIFF);
    8043             : 
    8044          96 :         if (poDS->m_nZLevel != -1)
    8045             :         {
    8046          12 :             TIFFSetField(l_hTIFF, TIFFTAG_ZIPQUALITY, poDS->m_nZLevel);
    8047             :         }
    8048             :     }
    8049        1920 :     if (l_nCompression == COMPRESSION_JPEG)
    8050             :     {
    8051          75 :         if (poDS->m_nJpegQuality != -1)
    8052             :         {
    8053           9 :             TIFFSetField(l_hTIFF, TIFFTAG_JPEGQUALITY, poDS->m_nJpegQuality);
    8054             :         }
    8055          75 :         TIFFSetField(l_hTIFF, TIFFTAG_JPEGTABLESMODE, poDS->m_nJpegTablesMode);
    8056             :     }
    8057        1920 :     if (l_nCompression == COMPRESSION_LZMA)
    8058             :     {
    8059           7 :         if (poDS->m_nLZMAPreset != -1)
    8060             :         {
    8061           6 :             TIFFSetField(l_hTIFF, TIFFTAG_LZMAPRESET, poDS->m_nLZMAPreset);
    8062             :         }
    8063             :     }
    8064        1920 :     if (l_nCompression == COMPRESSION_ZSTD ||
    8065        1913 :         l_nCompression == COMPRESSION_LERC)
    8066             :     {
    8067          78 :         if (poDS->m_nZSTDLevel != -1)
    8068             :         {
    8069           8 :             TIFFSetField(l_hTIFF, TIFFTAG_ZSTD_LEVEL, poDS->m_nZSTDLevel);
    8070             :         }
    8071             :     }
    8072        1920 :     if (l_nCompression == COMPRESSION_LERC)
    8073             :     {
    8074          71 :         TIFFSetField(l_hTIFF, TIFFTAG_LERC_MAXZERROR, poDS->m_dfMaxZError);
    8075             :     }
    8076             : #if HAVE_JXL
    8077        1920 :     if (l_nCompression == COMPRESSION_JXL ||
    8078        1920 :         l_nCompression == COMPRESSION_JXL_DNG_1_7)
    8079             :     {
    8080          88 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_LOSSYNESS,
    8081          88 :                      poDS->m_bJXLLossless ? JXL_LOSSLESS : JXL_LOSSY);
    8082          88 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_EFFORT, poDS->m_nJXLEffort);
    8083          88 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_DISTANCE, poDS->m_fJXLDistance);
    8084          88 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_ALPHA_DISTANCE,
    8085          88 :                      poDS->m_fJXLAlphaDistance);
    8086             :     }
    8087             : #endif
    8088        1920 :     if (l_nCompression == COMPRESSION_WEBP)
    8089             :     {
    8090          14 :         if (poDS->m_nWebPLevel != -1)
    8091             :         {
    8092          14 :             TIFFSetField(l_hTIFF, TIFFTAG_WEBP_LEVEL, poDS->m_nWebPLevel);
    8093             :         }
    8094             : 
    8095          14 :         if (poDS->m_bWebPLossless)
    8096             :         {
    8097           5 :             TIFFSetField(l_hTIFF, TIFFTAG_WEBP_LOSSLESS, poDS->m_bWebPLossless);
    8098             :         }
    8099             :     }
    8100             : 
    8101             :     /* -------------------------------------------------------------------- */
    8102             :     /*      Do we want to ensure all blocks get written out on close to     */
    8103             :     /*      avoid sparse files?                                             */
    8104             :     /* -------------------------------------------------------------------- */
    8105        1920 :     if (!CPLFetchBool(papszOptions, "SPARSE_OK", false))
    8106        1892 :         poDS->m_bFillEmptyTilesAtClosing = true;
    8107             : 
    8108        1920 :     poDS->m_bWriteEmptyTiles =
    8109        3669 :         (bCopySrcOverviews && poDS->m_bFillEmptyTilesAtClosing) || bStreaming ||
    8110        1749 :         (poDS->m_nCompression != COMPRESSION_NONE &&
    8111         271 :          poDS->m_bFillEmptyTilesAtClosing);
    8112             :     // Only required for people writing non-compressed striped files in the
    8113             :     // rightorder and wanting all tstrips to be written in the same order
    8114             :     // so that the end result can be memory mapped without knowledge of each
    8115             :     // strip offset
    8116        1920 :     if (CPLTestBool(CSLFetchNameValueDef(
    8117        3840 :             papszOptions, "WRITE_EMPTY_TILES_SYNCHRONOUSLY", "FALSE")) ||
    8118        1920 :         CPLTestBool(CSLFetchNameValueDef(
    8119             :             papszOptions, "@WRITE_EMPTY_TILES_SYNCHRONOUSLY", "FALSE")))
    8120             :     {
    8121           0 :         poDS->m_bWriteEmptyTiles = true;
    8122             :     }
    8123             : 
    8124             :     // Precreate (internal) mask, so that the IBuildOverviews() below
    8125             :     // has a chance to create also the overviews of the mask.
    8126        1920 :     CPLErr eErr = CE_None;
    8127             : 
    8128        1920 :     if (bCreateMask)
    8129             :     {
    8130          36 :         eErr = poDS->CreateMaskBand(nMaskFlags);
    8131          36 :         if (poDS->m_poMaskDS)
    8132             :         {
    8133          35 :             poDS->m_poMaskDS->m_bFillEmptyTilesAtClosing =
    8134          35 :                 poDS->m_bFillEmptyTilesAtClosing;
    8135          35 :             poDS->m_poMaskDS->m_bWriteEmptyTiles = poDS->m_bWriteEmptyTiles;
    8136             :         }
    8137             :     }
    8138             : 
    8139             :     /* -------------------------------------------------------------------- */
    8140             :     /*      Create and then copy existing overviews if requested            */
    8141             :     /*  We do it such that all the IFDs are at the beginning of the file,   */
    8142             :     /*  and that the imagery data for the smallest overview is written      */
    8143             :     /*  first, that way the file is more usable when embedded in a          */
    8144             :     /*  compressed stream.                                                  */
    8145             :     /* -------------------------------------------------------------------- */
    8146             : 
    8147             :     // For scaled progress due to overview copying.
    8148        1920 :     const int nBandsWidthMask = l_nBands + (bCreateMask ? 1 : 0);
    8149        1920 :     double dfTotalPixels =
    8150        1920 :         static_cast<double>(nXSize) * nYSize * nBandsWidthMask;
    8151        1920 :     double dfCurPixels = 0;
    8152             : 
    8153        1920 :     if (eErr == CE_None && bCopySrcOverviews)
    8154             :     {
    8155           0 :         std::unique_ptr<GDALDataset> poMaskOvrDS;
    8156             :         const char *pszMaskOvrDS =
    8157         172 :             CSLFetchNameValue(papszOptions, "@MASK_OVERVIEW_DATASET");
    8158         172 :         if (pszMaskOvrDS)
    8159             :         {
    8160          10 :             poMaskOvrDS.reset(GDALDataset::Open(pszMaskOvrDS));
    8161          10 :             if (!poMaskOvrDS)
    8162             :             {
    8163           0 :                 delete poDS;
    8164           0 :                 return nullptr;
    8165             :             }
    8166          10 :             if (poMaskOvrDS->GetRasterCount() != 1)
    8167             :             {
    8168           0 :                 delete poDS;
    8169           0 :                 return nullptr;
    8170             :             }
    8171             :         }
    8172         172 :         if (nSrcOverviews)
    8173             :         {
    8174          64 :             eErr = poDS->CreateOverviewsFromSrcOverviews(poSrcDS, poOvrDS.get(),
    8175             :                                                          nSrcOverviews);
    8176             : 
    8177         182 :             if (eErr == CE_None &&
    8178          64 :                 (poMaskOvrDS != nullptr ||
    8179          54 :                  (poSrcDS->GetRasterBand(1)->GetOverview(0) &&
    8180          29 :                   poSrcDS->GetRasterBand(1)->GetOverview(0)->GetMaskFlags() ==
    8181             :                       GMF_PER_DATASET)))
    8182             :             {
    8183          19 :                 int nOvrBlockXSize = 0;
    8184          19 :                 int nOvrBlockYSize = 0;
    8185          19 :                 GTIFFGetOverviewBlockSize(
    8186             :                     GDALRasterBand::ToHandle(poDS->GetRasterBand(1)),
    8187             :                     &nOvrBlockXSize, &nOvrBlockYSize);
    8188          19 :                 eErr = poDS->CreateInternalMaskOverviews(nOvrBlockXSize,
    8189             :                                                          nOvrBlockYSize);
    8190             :             }
    8191             :         }
    8192             : 
    8193         172 :         TIFFForceStrileArrayWriting(poDS->m_hTIFF);
    8194             : 
    8195         172 :         if (poDS->m_poMaskDS)
    8196             :         {
    8197          27 :             TIFFForceStrileArrayWriting(poDS->m_poMaskDS->m_hTIFF);
    8198             :         }
    8199             : 
    8200         295 :         for (int i = 0; i < poDS->m_nOverviewCount; i++)
    8201             :         {
    8202         123 :             TIFFForceStrileArrayWriting(poDS->m_papoOverviewDS[i]->m_hTIFF);
    8203             : 
    8204         123 :             if (poDS->m_papoOverviewDS[i]->m_poMaskDS)
    8205             :             {
    8206          36 :                 TIFFForceStrileArrayWriting(
    8207          36 :                     poDS->m_papoOverviewDS[i]->m_poMaskDS->m_hTIFF);
    8208             :             }
    8209             :         }
    8210             : 
    8211         172 :         if (eErr == CE_None && nSrcOverviews)
    8212             :         {
    8213          64 :             if (poDS->m_nOverviewCount != nSrcOverviews)
    8214             :             {
    8215           0 :                 ReportError(
    8216             :                     pszFilename, CE_Failure, CPLE_AppDefined,
    8217             :                     "Did only manage to instantiate %d overview levels, "
    8218             :                     "whereas source contains %d",
    8219           0 :                     poDS->m_nOverviewCount, nSrcOverviews);
    8220           0 :                 eErr = CE_Failure;
    8221             :             }
    8222             : 
    8223         187 :             for (int i = 0; eErr == CE_None && i < nSrcOverviews; ++i)
    8224             :             {
    8225             :                 GDALRasterBand *poOvrBand =
    8226             :                     poOvrDS
    8227         199 :                         ? (i == 0
    8228          76 :                                ? poOvrDS->GetRasterBand(1)
    8229          41 :                                : poOvrDS->GetRasterBand(1)->GetOverview(i - 1))
    8230         170 :                         : poSrcDS->GetRasterBand(1)->GetOverview(i);
    8231             :                 const double dfOvrPixels =
    8232         123 :                     static_cast<double>(poOvrBand->GetXSize()) *
    8233         123 :                     poOvrBand->GetYSize();
    8234         123 :                 dfTotalPixels += dfOvrPixels * l_nBands;
    8235         232 :                 if (poOvrBand->GetMaskFlags() == GMF_PER_DATASET ||
    8236         109 :                     poMaskOvrDS != nullptr)
    8237             :                 {
    8238          36 :                     dfTotalPixels += dfOvrPixels;
    8239             :                 }
    8240          87 :                 else if (i == 0 && poDS->GetRasterBand(1)->GetMaskFlags() ==
    8241             :                                        GMF_PER_DATASET)
    8242             :                 {
    8243           1 :                     ReportError(pszFilename, CE_Warning, CPLE_AppDefined,
    8244             :                                 "Source dataset has a mask band on full "
    8245             :                                 "resolution, overviews on the regular bands, "
    8246             :                                 "but lacks overviews on the mask band.");
    8247             :                 }
    8248             :             }
    8249             : 
    8250             :             // Now copy the imagery.
    8251             :             // Begin with the smallest overview.
    8252          64 :             for (int iOvrLevel = nSrcOverviews - 1;
    8253         186 :                  eErr == CE_None && iOvrLevel >= 0; --iOvrLevel)
    8254             :             {
    8255         122 :                 auto poDstDS = poDS->m_papoOverviewDS[iOvrLevel];
    8256             : 
    8257             :                 // Create a fake dataset with the source overview level so that
    8258             :                 // GDALDatasetCopyWholeRaster can cope with it.
    8259             :                 GDALDataset *poSrcOvrDS =
    8260             :                     poOvrDS
    8261         163 :                         ? (iOvrLevel == 0 ? poOvrDS.get()
    8262          41 :                                           : GDALCreateOverviewDataset(
    8263             :                                                 poOvrDS.get(), iOvrLevel - 1,
    8264             :                                                 /* bThisLevelOnly = */ true))
    8265          46 :                         : GDALCreateOverviewDataset(
    8266             :                               poSrcDS, iOvrLevel,
    8267         122 :                               /* bThisLevelOnly = */ true);
    8268             :                 GDALRasterBand *poSrcOvrBand =
    8269         198 :                     poOvrDS ? (iOvrLevel == 0
    8270          76 :                                    ? poOvrDS->GetRasterBand(1)
    8271          82 :                                    : poOvrDS->GetRasterBand(1)->GetOverview(
    8272          41 :                                          iOvrLevel - 1))
    8273         168 :                             : poSrcDS->GetRasterBand(1)->GetOverview(iOvrLevel);
    8274             :                 double dfNextCurPixels =
    8275             :                     dfCurPixels +
    8276         122 :                     static_cast<double>(poSrcOvrBand->GetXSize()) *
    8277         122 :                         poSrcOvrBand->GetYSize() * l_nBands;
    8278             : 
    8279         122 :                 poDstDS->m_bBlockOrderRowMajor = true;
    8280         122 :                 poDstDS->m_bLeaderSizeAsUInt4 = true;
    8281         122 :                 poDstDS->m_bTrailerRepeatedLast4BytesRepeated = true;
    8282         122 :                 poDstDS->m_bFillEmptyTilesAtClosing =
    8283         122 :                     poDS->m_bFillEmptyTilesAtClosing;
    8284         122 :                 poDstDS->m_bWriteEmptyTiles = poDS->m_bWriteEmptyTiles;
    8285         122 :                 poDstDS->m_bTileInterleave = poDS->m_bTileInterleave;
    8286         122 :                 GDALRasterBand *poSrcMaskBand = nullptr;
    8287         122 :                 if (poDstDS->m_poMaskDS)
    8288             :                 {
    8289          36 :                     poDstDS->m_poMaskDS->m_bBlockOrderRowMajor = true;
    8290          36 :                     poDstDS->m_poMaskDS->m_bLeaderSizeAsUInt4 = true;
    8291          36 :                     poDstDS->m_poMaskDS->m_bTrailerRepeatedLast4BytesRepeated =
    8292             :                         true;
    8293          36 :                     poDstDS->m_poMaskDS->m_bFillEmptyTilesAtClosing =
    8294          36 :                         poDS->m_bFillEmptyTilesAtClosing;
    8295          36 :                     poDstDS->m_poMaskDS->m_bWriteEmptyTiles =
    8296          36 :                         poDS->m_bWriteEmptyTiles;
    8297             : 
    8298          36 :                     poSrcMaskBand =
    8299             :                         poMaskOvrDS
    8300          58 :                             ? (iOvrLevel == 0
    8301          22 :                                    ? poMaskOvrDS->GetRasterBand(1)
    8302          24 :                                    : poMaskOvrDS->GetRasterBand(1)->GetOverview(
    8303          12 :                                          iOvrLevel - 1))
    8304          50 :                             : poSrcOvrBand->GetMaskBand();
    8305             :                 }
    8306             : 
    8307         122 :                 if (poDstDS->m_poMaskDS)
    8308             :                 {
    8309          36 :                     dfNextCurPixels +=
    8310          36 :                         static_cast<double>(poSrcOvrBand->GetXSize()) *
    8311          36 :                         poSrcOvrBand->GetYSize();
    8312             :                 }
    8313             :                 void *pScaledData =
    8314         122 :                     GDALCreateScaledProgress(dfCurPixels / dfTotalPixels,
    8315             :                                              dfNextCurPixels / dfTotalPixels,
    8316             :                                              pfnProgress, pProgressData);
    8317             : 
    8318         122 :                 eErr = CopyImageryAndMask(poDstDS, poSrcOvrDS, poSrcMaskBand,
    8319             :                                           GDALScaledProgress, pScaledData);
    8320             : 
    8321         122 :                 dfCurPixels = dfNextCurPixels;
    8322         122 :                 GDALDestroyScaledProgress(pScaledData);
    8323             : 
    8324         122 :                 if (poSrcOvrDS != poOvrDS.get())
    8325          87 :                     delete poSrcOvrDS;
    8326         122 :                 poSrcOvrDS = nullptr;
    8327             :             }
    8328             :         }
    8329             :     }
    8330             : 
    8331             :     /* -------------------------------------------------------------------- */
    8332             :     /*      Copy actual imagery.                                            */
    8333             :     /* -------------------------------------------------------------------- */
    8334        1920 :     double dfNextCurPixels =
    8335        1920 :         dfCurPixels + static_cast<double>(nXSize) * nYSize * l_nBands;
    8336        1920 :     void *pScaledData = GDALCreateScaledProgress(
    8337             :         dfCurPixels / dfTotalPixels, dfNextCurPixels / dfTotalPixels,
    8338             :         pfnProgress, pProgressData);
    8339             : 
    8340             : #if defined(HAVE_LIBJPEG) || defined(JPEG_DIRECT_COPY)
    8341        1920 :     bool bTryCopy = true;
    8342             : #endif
    8343             : 
    8344             : #ifdef HAVE_LIBJPEG
    8345        1920 :     if (bCopyFromJPEG)
    8346             :     {
    8347          12 :         eErr = GTIFF_CopyFromJPEG(poDS, poSrcDS, pfnProgress, pProgressData,
    8348             :                                   bTryCopy);
    8349             : 
    8350             :         // In case of failure in the decompression step, try normal copy.
    8351          12 :         if (bTryCopy)
    8352           0 :             eErr = CE_None;
    8353             :     }
    8354             : #endif
    8355             : 
    8356             : #ifdef JPEG_DIRECT_COPY
    8357             :     if (bDirectCopyFromJPEG)
    8358             :     {
    8359             :         eErr = GTIFF_DirectCopyFromJPEG(poDS, poSrcDS, pfnProgress,
    8360             :                                         pProgressData, bTryCopy);
    8361             : 
    8362             :         // In case of failure in the reading step, try normal copy.
    8363             :         if (bTryCopy)
    8364             :             eErr = CE_None;
    8365             :     }
    8366             : #endif
    8367             : 
    8368        1920 :     bool bWriteMask = true;
    8369        1920 :     if (
    8370             : #if defined(HAVE_LIBJPEG) || defined(JPEG_DIRECT_COPY)
    8371        1908 :         bTryCopy &&
    8372             : #endif
    8373        1908 :         (poDS->m_bTreatAsSplit || poDS->m_bTreatAsSplitBitmap))
    8374             :     {
    8375             :         // For split bands, we use TIFFWriteScanline() interface.
    8376           9 :         CPLAssert(poDS->m_nBitsPerSample == 8 || poDS->m_nBitsPerSample == 1);
    8377             : 
    8378           9 :         if (poDS->m_nPlanarConfig == PLANARCONFIG_CONTIG && poDS->nBands > 1)
    8379             :         {
    8380             :             GByte *pabyScanline = static_cast<GByte *>(
    8381           3 :                 VSI_MALLOC_VERBOSE(TIFFScanlineSize(l_hTIFF)));
    8382           3 :             if (pabyScanline == nullptr)
    8383           0 :                 eErr = CE_Failure;
    8384        9052 :             for (int j = 0; j < nYSize && eErr == CE_None; ++j)
    8385             :             {
    8386       18098 :                 eErr = poSrcDS->RasterIO(GF_Read, 0, j, nXSize, 1, pabyScanline,
    8387             :                                          nXSize, 1, GDT_Byte, l_nBands, nullptr,
    8388        9049 :                                          poDS->nBands, 0, 1, nullptr);
    8389       18098 :                 if (eErr == CE_None &&
    8390        9049 :                     TIFFWriteScanline(l_hTIFF, pabyScanline, j, 0) == -1)
    8391             :                 {
    8392           0 :                     ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
    8393             :                                 "TIFFWriteScanline() failed.");
    8394           0 :                     eErr = CE_Failure;
    8395             :                 }
    8396        9049 :                 if (!GDALScaledProgress((j + 1) * 1.0 / nYSize, nullptr,
    8397             :                                         pScaledData))
    8398           0 :                     eErr = CE_Failure;
    8399             :             }
    8400           3 :             CPLFree(pabyScanline);
    8401             :         }
    8402             :         else
    8403             :         {
    8404             :             GByte *pabyScanline =
    8405           6 :                 static_cast<GByte *>(VSI_MALLOC_VERBOSE(nXSize));
    8406           6 :             if (pabyScanline == nullptr)
    8407           0 :                 eErr = CE_Failure;
    8408             :             else
    8409           6 :                 eErr = CE_None;
    8410          14 :             for (int iBand = 1; iBand <= l_nBands && eErr == CE_None; ++iBand)
    8411             :             {
    8412       48211 :                 for (int j = 0; j < nYSize && eErr == CE_None; ++j)
    8413             :                 {
    8414       48203 :                     eErr = poSrcDS->GetRasterBand(iBand)->RasterIO(
    8415             :                         GF_Read, 0, j, nXSize, 1, pabyScanline, nXSize, 1,
    8416             :                         GDT_Byte, 0, 0, nullptr);
    8417       48203 :                     if (poDS->m_bTreatAsSplitBitmap)
    8418             :                     {
    8419     7225210 :                         for (int i = 0; i < nXSize; ++i)
    8420             :                         {
    8421     7216010 :                             const GByte byVal = pabyScanline[i];
    8422     7216010 :                             if ((i & 0x7) == 0)
    8423      902001 :                                 pabyScanline[i >> 3] = 0;
    8424     7216010 :                             if (byVal)
    8425     7097220 :                                 pabyScanline[i >> 3] |= 0x80 >> (i & 0x7);
    8426             :                         }
    8427             :                     }
    8428       96406 :                     if (eErr == CE_None &&
    8429       48203 :                         TIFFWriteScanline(l_hTIFF, pabyScanline, j,
    8430       48203 :                                           static_cast<uint16_t>(iBand - 1)) ==
    8431             :                             -1)
    8432             :                     {
    8433           0 :                         ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
    8434             :                                     "TIFFWriteScanline() failed.");
    8435           0 :                         eErr = CE_Failure;
    8436             :                     }
    8437       48203 :                     if (!GDALScaledProgress((j + 1 + (iBand - 1) * nYSize) *
    8438       48203 :                                                 1.0 / (l_nBands * nYSize),
    8439             :                                             nullptr, pScaledData))
    8440           0 :                         eErr = CE_Failure;
    8441             :                 }
    8442             :             }
    8443           6 :             CPLFree(pabyScanline);
    8444             :         }
    8445             : 
    8446             :         // Necessary to be able to read the file without re-opening.
    8447           9 :         TIFFSizeProc pfnSizeProc = TIFFGetSizeProc(l_hTIFF);
    8448             : 
    8449           9 :         TIFFFlushData(l_hTIFF);
    8450             : 
    8451           9 :         toff_t nNewDirOffset = pfnSizeProc(TIFFClientdata(l_hTIFF));
    8452           9 :         if ((nNewDirOffset % 2) == 1)
    8453           5 :             ++nNewDirOffset;
    8454             : 
    8455           9 :         TIFFFlush(l_hTIFF);
    8456             : 
    8457           9 :         if (poDS->m_nDirOffset != TIFFCurrentDirOffset(l_hTIFF))
    8458             :         {
    8459           0 :             poDS->m_nDirOffset = nNewDirOffset;
    8460           0 :             CPLDebug("GTiff", "directory moved during flush.");
    8461           9 :         }
    8462             :     }
    8463        1911 :     else if (
    8464             : #if defined(HAVE_LIBJPEG) || defined(JPEG_DIRECT_COPY)
    8465        1899 :         bTryCopy &&
    8466             : #endif
    8467             :         eErr == CE_None)
    8468             :     {
    8469        1898 :         const char *papszCopyWholeRasterOptions[3] = {nullptr, nullptr,
    8470             :                                                       nullptr};
    8471        1898 :         int iNextOption = 0;
    8472        1898 :         papszCopyWholeRasterOptions[iNextOption++] = "SKIP_HOLES=YES";
    8473        1898 :         if (l_nCompression != COMPRESSION_NONE)
    8474             :         {
    8475         409 :             papszCopyWholeRasterOptions[iNextOption++] = "COMPRESSED=YES";
    8476             :         }
    8477             : 
    8478             :         // For streaming with separate, we really want that bands are written
    8479             :         // after each other, even if the source is pixel interleaved.
    8480        1489 :         else if (bStreaming && poDS->m_nPlanarConfig == PLANARCONFIG_SEPARATE)
    8481             :         {
    8482           1 :             papszCopyWholeRasterOptions[iNextOption++] = "INTERLEAVE=BAND";
    8483             :         }
    8484             : 
    8485        1898 :         if (bCopySrcOverviews || bTileInterleaving)
    8486             :         {
    8487         172 :             poDS->m_bBlockOrderRowMajor = true;
    8488         172 :             poDS->m_bLeaderSizeAsUInt4 = bCopySrcOverviews;
    8489         172 :             poDS->m_bTrailerRepeatedLast4BytesRepeated = bCopySrcOverviews;
    8490         172 :             if (poDS->m_poMaskDS)
    8491             :             {
    8492          27 :                 poDS->m_poMaskDS->m_bBlockOrderRowMajor = true;
    8493          27 :                 poDS->m_poMaskDS->m_bLeaderSizeAsUInt4 = bCopySrcOverviews;
    8494          27 :                 poDS->m_poMaskDS->m_bTrailerRepeatedLast4BytesRepeated =
    8495             :                     bCopySrcOverviews;
    8496          27 :                 GDALDestroyScaledProgress(pScaledData);
    8497             :                 pScaledData =
    8498          27 :                     GDALCreateScaledProgress(dfCurPixels / dfTotalPixels, 1.0,
    8499             :                                              pfnProgress, pProgressData);
    8500             :             }
    8501             : 
    8502         172 :             eErr = CopyImageryAndMask(poDS, poSrcDS,
    8503         172 :                                       poSrcDS->GetRasterBand(1)->GetMaskBand(),
    8504             :                                       GDALScaledProgress, pScaledData);
    8505         172 :             if (poDS->m_poMaskDS)
    8506             :             {
    8507          27 :                 bWriteMask = false;
    8508             :             }
    8509             :         }
    8510             :         else
    8511             :         {
    8512        1726 :             eErr = GDALDatasetCopyWholeRaster(
    8513             :                 /* (GDALDatasetH) */ poSrcDS,
    8514             :                 /* (GDALDatasetH) */ poDS, papszCopyWholeRasterOptions,
    8515             :                 GDALScaledProgress, pScaledData);
    8516             :         }
    8517             :     }
    8518             : 
    8519        1920 :     GDALDestroyScaledProgress(pScaledData);
    8520             : 
    8521        1920 :     if (eErr == CE_None && !bStreaming && bWriteMask)
    8522             :     {
    8523        1874 :         pScaledData = GDALCreateScaledProgress(dfNextCurPixels / dfTotalPixels,
    8524             :                                                1.0, pfnProgress, pProgressData);
    8525        1874 :         if (poDS->m_poMaskDS)
    8526             :         {
    8527           8 :             const char *l_papszOptions[2] = {"COMPRESSED=YES", nullptr};
    8528           8 :             eErr = GDALRasterBandCopyWholeRaster(
    8529           8 :                 poSrcDS->GetRasterBand(1)->GetMaskBand(),
    8530           8 :                 poDS->GetRasterBand(1)->GetMaskBand(),
    8531             :                 const_cast<char **>(l_papszOptions), GDALScaledProgress,
    8532             :                 pScaledData);
    8533             :         }
    8534             :         else
    8535             :         {
    8536             :             eErr =
    8537        1866 :                 GDALDriver::DefaultCopyMasks(poSrcDS, poDS, bStrict, nullptr,
    8538             :                                              GDALScaledProgress, pScaledData);
    8539             :         }
    8540        1874 :         GDALDestroyScaledProgress(pScaledData);
    8541             :     }
    8542             : 
    8543        1920 :     poDS->m_bWriteCOGLayout = false;
    8544             : 
    8545        1920 :     if (eErr == CE_Failure)
    8546             :     {
    8547          15 :         delete poDS;
    8548          15 :         poDS = nullptr;
    8549             : 
    8550          15 :         if (CPLTestBool(CPLGetConfigOption("GTIFF_DELETE_ON_ERROR", "YES")))
    8551             :         {
    8552          14 :             if (!bStreaming)
    8553             :             {
    8554             :                 // Should really delete more carefully.
    8555          14 :                 VSIUnlink(pszFilename);
    8556             :             }
    8557             :         }
    8558             :     }
    8559             : 
    8560        1920 :     return poDS;
    8561             : }
    8562             : 
    8563             : /************************************************************************/
    8564             : /*                           SetSpatialRef()                            */
    8565             : /************************************************************************/
    8566             : 
    8567        1367 : CPLErr GTiffDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
    8568             : 
    8569             : {
    8570        1367 :     if (m_bStreamingOut && m_bCrystalized)
    8571             :     {
    8572           1 :         ReportError(CE_Failure, CPLE_NotSupported,
    8573             :                     "Cannot modify projection at that point in "
    8574             :                     "a streamed output file");
    8575           1 :         return CE_Failure;
    8576             :     }
    8577             : 
    8578        1366 :     LoadGeoreferencingAndPamIfNeeded();
    8579        1366 :     LookForProjection();
    8580             : 
    8581        1366 :     CPLErr eErr = CE_None;
    8582        1366 :     if (eAccess == GA_Update)
    8583             :     {
    8584        1368 :         if ((m_eProfile == GTiffProfile::BASELINE) &&
    8585           7 :             (GetPamFlags() & GPF_DISABLED) == 0)
    8586             :         {
    8587           7 :             eErr = GDALPamDataset::SetSpatialRef(poSRS);
    8588             :         }
    8589             :         else
    8590             :         {
    8591        1354 :             if (GDALPamDataset::GetSpatialRef() != nullptr)
    8592             :             {
    8593             :                 // Cancel any existing SRS from PAM file.
    8594           1 :                 GDALPamDataset::SetSpatialRef(nullptr);
    8595             :             }
    8596        1354 :             m_bGeoTIFFInfoChanged = true;
    8597             :         }
    8598             :     }
    8599             :     else
    8600             :     {
    8601           5 :         CPLDebug("GTIFF", "SetSpatialRef() goes to PAM instead of TIFF tags");
    8602           5 :         eErr = GDALPamDataset::SetSpatialRef(poSRS);
    8603             :     }
    8604             : 
    8605        1366 :     if (eErr == CE_None)
    8606             :     {
    8607        1366 :         if (poSRS == nullptr || poSRS->IsEmpty())
    8608             :         {
    8609          16 :             if (!m_oSRS.IsEmpty())
    8610             :             {
    8611           4 :                 m_bForceUnsetProjection = true;
    8612             :             }
    8613          16 :             m_oSRS.Clear();
    8614             :         }
    8615             :         else
    8616             :         {
    8617        1350 :             m_oSRS = *poSRS;
    8618        1350 :             m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    8619             :         }
    8620             :     }
    8621             : 
    8622        1366 :     return eErr;
    8623             : }
    8624             : 
    8625             : /************************************************************************/
    8626             : /*                          SetGeoTransform()                           */
    8627             : /************************************************************************/
    8628             : 
    8629        1586 : CPLErr GTiffDataset::SetGeoTransform(double *padfTransform)
    8630             : 
    8631             : {
    8632        1586 :     if (m_bStreamingOut && m_bCrystalized)
    8633             :     {
    8634           1 :         ReportError(CE_Failure, CPLE_NotSupported,
    8635             :                     "Cannot modify geotransform at that point in a "
    8636             :                     "streamed output file");
    8637           1 :         return CE_Failure;
    8638             :     }
    8639             : 
    8640        1585 :     LoadGeoreferencingAndPamIfNeeded();
    8641             : 
    8642        1585 :     CPLErr eErr = CE_None;
    8643        1585 :     if (eAccess == GA_Update)
    8644             :     {
    8645        1579 :         if (!m_aoGCPs.empty())
    8646             :         {
    8647           1 :             ReportError(CE_Warning, CPLE_AppDefined,
    8648             :                         "GCPs previously set are going to be cleared "
    8649             :                         "due to the setting of a geotransform.");
    8650           1 :             m_bForceUnsetGTOrGCPs = true;
    8651           1 :             m_aoGCPs.clear();
    8652             :         }
    8653        1578 :         else if (padfTransform[0] == 0.0 && padfTransform[1] == 0.0 &&
    8654           2 :                  padfTransform[2] == 0.0 && padfTransform[3] == 0.0 &&
    8655           2 :                  padfTransform[4] == 0.0 && padfTransform[5] == 0.0)
    8656             :         {
    8657           2 :             if (m_bGeoTransformValid)
    8658             :             {
    8659           2 :                 m_bForceUnsetGTOrGCPs = true;
    8660           2 :                 m_bGeoTIFFInfoChanged = true;
    8661             :             }
    8662           2 :             m_bGeoTransformValid = false;
    8663           2 :             memcpy(m_adfGeoTransform, padfTransform, sizeof(double) * 6);
    8664           2 :             return CE_None;
    8665             :         }
    8666             : 
    8667        3163 :         if ((m_eProfile == GTiffProfile::BASELINE) &&
    8668           9 :             !CPLFetchBool(m_papszCreationOptions, "TFW", false) &&
    8669        1591 :             !CPLFetchBool(m_papszCreationOptions, "WORLDFILE", false) &&
    8670           5 :             (GetPamFlags() & GPF_DISABLED) == 0)
    8671             :         {
    8672           5 :             eErr = GDALPamDataset::SetGeoTransform(padfTransform);
    8673             :         }
    8674             :         else
    8675             :         {
    8676             :             // Cancel any existing geotransform from PAM file.
    8677        1572 :             GDALPamDataset::DeleteGeoTransform();
    8678        1572 :             m_bGeoTIFFInfoChanged = true;
    8679             :         }
    8680             :     }
    8681             :     else
    8682             :     {
    8683           6 :         CPLDebug("GTIFF", "SetGeoTransform() goes to PAM instead of TIFF tags");
    8684           6 :         eErr = GDALPamDataset::SetGeoTransform(padfTransform);
    8685             :     }
    8686             : 
    8687        1583 :     if (eErr == CE_None)
    8688             :     {
    8689        1583 :         memcpy(m_adfGeoTransform, padfTransform, sizeof(double) * 6);
    8690        1583 :         m_bGeoTransformValid = true;
    8691             :     }
    8692             : 
    8693        1583 :     return eErr;
    8694             : }
    8695             : 
    8696             : /************************************************************************/
    8697             : /*                               SetGCPs()                              */
    8698             : /************************************************************************/
    8699             : 
    8700          21 : CPLErr GTiffDataset::SetGCPs(int nGCPCountIn, const GDAL_GCP *pasGCPListIn,
    8701             :                              const OGRSpatialReference *poGCPSRS)
    8702             : {
    8703          21 :     CPLErr eErr = CE_None;
    8704          21 :     LoadGeoreferencingAndPamIfNeeded();
    8705          21 :     LookForProjection();
    8706             : 
    8707          21 :     if (eAccess == GA_Update)
    8708             :     {
    8709          19 :         if (!m_aoGCPs.empty() && nGCPCountIn == 0)
    8710             :         {
    8711           3 :             m_bForceUnsetGTOrGCPs = true;
    8712             :         }
    8713          16 :         else if (nGCPCountIn > 0 && m_bGeoTransformValid)
    8714             :         {
    8715           4 :             ReportError(CE_Warning, CPLE_AppDefined,
    8716             :                         "A geotransform previously set is going to be cleared "
    8717             :                         "due to the setting of GCPs.");
    8718           4 :             m_adfGeoTransform[0] = 0.0;
    8719           4 :             m_adfGeoTransform[1] = 1.0;
    8720           4 :             m_adfGeoTransform[2] = 0.0;
    8721           4 :             m_adfGeoTransform[3] = 0.0;
    8722           4 :             m_adfGeoTransform[4] = 0.0;
    8723           4 :             m_adfGeoTransform[5] = 1.0;
    8724           4 :             m_bGeoTransformValid = false;
    8725           4 :             m_bForceUnsetGTOrGCPs = true;
    8726             :         }
    8727          19 :         if ((m_eProfile == GTiffProfile::BASELINE) &&
    8728           0 :             (GetPamFlags() & GPF_DISABLED) == 0)
    8729             :         {
    8730           0 :             eErr = GDALPamDataset::SetGCPs(nGCPCountIn, pasGCPListIn, poGCPSRS);
    8731             :         }
    8732             :         else
    8733             :         {
    8734          19 :             if (nGCPCountIn > knMAX_GCP_COUNT)
    8735             :             {
    8736           2 :                 if (GDALPamDataset::GetGCPCount() == 0 && !m_aoGCPs.empty())
    8737             :                 {
    8738           1 :                     m_bForceUnsetGTOrGCPs = true;
    8739             :                 }
    8740           2 :                 ReportError(CE_Warning, CPLE_AppDefined,
    8741             :                             "Trying to write %d GCPs, whereas the maximum "
    8742             :                             "supported in GeoTIFF tag is %d. "
    8743             :                             "Falling back to writing them to PAM",
    8744             :                             nGCPCountIn, knMAX_GCP_COUNT);
    8745           2 :                 eErr = GDALPamDataset::SetGCPs(nGCPCountIn, pasGCPListIn,
    8746             :                                                poGCPSRS);
    8747             :             }
    8748          17 :             else if (GDALPamDataset::GetGCPCount() > 0)
    8749             :             {
    8750             :                 // Cancel any existing GCPs from PAM file.
    8751           1 :                 GDALPamDataset::SetGCPs(
    8752             :                     0, nullptr,
    8753             :                     static_cast<const OGRSpatialReference *>(nullptr));
    8754             :             }
    8755          19 :             m_bGeoTIFFInfoChanged = true;
    8756             :         }
    8757             :     }
    8758             :     else
    8759             :     {
    8760           2 :         CPLDebug("GTIFF", "SetGCPs() goes to PAM instead of TIFF tags");
    8761           2 :         eErr = GDALPamDataset::SetGCPs(nGCPCountIn, pasGCPListIn, poGCPSRS);
    8762             :     }
    8763             : 
    8764          21 :     if (eErr == CE_None)
    8765             :     {
    8766          21 :         if (poGCPSRS == nullptr || poGCPSRS->IsEmpty())
    8767             :         {
    8768          11 :             if (!m_oSRS.IsEmpty())
    8769             :             {
    8770           4 :                 m_bForceUnsetProjection = true;
    8771             :             }
    8772          11 :             m_oSRS.Clear();
    8773             :         }
    8774             :         else
    8775             :         {
    8776          10 :             m_oSRS = *poGCPSRS;
    8777          10 :             m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    8778             :         }
    8779             : 
    8780          21 :         m_aoGCPs = gdal::GCP::fromC(pasGCPListIn, nGCPCountIn);
    8781             :     }
    8782             : 
    8783          21 :     return eErr;
    8784             : }
    8785             : 
    8786             : /************************************************************************/
    8787             : /*                            SetMetadata()                             */
    8788             : /************************************************************************/
    8789        2489 : CPLErr GTiffDataset::SetMetadata(char **papszMD, const char *pszDomain)
    8790             : 
    8791             : {
    8792        2489 :     LoadGeoreferencingAndPamIfNeeded();
    8793             : 
    8794        2489 :     if (m_bStreamingOut && m_bCrystalized)
    8795             :     {
    8796           1 :         ReportError(
    8797             :             CE_Failure, CPLE_NotSupported,
    8798             :             "Cannot modify metadata at that point in a streamed output file");
    8799           1 :         return CE_Failure;
    8800             :     }
    8801             : 
    8802        2488 :     CPLErr eErr = CE_None;
    8803        2488 :     if (eAccess == GA_Update)
    8804             :     {
    8805        2486 :         if (pszDomain != nullptr && EQUAL(pszDomain, MD_DOMAIN_RPC))
    8806             :         {
    8807             :             // So that a subsequent GetMetadata() wouldn't override our new
    8808             :             // values
    8809          22 :             LoadMetadata();
    8810          22 :             m_bForceUnsetRPC = (CSLCount(papszMD) == 0);
    8811             :         }
    8812             : 
    8813        2486 :         if ((papszMD != nullptr) && (pszDomain != nullptr) &&
    8814        1677 :             EQUAL(pszDomain, "COLOR_PROFILE"))
    8815             :         {
    8816           0 :             m_bColorProfileMetadataChanged = true;
    8817             :         }
    8818        2486 :         else if (pszDomain == nullptr || !EQUAL(pszDomain, "_temporary_"))
    8819             :         {
    8820        2486 :             m_bMetadataChanged = true;
    8821             :             // Cancel any existing metadata from PAM file.
    8822        2486 :             if (GDALPamDataset::GetMetadata(pszDomain) != nullptr)
    8823           1 :                 GDALPamDataset::SetMetadata(nullptr, pszDomain);
    8824             :         }
    8825             : 
    8826        4935 :         if ((pszDomain == nullptr || EQUAL(pszDomain, "")) &&
    8827        2449 :             CSLFetchNameValue(papszMD, GDALMD_AREA_OR_POINT) != nullptr)
    8828             :         {
    8829        1815 :             const char *pszPrevValue = GetMetadataItem(GDALMD_AREA_OR_POINT);
    8830             :             const char *pszNewValue =
    8831        1815 :                 CSLFetchNameValue(papszMD, GDALMD_AREA_OR_POINT);
    8832        1815 :             if (pszPrevValue == nullptr || pszNewValue == nullptr ||
    8833        1414 :                 !EQUAL(pszPrevValue, pszNewValue))
    8834             :             {
    8835         405 :                 LookForProjection();
    8836         405 :                 m_bGeoTIFFInfoChanged = true;
    8837             :             }
    8838             :         }
    8839             : 
    8840        2486 :         if (pszDomain != nullptr && EQUAL(pszDomain, "xml:XMP"))
    8841             :         {
    8842           2 :             if (papszMD != nullptr && *papszMD != nullptr)
    8843             :             {
    8844           1 :                 int nTagSize = static_cast<int>(strlen(*papszMD));
    8845           1 :                 TIFFSetField(m_hTIFF, TIFFTAG_XMLPACKET, nTagSize, *papszMD);
    8846             :             }
    8847             :             else
    8848             :             {
    8849           1 :                 TIFFUnsetField(m_hTIFF, TIFFTAG_XMLPACKET);
    8850             :             }
    8851             :         }
    8852             :     }
    8853             :     else
    8854             :     {
    8855           2 :         CPLDebug(
    8856             :             "GTIFF",
    8857             :             "GTiffDataset::SetMetadata() goes to PAM instead of TIFF tags");
    8858           2 :         eErr = GDALPamDataset::SetMetadata(papszMD, pszDomain);
    8859             :     }
    8860             : 
    8861        2488 :     if (eErr == CE_None)
    8862             :     {
    8863        2488 :         eErr = m_oGTiffMDMD.SetMetadata(papszMD, pszDomain);
    8864             :     }
    8865        2488 :     return eErr;
    8866             : }
    8867             : 
    8868             : /************************************************************************/
    8869             : /*                          SetMetadataItem()                           */
    8870             : /************************************************************************/
    8871             : 
    8872        3318 : CPLErr GTiffDataset::SetMetadataItem(const char *pszName, const char *pszValue,
    8873             :                                      const char *pszDomain)
    8874             : 
    8875             : {
    8876        3318 :     LoadGeoreferencingAndPamIfNeeded();
    8877             : 
    8878        3318 :     if (m_bStreamingOut && m_bCrystalized)
    8879             :     {
    8880           1 :         ReportError(
    8881             :             CE_Failure, CPLE_NotSupported,
    8882             :             "Cannot modify metadata at that point in a streamed output file");
    8883           1 :         return CE_Failure;
    8884             :     }
    8885             : 
    8886        3317 :     CPLErr eErr = CE_None;
    8887        3317 :     if (eAccess == GA_Update)
    8888             :     {
    8889        3310 :         if ((pszDomain != nullptr) && EQUAL(pszDomain, "COLOR_PROFILE"))
    8890             :         {
    8891           8 :             m_bColorProfileMetadataChanged = true;
    8892             :         }
    8893        3302 :         else if (pszDomain == nullptr || !EQUAL(pszDomain, "_temporary_"))
    8894             :         {
    8895        3302 :             m_bMetadataChanged = true;
    8896             :             // Cancel any existing metadata from PAM file.
    8897        3302 :             if (GDALPamDataset::GetMetadataItem(pszName, pszDomain) != nullptr)
    8898           1 :                 GDALPamDataset::SetMetadataItem(pszName, nullptr, pszDomain);
    8899             :         }
    8900             : 
    8901        3310 :         if ((pszDomain == nullptr || EQUAL(pszDomain, "")) &&
    8902          70 :             pszName != nullptr && EQUAL(pszName, GDALMD_AREA_OR_POINT))
    8903             :         {
    8904           7 :             LookForProjection();
    8905           7 :             m_bGeoTIFFInfoChanged = true;
    8906             :         }
    8907             :     }
    8908             :     else
    8909             :     {
    8910           7 :         CPLDebug(
    8911             :             "GTIFF",
    8912             :             "GTiffDataset::SetMetadataItem() goes to PAM instead of TIFF tags");
    8913           7 :         eErr = GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    8914             :     }
    8915             : 
    8916        3317 :     if (eErr == CE_None)
    8917             :     {
    8918        3317 :         eErr = m_oGTiffMDMD.SetMetadataItem(pszName, pszValue, pszDomain);
    8919             :     }
    8920             : 
    8921        3317 :     return eErr;
    8922             : }
    8923             : 
    8924             : /************************************************************************/
    8925             : /*                         CreateMaskBand()                             */
    8926             : /************************************************************************/
    8927             : 
    8928          93 : CPLErr GTiffDataset::CreateMaskBand(int nFlagsIn)
    8929             : {
    8930          93 :     ScanDirectories();
    8931             : 
    8932          93 :     if (m_poMaskDS != nullptr)
    8933             :     {
    8934           1 :         ReportError(CE_Failure, CPLE_AppDefined,
    8935             :                     "This TIFF dataset has already an internal mask band");
    8936           1 :         return CE_Failure;
    8937             :     }
    8938          92 :     else if (MustCreateInternalMask())
    8939             :     {
    8940          79 :         if (nFlagsIn != GMF_PER_DATASET)
    8941             :         {
    8942           1 :             ReportError(CE_Failure, CPLE_AppDefined,
    8943             :                         "The only flag value supported for internal mask is "
    8944             :                         "GMF_PER_DATASET");
    8945           1 :             return CE_Failure;
    8946             :         }
    8947             : 
    8948          78 :         int l_nCompression = COMPRESSION_PACKBITS;
    8949          78 :         if (strstr(GDALGetMetadataItem(GDALGetDriverByName("GTiff"),
    8950             :                                        GDAL_DMD_CREATIONOPTIONLIST, nullptr),
    8951          78 :                    "<Value>DEFLATE</Value>") != nullptr)
    8952          78 :             l_nCompression = COMPRESSION_ADOBE_DEFLATE;
    8953             : 
    8954             :         /* --------------------------------------------------------------------
    8955             :          */
    8956             :         /*      If we don't have read access, then create the mask externally.
    8957             :          */
    8958             :         /* --------------------------------------------------------------------
    8959             :          */
    8960          78 :         if (GetAccess() != GA_Update)
    8961             :         {
    8962           1 :             ReportError(CE_Warning, CPLE_AppDefined,
    8963             :                         "File open for read-only accessing, "
    8964             :                         "creating mask externally.");
    8965             : 
    8966           1 :             return GDALPamDataset::CreateMaskBand(nFlagsIn);
    8967             :         }
    8968             : 
    8969          77 :         if (m_bLayoutIFDSBeforeData && !m_bKnownIncompatibleEdition &&
    8970           0 :             !m_bWriteKnownIncompatibleEdition)
    8971             :         {
    8972           0 :             ReportError(CE_Warning, CPLE_AppDefined,
    8973             :                         "Adding a mask invalidates the "
    8974             :                         "LAYOUT=IFDS_BEFORE_DATA property");
    8975           0 :             m_bKnownIncompatibleEdition = true;
    8976           0 :             m_bWriteKnownIncompatibleEdition = true;
    8977             :         }
    8978             : 
    8979          77 :         bool bIsOverview = false;
    8980          77 :         uint32_t nSubType = 0;
    8981          77 :         if (TIFFGetField(m_hTIFF, TIFFTAG_SUBFILETYPE, &nSubType))
    8982             :         {
    8983           8 :             bIsOverview = (nSubType & FILETYPE_REDUCEDIMAGE) != 0;
    8984             : 
    8985           8 :             if ((nSubType & FILETYPE_MASK) != 0)
    8986             :             {
    8987           0 :                 ReportError(CE_Failure, CPLE_AppDefined,
    8988             :                             "Cannot create a mask on a TIFF mask IFD !");
    8989           0 :                 return CE_Failure;
    8990             :             }
    8991             :         }
    8992             : 
    8993          77 :         const int bIsTiled = TIFFIsTiled(m_hTIFF);
    8994             : 
    8995          77 :         FlushDirectory();
    8996             : 
    8997          77 :         const toff_t nOffset = GTIFFWriteDirectory(
    8998             :             m_hTIFF,
    8999             :             bIsOverview ? FILETYPE_REDUCEDIMAGE | FILETYPE_MASK : FILETYPE_MASK,
    9000             :             nRasterXSize, nRasterYSize, 1, PLANARCONFIG_CONTIG, 1,
    9001             :             m_nBlockXSize, m_nBlockYSize, bIsTiled, l_nCompression,
    9002             :             PHOTOMETRIC_MASK, PREDICTOR_NONE, SAMPLEFORMAT_UINT, nullptr,
    9003             :             nullptr, nullptr, 0, nullptr, "", nullptr, nullptr, nullptr,
    9004          77 :             nullptr, m_bWriteCOGLayout);
    9005             : 
    9006          77 :         ReloadDirectory();
    9007             : 
    9008          77 :         if (nOffset == 0)
    9009           0 :             return CE_Failure;
    9010             : 
    9011          77 :         m_poMaskDS = new GTiffDataset();
    9012          77 :         m_poMaskDS->m_poBaseDS = this;
    9013          77 :         m_poMaskDS->m_poImageryDS = this;
    9014          77 :         m_poMaskDS->ShareLockWithParentDataset(this);
    9015          77 :         m_poMaskDS->m_bPromoteTo8Bits = CPLTestBool(
    9016             :             CPLGetConfigOption("GDAL_TIFF_INTERNAL_MASK_TO_8BIT", "YES"));
    9017          77 :         if (m_poMaskDS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF), nOffset,
    9018          77 :                                    GA_Update) != CE_None)
    9019             :         {
    9020           0 :             delete m_poMaskDS;
    9021           0 :             m_poMaskDS = nullptr;
    9022           0 :             return CE_Failure;
    9023             :         }
    9024             : 
    9025          77 :         return CE_None;
    9026             :     }
    9027             : 
    9028          13 :     return GDALPamDataset::CreateMaskBand(nFlagsIn);
    9029             : }
    9030             : 
    9031             : /************************************************************************/
    9032             : /*                        MustCreateInternalMask()                      */
    9033             : /************************************************************************/
    9034             : 
    9035         128 : bool GTiffDataset::MustCreateInternalMask()
    9036             : {
    9037         128 :     return CPLTestBool(CPLGetConfigOption("GDAL_TIFF_INTERNAL_MASK", "YES"));
    9038             : }
    9039             : 
    9040             : /************************************************************************/
    9041             : /*                         CreateMaskBand()                             */
    9042             : /************************************************************************/
    9043             : 
    9044          27 : CPLErr GTiffRasterBand::CreateMaskBand(int nFlagsIn)
    9045             : {
    9046          27 :     m_poGDS->ScanDirectories();
    9047             : 
    9048          27 :     if (m_poGDS->m_poMaskDS != nullptr)
    9049             :     {
    9050           5 :         ReportError(CE_Failure, CPLE_AppDefined,
    9051             :                     "This TIFF dataset has already an internal mask band");
    9052           5 :         return CE_Failure;
    9053             :     }
    9054             : 
    9055             :     const char *pszGDAL_TIFF_INTERNAL_MASK =
    9056          22 :         CPLGetConfigOption("GDAL_TIFF_INTERNAL_MASK", nullptr);
    9057          25 :     if ((pszGDAL_TIFF_INTERNAL_MASK &&
    9058          22 :          CPLTestBool(pszGDAL_TIFF_INTERNAL_MASK)) ||
    9059             :         nFlagsIn == GMF_PER_DATASET)
    9060             :     {
    9061          15 :         return m_poGDS->CreateMaskBand(nFlagsIn);
    9062             :     }
    9063             : 
    9064           7 :     return GDALPamRasterBand::CreateMaskBand(nFlagsIn);
    9065             : }
    9066             : 
    9067             : /************************************************************************/
    9068             : /*                          ClampCTEntry()                              */
    9069             : /************************************************************************/
    9070             : 
    9071      227439 : /* static */ unsigned short GTiffDataset::ClampCTEntry(int iColor, int iComp,
    9072             :                                                        int nCTEntryVal,
    9073             :                                                        int nMultFactor)
    9074             : {
    9075      227439 :     const int nVal = nCTEntryVal * nMultFactor;
    9076      227439 :     if (nVal < 0)
    9077             :     {
    9078           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9079             :                  "Color table entry [%d][%d] = %d, clamped to 0", iColor, iComp,
    9080             :                  nCTEntryVal);
    9081           0 :         return 0;
    9082             :     }
    9083      227439 :     if (nVal > 65535)
    9084             :     {
    9085           2 :         CPLError(CE_Warning, CPLE_AppDefined,
    9086             :                  "Color table entry [%d][%d] = %d, clamped to 65535", iColor,
    9087             :                  iComp, nCTEntryVal);
    9088           2 :         return 65535;
    9089             :     }
    9090      227437 :     return static_cast<unsigned short>(nVal);
    9091             : }

Generated by: LCOV version 1.14