LCOV - code coverage report
Current view: top level - frmts/gtiff - gtiffdataset_write.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 3820 4173 91.5 %
Date: 2025-07-09 17:50:03 Functions: 109 138 79.0 %

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

Generated by: LCOV version 1.14