LCOV - code coverage report
Current view: top level - frmts/gtiff - gtiffdataset_write.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 3893 4250 91.6 %
Date: 2026-06-01 18:39:17 Functions: 110 139 79.1 %

          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             : #include "gtiffjpegoverviewds.h"
      18             : 
      19             : #include <cassert>
      20             : #include <cerrno>
      21             : 
      22             : #include <algorithm>
      23             : #include <cmath>
      24             : #include <limits>
      25             : #include <memory>
      26             : #include <mutex>
      27             : #include <set>
      28             : #include <string>
      29             : #include <tuple>
      30             : #include <utility>
      31             : 
      32             : #include "cpl_error.h"
      33             : #include "cpl_error_internal.h"  // CPLErrorHandlerAccumulatorStruct
      34             : #include "cpl_float.h"
      35             : #include "cpl_md5.h"
      36             : #include "cpl_vsi.h"
      37             : #include "cpl_vsi_virtual.h"
      38             : #include "cpl_worker_thread_pool.h"
      39             : #include "fetchbufferdirectio.h"
      40             : #include "gdal_mdreader.h"  // GDALWriteRPCTXTFile()
      41             : #include "gdal_priv.h"
      42             : #include "gdal_priv_templates.hpp"  // GDALIsValueInRange<>
      43             : #include "gdal_thread_pool.h"       // GDALGetGlobalThreadPool()
      44             : #include "geovalues.h"              // RasterPixelIsPoint
      45             : #include "gt_jpeg_copy.h"
      46             : #include "gt_overview.h"  // GTIFFBuildOverviewMetadata()
      47             : #include "quant_table_md5sum.h"
      48             : #include "quant_table_md5sum_jpeg9e.h"
      49             : #include "tif_jxl.h"
      50             : #include "tifvsi.h"
      51             : #include "xtiffio.h"
      52             : 
      53             : #if LIFFLIB_VERSION > 20230908 || defined(INTERNAL_LIBTIFF)
      54             : /* libtiff < 4.6.1 doesn't generate a LERC mask for multi-band contig configuration */
      55             : #define LIBTIFF_MULTIBAND_LERC_NAN_OK
      56             : #endif
      57             : 
      58             : static const int knGTIFFJpegTablesModeDefault = JPEGTABLESMODE_QUANT;
      59             : 
      60             : static constexpr const char szPROFILE_BASELINE[] = "BASELINE";
      61             : static constexpr const char szPROFILE_GeoTIFF[] = "GeoTIFF";
      62             : static constexpr const char szPROFILE_GDALGeoTIFF[] = "GDALGeoTIFF";
      63             : 
      64             : // Due to libgeotiff/xtiff.c declaring TIFFTAG_GEOTIEPOINTS with field_readcount
      65             : // and field_writecount == -1 == TIFF_VARIABLE, we are limited to writing
      66             : // 65535 values in that tag. That could potentially be overcome by changing the tag
      67             : // declaration to using TIFF_VARIABLE2 where the count is a uint32_t.
      68             : constexpr int knMAX_GCP_COUNT =
      69             :     static_cast<int>(std::numeric_limits<uint16_t>::max() / 6);
      70             : 
      71             : enum
      72             : {
      73             :     ENDIANNESS_NATIVE,
      74             :     ENDIANNESS_LITTLE,
      75             :     ENDIANNESS_BIG
      76             : };
      77             : 
      78       17938 : static signed char GTiffGetWebPLevel(CSLConstList papszOptions)
      79             : {
      80       17938 :     int nWebPLevel = DEFAULT_WEBP_LEVEL;
      81       17938 :     const char *pszValue = CSLFetchNameValue(papszOptions, "WEBP_LEVEL");
      82       17938 :     if (pszValue != nullptr)
      83             :     {
      84          51 :         nWebPLevel = atoi(pszValue);
      85          51 :         if (!(nWebPLevel >= 1 && nWebPLevel <= 100))
      86             :         {
      87           0 :             CPLError(CE_Warning, CPLE_IllegalArg,
      88             :                      "WEBP_LEVEL=%s value not recognised, ignoring.", pszValue);
      89           0 :             nWebPLevel = DEFAULT_WEBP_LEVEL;
      90             :         }
      91             :     }
      92       17938 :     return static_cast<signed char>(nWebPLevel);
      93             : }
      94             : 
      95       17944 : static bool GTiffGetWebPLossless(CSLConstList papszOptions)
      96             : {
      97       17944 :     return CPLFetchBool(papszOptions, "WEBP_LOSSLESS", false);
      98             : }
      99             : 
     100       18010 : static double GTiffGetLERCMaxZError(CSLConstList papszOptions)
     101             : {
     102       18010 :     return CPLAtof(CSLFetchNameValueDef(papszOptions, "MAX_Z_ERROR", "0.0"));
     103             : }
     104             : 
     105        8042 : static double GTiffGetLERCMaxZErrorOverview(CSLConstList papszOptions)
     106             : {
     107        8042 :     return CPLAtof(CSLFetchNameValueDef(
     108             :         papszOptions, "MAX_Z_ERROR_OVERVIEW",
     109        8042 :         CSLFetchNameValueDef(papszOptions, "MAX_Z_ERROR", "0.0")));
     110             : }
     111             : 
     112             : #if HAVE_JXL
     113       18014 : static bool GTiffGetJXLLossless(CSLConstList papszOptions,
     114             :                                 bool *pbIsSpecified = nullptr)
     115             : {
     116       18014 :     const char *pszVal = CSLFetchNameValue(papszOptions, "JXL_LOSSLESS");
     117       18014 :     if (pbIsSpecified)
     118        9968 :         *pbIsSpecified = pszVal != nullptr;
     119       18014 :     return pszVal == nullptr || CPLTestBool(pszVal);
     120             : }
     121             : 
     122       18014 : static uint32_t GTiffGetJXLEffort(CSLConstList papszOptions)
     123             : {
     124       18014 :     return atoi(CSLFetchNameValueDef(papszOptions, "JXL_EFFORT", "5"));
     125             : }
     126             : 
     127       17932 : static float GTiffGetJXLDistance(CSLConstList papszOptions,
     128             :                                  bool *pbIsSpecified = nullptr)
     129             : {
     130       17932 :     const char *pszVal = CSLFetchNameValue(papszOptions, "JXL_DISTANCE");
     131       17932 :     if (pbIsSpecified)
     132        9968 :         *pbIsSpecified = pszVal != nullptr;
     133       17932 :     return pszVal == nullptr ? 1.0f : static_cast<float>(CPLAtof(pszVal));
     134             : }
     135             : 
     136       18014 : static float GTiffGetJXLAlphaDistance(CSLConstList papszOptions,
     137             :                                       bool *pbIsSpecified = nullptr)
     138             : {
     139       18014 :     const char *pszVal = CSLFetchNameValue(papszOptions, "JXL_ALPHA_DISTANCE");
     140       18014 :     if (pbIsSpecified)
     141        9968 :         *pbIsSpecified = pszVal != nullptr;
     142       18014 :     return pszVal == nullptr ? -1.0f : static_cast<float>(CPLAtof(pszVal));
     143             : }
     144             : 
     145             : #endif
     146             : 
     147             : /************************************************************************/
     148             : /*                           FillEmptyTiles()                           */
     149             : /************************************************************************/
     150             : 
     151        8232 : CPLErr GTiffDataset::FillEmptyTiles()
     152             : 
     153             : {
     154             :     /* -------------------------------------------------------------------- */
     155             :     /*      How many blocks are there in this file?                         */
     156             :     /* -------------------------------------------------------------------- */
     157       16464 :     const int nBlockCount = m_nPlanarConfig == PLANARCONFIG_SEPARATE
     158        8232 :                                 ? m_nBlocksPerBand * nBands
     159             :                                 : m_nBlocksPerBand;
     160             : 
     161             :     /* -------------------------------------------------------------------- */
     162             :     /*      Fetch block maps.                                               */
     163             :     /* -------------------------------------------------------------------- */
     164        8232 :     toff_t *panByteCounts = nullptr;
     165             : 
     166        8232 :     if (TIFFIsTiled(m_hTIFF))
     167        1156 :         TIFFGetField(m_hTIFF, TIFFTAG_TILEBYTECOUNTS, &panByteCounts);
     168             :     else
     169        7076 :         TIFFGetField(m_hTIFF, TIFFTAG_STRIPBYTECOUNTS, &panByteCounts);
     170             : 
     171        8232 :     if (panByteCounts == nullptr)
     172             :     {
     173             :         // Got here with libtiff 3.9.3 and tiff_write_8 test.
     174           0 :         ReportError(CE_Failure, CPLE_AppDefined,
     175             :                     "FillEmptyTiles() failed because panByteCounts == NULL");
     176           0 :         return CE_Failure;
     177             :     }
     178             : 
     179             :     /* -------------------------------------------------------------------- */
     180             :     /*      Prepare a blank data buffer to write for uninitialized blocks.  */
     181             :     /* -------------------------------------------------------------------- */
     182             :     const GPtrDiff_t nBlockBytes =
     183        8232 :         TIFFIsTiled(m_hTIFF) ? static_cast<GPtrDiff_t>(TIFFTileSize(m_hTIFF))
     184        7076 :                              : static_cast<GPtrDiff_t>(TIFFStripSize(m_hTIFF));
     185             : 
     186        8232 :     GByte *pabyData = static_cast<GByte *>(VSI_CALLOC_VERBOSE(nBlockBytes, 1));
     187        8232 :     if (pabyData == nullptr)
     188             :     {
     189           0 :         return CE_Failure;
     190             :     }
     191             : 
     192             :     // Force tiles completely filled with the nodata value to be written.
     193        8232 :     m_bWriteEmptyTiles = true;
     194             : 
     195             :     /* -------------------------------------------------------------------- */
     196             :     /*      If set, fill data buffer with no data value.                    */
     197             :     /* -------------------------------------------------------------------- */
     198        8232 :     if ((m_bNoDataSet && m_dfNoDataValue != 0.0) ||
     199        7964 :         (m_bNoDataSetAsInt64 && m_nNoDataValueInt64 != 0) ||
     200        7959 :         (m_bNoDataSetAsUInt64 && m_nNoDataValueUInt64 != 0))
     201             :     {
     202         278 :         const GDALDataType eDataType = GetRasterBand(1)->GetRasterDataType();
     203         278 :         const int nDataTypeSize = GDALGetDataTypeSizeBytes(eDataType);
     204         278 :         if (nDataTypeSize &&
     205         278 :             nDataTypeSize * 8 == static_cast<int>(m_nBitsPerSample))
     206             :         {
     207         267 :             if (m_bNoDataSetAsInt64)
     208             :             {
     209           6 :                 GDALCopyWords64(&m_nNoDataValueInt64, GDT_Int64, 0, pabyData,
     210             :                                 eDataType, nDataTypeSize,
     211           6 :                                 nBlockBytes / nDataTypeSize);
     212             :             }
     213         261 :             else if (m_bNoDataSetAsUInt64)
     214             :             {
     215           5 :                 GDALCopyWords64(&m_nNoDataValueUInt64, GDT_UInt64, 0, pabyData,
     216             :                                 eDataType, nDataTypeSize,
     217           5 :                                 nBlockBytes / nDataTypeSize);
     218             :             }
     219             :             else
     220             :             {
     221         256 :                 double dfNoData = m_dfNoDataValue;
     222         256 :                 GDALCopyWords64(&dfNoData, GDT_Float64, 0, pabyData, eDataType,
     223         256 :                                 nDataTypeSize, nBlockBytes / nDataTypeSize);
     224         267 :             }
     225             :         }
     226          11 :         else if (nDataTypeSize)
     227             :         {
     228             :             // Handle non power-of-two depths.
     229             :             // Ideally make a packed buffer, but that is a bit tedious,
     230             :             // so use the normal I/O interfaces.
     231             : 
     232          11 :             CPLFree(pabyData);
     233             : 
     234          11 :             pabyData = static_cast<GByte *>(VSI_MALLOC3_VERBOSE(
     235             :                 m_nBlockXSize, m_nBlockYSize, nDataTypeSize));
     236          11 :             if (pabyData == nullptr)
     237           0 :                 return CE_Failure;
     238          11 :             if (m_bNoDataSetAsInt64)
     239             :             {
     240           0 :                 GDALCopyWords64(&m_nNoDataValueInt64, GDT_Int64, 0, pabyData,
     241             :                                 eDataType, nDataTypeSize,
     242           0 :                                 static_cast<GPtrDiff_t>(m_nBlockXSize) *
     243           0 :                                     m_nBlockYSize);
     244             :             }
     245          11 :             else if (m_bNoDataSetAsUInt64)
     246             :             {
     247           0 :                 GDALCopyWords64(&m_nNoDataValueUInt64, GDT_UInt64, 0, pabyData,
     248             :                                 eDataType, nDataTypeSize,
     249           0 :                                 static_cast<GPtrDiff_t>(m_nBlockXSize) *
     250           0 :                                     m_nBlockYSize);
     251             :             }
     252             :             else
     253             :             {
     254          11 :                 GDALCopyWords64(&m_dfNoDataValue, GDT_Float64, 0, pabyData,
     255             :                                 eDataType, nDataTypeSize,
     256          11 :                                 static_cast<GPtrDiff_t>(m_nBlockXSize) *
     257          11 :                                     m_nBlockYSize);
     258             :             }
     259          11 :             CPLErr eErr = CE_None;
     260          46 :             for (int iBlock = 0; iBlock < nBlockCount; ++iBlock)
     261             :             {
     262          35 :                 if (panByteCounts[iBlock] == 0)
     263             :                 {
     264          18 :                     if (m_nPlanarConfig == PLANARCONFIG_SEPARATE || nBands == 1)
     265             :                     {
     266          24 :                         if (GetRasterBand(1 + iBlock / m_nBlocksPerBand)
     267          12 :                                 ->WriteBlock((iBlock % m_nBlocksPerBand) %
     268          12 :                                                  m_nBlocksPerRow,
     269          12 :                                              (iBlock % m_nBlocksPerBand) /
     270          12 :                                                  m_nBlocksPerRow,
     271          12 :                                              pabyData) != CE_None)
     272             :                         {
     273           0 :                             eErr = CE_Failure;
     274             :                         }
     275             :                     }
     276             :                     else
     277             :                     {
     278             :                         // In contig case, don't directly call WriteBlock(), as
     279             :                         // it could cause useless decompression-recompression.
     280           6 :                         const int nXOff =
     281           6 :                             (iBlock % m_nBlocksPerRow) * m_nBlockXSize;
     282           6 :                         const int nYOff =
     283           6 :                             (iBlock / m_nBlocksPerRow) * m_nBlockYSize;
     284           6 :                         const int nXSize =
     285           6 :                             (nXOff + m_nBlockXSize <= nRasterXSize)
     286           6 :                                 ? m_nBlockXSize
     287           2 :                                 : nRasterXSize - nXOff;
     288           6 :                         const int nYSize =
     289           6 :                             (nYOff + m_nBlockYSize <= nRasterYSize)
     290           6 :                                 ? m_nBlockYSize
     291           3 :                                 : nRasterYSize - nYOff;
     292          18 :                         for (int iBand = 1; iBand <= nBands; ++iBand)
     293             :                         {
     294          12 :                             if (GetRasterBand(iBand)->RasterIO(
     295             :                                     GF_Write, nXOff, nYOff, nXSize, nYSize,
     296             :                                     pabyData, nXSize, nYSize, eDataType, 0, 0,
     297          12 :                                     nullptr) != CE_None)
     298             :                             {
     299           0 :                                 eErr = CE_Failure;
     300             :                             }
     301             :                         }
     302             :                     }
     303             :                 }
     304             :             }
     305          11 :             CPLFree(pabyData);
     306          11 :             return eErr;
     307         267 :         }
     308             :     }
     309             : 
     310             :     /* -------------------------------------------------------------------- */
     311             :     /*      When we must fill with zeroes, try to create non-sparse file    */
     312             :     /*      w.r.t TIFF spec ... as a sparse file w.r.t filesystem, ie by    */
     313             :     /*      seeking to end of file instead of writing zero blocks.          */
     314             :     /* -------------------------------------------------------------------- */
     315        7954 :     else if (m_nCompression == COMPRESSION_NONE && (m_nBitsPerSample % 8) == 0)
     316             :     {
     317        6374 :         CPLErr eErr = CE_None;
     318             :         // Only use libtiff to write the first sparse block to ensure that it
     319             :         // will serialize offset and count arrays back to disk.
     320        6374 :         int nCountBlocksToZero = 0;
     321     2330240 :         for (int iBlock = 0; iBlock < nBlockCount; ++iBlock)
     322             :         {
     323     2323860 :             if (panByteCounts[iBlock] == 0)
     324             :             {
     325     2228340 :                 if (nCountBlocksToZero == 0)
     326             :                 {
     327        1137 :                     const bool bWriteEmptyTilesBak = m_bWriteEmptyTiles;
     328        1137 :                     m_bWriteEmptyTiles = true;
     329        1137 :                     const bool bOK = WriteEncodedTileOrStrip(iBlock, pabyData,
     330        1137 :                                                              FALSE) == CE_None;
     331        1137 :                     m_bWriteEmptyTiles = bWriteEmptyTilesBak;
     332        1137 :                     if (!bOK)
     333             :                     {
     334           2 :                         eErr = CE_Failure;
     335           2 :                         break;
     336             :                     }
     337             :                 }
     338     2228340 :                 nCountBlocksToZero++;
     339             :             }
     340             :         }
     341        6374 :         CPLFree(pabyData);
     342             : 
     343        6374 :         --nCountBlocksToZero;
     344             : 
     345             :         // And then seek to end of file for other ones.
     346        6374 :         if (nCountBlocksToZero > 0)
     347             :         {
     348         348 :             toff_t *panByteOffsets = nullptr;
     349             : 
     350         348 :             if (TIFFIsTiled(m_hTIFF))
     351         101 :                 TIFFGetField(m_hTIFF, TIFFTAG_TILEOFFSETS, &panByteOffsets);
     352             :             else
     353         247 :                 TIFFGetField(m_hTIFF, TIFFTAG_STRIPOFFSETS, &panByteOffsets);
     354             : 
     355         348 :             if (panByteOffsets == nullptr)
     356             :             {
     357           0 :                 ReportError(
     358             :                     CE_Failure, CPLE_AppDefined,
     359             :                     "FillEmptyTiles() failed because panByteOffsets == NULL");
     360           0 :                 return CE_Failure;
     361             :             }
     362             : 
     363         348 :             VSILFILE *fpTIF = VSI_TIFFGetVSILFile(TIFFClientdata(m_hTIFF));
     364         348 :             VSIFSeekL(fpTIF, 0, SEEK_END);
     365         348 :             const vsi_l_offset nOffset = VSIFTellL(fpTIF);
     366             : 
     367         348 :             vsi_l_offset iBlockToZero = 0;
     368     2236440 :             for (int iBlock = 0; iBlock < nBlockCount; ++iBlock)
     369             :             {
     370     2236090 :                 if (panByteCounts[iBlock] == 0)
     371             :                 {
     372     2227200 :                     panByteOffsets[iBlock] = static_cast<toff_t>(
     373     2227200 :                         nOffset + iBlockToZero * nBlockBytes);
     374     2227200 :                     panByteCounts[iBlock] = nBlockBytes;
     375     2227200 :                     iBlockToZero++;
     376             :                 }
     377             :             }
     378         348 :             CPLAssert(iBlockToZero ==
     379             :                       static_cast<vsi_l_offset>(nCountBlocksToZero));
     380             : 
     381         348 :             if (VSIFTruncateL(fpTIF, nOffset + iBlockToZero * nBlockBytes) != 0)
     382             :             {
     383           0 :                 eErr = CE_Failure;
     384           0 :                 ReportError(CE_Failure, CPLE_FileIO,
     385             :                             "Cannot initialize empty blocks");
     386             :             }
     387             :         }
     388             : 
     389        6374 :         return eErr;
     390             :     }
     391             : 
     392             :     /* -------------------------------------------------------------------- */
     393             :     /*      Check all blocks, writing out data for uninitialized blocks.    */
     394             :     /* -------------------------------------------------------------------- */
     395             : 
     396        1847 :     GByte *pabyRaw = nullptr;
     397        1847 :     vsi_l_offset nRawSize = 0;
     398        1847 :     CPLErr eErr = CE_None;
     399       56558 :     for (int iBlock = 0; iBlock < nBlockCount; ++iBlock)
     400             :     {
     401       54718 :         if (panByteCounts[iBlock] == 0)
     402             :         {
     403       17570 :             if (pabyRaw == nullptr)
     404             :             {
     405       10167 :                 if (WriteEncodedTileOrStrip(iBlock, pabyData, FALSE) != CE_None)
     406             :                 {
     407           7 :                     eErr = CE_Failure;
     408           7 :                     break;
     409             :                 }
     410             : 
     411       10160 :                 vsi_l_offset nOffset = 0;
     412       10160 :                 if (!IsBlockAvailable(iBlock, &nOffset, &nRawSize, nullptr))
     413           0 :                     break;
     414             : 
     415             :                 // When using compression, get back the compressed block
     416             :                 // so we can use the raw API to write it faster.
     417       10160 :                 if (m_nCompression != COMPRESSION_NONE)
     418             :                 {
     419             :                     pabyRaw = static_cast<GByte *>(
     420         486 :                         VSI_MALLOC_VERBOSE(static_cast<size_t>(nRawSize)));
     421         486 :                     if (pabyRaw)
     422             :                     {
     423             :                         VSILFILE *fp =
     424         486 :                             VSI_TIFFGetVSILFile(TIFFClientdata(m_hTIFF));
     425         486 :                         const vsi_l_offset nCurOffset = VSIFTellL(fp);
     426         486 :                         VSIFSeekL(fp, nOffset, SEEK_SET);
     427         486 :                         VSIFReadL(pabyRaw, 1, static_cast<size_t>(nRawSize),
     428             :                                   fp);
     429         486 :                         VSIFSeekL(fp, nCurOffset, SEEK_SET);
     430             :                     }
     431             :                 }
     432             :             }
     433             :             else
     434             :             {
     435        7403 :                 WriteRawStripOrTile(iBlock, pabyRaw,
     436             :                                     static_cast<GPtrDiff_t>(nRawSize));
     437             :             }
     438             :         }
     439             :     }
     440             : 
     441        1847 :     CPLFree(pabyData);
     442        1847 :     VSIFree(pabyRaw);
     443        1847 :     return eErr;
     444             : }
     445             : 
     446             : /************************************************************************/
     447             : /*                           HasOnlyNoData()                            */
     448             : /************************************************************************/
     449             : 
     450       42914 : bool GTiffDataset::HasOnlyNoData(const void *pBuffer, int nWidth, int nHeight,
     451             :                                  int nLineStride, int nComponents)
     452             : {
     453       42914 :     if (m_nSampleFormat == SAMPLEFORMAT_COMPLEXINT ||
     454       42914 :         m_nSampleFormat == SAMPLEFORMAT_COMPLEXIEEEFP)
     455           0 :         return false;
     456       42914 :     if (m_bNoDataSetAsInt64 || m_bNoDataSetAsUInt64)
     457           6 :         return false;  // FIXME: over pessimistic
     458       85816 :     return GDALBufferHasOnlyNoData(
     459       42908 :         pBuffer, m_bNoDataSet ? m_dfNoDataValue : 0.0, nWidth, nHeight,
     460       42908 :         nLineStride, nComponents, m_nBitsPerSample,
     461       42908 :         m_nSampleFormat == SAMPLEFORMAT_UINT  ? GSF_UNSIGNED_INT
     462        4926 :         : m_nSampleFormat == SAMPLEFORMAT_INT ? GSF_SIGNED_INT
     463       42908 :                                               : GSF_FLOATING_POINT);
     464             : }
     465             : 
     466             : /************************************************************************/
     467             : /*                     IsFirstPixelEqualToNoData()                      */
     468             : /************************************************************************/
     469             : 
     470      169369 : inline bool GTiffDataset::IsFirstPixelEqualToNoData(const void *pBuffer)
     471             : {
     472      169369 :     const GDALDataType eDT = GetRasterBand(1)->GetRasterDataType();
     473      169369 :     const double dfEffectiveNoData = (m_bNoDataSet) ? m_dfNoDataValue : 0.0;
     474      169369 :     if (m_bNoDataSetAsInt64 || m_bNoDataSetAsUInt64)
     475          10 :         return true;  // FIXME: over pessimistic
     476      169359 :     if (m_nBitsPerSample == 8 ||
     477       59019 :         (m_nBitsPerSample < 8 && dfEffectiveNoData == 0))
     478             :     {
     479      113786 :         if (eDT == GDT_Int8)
     480             :         {
     481         278 :             return GDALIsValueInRange<signed char>(dfEffectiveNoData) &&
     482         139 :                    *(static_cast<const signed char *>(pBuffer)) ==
     483         278 :                        static_cast<signed char>(dfEffectiveNoData);
     484             :         }
     485      227263 :         return GDALIsValueInRange<GByte>(dfEffectiveNoData) &&
     486      113616 :                *(static_cast<const GByte *>(pBuffer)) ==
     487      227263 :                    static_cast<GByte>(dfEffectiveNoData);
     488             :     }
     489       55573 :     if (m_nBitsPerSample == 16 && eDT == GDT_UInt16)
     490             :     {
     491        4686 :         return GDALIsValueInRange<GUInt16>(dfEffectiveNoData) &&
     492        2343 :                *(static_cast<const GUInt16 *>(pBuffer)) ==
     493        4686 :                    static_cast<GUInt16>(dfEffectiveNoData);
     494             :     }
     495       53230 :     if (m_nBitsPerSample == 16 && eDT == GDT_Int16)
     496             :     {
     497        8476 :         return GDALIsValueInRange<GInt16>(dfEffectiveNoData) &&
     498        4238 :                *(static_cast<const GInt16 *>(pBuffer)) ==
     499        8476 :                    static_cast<GInt16>(dfEffectiveNoData);
     500             :     }
     501       48992 :     if (m_nBitsPerSample == 32 && eDT == GDT_UInt32)
     502             :     {
     503         378 :         return GDALIsValueInRange<GUInt32>(dfEffectiveNoData) &&
     504         189 :                *(static_cast<const GUInt32 *>(pBuffer)) ==
     505         378 :                    static_cast<GUInt32>(dfEffectiveNoData);
     506             :     }
     507       48803 :     if (m_nBitsPerSample == 32 && eDT == GDT_Int32)
     508             :     {
     509         506 :         return GDALIsValueInRange<GInt32>(dfEffectiveNoData) &&
     510         253 :                *(static_cast<const GInt32 *>(pBuffer)) ==
     511         506 :                    static_cast<GInt32>(dfEffectiveNoData);
     512             :     }
     513       48550 :     if (m_nBitsPerSample == 64 && eDT == GDT_UInt64)
     514             :     {
     515         234 :         return GDALIsValueInRange<std::uint64_t>(dfEffectiveNoData) &&
     516         117 :                *(static_cast<const std::uint64_t *>(pBuffer)) ==
     517         234 :                    static_cast<std::uint64_t>(dfEffectiveNoData);
     518             :     }
     519       48433 :     if (m_nBitsPerSample == 64 && eDT == GDT_Int64)
     520             :     {
     521         236 :         return GDALIsValueInRange<std::int64_t>(dfEffectiveNoData) &&
     522         118 :                *(static_cast<const std::int64_t *>(pBuffer)) ==
     523         236 :                    static_cast<std::int64_t>(dfEffectiveNoData);
     524             :     }
     525       48315 :     if (m_nBitsPerSample == 32 && eDT == GDT_Float32)
     526             :     {
     527       41191 :         if (std::isnan(m_dfNoDataValue))
     528           3 :             return std::isnan(*(static_cast<const float *>(pBuffer)));
     529       82376 :         return GDALIsValueInRange<float>(dfEffectiveNoData) &&
     530       41188 :                *(static_cast<const float *>(pBuffer)) ==
     531       82376 :                    static_cast<float>(dfEffectiveNoData);
     532             :     }
     533        7124 :     if (m_nBitsPerSample == 64 && eDT == GDT_Float64)
     534             :     {
     535        4451 :         if (std::isnan(dfEffectiveNoData))
     536           3 :             return std::isnan(*(static_cast<const double *>(pBuffer)));
     537        4448 :         return *(static_cast<const double *>(pBuffer)) == dfEffectiveNoData;
     538             :     }
     539        2673 :     return false;
     540             : }
     541             : 
     542             : /************************************************************************/
     543             : /*                      WriteDealWithLercAndNan()                       */
     544             : /************************************************************************/
     545             : 
     546             : template <typename T>
     547           0 : void GTiffDataset::WriteDealWithLercAndNan(T *pBuffer, int nActualBlockWidth,
     548             :                                            int nActualBlockHeight,
     549             :                                            int nStrileHeight)
     550             : {
     551             :     // This method does 2 things:
     552             :     // - warn the user if he tries to write NaN values with libtiff < 4.6.1
     553             :     //   and multi-band PlanarConfig=Contig configuration
     554             :     // - and in right-most and bottom-most tiles, replace non accessible
     555             :     //   pixel values by a safe one.
     556             : 
     557           0 :     const auto fPaddingValue =
     558             : #if !defined(LIBTIFF_MULTIBAND_LERC_NAN_OK)
     559             :         m_nPlanarConfig == PLANARCONFIG_CONTIG && nBands > 1
     560             :             ? 0
     561             :             :
     562             : #endif
     563             :             std::numeric_limits<T>::quiet_NaN();
     564             : 
     565           0 :     const int nBandsPerStrile =
     566           0 :         m_nPlanarConfig == PLANARCONFIG_CONTIG ? nBands : 1;
     567           0 :     for (int j = 0; j < nActualBlockHeight; ++j)
     568             :     {
     569             : #if !defined(LIBTIFF_MULTIBAND_LERC_NAN_OK)
     570             :         static bool bHasWarned = false;
     571             :         if (m_nPlanarConfig == PLANARCONFIG_CONTIG && nBands > 1 && !bHasWarned)
     572             :         {
     573             :             for (int i = 0; i < nActualBlockWidth * nBandsPerStrile; ++i)
     574             :             {
     575             :                 if (std::isnan(
     576             :                         pBuffer[j * m_nBlockXSize * nBandsPerStrile + i]))
     577             :                 {
     578             :                     bHasWarned = true;
     579             :                     CPLError(CE_Warning, CPLE_AppDefined,
     580             :                              "libtiff < 4.6.1 does not handle properly NaN "
     581             :                              "values for multi-band PlanarConfig=Contig "
     582             :                              "configuration. As a workaround, you can set the "
     583             :                              "INTERLEAVE=BAND creation option.");
     584             :                     break;
     585             :                 }
     586             :             }
     587             :         }
     588             : #endif
     589           0 :         for (int i = nActualBlockWidth * nBandsPerStrile;
     590           0 :              i < m_nBlockXSize * nBandsPerStrile; ++i)
     591             :         {
     592           0 :             pBuffer[j * m_nBlockXSize * nBandsPerStrile + i] = fPaddingValue;
     593             :         }
     594             :     }
     595           0 :     for (int j = nActualBlockHeight; j < nStrileHeight; ++j)
     596             :     {
     597           0 :         for (int i = 0; i < m_nBlockXSize * nBandsPerStrile; ++i)
     598             :         {
     599           0 :             pBuffer[j * m_nBlockXSize * nBandsPerStrile + i] = fPaddingValue;
     600             :         }
     601             :     }
     602           0 : }
     603             : 
     604             : /************************************************************************/
     605             : /*                          WriteEncodedTile()                          */
     606             : /************************************************************************/
     607             : 
     608       50512 : bool GTiffDataset::WriteEncodedTile(uint32_t tile, GByte *pabyData,
     609             :                                     int bPreserveDataBuffer)
     610             : {
     611       50512 :     const int iColumn = (tile % m_nBlocksPerBand) % m_nBlocksPerRow;
     612       50512 :     const int iRow = (tile % m_nBlocksPerBand) / m_nBlocksPerRow;
     613             : 
     614      101024 :     const int nActualBlockWidth = (iColumn == m_nBlocksPerRow - 1)
     615       50512 :                                       ? nRasterXSize - iColumn * m_nBlockXSize
     616             :                                       : m_nBlockXSize;
     617      101024 :     const int nActualBlockHeight = (iRow == m_nBlocksPerColumn - 1)
     618       50512 :                                        ? nRasterYSize - iRow * m_nBlockYSize
     619             :                                        : m_nBlockYSize;
     620             : 
     621             :     /* -------------------------------------------------------------------- */
     622             :     /*      Don't write empty blocks in some cases.                         */
     623             :     /* -------------------------------------------------------------------- */
     624       50512 :     if (!m_bWriteEmptyTiles && IsFirstPixelEqualToNoData(pabyData))
     625             :     {
     626        1975 :         if (!IsBlockAvailable(tile, nullptr, nullptr, nullptr))
     627             :         {
     628        1975 :             const int nComponents =
     629        1975 :                 m_nPlanarConfig == PLANARCONFIG_CONTIG ? nBands : 1;
     630             : 
     631        1975 :             if (HasOnlyNoData(pabyData, nActualBlockWidth, nActualBlockHeight,
     632             :                               m_nBlockXSize, nComponents))
     633             :             {
     634        1200 :                 return true;
     635             :             }
     636             :         }
     637             :     }
     638             : 
     639             :     // Is this a partial right edge or bottom edge tile?
     640       95606 :     const bool bPartialTile = (nActualBlockWidth < m_nBlockXSize) ||
     641       46294 :                               (nActualBlockHeight < m_nBlockYSize);
     642             : 
     643             :     const bool bIsLercFloatingPoint =
     644       49378 :         m_nCompression == COMPRESSION_LERC &&
     645          66 :         (GetRasterBand(1)->GetRasterDataType() == GDT_Float32 ||
     646          64 :          GetRasterBand(1)->GetRasterDataType() == GDT_Float64);
     647             : 
     648             :     // Do we need to spread edge values right or down for a partial
     649             :     // JPEG encoded tile?  We do this to avoid edge artifacts.
     650             :     // We also need to be careful with LERC and NaN values
     651       49312 :     const bool bNeedTempBuffer =
     652       54025 :         bPartialTile &&
     653        4713 :         (m_nCompression == COMPRESSION_JPEG || bIsLercFloatingPoint);
     654             : 
     655             :     // If we need to fill out the tile, or if we want to prevent
     656             :     // TIFFWriteEncodedTile from altering the buffer as part of
     657             :     // byte swapping the data on write then we will need a temporary
     658             :     // working buffer.  If not, we can just do a direct write.
     659       49312 :     const GPtrDiff_t cc = static_cast<GPtrDiff_t>(TIFFTileSize(m_hTIFF));
     660             : 
     661       63621 :     if (bPreserveDataBuffer &&
     662       14309 :         (TIFFIsByteSwapped(m_hTIFF) || bNeedTempBuffer || m_panMaskOffsetLsb))
     663             :     {
     664         158 :         if (m_pabyTempWriteBuffer == nullptr)
     665             :         {
     666          35 :             m_pabyTempWriteBuffer = CPLMalloc(cc);
     667             :         }
     668         158 :         memcpy(m_pabyTempWriteBuffer, pabyData, cc);
     669             : 
     670         158 :         pabyData = static_cast<GByte *>(m_pabyTempWriteBuffer);
     671             :     }
     672             : 
     673             :     // Perform tile fill if needed.
     674             :     // TODO: we should also handle the case of nBitsPerSample == 12
     675             :     // but this is more involved.
     676       49312 :     if (bPartialTile && m_nCompression == COMPRESSION_JPEG &&
     677         134 :         m_nBitsPerSample == 8)
     678             :     {
     679         132 :         const int nComponents =
     680         132 :             m_nPlanarConfig == PLANARCONFIG_CONTIG ? nBands : 1;
     681             : 
     682         132 :         CPLDebug("GTiff", "Filling out jpeg edge tile on write.");
     683             : 
     684         132 :         const int nRightPixelsToFill =
     685         132 :             iColumn == m_nBlocksPerRow - 1
     686         132 :                 ? m_nBlockXSize * (iColumn + 1) - nRasterXSize
     687             :                 : 0;
     688         132 :         const int nBottomPixelsToFill =
     689         132 :             iRow == m_nBlocksPerColumn - 1
     690         132 :                 ? m_nBlockYSize * (iRow + 1) - nRasterYSize
     691             :                 : 0;
     692             : 
     693             :         // Fill out to the right.
     694         132 :         const int iSrcX = m_nBlockXSize - nRightPixelsToFill - 1;
     695             : 
     696       12461 :         for (int iX = iSrcX + 1; iX < m_nBlockXSize; ++iX)
     697             :         {
     698     3955880 :             for (int iY = 0; iY < m_nBlockYSize; ++iY)
     699             :             {
     700     3943550 :                 memcpy(pabyData +
     701     3943550 :                            (static_cast<GPtrDiff_t>(m_nBlockXSize) * iY + iX) *
     702     3943550 :                                nComponents,
     703     3943550 :                        pabyData + (static_cast<GPtrDiff_t>(m_nBlockXSize) * iY +
     704     3943550 :                                    iSrcX) *
     705     3943550 :                                       nComponents,
     706             :                        nComponents);
     707             :             }
     708             :         }
     709             : 
     710             :         // Now fill out the bottom.
     711         132 :         const int iSrcY = m_nBlockYSize - nBottomPixelsToFill - 1;
     712       17682 :         for (int iY = iSrcY + 1; iY < m_nBlockYSize; ++iY)
     713             :         {
     714       17550 :             memcpy(pabyData + static_cast<GPtrDiff_t>(m_nBlockXSize) *
     715       17550 :                                   nComponents * iY,
     716       17550 :                    pabyData + static_cast<GPtrDiff_t>(m_nBlockXSize) *
     717       17550 :                                   nComponents * iSrcY,
     718       17550 :                    static_cast<GPtrDiff_t>(m_nBlockXSize) * nComponents);
     719             :         }
     720             :     }
     721             : 
     722       49312 :     if (bIsLercFloatingPoint &&
     723             :         (bPartialTile
     724             : #if !defined(LIBTIFF_MULTIBAND_LERC_NAN_OK)
     725             :          /* libtiff < 4.6.1 doesn't generate a LERC mask for multi-band contig configuration */
     726             :          || (m_nPlanarConfig == PLANARCONFIG_CONTIG && nBands > 1)
     727             : #endif
     728             :              ))
     729             :     {
     730           0 :         if (GetRasterBand(1)->GetRasterDataType() == GDT_Float32)
     731           0 :             WriteDealWithLercAndNan(reinterpret_cast<float *>(pabyData),
     732             :                                     nActualBlockWidth, nActualBlockHeight,
     733             :                                     m_nBlockYSize);
     734             :         else
     735           0 :             WriteDealWithLercAndNan(reinterpret_cast<double *>(pabyData),
     736             :                                     nActualBlockWidth, nActualBlockHeight,
     737             :                                     m_nBlockYSize);
     738             :     }
     739             : 
     740       49312 :     if (m_panMaskOffsetLsb)
     741             :     {
     742           0 :         const int iBand = m_nPlanarConfig == PLANARCONFIG_SEPARATE
     743           0 :                               ? static_cast<int>(tile) / m_nBlocksPerBand
     744             :                               : -1;
     745           0 :         DiscardLsb(pabyData, cc, iBand);
     746             :     }
     747             : 
     748       49312 :     if (m_bStreamingOut)
     749             :     {
     750          17 :         if (tile != static_cast<uint32_t>(m_nLastWrittenBlockId + 1))
     751             :         {
     752           1 :             ReportError(CE_Failure, CPLE_NotSupported,
     753             :                         "Attempt to write block %d whereas %d was expected",
     754           1 :                         tile, m_nLastWrittenBlockId + 1);
     755           1 :             return false;
     756             :         }
     757          16 :         if (static_cast<GPtrDiff_t>(VSIFWriteL(pabyData, 1, cc, m_fpToWrite)) !=
     758             :             cc)
     759             :         {
     760           0 :             ReportError(CE_Failure, CPLE_FileIO,
     761             :                         "Could not write " CPL_FRMT_GUIB " bytes",
     762             :                         static_cast<GUIntBig>(cc));
     763           0 :             return false;
     764             :         }
     765          16 :         m_nLastWrittenBlockId = tile;
     766          16 :         return true;
     767             :     }
     768             : 
     769             :     /* -------------------------------------------------------------------- */
     770             :     /*      Should we do compression in a worker thread ?                   */
     771             :     /* -------------------------------------------------------------------- */
     772       49295 :     if (SubmitCompressionJob(tile, pabyData, cc, m_nBlockYSize))
     773       19943 :         return true;
     774             : 
     775       29352 :     return TIFFWriteEncodedTile(m_hTIFF, tile, pabyData, cc) == cc;
     776             : }
     777             : 
     778             : /************************************************************************/
     779             : /*                         WriteEncodedStrip()                          */
     780             : /************************************************************************/
     781             : 
     782      178385 : bool GTiffDataset::WriteEncodedStrip(uint32_t strip, GByte *pabyData,
     783             :                                      int bPreserveDataBuffer)
     784             : {
     785      178385 :     GPtrDiff_t cc = static_cast<GPtrDiff_t>(TIFFStripSize(m_hTIFF));
     786      178385 :     const auto ccFull = cc;
     787             : 
     788             :     /* -------------------------------------------------------------------- */
     789             :     /*      If this is the last strip in the image, and is partial, then    */
     790             :     /*      we need to trim the number of scanlines written to the          */
     791             :     /*      amount of valid data we have. (#2748)                           */
     792             :     /* -------------------------------------------------------------------- */
     793      178385 :     const int nStripWithinBand = strip % m_nBlocksPerBand;
     794      178385 :     int nStripHeight = m_nRowsPerStrip;
     795             : 
     796      178385 :     if (nStripWithinBand * nStripHeight > GetRasterYSize() - nStripHeight)
     797             :     {
     798         387 :         nStripHeight = GetRasterYSize() - nStripWithinBand * m_nRowsPerStrip;
     799         387 :         cc = (cc / m_nRowsPerStrip) * nStripHeight;
     800         774 :         CPLDebug("GTiff",
     801             :                  "Adjusted bytes to write from " CPL_FRMT_GUIB
     802             :                  " to " CPL_FRMT_GUIB ".",
     803         387 :                  static_cast<GUIntBig>(TIFFStripSize(m_hTIFF)),
     804             :                  static_cast<GUIntBig>(cc));
     805             :     }
     806             : 
     807             :     /* -------------------------------------------------------------------- */
     808             :     /*      Don't write empty blocks in some cases.                         */
     809             :     /* -------------------------------------------------------------------- */
     810      178385 :     if (!m_bWriteEmptyTiles && IsFirstPixelEqualToNoData(pabyData))
     811             :     {
     812       41113 :         if (!IsBlockAvailable(strip, nullptr, nullptr, nullptr))
     813             :         {
     814       40939 :             const int nComponents =
     815       40939 :                 m_nPlanarConfig == PLANARCONFIG_CONTIG ? nBands : 1;
     816             : 
     817       40939 :             if (HasOnlyNoData(pabyData, m_nBlockXSize, nStripHeight,
     818             :                               m_nBlockXSize, nComponents))
     819             :             {
     820       28307 :                 return true;
     821             :             }
     822             :         }
     823             :     }
     824             : 
     825             :     /* -------------------------------------------------------------------- */
     826             :     /*      TIFFWriteEncodedStrip can alter the passed buffer if            */
     827             :     /*      byte-swapping is necessary so we use a temporary buffer         */
     828             :     /*      before calling it.                                              */
     829             :     /* -------------------------------------------------------------------- */
     830      239664 :     if (bPreserveDataBuffer &&
     831       89586 :         (TIFFIsByteSwapped(m_hTIFF) || m_panMaskOffsetLsb))
     832             :     {
     833         294 :         if (m_pabyTempWriteBuffer == nullptr)
     834             :         {
     835         126 :             m_pabyTempWriteBuffer = CPLMalloc(ccFull);
     836             :         }
     837         294 :         memcpy(m_pabyTempWriteBuffer, pabyData, cc);
     838         294 :         pabyData = static_cast<GByte *>(m_pabyTempWriteBuffer);
     839             :     }
     840             : 
     841             : #if !defined(LIBTIFF_MULTIBAND_LERC_NAN_OK)
     842             :     const bool bIsLercFloatingPoint =
     843             :         m_nCompression == COMPRESSION_LERC &&
     844             :         (GetRasterBand(1)->GetRasterDataType() == GDT_Float32 ||
     845             :          GetRasterBand(1)->GetRasterDataType() == GDT_Float64);
     846             :     if (bIsLercFloatingPoint &&
     847             :         /* libtiff < 4.6.1 doesn't generate a LERC mask for multi-band contig configuration */
     848             :         m_nPlanarConfig == PLANARCONFIG_CONTIG && nBands > 1)
     849             :     {
     850             :         if (GetRasterBand(1)->GetRasterDataType() == GDT_Float32)
     851             :             WriteDealWithLercAndNan(reinterpret_cast<float *>(pabyData),
     852             :                                     m_nBlockXSize, nStripHeight, nStripHeight);
     853             :         else
     854             :             WriteDealWithLercAndNan(reinterpret_cast<double *>(pabyData),
     855             :                                     m_nBlockXSize, nStripHeight, nStripHeight);
     856             :     }
     857             : #endif
     858             : 
     859      150078 :     if (m_panMaskOffsetLsb)
     860             :     {
     861         366 :         int iBand = m_nPlanarConfig == PLANARCONFIG_SEPARATE
     862         183 :                         ? static_cast<int>(strip) / m_nBlocksPerBand
     863             :                         : -1;
     864         183 :         DiscardLsb(pabyData, cc, iBand);
     865             :     }
     866             : 
     867      150078 :     if (m_bStreamingOut)
     868             :     {
     869        1408 :         if (strip != static_cast<uint32_t>(m_nLastWrittenBlockId + 1))
     870             :         {
     871           1 :             ReportError(CE_Failure, CPLE_NotSupported,
     872             :                         "Attempt to write block %d whereas %d was expected",
     873           1 :                         strip, m_nLastWrittenBlockId + 1);
     874           1 :             return false;
     875             :         }
     876        1407 :         if (static_cast<GPtrDiff_t>(VSIFWriteL(pabyData, 1, cc, m_fpToWrite)) !=
     877             :             cc)
     878             :         {
     879           0 :             ReportError(CE_Failure, CPLE_FileIO,
     880             :                         "Could not write " CPL_FRMT_GUIB " bytes",
     881             :                         static_cast<GUIntBig>(cc));
     882           0 :             return false;
     883             :         }
     884        1407 :         m_nLastWrittenBlockId = strip;
     885        1407 :         return true;
     886             :     }
     887             : 
     888             :     /* -------------------------------------------------------------------- */
     889             :     /*      Should we do compression in a worker thread ?                   */
     890             :     /* -------------------------------------------------------------------- */
     891      148670 :     if (SubmitCompressionJob(strip, pabyData, cc, nStripHeight))
     892        6727 :         return true;
     893             : 
     894      141943 :     return TIFFWriteEncodedStrip(m_hTIFF, strip, pabyData, cc) == cc;
     895             : }
     896             : 
     897             : /************************************************************************/
     898             : /*                       InitCompressionThreads()                       */
     899             : /************************************************************************/
     900             : 
     901       32182 : void GTiffDataset::InitCompressionThreads(bool bUpdateMode,
     902             :                                           CSLConstList papszOptions)
     903             : {
     904             :     // Raster == tile, then no need for threads
     905       32182 :     if (m_nBlockXSize == nRasterXSize && m_nBlockYSize == nRasterYSize)
     906       23515 :         return;
     907             : 
     908        8667 :     const char *pszNumThreads = "";
     909        8667 :     bool bOK = false;
     910        8667 :     const int nThreads = GDALGetNumThreads(
     911             :         papszOptions, "NUM_THREADS", GDAL_DEFAULT_MAX_THREAD_COUNT,
     912             :         /* bDefaultToAllCPUs=*/false, &pszNumThreads, &bOK);
     913        8667 :     if (nThreads > 1)
     914             :     {
     915         106 :         if ((bUpdateMode && m_nCompression != COMPRESSION_NONE) ||
     916          24 :             (nBands >= 1 && IsMultiThreadedReadCompatible()))
     917             :         {
     918          77 :             CPLDebug("GTiff",
     919             :                      "Using up to %d threads for compression/decompression",
     920             :                      nThreads);
     921             : 
     922          77 :             m_poThreadPool = GDALGetGlobalThreadPool(nThreads);
     923          77 :             if (bUpdateMode && m_poThreadPool)
     924          58 :                 m_poCompressQueue = m_poThreadPool->CreateJobQueue();
     925             : 
     926          77 :             if (m_poCompressQueue != nullptr)
     927             :             {
     928             :                 // Add a margin of an extra job w.r.t thread number
     929             :                 // so as to optimize compression time (enables the main
     930             :                 // thread to do boring I/O while all CPUs are working).
     931          58 :                 m_asCompressionJobs.resize(nThreads + 1);
     932          58 :                 memset(&m_asCompressionJobs[0], 0,
     933          58 :                        m_asCompressionJobs.size() *
     934             :                            sizeof(GTiffCompressionJob));
     935          58 :                 for (int i = 0;
     936         280 :                      i < static_cast<int>(m_asCompressionJobs.size()); ++i)
     937             :                 {
     938         444 :                     m_asCompressionJobs[i].pszTmpFilename =
     939         222 :                         CPLStrdup(VSIMemGenerateHiddenFilename(
     940             :                             CPLSPrintf("thread_job_%d.tif", i)));
     941         222 :                     m_asCompressionJobs[i].nStripOrTile = -1;
     942             :                 }
     943             : 
     944             :                 // This is kind of a hack, but basically using
     945             :                 // TIFFWriteRawStrip/Tile and then TIFFReadEncodedStrip/Tile
     946             :                 // does not work on a newly created file, because
     947             :                 // TIFF_MYBUFFER is not set in tif_flags
     948             :                 // (if using TIFFWriteEncodedStrip/Tile first,
     949             :                 // TIFFWriteBufferSetup() is automatically called).
     950             :                 // This should likely rather fixed in libtiff itself.
     951          58 :                 CPL_IGNORE_RET_VAL(TIFFWriteBufferSetup(m_hTIFF, nullptr, -1));
     952             :             }
     953             :         }
     954             :     }
     955        8585 :     else if (!bOK)
     956             :     {
     957           3 :         ReportError(CE_Warning, CPLE_AppDefined,
     958             :                     "Invalid value for NUM_THREADS: %s", pszNumThreads);
     959             :     }
     960             : }
     961             : 
     962             : /************************************************************************/
     963             : /*                       ThreadCompressionFunc()                        */
     964             : /************************************************************************/
     965             : 
     966       26682 : void GTiffDataset::ThreadCompressionFunc(void *pData)
     967             : {
     968       26682 :     GTiffCompressionJob *psJob = static_cast<GTiffCompressionJob *>(pData);
     969       26682 :     GTiffDataset *poDS = psJob->poDS;
     970             : 
     971       26682 :     VSILFILE *fpTmp = VSIFOpenL(psJob->pszTmpFilename, "wb+");
     972       26682 :     TIFF *hTIFFTmp = VSI_TIFFOpen(
     973       53364 :         psJob->pszTmpFilename, psJob->bTIFFIsBigEndian ? "wb+" : "wl+", fpTmp);
     974       26682 :     CPLAssert(hTIFFTmp != nullptr);
     975       26682 :     TIFFSetField(hTIFFTmp, TIFFTAG_IMAGEWIDTH, poDS->m_nBlockXSize);
     976       26682 :     TIFFSetField(hTIFFTmp, TIFFTAG_IMAGELENGTH, psJob->nHeight);
     977       26682 :     TIFFSetField(hTIFFTmp, TIFFTAG_BITSPERSAMPLE, poDS->m_nBitsPerSample);
     978       26682 :     TIFFSetField(hTIFFTmp, TIFFTAG_COMPRESSION, poDS->m_nCompression);
     979       26682 :     TIFFSetField(hTIFFTmp, TIFFTAG_PHOTOMETRIC, poDS->m_nPhotometric);
     980       26682 :     TIFFSetField(hTIFFTmp, TIFFTAG_SAMPLEFORMAT, poDS->m_nSampleFormat);
     981       26682 :     TIFFSetField(hTIFFTmp, TIFFTAG_SAMPLESPERPIXEL, poDS->m_nSamplesPerPixel);
     982       26682 :     TIFFSetField(hTIFFTmp, TIFFTAG_ROWSPERSTRIP, poDS->m_nBlockYSize);
     983       26682 :     TIFFSetField(hTIFFTmp, TIFFTAG_PLANARCONFIG, poDS->m_nPlanarConfig);
     984       26682 :     if (psJob->nPredictor != PREDICTOR_NONE)
     985         263 :         TIFFSetField(hTIFFTmp, TIFFTAG_PREDICTOR, psJob->nPredictor);
     986       26682 :     if (poDS->m_nCompression == COMPRESSION_LERC)
     987             :     {
     988          24 :         TIFFSetField(hTIFFTmp, TIFFTAG_LERC_PARAMETERS, 2,
     989          24 :                      poDS->m_anLercAddCompressionAndVersion);
     990             :     }
     991       26682 :     if (psJob->nExtraSampleCount)
     992             :     {
     993         352 :         TIFFSetField(hTIFFTmp, TIFFTAG_EXTRASAMPLES, psJob->nExtraSampleCount,
     994             :                      psJob->pExtraSamples);
     995             :     }
     996             : 
     997       26682 :     poDS->RestoreVolatileParameters(hTIFFTmp);
     998             : 
     999       53364 :     bool bOK = TIFFWriteEncodedStrip(hTIFFTmp, 0, psJob->pabyBuffer,
    1000       26682 :                                      psJob->nBufferSize) == psJob->nBufferSize;
    1001             : 
    1002       26682 :     toff_t nOffset = 0;
    1003       26682 :     if (bOK)
    1004             :     {
    1005       26682 :         toff_t *panOffsets = nullptr;
    1006       26682 :         toff_t *panByteCounts = nullptr;
    1007       26682 :         TIFFGetField(hTIFFTmp, TIFFTAG_STRIPOFFSETS, &panOffsets);
    1008       26682 :         TIFFGetField(hTIFFTmp, TIFFTAG_STRIPBYTECOUNTS, &panByteCounts);
    1009             : 
    1010       26682 :         nOffset = panOffsets[0];
    1011       26682 :         psJob->nCompressedBufferSize =
    1012       26682 :             static_cast<GPtrDiff_t>(panByteCounts[0]);
    1013             :     }
    1014             :     else
    1015             :     {
    1016           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1017             :                  "Error when compressing strip/tile %d", psJob->nStripOrTile);
    1018             :     }
    1019             : 
    1020       26682 :     XTIFFClose(hTIFFTmp);
    1021       26682 :     if (VSIFCloseL(fpTmp) != 0)
    1022             :     {
    1023           0 :         if (bOK)
    1024             :         {
    1025           0 :             bOK = false;
    1026           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    1027             :                      "Error when compressing strip/tile %d",
    1028             :                      psJob->nStripOrTile);
    1029             :         }
    1030             :     }
    1031             : 
    1032       26682 :     if (bOK)
    1033             :     {
    1034       26682 :         vsi_l_offset nFileSize = 0;
    1035             :         GByte *pabyCompressedBuffer =
    1036       26682 :             VSIGetMemFileBuffer(psJob->pszTmpFilename, &nFileSize, FALSE);
    1037       26682 :         CPLAssert(static_cast<vsi_l_offset>(
    1038             :                       nOffset + psJob->nCompressedBufferSize) <= nFileSize);
    1039       26682 :         psJob->pabyCompressedBuffer = pabyCompressedBuffer + nOffset;
    1040             :     }
    1041             :     else
    1042             :     {
    1043           0 :         psJob->pabyCompressedBuffer = nullptr;
    1044           0 :         psJob->nCompressedBufferSize = 0;
    1045             :     }
    1046             : 
    1047       26682 :     auto poMainDS = poDS->m_poBaseDS ? poDS->m_poBaseDS : poDS;
    1048       26682 :     if (poMainDS->m_poCompressQueue)
    1049             :     {
    1050        1576 :         std::lock_guard oLock(poMainDS->m_oCompressThreadPoolMutex);
    1051        1576 :         psJob->bReady = true;
    1052             :     }
    1053       26682 : }
    1054             : 
    1055             : /************************************************************************/
    1056             : /*                        WriteRawStripOrTile()                         */
    1057             : /************************************************************************/
    1058             : 
    1059       34085 : void GTiffDataset::WriteRawStripOrTile(int nStripOrTile,
    1060             :                                        GByte *pabyCompressedBuffer,
    1061             :                                        GPtrDiff_t nCompressedBufferSize)
    1062             : {
    1063             : #ifdef DEBUG_VERBOSE
    1064             :     CPLDebug("GTIFF", "Writing raw strip/tile %d, size " CPL_FRMT_GUIB,
    1065             :              nStripOrTile, static_cast<GUIntBig>(nCompressedBufferSize));
    1066             : #endif
    1067       34085 :     toff_t *panOffsets = nullptr;
    1068       34085 :     toff_t *panByteCounts = nullptr;
    1069       34085 :     bool bWriteAtEnd = true;
    1070       34085 :     bool bWriteLeader = m_bLeaderSizeAsUInt4;
    1071       34085 :     bool bWriteTrailer = m_bTrailerRepeatedLast4BytesRepeated;
    1072       34085 :     if (TIFFGetField(m_hTIFF,
    1073       34085 :                      TIFFIsTiled(m_hTIFF) ? TIFFTAG_TILEOFFSETS
    1074             :                                           : TIFFTAG_STRIPOFFSETS,
    1075       34085 :                      &panOffsets) &&
    1076       34085 :         panOffsets != nullptr && panOffsets[nStripOrTile] != 0)
    1077             :     {
    1078             :         // Forces TIFFAppendStrip() to consider if the location of the
    1079             :         // tile/strip can be reused or if the strile should be written at end of
    1080             :         // file.
    1081         360 :         TIFFSetWriteOffset(m_hTIFF, 0);
    1082             : 
    1083         360 :         if (m_bBlockOrderRowMajor)
    1084             :         {
    1085         264 :             if (TIFFGetField(m_hTIFF,
    1086         264 :                              TIFFIsTiled(m_hTIFF) ? TIFFTAG_TILEBYTECOUNTS
    1087             :                                                   : TIFFTAG_STRIPBYTECOUNTS,
    1088         528 :                              &panByteCounts) &&
    1089         264 :                 panByteCounts != nullptr)
    1090             :             {
    1091         264 :                 if (static_cast<GUIntBig>(nCompressedBufferSize) >
    1092         264 :                     panByteCounts[nStripOrTile])
    1093             :                 {
    1094           8 :                     GTiffDataset *poRootDS = m_poBaseDS ? m_poBaseDS : this;
    1095           8 :                     if (!poRootDS->m_bKnownIncompatibleEdition &&
    1096           8 :                         !poRootDS->m_bWriteKnownIncompatibleEdition)
    1097             :                     {
    1098           8 :                         ReportError(
    1099             :                             CE_Warning, CPLE_AppDefined,
    1100             :                             "A strile cannot be rewritten in place, which "
    1101             :                             "invalidates the BLOCK_ORDER optimization.");
    1102           8 :                         poRootDS->m_bKnownIncompatibleEdition = true;
    1103           8 :                         poRootDS->m_bWriteKnownIncompatibleEdition = true;
    1104             :                     }
    1105             :                 }
    1106             :                 // For mask interleaving, if the size is not exactly the same,
    1107             :                 // completely give up (we could potentially move the mask in
    1108             :                 // case the imagery is smaller)
    1109         256 :                 else if (m_poMaskDS && m_bMaskInterleavedWithImagery &&
    1110           0 :                          static_cast<GUIntBig>(nCompressedBufferSize) !=
    1111           0 :                              panByteCounts[nStripOrTile])
    1112             :                 {
    1113           0 :                     GTiffDataset *poRootDS = m_poBaseDS ? m_poBaseDS : this;
    1114           0 :                     if (!poRootDS->m_bKnownIncompatibleEdition &&
    1115           0 :                         !poRootDS->m_bWriteKnownIncompatibleEdition)
    1116             :                     {
    1117           0 :                         ReportError(
    1118             :                             CE_Warning, CPLE_AppDefined,
    1119             :                             "A strile cannot be rewritten in place, which "
    1120             :                             "invalidates the MASK_INTERLEAVED_WITH_IMAGERY "
    1121             :                             "optimization.");
    1122           0 :                         poRootDS->m_bKnownIncompatibleEdition = true;
    1123           0 :                         poRootDS->m_bWriteKnownIncompatibleEdition = true;
    1124             :                     }
    1125           0 :                     bWriteLeader = false;
    1126           0 :                     bWriteTrailer = false;
    1127           0 :                     if (m_bLeaderSizeAsUInt4)
    1128             :                     {
    1129             :                         // If there was a valid leader, invalidat it
    1130           0 :                         VSI_TIFFSeek(m_hTIFF, panOffsets[nStripOrTile] - 4,
    1131             :                                      SEEK_SET);
    1132             :                         uint32_t nOldSize;
    1133           0 :                         VSIFReadL(&nOldSize, 1, 4,
    1134             :                                   VSI_TIFFGetVSILFile(TIFFClientdata(m_hTIFF)));
    1135           0 :                         CPL_LSBPTR32(&nOldSize);
    1136           0 :                         if (nOldSize == panByteCounts[nStripOrTile])
    1137             :                         {
    1138           0 :                             uint32_t nInvalidatedSize = 0;
    1139           0 :                             VSI_TIFFSeek(m_hTIFF, panOffsets[nStripOrTile] - 4,
    1140             :                                          SEEK_SET);
    1141           0 :                             VSI_TIFFWrite(m_hTIFF, &nInvalidatedSize,
    1142             :                                           sizeof(nInvalidatedSize));
    1143             :                         }
    1144             :                     }
    1145             :                 }
    1146             :                 else
    1147             :                 {
    1148         256 :                     bWriteAtEnd = false;
    1149             :                 }
    1150             :             }
    1151             :         }
    1152             :     }
    1153       34085 :     if (bWriteLeader &&
    1154       25111 :         static_cast<GUIntBig>(nCompressedBufferSize) <= 0xFFFFFFFFU)
    1155             :     {
    1156             :         // cppcheck-suppress knownConditionTrueFalse
    1157       25111 :         if (bWriteAtEnd)
    1158             :         {
    1159       24855 :             VSI_TIFFSeek(m_hTIFF, 0, SEEK_END);
    1160             :         }
    1161             :         else
    1162             :         {
    1163             :             // If we rewrite an existing strile in place with an existing
    1164             :             // leader, check that the leader is valid, before rewriting it. And
    1165             :             // if it is not valid, then do not write the trailer, as we could
    1166             :             // corrupt other data.
    1167         256 :             VSI_TIFFSeek(m_hTIFF, panOffsets[nStripOrTile] - 4, SEEK_SET);
    1168             :             uint32_t nOldSize;
    1169         256 :             VSIFReadL(&nOldSize, 1, 4,
    1170             :                       VSI_TIFFGetVSILFile(TIFFClientdata(m_hTIFF)));
    1171         256 :             CPL_LSBPTR32(&nOldSize);
    1172         256 :             bWriteLeader =
    1173         256 :                 panByteCounts && nOldSize == panByteCounts[nStripOrTile];
    1174         256 :             bWriteTrailer = bWriteLeader;
    1175         256 :             VSI_TIFFSeek(m_hTIFF, panOffsets[nStripOrTile] - 4, SEEK_SET);
    1176             :         }
    1177             :         // cppcheck-suppress knownConditionTrueFalse
    1178       25111 :         if (bWriteLeader)
    1179             :         {
    1180       25111 :             uint32_t nSize = static_cast<uint32_t>(nCompressedBufferSize);
    1181       25111 :             CPL_LSBPTR32(&nSize);
    1182       25111 :             if (!VSI_TIFFWrite(m_hTIFF, &nSize, sizeof(nSize)))
    1183           0 :                 m_bWriteError = true;
    1184             :         }
    1185             :     }
    1186             :     tmsize_t written;
    1187       34085 :     if (TIFFIsTiled(m_hTIFF))
    1188       26410 :         written = TIFFWriteRawTile(m_hTIFF, nStripOrTile, pabyCompressedBuffer,
    1189             :                                    nCompressedBufferSize);
    1190             :     else
    1191        7675 :         written = TIFFWriteRawStrip(m_hTIFF, nStripOrTile, pabyCompressedBuffer,
    1192             :                                     nCompressedBufferSize);
    1193       34085 :     if (written != nCompressedBufferSize)
    1194          12 :         m_bWriteError = true;
    1195       34085 :     if (bWriteTrailer &&
    1196       25111 :         static_cast<GUIntBig>(nCompressedBufferSize) <= 0xFFFFFFFFU)
    1197             :     {
    1198       25111 :         GByte abyLastBytes[4] = {};
    1199       25111 :         if (nCompressedBufferSize >= 4)
    1200       25111 :             memcpy(abyLastBytes,
    1201       25111 :                    pabyCompressedBuffer + nCompressedBufferSize - 4, 4);
    1202             :         else
    1203           0 :             memcpy(abyLastBytes, pabyCompressedBuffer, nCompressedBufferSize);
    1204       25111 :         if (!VSI_TIFFWrite(m_hTIFF, abyLastBytes, 4))
    1205           0 :             m_bWriteError = true;
    1206             :     }
    1207       34085 : }
    1208             : 
    1209             : /************************************************************************/
    1210             : /*                      WaitCompletionForJobIdx()                       */
    1211             : /************************************************************************/
    1212             : 
    1213        1576 : void GTiffDataset::WaitCompletionForJobIdx(int i)
    1214             : {
    1215        1576 :     auto poMainDS = m_poBaseDS ? m_poBaseDS : this;
    1216        1576 :     auto poQueue = poMainDS->m_poCompressQueue.get();
    1217        1576 :     auto &oQueue = poMainDS->m_asQueueJobIdx;
    1218        1576 :     auto &asJobs = poMainDS->m_asCompressionJobs;
    1219        1576 :     auto &mutex = poMainDS->m_oCompressThreadPoolMutex;
    1220             : 
    1221        1576 :     CPLAssert(i >= 0 && static_cast<size_t>(i) < asJobs.size());
    1222        1576 :     CPLAssert(asJobs[i].nStripOrTile >= 0);
    1223        1576 :     CPLAssert(!oQueue.empty());
    1224             : 
    1225        1576 :     bool bHasWarned = false;
    1226             :     while (true)
    1227             :     {
    1228             :         bool bReady;
    1229             :         {
    1230        2240 :             std::lock_guard oLock(mutex);
    1231        2240 :             bReady = asJobs[i].bReady;
    1232             :         }
    1233        2240 :         if (!bReady)
    1234             :         {
    1235         664 :             if (!bHasWarned)
    1236             :             {
    1237         431 :                 CPLDebug("GTIFF",
    1238             :                          "Waiting for worker job to finish handling block %d",
    1239         431 :                          asJobs[i].nStripOrTile);
    1240         431 :                 bHasWarned = true;
    1241             :             }
    1242         664 :             poQueue->GetPool()->WaitEvent();
    1243             :         }
    1244             :         else
    1245             :         {
    1246        1576 :             break;
    1247             :         }
    1248         664 :     }
    1249             : 
    1250        1576 :     if (asJobs[i].nCompressedBufferSize)
    1251             :     {
    1252        3152 :         asJobs[i].poDS->WriteRawStripOrTile(asJobs[i].nStripOrTile,
    1253        1576 :                                             asJobs[i].pabyCompressedBuffer,
    1254        1576 :                                             asJobs[i].nCompressedBufferSize);
    1255             :     }
    1256        1576 :     asJobs[i].pabyCompressedBuffer = nullptr;
    1257        1576 :     asJobs[i].nBufferSize = 0;
    1258             :     {
    1259             :         // Likely useless, but makes Coverity happy
    1260        1576 :         std::lock_guard oLock(mutex);
    1261        1576 :         asJobs[i].bReady = false;
    1262             :     }
    1263        1576 :     asJobs[i].nStripOrTile = -1;
    1264        1576 :     oQueue.pop();
    1265        1576 : }
    1266             : 
    1267             : /************************************************************************/
    1268             : /*                       WaitCompletionForBlock()                       */
    1269             : /************************************************************************/
    1270             : 
    1271     2320740 : void GTiffDataset::WaitCompletionForBlock(int nBlockId)
    1272             : {
    1273     2320740 :     auto poQueue = m_poBaseDS ? m_poBaseDS->m_poCompressQueue.get()
    1274     2301500 :                               : m_poCompressQueue.get();
    1275             :     // cppcheck-suppress constVariableReference
    1276     2320740 :     auto &oQueue = m_poBaseDS ? m_poBaseDS->m_asQueueJobIdx : m_asQueueJobIdx;
    1277             :     // cppcheck-suppress constVariableReference
    1278     2301500 :     auto &asJobs =
    1279     2320740 :         m_poBaseDS ? m_poBaseDS->m_asCompressionJobs : m_asCompressionJobs;
    1280             : 
    1281     2320740 :     if (poQueue != nullptr && !oQueue.empty())
    1282             :     {
    1283        1066 :         for (int i = 0; i < static_cast<int>(asJobs.size()); ++i)
    1284             :         {
    1285         888 :             if (asJobs[i].poDS == this && asJobs[i].nStripOrTile == nBlockId)
    1286             :             {
    1287         128 :                 while (!oQueue.empty() &&
    1288          64 :                        !(asJobs[oQueue.front()].poDS == this &&
    1289          64 :                          asJobs[oQueue.front()].nStripOrTile == nBlockId))
    1290             :                 {
    1291           0 :                     WaitCompletionForJobIdx(oQueue.front());
    1292             :                 }
    1293          64 :                 CPLAssert(!oQueue.empty() &&
    1294             :                           asJobs[oQueue.front()].poDS == this &&
    1295             :                           asJobs[oQueue.front()].nStripOrTile == nBlockId);
    1296          64 :                 WaitCompletionForJobIdx(oQueue.front());
    1297             :             }
    1298             :         }
    1299             :     }
    1300     2320740 : }
    1301             : 
    1302             : /************************************************************************/
    1303             : /*                        SubmitCompressionJob()                        */
    1304             : /************************************************************************/
    1305             : 
    1306      197965 : bool GTiffDataset::SubmitCompressionJob(int nStripOrTile, GByte *pabyData,
    1307             :                                         GPtrDiff_t cc, int nHeight)
    1308             : {
    1309             :     /* -------------------------------------------------------------------- */
    1310             :     /*      Should we do compression in a worker thread ?                   */
    1311             :     /* -------------------------------------------------------------------- */
    1312      197965 :     auto poQueue = m_poBaseDS ? m_poBaseDS->m_poCompressQueue.get()
    1313      183912 :                               : m_poCompressQueue.get();
    1314             : 
    1315      197965 :     if (poQueue && m_nCompression == COMPRESSION_NONE)
    1316             :     {
    1317             :         // We don't do multi-threaded compression for uncompressed...
    1318             :         // but we must wait for other related compression tasks (e.g mask)
    1319             :         // to be completed
    1320           0 :         poQueue->WaitCompletion();
    1321             : 
    1322             :         // Flush remaining data
    1323             :         // cppcheck-suppress constVariableReference
    1324           0 :         auto &oQueue =
    1325           0 :             m_poBaseDS ? m_poBaseDS->m_asQueueJobIdx : m_asQueueJobIdx;
    1326           0 :         while (!oQueue.empty())
    1327             :         {
    1328           0 :             WaitCompletionForJobIdx(oQueue.front());
    1329             :         }
    1330             :     }
    1331             : 
    1332             :     const auto SetupJob =
    1333      123563 :         [this, pabyData, cc, nHeight, nStripOrTile](GTiffCompressionJob &sJob)
    1334             :     {
    1335       26682 :         sJob.poDS = this;
    1336       26682 :         sJob.bTIFFIsBigEndian = CPL_TO_BOOL(TIFFIsBigEndian(m_hTIFF));
    1337             :         GByte *pabyBuffer =
    1338       26682 :             static_cast<GByte *>(VSI_REALLOC_VERBOSE(sJob.pabyBuffer, cc));
    1339       26682 :         if (!pabyBuffer)
    1340           0 :             return false;
    1341       26682 :         sJob.pabyBuffer = pabyBuffer;
    1342       26682 :         memcpy(sJob.pabyBuffer, pabyData, cc);
    1343       26682 :         sJob.nBufferSize = cc;
    1344       26682 :         sJob.nHeight = nHeight;
    1345       26682 :         sJob.nStripOrTile = nStripOrTile;
    1346       26682 :         sJob.nPredictor = PREDICTOR_NONE;
    1347       26682 :         if (GTIFFSupportsPredictor(m_nCompression))
    1348             :         {
    1349       16835 :             TIFFGetField(m_hTIFF, TIFFTAG_PREDICTOR, &sJob.nPredictor);
    1350             :         }
    1351             : 
    1352       26682 :         sJob.pExtraSamples = nullptr;
    1353       26682 :         sJob.nExtraSampleCount = 0;
    1354       26682 :         TIFFGetField(m_hTIFF, TIFFTAG_EXTRASAMPLES, &sJob.nExtraSampleCount,
    1355             :                      &sJob.pExtraSamples);
    1356       26682 :         return true;
    1357      197965 :     };
    1358             : 
    1359      197965 :     if (poQueue == nullptr || !(m_nCompression == COMPRESSION_ADOBE_DEFLATE ||
    1360         806 :                                 m_nCompression == COMPRESSION_LZW ||
    1361          78 :                                 m_nCompression == COMPRESSION_PACKBITS ||
    1362          72 :                                 m_nCompression == COMPRESSION_LZMA ||
    1363          62 :                                 m_nCompression == COMPRESSION_ZSTD ||
    1364          52 :                                 m_nCompression == COMPRESSION_LERC ||
    1365          46 :                                 m_nCompression == COMPRESSION_JXL ||
    1366          46 :                                 m_nCompression == COMPRESSION_JXL_DNG_1_7 ||
    1367          28 :                                 m_nCompression == COMPRESSION_WEBP ||
    1368          18 :                                 m_nCompression == COMPRESSION_JPEG))
    1369             :     {
    1370      196389 :         if (m_bBlockOrderRowMajor || m_bLeaderSizeAsUInt4 ||
    1371      171283 :             m_bTrailerRepeatedLast4BytesRepeated)
    1372             :         {
    1373             :             GTiffCompressionJob sJob;
    1374       25106 :             memset(&sJob, 0, sizeof(sJob));
    1375       25106 :             if (SetupJob(sJob))
    1376             :             {
    1377       25106 :                 sJob.pszTmpFilename =
    1378       25106 :                     CPLStrdup(VSIMemGenerateHiddenFilename("temp.tif"));
    1379             : 
    1380       25106 :                 ThreadCompressionFunc(&sJob);
    1381             : 
    1382       25106 :                 if (sJob.nCompressedBufferSize)
    1383             :                 {
    1384       25106 :                     sJob.poDS->WriteRawStripOrTile(sJob.nStripOrTile,
    1385             :                                                    sJob.pabyCompressedBuffer,
    1386             :                                                    sJob.nCompressedBufferSize);
    1387             :                 }
    1388             : 
    1389       25106 :                 CPLFree(sJob.pabyBuffer);
    1390       25106 :                 VSIUnlink(sJob.pszTmpFilename);
    1391       25106 :                 CPLFree(sJob.pszTmpFilename);
    1392       25106 :                 return sJob.nCompressedBufferSize > 0 && !m_bWriteError;
    1393             :             }
    1394             :         }
    1395             : 
    1396      171283 :         return false;
    1397             :     }
    1398             : 
    1399        1576 :     auto poMainDS = m_poBaseDS ? m_poBaseDS : this;
    1400        1576 :     auto &oQueue = poMainDS->m_asQueueJobIdx;
    1401        1576 :     auto &asJobs = poMainDS->m_asCompressionJobs;
    1402             : 
    1403        1576 :     int nNextCompressionJobAvail = -1;
    1404             : 
    1405        1576 :     if (oQueue.size() == asJobs.size())
    1406             :     {
    1407        1443 :         CPLAssert(!oQueue.empty());
    1408        1443 :         nNextCompressionJobAvail = oQueue.front();
    1409        1443 :         WaitCompletionForJobIdx(nNextCompressionJobAvail);
    1410             :     }
    1411             :     else
    1412             :     {
    1413         133 :         const int nJobs = static_cast<int>(asJobs.size());
    1414         324 :         for (int i = 0; i < nJobs; ++i)
    1415             :         {
    1416         324 :             if (asJobs[i].nBufferSize == 0)
    1417             :             {
    1418         133 :                 nNextCompressionJobAvail = i;
    1419         133 :                 break;
    1420             :             }
    1421             :         }
    1422             :     }
    1423        1576 :     CPLAssert(nNextCompressionJobAvail >= 0);
    1424             : 
    1425        1576 :     GTiffCompressionJob *psJob = &asJobs[nNextCompressionJobAvail];
    1426        1576 :     bool bOK = SetupJob(*psJob);
    1427        1576 :     if (bOK)
    1428             :     {
    1429        1576 :         poQueue->SubmitJob(ThreadCompressionFunc, psJob);
    1430        1576 :         oQueue.push(nNextCompressionJobAvail);
    1431             :     }
    1432             : 
    1433        1576 :     return bOK;
    1434             : }
    1435             : 
    1436             : /************************************************************************/
    1437             : /*                             DiscardLsb()                             */
    1438             : /************************************************************************/
    1439             : 
    1440         272 : template <class T> bool MustNotDiscardLsb(T value, bool bHasNoData, T nodata)
    1441             : {
    1442         272 :     return bHasNoData && value == nodata;
    1443             : }
    1444             : 
    1445             : template <>
    1446          44 : bool MustNotDiscardLsb<float>(float value, bool bHasNoData, float nodata)
    1447             : {
    1448          44 :     return (bHasNoData && value == nodata) || !std::isfinite(value);
    1449             : }
    1450             : 
    1451             : template <>
    1452          44 : bool MustNotDiscardLsb<double>(double value, bool bHasNoData, double nodata)
    1453             : {
    1454          44 :     return (bHasNoData && value == nodata) || !std::isfinite(value);
    1455             : }
    1456             : 
    1457             : template <class T> T AdjustValue(T value, uint64_t nRoundUpBitTest);
    1458             : 
    1459          10 : template <class T> T AdjustValueInt(T value, uint64_t nRoundUpBitTest)
    1460             : {
    1461          10 :     if (value >=
    1462          10 :         static_cast<T>(std::numeric_limits<T>::max() - (nRoundUpBitTest << 1)))
    1463           0 :         return static_cast<T>(value - (nRoundUpBitTest << 1));
    1464          10 :     return static_cast<T>(value + (nRoundUpBitTest << 1));
    1465             : }
    1466             : 
    1467           0 : template <> int8_t AdjustValue<int8_t>(int8_t value, uint64_t nRoundUpBitTest)
    1468             : {
    1469           0 :     return AdjustValueInt(value, nRoundUpBitTest);
    1470             : }
    1471             : 
    1472             : template <>
    1473           2 : uint8_t AdjustValue<uint8_t>(uint8_t value, uint64_t nRoundUpBitTest)
    1474             : {
    1475           2 :     return AdjustValueInt(value, nRoundUpBitTest);
    1476             : }
    1477             : 
    1478             : template <>
    1479           2 : int16_t AdjustValue<int16_t>(int16_t value, uint64_t nRoundUpBitTest)
    1480             : {
    1481           2 :     return AdjustValueInt(value, nRoundUpBitTest);
    1482             : }
    1483             : 
    1484             : template <>
    1485           2 : uint16_t AdjustValue<uint16_t>(uint16_t value, uint64_t nRoundUpBitTest)
    1486             : {
    1487           2 :     return AdjustValueInt(value, nRoundUpBitTest);
    1488             : }
    1489             : 
    1490             : template <>
    1491           2 : int32_t AdjustValue<int32_t>(int32_t value, uint64_t nRoundUpBitTest)
    1492             : {
    1493           2 :     return AdjustValueInt(value, nRoundUpBitTest);
    1494             : }
    1495             : 
    1496             : template <>
    1497           2 : uint32_t AdjustValue<uint32_t>(uint32_t value, uint64_t nRoundUpBitTest)
    1498             : {
    1499           2 :     return AdjustValueInt(value, nRoundUpBitTest);
    1500             : }
    1501             : 
    1502             : template <>
    1503           0 : int64_t AdjustValue<int64_t>(int64_t value, uint64_t nRoundUpBitTest)
    1504             : {
    1505           0 :     return AdjustValueInt(value, nRoundUpBitTest);
    1506             : }
    1507             : 
    1508             : template <>
    1509           0 : uint64_t AdjustValue<uint64_t>(uint64_t value, uint64_t nRoundUpBitTest)
    1510             : {
    1511           0 :     return AdjustValueInt(value, nRoundUpBitTest);
    1512             : }
    1513             : 
    1514           0 : template <> GFloat16 AdjustValue<GFloat16>(GFloat16 value, uint64_t)
    1515             : {
    1516             :     using std::nextafter;
    1517           0 :     return nextafter(value, cpl::NumericLimits<GFloat16>::max());
    1518             : }
    1519             : 
    1520           0 : template <> float AdjustValue<float>(float value, uint64_t)
    1521             : {
    1522           0 :     return std::nextafter(value, std::numeric_limits<float>::max());
    1523             : }
    1524             : 
    1525           0 : template <> double AdjustValue<double>(double value, uint64_t)
    1526             : {
    1527           0 :     return std::nextafter(value, std::numeric_limits<double>::max());
    1528             : }
    1529             : 
    1530             : template <class Teffective, class T>
    1531             : T RoundValueDiscardLsb(const void *ptr, uint64_t nMask,
    1532             :                        uint64_t nRoundUpBitTest);
    1533             : 
    1534             : template <class T>
    1535          16 : T RoundValueDiscardLsbUnsigned(const void *ptr, uint64_t nMask,
    1536             :                                uint64_t nRoundUpBitTest)
    1537             : {
    1538          32 :     if ((*reinterpret_cast<const T *>(ptr) & nMask) >
    1539          16 :         static_cast<uint64_t>(std::numeric_limits<T>::max()) -
    1540          16 :             (nRoundUpBitTest << 1U))
    1541             :     {
    1542           4 :         return static_cast<T>(std::numeric_limits<T>::max() & nMask);
    1543             :     }
    1544          12 :     const uint64_t newval =
    1545          12 :         (*reinterpret_cast<const T *>(ptr) & nMask) + (nRoundUpBitTest << 1U);
    1546          12 :     return static_cast<T>(newval);
    1547             : }
    1548             : 
    1549             : template <class T>
    1550          18 : T RoundValueDiscardLsbSigned(const void *ptr, uint64_t nMask,
    1551             :                              uint64_t nRoundUpBitTest)
    1552             : {
    1553          18 :     T oldval = *reinterpret_cast<const T *>(ptr);
    1554          18 :     if (oldval < 0)
    1555             :     {
    1556           4 :         return static_cast<T>(oldval & nMask);
    1557             :     }
    1558          14 :     const uint64_t newval =
    1559          14 :         (*reinterpret_cast<const T *>(ptr) & nMask) + (nRoundUpBitTest << 1U);
    1560          14 :     if (newval > static_cast<uint64_t>(std::numeric_limits<T>::max()))
    1561           4 :         return static_cast<T>(std::numeric_limits<T>::max() & nMask);
    1562          10 :     return static_cast<T>(newval);
    1563             : }
    1564             : 
    1565             : template <>
    1566          11 : uint16_t RoundValueDiscardLsb<uint16_t, uint16_t>(const void *ptr,
    1567             :                                                   uint64_t nMask,
    1568             :                                                   uint64_t nRoundUpBitTest)
    1569             : {
    1570          11 :     return RoundValueDiscardLsbUnsigned<uint16_t>(ptr, nMask, nRoundUpBitTest);
    1571             : }
    1572             : 
    1573             : template <>
    1574           5 : uint32_t RoundValueDiscardLsb<uint32_t, uint32_t>(const void *ptr,
    1575             :                                                   uint64_t nMask,
    1576             :                                                   uint64_t nRoundUpBitTest)
    1577             : {
    1578           5 :     return RoundValueDiscardLsbUnsigned<uint32_t>(ptr, nMask, nRoundUpBitTest);
    1579             : }
    1580             : 
    1581             : template <>
    1582           0 : uint64_t RoundValueDiscardLsb<uint64_t, uint64_t>(const void *ptr,
    1583             :                                                   uint64_t nMask,
    1584             :                                                   uint64_t nRoundUpBitTest)
    1585             : {
    1586           0 :     return RoundValueDiscardLsbUnsigned<uint64_t>(ptr, nMask, nRoundUpBitTest);
    1587             : }
    1588             : 
    1589             : template <>
    1590           0 : int8_t RoundValueDiscardLsb<int8_t, int8_t>(const void *ptr, uint64_t nMask,
    1591             :                                             uint64_t nRoundUpBitTest)
    1592             : {
    1593           0 :     return RoundValueDiscardLsbSigned<int8_t>(ptr, nMask, nRoundUpBitTest);
    1594             : }
    1595             : 
    1596             : template <>
    1597          13 : int16_t RoundValueDiscardLsb<int16_t, int16_t>(const void *ptr, uint64_t nMask,
    1598             :                                                uint64_t nRoundUpBitTest)
    1599             : {
    1600          13 :     return RoundValueDiscardLsbSigned<int16_t>(ptr, nMask, nRoundUpBitTest);
    1601             : }
    1602             : 
    1603             : template <>
    1604           5 : int32_t RoundValueDiscardLsb<int32_t, int32_t>(const void *ptr, uint64_t nMask,
    1605             :                                                uint64_t nRoundUpBitTest)
    1606             : {
    1607           5 :     return RoundValueDiscardLsbSigned<int32_t>(ptr, nMask, nRoundUpBitTest);
    1608             : }
    1609             : 
    1610             : template <>
    1611           0 : int64_t RoundValueDiscardLsb<int64_t, int64_t>(const void *ptr, uint64_t nMask,
    1612             :                                                uint64_t nRoundUpBitTest)
    1613             : {
    1614           0 :     return RoundValueDiscardLsbSigned<int64_t>(ptr, nMask, nRoundUpBitTest);
    1615             : }
    1616             : 
    1617             : template <>
    1618           0 : uint16_t RoundValueDiscardLsb<GFloat16, uint16_t>(const void *ptr,
    1619             :                                                   uint64_t nMask,
    1620             :                                                   uint64_t nRoundUpBitTest)
    1621             : {
    1622           0 :     return RoundValueDiscardLsbUnsigned<uint16_t>(ptr, nMask, nRoundUpBitTest);
    1623             : }
    1624             : 
    1625             : template <>
    1626           0 : uint32_t RoundValueDiscardLsb<float, uint32_t>(const void *ptr, uint64_t nMask,
    1627             :                                                uint64_t nRoundUpBitTest)
    1628             : {
    1629           0 :     return RoundValueDiscardLsbUnsigned<uint32_t>(ptr, nMask, nRoundUpBitTest);
    1630             : }
    1631             : 
    1632             : template <>
    1633           0 : uint64_t RoundValueDiscardLsb<double, uint64_t>(const void *ptr, uint64_t nMask,
    1634             :                                                 uint64_t nRoundUpBitTest)
    1635             : {
    1636           0 :     return RoundValueDiscardLsbUnsigned<uint64_t>(ptr, nMask, nRoundUpBitTest);
    1637             : }
    1638             : 
    1639             : template <class Teffective, class T>
    1640         145 : static void DiscardLsbT(GByte *pabyBuffer, size_t nBytes, int iBand, int nBands,
    1641             :                         uint16_t nPlanarConfig,
    1642             :                         const GTiffDataset::MaskOffset *panMaskOffsetLsb,
    1643             :                         bool bHasNoData, Teffective nNoDataValue)
    1644             : {
    1645             :     static_assert(sizeof(Teffective) == sizeof(T),
    1646             :                   "sizeof(Teffective) == sizeof(T)");
    1647         145 :     if (nPlanarConfig == PLANARCONFIG_SEPARATE)
    1648             :     {
    1649          98 :         const auto nMask = panMaskOffsetLsb[iBand].nMask;
    1650          98 :         const auto nRoundUpBitTest = panMaskOffsetLsb[iBand].nRoundUpBitTest;
    1651         196 :         for (size_t i = 0; i < nBytes / sizeof(T); ++i)
    1652             :         {
    1653          98 :             if (MustNotDiscardLsb(reinterpret_cast<Teffective *>(pabyBuffer)[i],
    1654             :                                   bHasNoData, nNoDataValue))
    1655             :             {
    1656          22 :                 continue;
    1657             :             }
    1658             : 
    1659          76 :             if (reinterpret_cast<T *>(pabyBuffer)[i] & nRoundUpBitTest)
    1660             :             {
    1661          30 :                 reinterpret_cast<T *>(pabyBuffer)[i] =
    1662          15 :                     RoundValueDiscardLsb<Teffective, T>(
    1663          15 :                         &(reinterpret_cast<T *>(pabyBuffer)[i]), nMask,
    1664             :                         nRoundUpBitTest);
    1665             :             }
    1666             :             else
    1667             :             {
    1668          61 :                 reinterpret_cast<T *>(pabyBuffer)[i] = static_cast<T>(
    1669          61 :                     reinterpret_cast<T *>(pabyBuffer)[i] & nMask);
    1670             :             }
    1671             : 
    1672             :             // Make sure that by discarding LSB we don't end up to a value
    1673             :             // that is no the nodata value
    1674          76 :             if (MustNotDiscardLsb(reinterpret_cast<Teffective *>(pabyBuffer)[i],
    1675             :                                   bHasNoData, nNoDataValue))
    1676             :             {
    1677           8 :                 reinterpret_cast<Teffective *>(pabyBuffer)[i] =
    1678           4 :                     AdjustValue(nNoDataValue, nRoundUpBitTest);
    1679             :             }
    1680             :         }
    1681             :     }
    1682             :     else
    1683             :     {
    1684          94 :         for (size_t i = 0; i < nBytes / sizeof(T); i += nBands)
    1685             :         {
    1686         147 :             for (int j = 0; j < nBands; ++j)
    1687             :             {
    1688         100 :                 if (MustNotDiscardLsb(
    1689         100 :                         reinterpret_cast<Teffective *>(pabyBuffer)[i + j],
    1690             :                         bHasNoData, nNoDataValue))
    1691             :                 {
    1692          14 :                     continue;
    1693             :                 }
    1694             : 
    1695          86 :                 if (reinterpret_cast<T *>(pabyBuffer)[i + j] &
    1696          86 :                     panMaskOffsetLsb[j].nRoundUpBitTest)
    1697             :                 {
    1698          38 :                     reinterpret_cast<T *>(pabyBuffer)[i + j] =
    1699          19 :                         RoundValueDiscardLsb<Teffective, T>(
    1700          19 :                             &(reinterpret_cast<T *>(pabyBuffer)[i + j]),
    1701          19 :                             panMaskOffsetLsb[j].nMask,
    1702          19 :                             panMaskOffsetLsb[j].nRoundUpBitTest);
    1703             :                 }
    1704             :                 else
    1705             :                 {
    1706          67 :                     reinterpret_cast<T *>(pabyBuffer)[i + j] = static_cast<T>(
    1707          67 :                         (reinterpret_cast<T *>(pabyBuffer)[i + j] &
    1708          67 :                          panMaskOffsetLsb[j].nMask));
    1709             :                 }
    1710             : 
    1711             :                 // Make sure that by discarding LSB we don't end up to a value
    1712             :                 // that is no the nodata value
    1713          86 :                 if (MustNotDiscardLsb(
    1714          86 :                         reinterpret_cast<Teffective *>(pabyBuffer)[i + j],
    1715             :                         bHasNoData, nNoDataValue))
    1716             :                 {
    1717           8 :                     reinterpret_cast<Teffective *>(pabyBuffer)[i + j] =
    1718           4 :                         AdjustValue(nNoDataValue,
    1719           4 :                                     panMaskOffsetLsb[j].nRoundUpBitTest);
    1720             :                 }
    1721             :             }
    1722             :         }
    1723             :     }
    1724         145 : }
    1725             : 
    1726         183 : static void DiscardLsb(GByte *pabyBuffer, GPtrDiff_t nBytes, int iBand,
    1727             :                        int nBands, uint16_t nSampleFormat,
    1728             :                        uint16_t nBitsPerSample, uint16_t nPlanarConfig,
    1729             :                        const GTiffDataset::MaskOffset *panMaskOffsetLsb,
    1730             :                        bool bHasNoData, double dfNoDataValue)
    1731             : {
    1732         183 :     if (nBitsPerSample == 8 && nSampleFormat == SAMPLEFORMAT_UINT)
    1733             :     {
    1734          38 :         uint8_t nNoDataValue = 0;
    1735          38 :         if (bHasNoData && GDALIsValueExactAs<uint8_t>(dfNoDataValue))
    1736             :         {
    1737           6 :             nNoDataValue = static_cast<uint8_t>(dfNoDataValue);
    1738             :         }
    1739             :         else
    1740             :         {
    1741          32 :             bHasNoData = false;
    1742             :         }
    1743          38 :         if (nPlanarConfig == PLANARCONFIG_SEPARATE)
    1744             :         {
    1745          25 :             const auto nMask =
    1746          25 :                 static_cast<unsigned>(panMaskOffsetLsb[iBand].nMask);
    1747          25 :             const auto nRoundUpBitTest =
    1748          25 :                 static_cast<unsigned>(panMaskOffsetLsb[iBand].nRoundUpBitTest);
    1749          50 :             for (decltype(nBytes) i = 0; i < nBytes; ++i)
    1750             :             {
    1751          25 :                 if (bHasNoData && pabyBuffer[i] == nNoDataValue)
    1752           3 :                     continue;
    1753             : 
    1754             :                 // Keep 255 in case it is alpha.
    1755          22 :                 if (pabyBuffer[i] != 255)
    1756             :                 {
    1757          21 :                     if (pabyBuffer[i] & nRoundUpBitTest)
    1758           5 :                         pabyBuffer[i] = static_cast<GByte>(
    1759           5 :                             std::min(255U, (pabyBuffer[i] & nMask) +
    1760           5 :                                                (nRoundUpBitTest << 1U)));
    1761             :                     else
    1762          16 :                         pabyBuffer[i] =
    1763          16 :                             static_cast<GByte>(pabyBuffer[i] & nMask);
    1764             : 
    1765             :                     // Make sure that by discarding LSB we don't end up to a
    1766             :                     // value that is no the nodata value
    1767          21 :                     if (bHasNoData && pabyBuffer[i] == nNoDataValue)
    1768           2 :                         pabyBuffer[i] =
    1769           1 :                             AdjustValue(nNoDataValue, nRoundUpBitTest);
    1770             :                 }
    1771             :             }
    1772             :         }
    1773             :         else
    1774             :         {
    1775          26 :             for (decltype(nBytes) i = 0; i < nBytes; i += nBands)
    1776             :             {
    1777          42 :                 for (int j = 0; j < nBands; ++j)
    1778             :                 {
    1779          29 :                     if (bHasNoData && pabyBuffer[i + j] == nNoDataValue)
    1780           2 :                         continue;
    1781             : 
    1782             :                     // Keep 255 in case it is alpha.
    1783          27 :                     if (pabyBuffer[i + j] != 255)
    1784             :                     {
    1785          25 :                         if (pabyBuffer[i + j] &
    1786          25 :                             panMaskOffsetLsb[j].nRoundUpBitTest)
    1787             :                         {
    1788           6 :                             pabyBuffer[i + j] = static_cast<GByte>(std::min(
    1789          12 :                                 255U,
    1790           6 :                                 (pabyBuffer[i + j] &
    1791             :                                  static_cast<unsigned>(
    1792           6 :                                      panMaskOffsetLsb[j].nMask)) +
    1793             :                                     (static_cast<unsigned>(
    1794           6 :                                          panMaskOffsetLsb[j].nRoundUpBitTest)
    1795           6 :                                      << 1U)));
    1796             :                         }
    1797             :                         else
    1798             :                         {
    1799          19 :                             pabyBuffer[i + j] = static_cast<GByte>(
    1800          19 :                                 pabyBuffer[i + j] & panMaskOffsetLsb[j].nMask);
    1801             :                         }
    1802             : 
    1803             :                         // Make sure that by discarding LSB we don't end up to a
    1804             :                         // value that is no the nodata value
    1805          25 :                         if (bHasNoData && pabyBuffer[i + j] == nNoDataValue)
    1806           1 :                             pabyBuffer[i + j] = AdjustValue(
    1807             :                                 nNoDataValue,
    1808           1 :                                 panMaskOffsetLsb[j].nRoundUpBitTest);
    1809             :                     }
    1810             :                 }
    1811             :             }
    1812          38 :         }
    1813             :     }
    1814         145 :     else if (nBitsPerSample == 8 && nSampleFormat == SAMPLEFORMAT_INT)
    1815             :     {
    1816           0 :         int8_t nNoDataValue = 0;
    1817           0 :         if (bHasNoData && GDALIsValueExactAs<int8_t>(dfNoDataValue))
    1818             :         {
    1819           0 :             nNoDataValue = static_cast<int8_t>(dfNoDataValue);
    1820             :         }
    1821             :         else
    1822             :         {
    1823           0 :             bHasNoData = false;
    1824             :         }
    1825           0 :         DiscardLsbT<int8_t, int8_t>(pabyBuffer, nBytes, iBand, nBands,
    1826             :                                     nPlanarConfig, panMaskOffsetLsb, bHasNoData,
    1827           0 :                                     nNoDataValue);
    1828             :     }
    1829         145 :     else if (nBitsPerSample == 16 && nSampleFormat == SAMPLEFORMAT_INT)
    1830             :     {
    1831          48 :         int16_t nNoDataValue = 0;
    1832          48 :         if (bHasNoData && GDALIsValueExactAs<int16_t>(dfNoDataValue))
    1833             :         {
    1834           6 :             nNoDataValue = static_cast<int16_t>(dfNoDataValue);
    1835             :         }
    1836             :         else
    1837             :         {
    1838          42 :             bHasNoData = false;
    1839             :         }
    1840          48 :         DiscardLsbT<int16_t, int16_t>(pabyBuffer, nBytes, iBand, nBands,
    1841             :                                       nPlanarConfig, panMaskOffsetLsb,
    1842          48 :                                       bHasNoData, nNoDataValue);
    1843             :     }
    1844          97 :     else if (nBitsPerSample == 16 && nSampleFormat == SAMPLEFORMAT_UINT)
    1845             :     {
    1846          33 :         uint16_t nNoDataValue = 0;
    1847          33 :         if (bHasNoData && GDALIsValueExactAs<uint16_t>(dfNoDataValue))
    1848             :         {
    1849           6 :             nNoDataValue = static_cast<uint16_t>(dfNoDataValue);
    1850             :         }
    1851             :         else
    1852             :         {
    1853          27 :             bHasNoData = false;
    1854             :         }
    1855          33 :         DiscardLsbT<uint16_t, uint16_t>(pabyBuffer, nBytes, iBand, nBands,
    1856             :                                         nPlanarConfig, panMaskOffsetLsb,
    1857          33 :                                         bHasNoData, nNoDataValue);
    1858             :     }
    1859          64 :     else if (nBitsPerSample == 32 && nSampleFormat == SAMPLEFORMAT_INT)
    1860             :     {
    1861          13 :         int32_t nNoDataValue = 0;
    1862          13 :         if (bHasNoData && GDALIsValueExactAs<int32_t>(dfNoDataValue))
    1863             :         {
    1864           6 :             nNoDataValue = static_cast<int32_t>(dfNoDataValue);
    1865             :         }
    1866             :         else
    1867             :         {
    1868           7 :             bHasNoData = false;
    1869             :         }
    1870          13 :         DiscardLsbT<int32_t, int32_t>(pabyBuffer, nBytes, iBand, nBands,
    1871             :                                       nPlanarConfig, panMaskOffsetLsb,
    1872          13 :                                       bHasNoData, nNoDataValue);
    1873             :     }
    1874          51 :     else if (nBitsPerSample == 32 && nSampleFormat == SAMPLEFORMAT_UINT)
    1875             :     {
    1876          13 :         uint32_t nNoDataValue = 0;
    1877          13 :         if (bHasNoData && GDALIsValueExactAs<uint32_t>(dfNoDataValue))
    1878             :         {
    1879           6 :             nNoDataValue = static_cast<uint32_t>(dfNoDataValue);
    1880             :         }
    1881             :         else
    1882             :         {
    1883           7 :             bHasNoData = false;
    1884             :         }
    1885          13 :         DiscardLsbT<uint32_t, uint32_t>(pabyBuffer, nBytes, iBand, nBands,
    1886             :                                         nPlanarConfig, panMaskOffsetLsb,
    1887          13 :                                         bHasNoData, nNoDataValue);
    1888             :     }
    1889          38 :     else if (nBitsPerSample == 64 && nSampleFormat == SAMPLEFORMAT_INT)
    1890             :     {
    1891             :         // FIXME: we should not rely on dfNoDataValue when we support native
    1892             :         // data type for nodata
    1893           0 :         int64_t nNoDataValue = 0;
    1894           0 :         if (bHasNoData && GDALIsValueExactAs<int64_t>(dfNoDataValue))
    1895             :         {
    1896           0 :             nNoDataValue = static_cast<int64_t>(dfNoDataValue);
    1897             :         }
    1898             :         else
    1899             :         {
    1900           0 :             bHasNoData = false;
    1901             :         }
    1902           0 :         DiscardLsbT<int64_t, int64_t>(pabyBuffer, nBytes, iBand, nBands,
    1903             :                                       nPlanarConfig, panMaskOffsetLsb,
    1904           0 :                                       bHasNoData, nNoDataValue);
    1905             :     }
    1906          38 :     else if (nBitsPerSample == 64 && nSampleFormat == SAMPLEFORMAT_UINT)
    1907             :     {
    1908             :         // FIXME: we should not rely on dfNoDataValue when we support native
    1909             :         // data type for nodata
    1910           0 :         uint64_t nNoDataValue = 0;
    1911           0 :         if (bHasNoData && GDALIsValueExactAs<uint64_t>(dfNoDataValue))
    1912             :         {
    1913           0 :             nNoDataValue = static_cast<uint64_t>(dfNoDataValue);
    1914             :         }
    1915             :         else
    1916             :         {
    1917           0 :             bHasNoData = false;
    1918             :         }
    1919           0 :         DiscardLsbT<uint64_t, uint64_t>(pabyBuffer, nBytes, iBand, nBands,
    1920             :                                         nPlanarConfig, panMaskOffsetLsb,
    1921           0 :                                         bHasNoData, nNoDataValue);
    1922             :     }
    1923          38 :     else if (nBitsPerSample == 16 && nSampleFormat == SAMPLEFORMAT_IEEEFP)
    1924             :     {
    1925           0 :         const GFloat16 fNoDataValue = static_cast<GFloat16>(dfNoDataValue);
    1926           0 :         DiscardLsbT<GFloat16, uint16_t>(pabyBuffer, nBytes, iBand, nBands,
    1927             :                                         nPlanarConfig, panMaskOffsetLsb,
    1928           0 :                                         bHasNoData, fNoDataValue);
    1929             :     }
    1930          38 :     else if (nBitsPerSample == 32 && nSampleFormat == SAMPLEFORMAT_IEEEFP)
    1931             :     {
    1932          19 :         const float fNoDataValue = static_cast<float>(dfNoDataValue);
    1933          19 :         DiscardLsbT<float, uint32_t>(pabyBuffer, nBytes, iBand, nBands,
    1934             :                                      nPlanarConfig, panMaskOffsetLsb,
    1935          19 :                                      bHasNoData, fNoDataValue);
    1936             :     }
    1937          19 :     else if (nBitsPerSample == 64 && nSampleFormat == SAMPLEFORMAT_IEEEFP)
    1938             :     {
    1939          19 :         DiscardLsbT<double, uint64_t>(pabyBuffer, nBytes, iBand, nBands,
    1940             :                                       nPlanarConfig, panMaskOffsetLsb,
    1941             :                                       bHasNoData, dfNoDataValue);
    1942             :     }
    1943         183 : }
    1944             : 
    1945         183 : void GTiffDataset::DiscardLsb(GByte *pabyBuffer, GPtrDiff_t nBytes,
    1946             :                               int iBand) const
    1947             : {
    1948         183 :     ::DiscardLsb(pabyBuffer, nBytes, iBand, nBands, m_nSampleFormat,
    1949         183 :                  m_nBitsPerSample, m_nPlanarConfig, m_panMaskOffsetLsb,
    1950         183 :                  m_bNoDataSet, m_dfNoDataValue);
    1951         183 : }
    1952             : 
    1953             : /************************************************************************/
    1954             : /*                      WriteEncodedTileOrStrip()                       */
    1955             : /************************************************************************/
    1956             : 
    1957      228897 : CPLErr GTiffDataset::WriteEncodedTileOrStrip(uint32_t tile_or_strip, void *data,
    1958             :                                              int bPreserveDataBuffer)
    1959             : {
    1960      228897 :     CPLErr eErr = CE_None;
    1961             : 
    1962      228897 :     if (TIFFIsTiled(m_hTIFF))
    1963             :     {
    1964       50512 :         if (!(WriteEncodedTile(tile_or_strip, static_cast<GByte *>(data),
    1965             :                                bPreserveDataBuffer)))
    1966             :         {
    1967          14 :             eErr = CE_Failure;
    1968             :         }
    1969             :     }
    1970             :     else
    1971             :     {
    1972      178385 :         if (!(WriteEncodedStrip(tile_or_strip, static_cast<GByte *>(data),
    1973             :                                 bPreserveDataBuffer)))
    1974             :         {
    1975           8 :             eErr = CE_Failure;
    1976             :         }
    1977             :     }
    1978             : 
    1979      228897 :     return eErr;
    1980             : }
    1981             : 
    1982             : /************************************************************************/
    1983             : /*                           FlushBlockBuf()                            */
    1984             : /************************************************************************/
    1985             : 
    1986        9616 : CPLErr GTiffDataset::FlushBlockBuf()
    1987             : 
    1988             : {
    1989        9616 :     if (m_nLoadedBlock < 0 || !m_bLoadedBlockDirty)
    1990           0 :         return CE_None;
    1991             : 
    1992        9616 :     m_bLoadedBlockDirty = false;
    1993             : 
    1994             :     const CPLErr eErr =
    1995        9616 :         WriteEncodedTileOrStrip(m_nLoadedBlock, m_pabyBlockBuf, true);
    1996        9616 :     if (eErr != CE_None)
    1997             :     {
    1998           0 :         ReportError(CE_Failure, CPLE_AppDefined,
    1999             :                     "WriteEncodedTile/Strip() failed.");
    2000           0 :         m_bWriteError = true;
    2001             :     }
    2002             : 
    2003        9616 :     return eErr;
    2004             : }
    2005             : 
    2006             : /************************************************************************/
    2007             : /*                 GTiffFillStreamableOffsetAndCount()                  */
    2008             : /************************************************************************/
    2009             : 
    2010           8 : static void GTiffFillStreamableOffsetAndCount(TIFF *hTIFF, int nSize)
    2011             : {
    2012           8 :     uint32_t nXSize = 0;
    2013           8 :     uint32_t nYSize = 0;
    2014           8 :     TIFFGetField(hTIFF, TIFFTAG_IMAGEWIDTH, &nXSize);
    2015           8 :     TIFFGetField(hTIFF, TIFFTAG_IMAGELENGTH, &nYSize);
    2016           8 :     const bool bIsTiled = CPL_TO_BOOL(TIFFIsTiled(hTIFF));
    2017             :     const int nBlockCount =
    2018           8 :         bIsTiled ? TIFFNumberOfTiles(hTIFF) : TIFFNumberOfStrips(hTIFF);
    2019             : 
    2020           8 :     toff_t *panOffset = nullptr;
    2021           8 :     TIFFGetField(hTIFF, bIsTiled ? TIFFTAG_TILEOFFSETS : TIFFTAG_STRIPOFFSETS,
    2022             :                  &panOffset);
    2023           8 :     toff_t *panSize = nullptr;
    2024           8 :     TIFFGetField(hTIFF,
    2025             :                  bIsTiled ? TIFFTAG_TILEBYTECOUNTS : TIFFTAG_STRIPBYTECOUNTS,
    2026             :                  &panSize);
    2027           8 :     toff_t nOffset = nSize;
    2028             :     // Trick to avoid clang static analyzer raising false positive about
    2029             :     // divide by zero later.
    2030           8 :     int nBlocksPerBand = 1;
    2031           8 :     uint32_t nRowsPerStrip = 0;
    2032           8 :     if (!bIsTiled)
    2033             :     {
    2034           6 :         TIFFGetField(hTIFF, TIFFTAG_ROWSPERSTRIP, &nRowsPerStrip);
    2035           6 :         if (nRowsPerStrip > static_cast<uint32_t>(nYSize))
    2036           0 :             nRowsPerStrip = nYSize;
    2037           6 :         nBlocksPerBand = DIV_ROUND_UP(nYSize, nRowsPerStrip);
    2038             :     }
    2039        2947 :     for (int i = 0; i < nBlockCount; ++i)
    2040             :     {
    2041             :         GPtrDiff_t cc = bIsTiled
    2042        2939 :                             ? static_cast<GPtrDiff_t>(TIFFTileSize(hTIFF))
    2043        2907 :                             : static_cast<GPtrDiff_t>(TIFFStripSize(hTIFF));
    2044        2939 :         if (!bIsTiled)
    2045             :         {
    2046             :             /* --------------------------------------------------------------------
    2047             :              */
    2048             :             /*      If this is the last strip in the image, and is partial, then
    2049             :              */
    2050             :             /*      we need to trim the number of scanlines written to the */
    2051             :             /*      amount of valid data we have. (#2748) */
    2052             :             /* --------------------------------------------------------------------
    2053             :              */
    2054        2907 :             int nStripWithinBand = i % nBlocksPerBand;
    2055        2907 :             if (nStripWithinBand * nRowsPerStrip > nYSize - nRowsPerStrip)
    2056             :             {
    2057           1 :                 cc = (cc / nRowsPerStrip) *
    2058           1 :                      (nYSize - nStripWithinBand * nRowsPerStrip);
    2059             :             }
    2060             :         }
    2061        2939 :         panOffset[i] = nOffset;
    2062        2939 :         panSize[i] = cc;
    2063        2939 :         nOffset += cc;
    2064             :     }
    2065           8 : }
    2066             : 
    2067             : /************************************************************************/
    2068             : /*                             Crystalize()                             */
    2069             : /*                                                                      */
    2070             : /*      Make sure that the directory information is written out for     */
    2071             : /*      a new file, require before writing any imagery data.            */
    2072             : /************************************************************************/
    2073             : 
    2074     2656180 : void GTiffDataset::Crystalize()
    2075             : 
    2076             : {
    2077     2656180 :     if (m_bCrystalized)
    2078     2650380 :         return;
    2079             : 
    2080             :     // TODO: libtiff writes extended tags in the order they are specified
    2081             :     // and not in increasing order.
    2082        5792 :     WriteMetadata(this, m_hTIFF, true, m_eProfile, m_osFilename.c_str(),
    2083        5792 :                   m_papszCreationOptions);
    2084        5792 :     WriteGeoTIFFInfo();
    2085        5792 :     if (m_bNoDataSet)
    2086         345 :         WriteNoDataValue(m_hTIFF, m_dfNoDataValue);
    2087        5447 :     else if (m_bNoDataSetAsInt64)
    2088           4 :         WriteNoDataValue(m_hTIFF, m_nNoDataValueInt64);
    2089        5443 :     else if (m_bNoDataSetAsUInt64)
    2090           4 :         WriteNoDataValue(m_hTIFF, m_nNoDataValueUInt64);
    2091             : 
    2092        5792 :     m_bMetadataChanged = false;
    2093        5792 :     m_bGeoTIFFInfoChanged = false;
    2094        5792 :     m_bNoDataChanged = false;
    2095        5792 :     m_bNeedsRewrite = false;
    2096             : 
    2097        5792 :     m_bCrystalized = true;
    2098             : 
    2099        5792 :     TIFFWriteCheck(m_hTIFF, TIFFIsTiled(m_hTIFF), "GTiffDataset::Crystalize");
    2100             : 
    2101        5792 :     TIFFWriteDirectory(m_hTIFF);
    2102        5792 :     if (m_bStreamingOut)
    2103             :     {
    2104             :         // We need to write twice the directory to be sure that custom
    2105             :         // TIFF tags are correctly sorted and that padding bytes have been
    2106             :         // added.
    2107           3 :         TIFFSetDirectory(m_hTIFF, 0);
    2108           3 :         TIFFWriteDirectory(m_hTIFF);
    2109             : 
    2110           3 :         if (VSIFSeekL(m_fpL, 0, SEEK_END) != 0)
    2111             :         {
    2112           0 :             ReportError(CE_Failure, CPLE_FileIO, "Could not seek");
    2113             :         }
    2114           3 :         const int nSize = static_cast<int>(VSIFTellL(m_fpL));
    2115             : 
    2116           3 :         TIFFSetDirectory(m_hTIFF, 0);
    2117           3 :         GTiffFillStreamableOffsetAndCount(m_hTIFF, nSize);
    2118           3 :         TIFFWriteDirectory(m_hTIFF);
    2119             : 
    2120           3 :         vsi_l_offset nDataLength = 0;
    2121             :         void *pabyBuffer =
    2122           3 :             VSIGetMemFileBuffer(m_pszTmpFilename, &nDataLength, FALSE);
    2123           3 :         if (static_cast<int>(VSIFWriteL(
    2124           3 :                 pabyBuffer, 1, static_cast<int>(nDataLength), m_fpToWrite)) !=
    2125             :             static_cast<int>(nDataLength))
    2126             :         {
    2127           0 :             ReportError(CE_Failure, CPLE_FileIO, "Could not write %d bytes",
    2128             :                         static_cast<int>(nDataLength));
    2129             :         }
    2130             :         // In case of single strip file, there's a libtiff check that would
    2131             :         // issue a warning since the file hasn't the required size.
    2132           3 :         CPLPushErrorHandler(CPLQuietErrorHandler);
    2133           3 :         TIFFSetDirectory(m_hTIFF, 0);
    2134           3 :         CPLPopErrorHandler();
    2135             :     }
    2136             :     else
    2137             :     {
    2138        5789 :         const tdir_t nNumberOfDirs = TIFFNumberOfDirectories(m_hTIFF);
    2139        5789 :         if (nNumberOfDirs > 0)
    2140             :         {
    2141        5789 :             TIFFSetDirectory(m_hTIFF, static_cast<tdir_t>(nNumberOfDirs - 1));
    2142             :         }
    2143             :     }
    2144             : 
    2145        5792 :     RestoreVolatileParameters(m_hTIFF);
    2146             : 
    2147        5792 :     m_nDirOffset = TIFFCurrentDirOffset(m_hTIFF);
    2148             : }
    2149             : 
    2150             : /************************************************************************/
    2151             : /*                             FlushCache()                             */
    2152             : /*                                                                      */
    2153             : /*      We override this so we can also flush out local tiff strip      */
    2154             : /*      cache if need be.                                               */
    2155             : /************************************************************************/
    2156             : 
    2157        4596 : CPLErr GTiffDataset::FlushCache(bool bAtClosing)
    2158             : 
    2159             : {
    2160        4596 :     return FlushCacheInternal(bAtClosing, true);
    2161             : }
    2162             : 
    2163       46845 : CPLErr GTiffDataset::FlushCacheInternal(bool bAtClosing, bool bFlushDirectory)
    2164             : {
    2165       46845 :     if (m_bIsFinalized)
    2166           2 :         return CE_None;
    2167             : 
    2168       46843 :     CPLErr eErr = GDALPamDataset::FlushCache(bAtClosing);
    2169             : 
    2170       46843 :     if (m_bLoadedBlockDirty && m_nLoadedBlock != -1)
    2171             :     {
    2172         275 :         if (FlushBlockBuf() != CE_None)
    2173           0 :             eErr = CE_Failure;
    2174             :     }
    2175             : 
    2176       46843 :     CPLFree(m_pabyBlockBuf);
    2177       46843 :     m_pabyBlockBuf = nullptr;
    2178       46843 :     m_nLoadedBlock = -1;
    2179       46843 :     m_bLoadedBlockDirty = false;
    2180             : 
    2181             :     // Finish compression
    2182       46843 :     auto poQueue = m_poBaseDS ? m_poBaseDS->m_poCompressQueue.get()
    2183       44493 :                               : m_poCompressQueue.get();
    2184       46843 :     if (poQueue)
    2185             :     {
    2186         161 :         poQueue->WaitCompletion();
    2187             : 
    2188             :         // Flush remaining data
    2189             :         // cppcheck-suppress constVariableReference
    2190             : 
    2191         161 :         auto &oQueue =
    2192         161 :             m_poBaseDS ? m_poBaseDS->m_asQueueJobIdx : m_asQueueJobIdx;
    2193         230 :         while (!oQueue.empty())
    2194             :         {
    2195          69 :             WaitCompletionForJobIdx(oQueue.front());
    2196             :         }
    2197             :     }
    2198             : 
    2199       46843 :     if (bFlushDirectory && GetAccess() == GA_Update)
    2200             :     {
    2201       14035 :         if (FlushDirectory() != CE_None)
    2202          12 :             eErr = CE_Failure;
    2203             :     }
    2204       46843 :     return eErr;
    2205             : }
    2206             : 
    2207             : /************************************************************************/
    2208             : /*                           FlushDirectory()                           */
    2209             : /************************************************************************/
    2210             : 
    2211       22063 : CPLErr GTiffDataset::FlushDirectory()
    2212             : 
    2213             : {
    2214       22063 :     CPLErr eErr = CE_None;
    2215             : 
    2216         688 :     const auto ReloadAllOtherDirectories = [this]()
    2217             :     {
    2218         339 :         const auto poBaseDS = m_poBaseDS ? m_poBaseDS : this;
    2219         342 :         for (auto &poOvrDS : poBaseDS->m_apoOverviewDS)
    2220             :         {
    2221           3 :             if (poOvrDS->m_bCrystalized && poOvrDS.get() != this)
    2222             :             {
    2223           3 :                 poOvrDS->ReloadDirectory(true);
    2224             :             }
    2225             : 
    2226           3 :             if (poOvrDS->m_poMaskDS && poOvrDS->m_poMaskDS.get() != this &&
    2227           0 :                 poOvrDS->m_poMaskDS->m_bCrystalized)
    2228             :             {
    2229           0 :                 poOvrDS->m_poMaskDS->ReloadDirectory(true);
    2230             :             }
    2231             :         }
    2232         339 :         if (poBaseDS->m_poMaskDS && poBaseDS->m_poMaskDS.get() != this &&
    2233           0 :             poBaseDS->m_poMaskDS->m_bCrystalized)
    2234             :         {
    2235           0 :             poBaseDS->m_poMaskDS->ReloadDirectory(true);
    2236             :         }
    2237         339 :         if (poBaseDS->m_bCrystalized && poBaseDS != this)
    2238             :         {
    2239           7 :             poBaseDS->ReloadDirectory(true);
    2240             :         }
    2241         339 :     };
    2242             : 
    2243       22063 :     if (eAccess == GA_Update)
    2244             :     {
    2245       15728 :         if (m_bMetadataChanged)
    2246             :         {
    2247         201 :             m_bNeedsRewrite =
    2248         201 :                 WriteMetadata(this, m_hTIFF, true, m_eProfile,
    2249         201 :                               m_osFilename.c_str(), m_papszCreationOptions);
    2250         201 :             m_bMetadataChanged = false;
    2251             : 
    2252         201 :             if (m_bForceUnsetRPC)
    2253             :             {
    2254           5 :                 double *padfRPCTag = nullptr;
    2255             :                 uint16_t nCount;
    2256           5 :                 if (TIFFGetField(m_hTIFF, TIFFTAG_RPCCOEFFICIENT, &nCount,
    2257           5 :                                  &padfRPCTag))
    2258             :                 {
    2259           3 :                     std::vector<double> zeroes(92);
    2260           3 :                     TIFFSetField(m_hTIFF, TIFFTAG_RPCCOEFFICIENT, 92,
    2261             :                                  zeroes.data());
    2262           3 :                     TIFFUnsetField(m_hTIFF, TIFFTAG_RPCCOEFFICIENT);
    2263           3 :                     m_bNeedsRewrite = true;
    2264             :                 }
    2265             : 
    2266           5 :                 if (m_poBaseDS == nullptr)
    2267             :                 {
    2268           5 :                     GDALWriteRPCTXTFile(m_osFilename.c_str(), nullptr);
    2269           5 :                     GDALWriteRPBFile(m_osFilename.c_str(), nullptr);
    2270             :                 }
    2271             :             }
    2272             :         }
    2273             : 
    2274       15728 :         if (m_bGeoTIFFInfoChanged)
    2275             :         {
    2276         146 :             WriteGeoTIFFInfo();
    2277         146 :             m_bGeoTIFFInfoChanged = false;
    2278             :         }
    2279             : 
    2280       15728 :         if (m_bNoDataChanged)
    2281             :         {
    2282          53 :             if (m_bNoDataSet)
    2283             :             {
    2284          37 :                 WriteNoDataValue(m_hTIFF, m_dfNoDataValue);
    2285             :             }
    2286          16 :             else if (m_bNoDataSetAsInt64)
    2287             :             {
    2288           0 :                 WriteNoDataValue(m_hTIFF, m_nNoDataValueInt64);
    2289             :             }
    2290          16 :             else if (m_bNoDataSetAsUInt64)
    2291             :             {
    2292           0 :                 WriteNoDataValue(m_hTIFF, m_nNoDataValueUInt64);
    2293             :             }
    2294             :             else
    2295             :             {
    2296          16 :                 UnsetNoDataValue(m_hTIFF);
    2297             :             }
    2298          53 :             m_bNeedsRewrite = true;
    2299          53 :             m_bNoDataChanged = false;
    2300             :         }
    2301             : 
    2302       15728 :         if (m_bNeedsRewrite)
    2303             :         {
    2304         364 :             if (!m_bCrystalized)
    2305             :             {
    2306          28 :                 Crystalize();
    2307             :             }
    2308             :             else
    2309             :             {
    2310         336 :                 const TIFFSizeProc pfnSizeProc = TIFFGetSizeProc(m_hTIFF);
    2311             : 
    2312         336 :                 m_nDirOffset = pfnSizeProc(TIFFClientdata(m_hTIFF));
    2313         336 :                 if ((m_nDirOffset % 2) == 1)
    2314          72 :                     ++m_nDirOffset;
    2315             : 
    2316         336 :                 if (TIFFRewriteDirectory(m_hTIFF) == 0)
    2317           0 :                     eErr = CE_Failure;
    2318             : 
    2319         336 :                 TIFFSetSubDirectory(m_hTIFF, m_nDirOffset);
    2320             : 
    2321         336 :                 ReloadAllOtherDirectories();
    2322             : 
    2323         336 :                 if (m_bLayoutIFDSBeforeData && m_bBlockOrderRowMajor &&
    2324           2 :                     m_bLeaderSizeAsUInt4 &&
    2325           2 :                     m_bTrailerRepeatedLast4BytesRepeated &&
    2326           2 :                     !m_bKnownIncompatibleEdition &&
    2327           2 :                     !m_bWriteKnownIncompatibleEdition)
    2328             :                 {
    2329           2 :                     ReportError(CE_Warning, CPLE_AppDefined,
    2330             :                                 "The IFD has been rewritten at the end of "
    2331             :                                 "the file, which breaks COG layout.");
    2332           2 :                     m_bKnownIncompatibleEdition = true;
    2333           2 :                     m_bWriteKnownIncompatibleEdition = true;
    2334             :                 }
    2335             :             }
    2336             : 
    2337         364 :             m_bNeedsRewrite = false;
    2338             :         }
    2339             :     }
    2340             : 
    2341             :     // There are some circumstances in which we can reach this point
    2342             :     // without having made this our directory (SetDirectory()) in which
    2343             :     // case we should not risk a flush.
    2344       37791 :     if (GetAccess() == GA_Update &&
    2345       15728 :         TIFFCurrentDirOffset(m_hTIFF) == m_nDirOffset)
    2346             :     {
    2347       15728 :         const TIFFSizeProc pfnSizeProc = TIFFGetSizeProc(m_hTIFF);
    2348             : 
    2349       15728 :         toff_t nNewDirOffset = pfnSizeProc(TIFFClientdata(m_hTIFF));
    2350       15728 :         if ((nNewDirOffset % 2) == 1)
    2351        3483 :             ++nNewDirOffset;
    2352             : 
    2353       15728 :         if (TIFFFlush(m_hTIFF) == 0)
    2354          12 :             eErr = CE_Failure;
    2355             : 
    2356       15728 :         if (m_nDirOffset != TIFFCurrentDirOffset(m_hTIFF))
    2357             :         {
    2358           3 :             m_nDirOffset = nNewDirOffset;
    2359           3 :             ReloadAllOtherDirectories();
    2360           3 :             CPLDebug("GTiff",
    2361             :                      "directory moved during flush in FlushDirectory()");
    2362             :         }
    2363             :     }
    2364             : 
    2365       22063 :     SetDirectory();
    2366       22063 :     return eErr;
    2367             : }
    2368             : 
    2369             : /************************************************************************/
    2370             : /*                           CleanOverviews()                           */
    2371             : /************************************************************************/
    2372             : 
    2373           5 : CPLErr GTiffDataset::CleanOverviews()
    2374             : 
    2375             : {
    2376           5 :     CPLAssert(!m_poBaseDS);
    2377             : 
    2378           5 :     ScanDirectories();
    2379             : 
    2380           5 :     FlushDirectory();
    2381             : 
    2382             :     /* -------------------------------------------------------------------- */
    2383             :     /*      Cleanup overviews objects, and get offsets to all overview      */
    2384             :     /*      directories.                                                    */
    2385             :     /* -------------------------------------------------------------------- */
    2386          10 :     std::vector<toff_t> anOvDirOffsets;
    2387             : 
    2388          10 :     for (auto &poOvrDS : m_apoOverviewDS)
    2389             :     {
    2390           5 :         anOvDirOffsets.push_back(poOvrDS->m_nDirOffset);
    2391           5 :         if (poOvrDS->m_poMaskDS)
    2392           1 :             anOvDirOffsets.push_back(poOvrDS->m_poMaskDS->m_nDirOffset);
    2393             :     }
    2394           5 :     m_apoOverviewDS.clear();
    2395             : 
    2396             :     /* -------------------------------------------------------------------- */
    2397             :     /*      Loop through all the directories, translating the offsets       */
    2398             :     /*      into indexes we can use with TIFFUnlinkDirectory().             */
    2399             :     /* -------------------------------------------------------------------- */
    2400          10 :     std::vector<uint16_t> anOvDirIndexes;
    2401           5 :     int iThisOffset = 1;
    2402             : 
    2403           5 :     TIFFSetDirectory(m_hTIFF, 0);
    2404             : 
    2405             :     while (true)
    2406             :     {
    2407          28 :         for (toff_t nOffset : anOvDirOffsets)
    2408             :         {
    2409          16 :             if (nOffset == TIFFCurrentDirOffset(m_hTIFF))
    2410             :             {
    2411           6 :                 anOvDirIndexes.push_back(static_cast<uint16_t>(iThisOffset));
    2412             :             }
    2413             :         }
    2414             : 
    2415          12 :         if (TIFFLastDirectory(m_hTIFF))
    2416           5 :             break;
    2417             : 
    2418           7 :         TIFFReadDirectory(m_hTIFF);
    2419           7 :         ++iThisOffset;
    2420           7 :     }
    2421             : 
    2422             :     /* -------------------------------------------------------------------- */
    2423             :     /*      Actually unlink the target directories.  Note that we do        */
    2424             :     /*      this from last to first so as to avoid renumbering any of       */
    2425             :     /*      the earlier directories we need to remove.                      */
    2426             :     /* -------------------------------------------------------------------- */
    2427          11 :     while (!anOvDirIndexes.empty())
    2428             :     {
    2429           6 :         TIFFUnlinkDirectory(m_hTIFF, anOvDirIndexes.back());
    2430           6 :         anOvDirIndexes.pop_back();
    2431             :     }
    2432             : 
    2433           5 :     if (m_poMaskDS)
    2434             :     {
    2435           1 :         m_poMaskDS->m_apoOverviewDS.clear();
    2436             :     }
    2437             : 
    2438           5 :     if (!SetDirectory())
    2439           0 :         return CE_Failure;
    2440             : 
    2441           5 :     return CE_None;
    2442             : }
    2443             : 
    2444             : /************************************************************************/
    2445             : /*                     RegisterNewOverviewDataset()                     */
    2446             : /************************************************************************/
    2447             : 
    2448         515 : CPLErr GTiffDataset::RegisterNewOverviewDataset(toff_t nOverviewOffset,
    2449             :                                                 int l_nJpegQuality,
    2450             :                                                 CSLConstList papszOptions)
    2451             : {
    2452             :     const auto GetOptionValue =
    2453        5665 :         [papszOptions](const char *pszOptionKey, const char *pszConfigOptionKey,
    2454       11329 :                        const char **ppszKeyUsed = nullptr)
    2455             :     {
    2456        5665 :         const char *pszVal = CSLFetchNameValue(papszOptions, pszOptionKey);
    2457        5665 :         if (pszVal)
    2458             :         {
    2459           1 :             if (ppszKeyUsed)
    2460           1 :                 *ppszKeyUsed = pszOptionKey;
    2461           1 :             return pszVal;
    2462             :         }
    2463        5664 :         pszVal = CSLFetchNameValue(papszOptions, pszConfigOptionKey);
    2464        5664 :         if (pszVal)
    2465             :         {
    2466           0 :             if (ppszKeyUsed)
    2467           0 :                 *ppszKeyUsed = pszConfigOptionKey;
    2468           0 :             return pszVal;
    2469             :         }
    2470        5664 :         if (pszConfigOptionKey)
    2471             :         {
    2472        5664 :             pszVal = CPLGetConfigOption(pszConfigOptionKey, nullptr);
    2473        5664 :             if (pszVal && ppszKeyUsed)
    2474          13 :                 *ppszKeyUsed = pszConfigOptionKey;
    2475             :         }
    2476        5664 :         return pszVal;
    2477         515 :     };
    2478             : 
    2479         515 :     int nZLevel = m_nZLevel;
    2480         515 :     if (const char *opt = GetOptionValue("ZLEVEL", "ZLEVEL_OVERVIEW"))
    2481             :     {
    2482           4 :         nZLevel = atoi(opt);
    2483             :     }
    2484             : 
    2485         515 :     int nZSTDLevel = m_nZSTDLevel;
    2486         515 :     if (const char *opt = GetOptionValue("ZSTD_LEVEL", "ZSTD_LEVEL_OVERVIEW"))
    2487             :     {
    2488           4 :         nZSTDLevel = atoi(opt);
    2489             :     }
    2490             : 
    2491         515 :     bool bWebpLossless = m_bWebPLossless;
    2492             :     const char *pszWebPLosslessOverview =
    2493         515 :         GetOptionValue("WEBP_LOSSLESS", "WEBP_LOSSLESS_OVERVIEW");
    2494         515 :     if (pszWebPLosslessOverview)
    2495             :     {
    2496           2 :         bWebpLossless = CPLTestBool(pszWebPLosslessOverview);
    2497             :     }
    2498             : 
    2499         515 :     int nWebpLevel = m_nWebPLevel;
    2500         515 :     const char *pszKeyWebpLevel = "";
    2501         515 :     if (const char *opt = GetOptionValue("WEBP_LEVEL", "WEBP_LEVEL_OVERVIEW",
    2502             :                                          &pszKeyWebpLevel))
    2503             :     {
    2504          14 :         if (pszWebPLosslessOverview == nullptr && m_bWebPLossless)
    2505             :         {
    2506           1 :             CPLDebug("GTiff",
    2507             :                      "%s specified, but not WEBP_LOSSLESS_OVERVIEW. "
    2508             :                      "Assuming WEBP_LOSSLESS_OVERVIEW=NO",
    2509             :                      pszKeyWebpLevel);
    2510           1 :             bWebpLossless = false;
    2511             :         }
    2512          13 :         else if (bWebpLossless)
    2513             :         {
    2514           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2515             :                      "%s is specified, but WEBP_LOSSLESS_OVERVIEW=YES. "
    2516             :                      "%s will be ignored.",
    2517             :                      pszKeyWebpLevel, pszKeyWebpLevel);
    2518             :         }
    2519          14 :         nWebpLevel = atoi(opt);
    2520             :     }
    2521             : 
    2522         515 :     double dfMaxZError = m_dfMaxZErrorOverview;
    2523         515 :     if (const char *opt = GetOptionValue("MAX_Z_ERROR", "MAX_Z_ERROR_OVERVIEW"))
    2524             :     {
    2525          20 :         dfMaxZError = CPLAtof(opt);
    2526             :     }
    2527             : 
    2528         515 :     signed char nJpegTablesMode = m_nJpegTablesMode;
    2529         515 :     if (const char *opt =
    2530         515 :             GetOptionValue("JPEG_TABLESMODE", "JPEG_TABLESMODE_OVERVIEW"))
    2531             :     {
    2532           0 :         nJpegTablesMode = static_cast<signed char>(atoi(opt));
    2533             :     }
    2534             : 
    2535             : #ifdef HAVE_JXL
    2536         515 :     bool bJXLLossless = m_bJXLLossless;
    2537         515 :     if (const char *opt =
    2538         515 :             GetOptionValue("JXL_LOSSLESS", "JXL_LOSSLESS_OVERVIEW"))
    2539             :     {
    2540           0 :         bJXLLossless = CPLTestBool(opt);
    2541             :     }
    2542             : 
    2543         515 :     float fJXLDistance = m_fJXLDistance;
    2544         515 :     if (const char *opt =
    2545         515 :             GetOptionValue("JXL_DISTANCE", "JXL_DISTANCE_OVERVIEW"))
    2546             :     {
    2547           0 :         fJXLDistance = static_cast<float>(CPLAtof(opt));
    2548             :     }
    2549             : 
    2550         515 :     float fJXLAlphaDistance = m_fJXLAlphaDistance;
    2551         515 :     if (const char *opt =
    2552         515 :             GetOptionValue("JXL_ALPHA_DISTANCE", "JXL_ALPHA_DISTANCE_OVERVIEW"))
    2553             :     {
    2554           0 :         fJXLAlphaDistance = static_cast<float>(CPLAtof(opt));
    2555             :     }
    2556             : 
    2557         515 :     int nJXLEffort = m_nJXLEffort;
    2558         515 :     if (const char *opt = GetOptionValue("JXL_EFFORT", "JXL_EFFORT_OVERVIEW"))
    2559             :     {
    2560           0 :         nJXLEffort = atoi(opt);
    2561             :     }
    2562             : #endif
    2563             : 
    2564        1030 :     auto poODS = std::make_shared<GTiffDataset>();
    2565         515 :     poODS->ShareLockWithParentDataset(this);
    2566         515 :     poODS->eAccess = GA_Update;
    2567         515 :     poODS->m_osFilename = m_osFilename;
    2568         515 :     const char *pszSparseOK = GetOptionValue("SPARSE_OK", "SPARSE_OK_OVERVIEW");
    2569         515 :     if (pszSparseOK && CPLTestBool(pszSparseOK))
    2570             :     {
    2571           1 :         poODS->m_bWriteEmptyTiles = false;
    2572           1 :         poODS->m_bFillEmptyTilesAtClosing = false;
    2573             :     }
    2574             :     else
    2575             :     {
    2576         514 :         poODS->m_bWriteEmptyTiles = m_bWriteEmptyTiles;
    2577         514 :         poODS->m_bFillEmptyTilesAtClosing = m_bFillEmptyTilesAtClosing;
    2578             :     }
    2579         515 :     poODS->m_nJpegQuality = static_cast<signed char>(l_nJpegQuality);
    2580         515 :     poODS->m_nWebPLevel = static_cast<signed char>(nWebpLevel);
    2581         515 :     poODS->m_nZLevel = static_cast<signed char>(nZLevel);
    2582         515 :     poODS->m_nLZMAPreset = m_nLZMAPreset;
    2583         515 :     poODS->m_nZSTDLevel = static_cast<signed char>(nZSTDLevel);
    2584         515 :     poODS->m_bWebPLossless = bWebpLossless;
    2585         515 :     poODS->m_nJpegTablesMode = nJpegTablesMode;
    2586         515 :     poODS->m_dfMaxZError = dfMaxZError;
    2587         515 :     poODS->m_dfMaxZErrorOverview = dfMaxZError;
    2588        1030 :     memcpy(poODS->m_anLercAddCompressionAndVersion,
    2589         515 :            m_anLercAddCompressionAndVersion,
    2590             :            sizeof(m_anLercAddCompressionAndVersion));
    2591             : #ifdef HAVE_JXL
    2592         515 :     poODS->m_bJXLLossless = bJXLLossless;
    2593         515 :     poODS->m_fJXLDistance = fJXLDistance;
    2594         515 :     poODS->m_fJXLAlphaDistance = fJXLAlphaDistance;
    2595         515 :     poODS->m_nJXLEffort = nJXLEffort;
    2596             : #endif
    2597             : 
    2598         515 :     if (poODS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF), nOverviewOffset,
    2599         515 :                           GA_Update) != CE_None)
    2600             :     {
    2601           0 :         return CE_Failure;
    2602             :     }
    2603             : 
    2604             :     // Assign color interpretation from main dataset
    2605         515 :     const int l_nBands = GetRasterCount();
    2606        1534 :     for (int i = 1; i <= l_nBands; i++)
    2607             :     {
    2608        1019 :         auto poBand = dynamic_cast<GTiffRasterBand *>(poODS->GetRasterBand(i));
    2609        1019 :         if (poBand)
    2610        1019 :             poBand->m_eBandInterp = GetRasterBand(i)->GetColorInterpretation();
    2611             :     }
    2612             : 
    2613             :     // Do that now that m_nCompression is set
    2614         515 :     poODS->RestoreVolatileParameters(poODS->m_hTIFF);
    2615             : 
    2616         515 :     poODS->m_poBaseDS = this;
    2617         515 :     poODS->m_bIsOverview = true;
    2618             : 
    2619         515 :     m_apoOverviewDS.push_back(std::move(poODS));
    2620         515 :     return CE_None;
    2621             : }
    2622             : 
    2623             : /************************************************************************/
    2624             : /*                        CreateTIFFColorTable()                        */
    2625             : /************************************************************************/
    2626             : 
    2627          12 : static void CreateTIFFColorTable(
    2628             :     GDALColorTable *poColorTable, int nBits, int nColorTableMultiplier,
    2629             :     std::vector<unsigned short> &anTRed, std::vector<unsigned short> &anTGreen,
    2630             :     std::vector<unsigned short> &anTBlue, unsigned short *&panRed,
    2631             :     unsigned short *&panGreen, unsigned short *&panBlue)
    2632             : {
    2633             :     int nColors;
    2634             : 
    2635          12 :     if (nBits == 8)
    2636          12 :         nColors = 256;
    2637           0 :     else if (nBits < 8)
    2638           0 :         nColors = 1 << nBits;
    2639             :     else
    2640           0 :         nColors = 65536;
    2641             : 
    2642          12 :     anTRed.resize(nColors, 0);
    2643          12 :     anTGreen.resize(nColors, 0);
    2644          12 :     anTBlue.resize(nColors, 0);
    2645             : 
    2646        3084 :     for (int iColor = 0; iColor < nColors; ++iColor)
    2647             :     {
    2648        3072 :         if (iColor < poColorTable->GetColorEntryCount())
    2649             :         {
    2650             :             GDALColorEntry sRGB;
    2651             : 
    2652        3072 :             poColorTable->GetColorEntryAsRGB(iColor, &sRGB);
    2653             : 
    2654        3072 :             anTRed[iColor] = GTiffDataset::ClampCTEntry(iColor, 1, sRGB.c1,
    2655             :                                                         nColorTableMultiplier);
    2656        3072 :             anTGreen[iColor] = GTiffDataset::ClampCTEntry(
    2657        3072 :                 iColor, 2, sRGB.c2, nColorTableMultiplier);
    2658        3072 :             anTBlue[iColor] = GTiffDataset::ClampCTEntry(iColor, 3, sRGB.c3,
    2659             :                                                          nColorTableMultiplier);
    2660             :         }
    2661             :         else
    2662             :         {
    2663           0 :             anTRed[iColor] = 0;
    2664           0 :             anTGreen[iColor] = 0;
    2665           0 :             anTBlue[iColor] = 0;
    2666             :         }
    2667             :     }
    2668             : 
    2669          12 :     panRed = &(anTRed[0]);
    2670          12 :     panGreen = &(anTGreen[0]);
    2671          12 :     panBlue = &(anTBlue[0]);
    2672          12 : }
    2673             : 
    2674             : /************************************************************************/
    2675             : /*                       GetOverviewParameters()                        */
    2676             : /************************************************************************/
    2677             : 
    2678         330 : bool GTiffDataset::GetOverviewParameters(
    2679             :     int &nCompression, uint16_t &nPlanarConfig, uint16_t &nPredictor,
    2680             :     uint16_t &nPhotometric, int &nOvrJpegQuality, std::string &osNoData,
    2681             :     uint16_t *&panExtraSampleValues, uint16_t &nExtraSamples,
    2682             :     CSLConstList papszOptions) const
    2683             : {
    2684             :     const auto GetOptionValue =
    2685        1094 :         [papszOptions](const char *pszOptionKey, const char *pszConfigOptionKey,
    2686        2180 :                        const char **ppszKeyUsed = nullptr)
    2687             :     {
    2688        1094 :         const char *pszVal = CSLFetchNameValue(papszOptions, pszOptionKey);
    2689        1094 :         if (pszVal)
    2690             :         {
    2691           8 :             if (ppszKeyUsed)
    2692           8 :                 *ppszKeyUsed = pszOptionKey;
    2693           8 :             return pszVal;
    2694             :         }
    2695        1086 :         pszVal = CSLFetchNameValue(papszOptions, pszConfigOptionKey);
    2696        1086 :         if (pszVal)
    2697             :         {
    2698           0 :             if (ppszKeyUsed)
    2699           0 :                 *ppszKeyUsed = pszConfigOptionKey;
    2700           0 :             return pszVal;
    2701             :         }
    2702        1086 :         pszVal = CPLGetConfigOption(pszConfigOptionKey, nullptr);
    2703        1086 :         if (pszVal && ppszKeyUsed)
    2704          60 :             *ppszKeyUsed = pszConfigOptionKey;
    2705        1086 :         return pszVal;
    2706         330 :     };
    2707             : 
    2708             :     /* -------------------------------------------------------------------- */
    2709             :     /*      Determine compression method.                                   */
    2710             :     /* -------------------------------------------------------------------- */
    2711         330 :     nCompression = m_nCompression;
    2712         330 :     const char *pszOptionKey = "";
    2713             :     const char *pszCompressValue =
    2714         330 :         GetOptionValue("COMPRESS", "COMPRESS_OVERVIEW", &pszOptionKey);
    2715         330 :     if (pszCompressValue != nullptr)
    2716             :     {
    2717          58 :         nCompression =
    2718          58 :             GTIFFGetCompressionMethod(pszCompressValue, pszOptionKey);
    2719          58 :         if (nCompression < 0)
    2720             :         {
    2721           0 :             nCompression = m_nCompression;
    2722             :         }
    2723             :     }
    2724             : 
    2725             :     /* -------------------------------------------------------------------- */
    2726             :     /*      Determine planar configuration.                                 */
    2727             :     /* -------------------------------------------------------------------- */
    2728         330 :     nPlanarConfig = m_nPlanarConfig;
    2729         330 :     if (nCompression == COMPRESSION_WEBP)
    2730             :     {
    2731          11 :         nPlanarConfig = PLANARCONFIG_CONTIG;
    2732             :     }
    2733             :     const char *pszInterleave =
    2734         330 :         GetOptionValue("INTERLEAVE", "INTERLEAVE_OVERVIEW", &pszOptionKey);
    2735         330 :     if (pszInterleave != nullptr && pszInterleave[0] != '\0')
    2736             :     {
    2737           2 :         if (EQUAL(pszInterleave, "PIXEL"))
    2738           1 :             nPlanarConfig = PLANARCONFIG_CONTIG;
    2739           1 :         else if (EQUAL(pszInterleave, "BAND"))
    2740           1 :             nPlanarConfig = PLANARCONFIG_SEPARATE;
    2741             :         else
    2742             :         {
    2743           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2744             :                      "%s=%s unsupported, "
    2745             :                      "value must be PIXEL or BAND. ignoring",
    2746             :                      pszOptionKey, pszInterleave);
    2747             :         }
    2748             :     }
    2749             : 
    2750             :     /* -------------------------------------------------------------------- */
    2751             :     /*      Determine predictor tag                                         */
    2752             :     /* -------------------------------------------------------------------- */
    2753         330 :     nPredictor = PREDICTOR_NONE;
    2754         330 :     if (GTIFFSupportsPredictor(nCompression))
    2755             :     {
    2756             :         const char *pszPredictor =
    2757          77 :             GetOptionValue("PREDICTOR", "PREDICTOR_OVERVIEW");
    2758          77 :         if (pszPredictor != nullptr)
    2759             :         {
    2760           1 :             nPredictor = static_cast<uint16_t>(atoi(pszPredictor));
    2761             :         }
    2762          76 :         else if (GTIFFSupportsPredictor(m_nCompression))
    2763          75 :             TIFFGetField(m_hTIFF, TIFFTAG_PREDICTOR, &nPredictor);
    2764             :     }
    2765             : 
    2766             :     /* -------------------------------------------------------------------- */
    2767             :     /*      Determine photometric tag                                       */
    2768             :     /* -------------------------------------------------------------------- */
    2769         330 :     if (m_nPhotometric == PHOTOMETRIC_YCBCR && nCompression != COMPRESSION_JPEG)
    2770           1 :         nPhotometric = PHOTOMETRIC_RGB;
    2771             :     else
    2772         329 :         nPhotometric = m_nPhotometric;
    2773             :     const char *pszPhotometric =
    2774         330 :         GetOptionValue("PHOTOMETRIC", "PHOTOMETRIC_OVERVIEW", &pszOptionKey);
    2775         330 :     if (!GTIFFUpdatePhotometric(pszPhotometric, pszOptionKey, nCompression,
    2776         330 :                                 pszInterleave, nBands, nPhotometric,
    2777             :                                 nPlanarConfig))
    2778             :     {
    2779           0 :         return false;
    2780             :     }
    2781             : 
    2782             :     /* -------------------------------------------------------------------- */
    2783             :     /*      Determine JPEG quality                                          */
    2784             :     /* -------------------------------------------------------------------- */
    2785         330 :     nOvrJpegQuality = m_nJpegQuality;
    2786         330 :     if (nCompression == COMPRESSION_JPEG)
    2787             :     {
    2788             :         const char *pszJPEGQuality =
    2789          27 :             GetOptionValue("JPEG_QUALITY", "JPEG_QUALITY_OVERVIEW");
    2790          27 :         if (pszJPEGQuality != nullptr)
    2791             :         {
    2792           9 :             nOvrJpegQuality = atoi(pszJPEGQuality);
    2793             :         }
    2794             :     }
    2795             : 
    2796             :     /* -------------------------------------------------------------------- */
    2797             :     /*      Set nodata.                                                     */
    2798             :     /* -------------------------------------------------------------------- */
    2799         330 :     if (m_bNoDataSet)
    2800             :     {
    2801          17 :         osNoData = GTiffFormatGDALNoDataTagValue(m_dfNoDataValue);
    2802             :     }
    2803             : 
    2804             :     /* -------------------------------------------------------------------- */
    2805             :     /*      Fetch extra sample tag                                          */
    2806             :     /* -------------------------------------------------------------------- */
    2807         330 :     panExtraSampleValues = nullptr;
    2808         330 :     nExtraSamples = 0;
    2809         330 :     if (TIFFGetField(m_hTIFF, TIFFTAG_EXTRASAMPLES, &nExtraSamples,
    2810         330 :                      &panExtraSampleValues))
    2811             :     {
    2812             :         uint16_t *panExtraSampleValuesNew = static_cast<uint16_t *>(
    2813          40 :             CPLMalloc(nExtraSamples * sizeof(uint16_t)));
    2814          40 :         memcpy(panExtraSampleValuesNew, panExtraSampleValues,
    2815          40 :                nExtraSamples * sizeof(uint16_t));
    2816          40 :         panExtraSampleValues = panExtraSampleValuesNew;
    2817             :     }
    2818             :     else
    2819             :     {
    2820         290 :         panExtraSampleValues = nullptr;
    2821         290 :         nExtraSamples = 0;
    2822             :     }
    2823             : 
    2824         330 :     return true;
    2825             : }
    2826             : 
    2827             : /************************************************************************/
    2828             : /*                  CreateOverviewsFromSrcOverviews()                   */
    2829             : /************************************************************************/
    2830             : 
    2831             : // If poOvrDS is not null, it is used and poSrcDS is ignored.
    2832             : 
    2833          71 : CPLErr GTiffDataset::CreateOverviewsFromSrcOverviews(GDALDataset *poSrcDS,
    2834             :                                                      GDALDataset *poOvrDS,
    2835             :                                                      int nOverviews)
    2836             : {
    2837          71 :     CPLAssert(poSrcDS->GetRasterCount() != 0);
    2838          71 :     CPLAssert(m_apoOverviewDS.empty());
    2839             : 
    2840          71 :     ScanDirectories();
    2841             : 
    2842          71 :     FlushDirectory();
    2843             : 
    2844          71 :     int nOvBitsPerSample = m_nBitsPerSample;
    2845             : 
    2846             :     /* -------------------------------------------------------------------- */
    2847             :     /*      Do we need some metadata for the overviews?                     */
    2848             :     /* -------------------------------------------------------------------- */
    2849         142 :     CPLString osMetadata;
    2850             : 
    2851          71 :     GTIFFBuildOverviewMetadata("NONE", this, false, osMetadata);
    2852             : 
    2853             :     int nCompression;
    2854             :     uint16_t nPlanarConfig;
    2855             :     uint16_t nPredictor;
    2856             :     uint16_t nPhotometric;
    2857             :     int nOvrJpegQuality;
    2858         142 :     std::string osNoData;
    2859          71 :     uint16_t *panExtraSampleValues = nullptr;
    2860          71 :     uint16_t nExtraSamples = 0;
    2861          71 :     if (!GetOverviewParameters(nCompression, nPlanarConfig, nPredictor,
    2862             :                                nPhotometric, nOvrJpegQuality, osNoData,
    2863             :                                panExtraSampleValues, nExtraSamples,
    2864             :                                /*papszOptions=*/nullptr))
    2865             :     {
    2866           0 :         return CE_Failure;
    2867             :     }
    2868             : 
    2869             :     /* -------------------------------------------------------------------- */
    2870             :     /*      Do we have a palette?  If so, create a TIFF compatible version. */
    2871             :     /* -------------------------------------------------------------------- */
    2872         142 :     std::vector<unsigned short> anTRed;
    2873         142 :     std::vector<unsigned short> anTGreen;
    2874          71 :     std::vector<unsigned short> anTBlue;
    2875          71 :     unsigned short *panRed = nullptr;
    2876          71 :     unsigned short *panGreen = nullptr;
    2877          71 :     unsigned short *panBlue = nullptr;
    2878             : 
    2879          71 :     if (nPhotometric == PHOTOMETRIC_PALETTE && m_poColorTable != nullptr)
    2880             :     {
    2881           0 :         if (m_nColorTableMultiplier == 0)
    2882           0 :             m_nColorTableMultiplier = DEFAULT_COLOR_TABLE_MULTIPLIER_257;
    2883             : 
    2884           0 :         CreateTIFFColorTable(m_poColorTable.get(), nOvBitsPerSample,
    2885             :                              m_nColorTableMultiplier, anTRed, anTGreen, anTBlue,
    2886             :                              panRed, panGreen, panBlue);
    2887             :     }
    2888             : 
    2889          71 :     int nOvrBlockXSize = 0;
    2890          71 :     int nOvrBlockYSize = 0;
    2891          71 :     GTIFFGetOverviewBlockSize(GDALRasterBand::ToHandle(GetRasterBand(1)),
    2892             :                               &nOvrBlockXSize, &nOvrBlockYSize, nullptr,
    2893             :                               nullptr);
    2894             : 
    2895          71 :     CPLErr eErr = CE_None;
    2896             : 
    2897         202 :     for (int i = 0; i < nOverviews && eErr == CE_None; ++i)
    2898             :     {
    2899             :         GDALRasterBand *poOvrBand =
    2900         171 :             poOvrDS ? ((i == 0) ? poOvrDS->GetRasterBand(1)
    2901          40 :                                 : poOvrDS->GetRasterBand(1)->GetOverview(i - 1))
    2902          55 :                     : poSrcDS->GetRasterBand(1)->GetOverview(i);
    2903             : 
    2904         131 :         int nOXSize = poOvrBand->GetXSize();
    2905         131 :         int nOYSize = poOvrBand->GetYSize();
    2906             : 
    2907         262 :         toff_t nOverviewOffset = GTIFFWriteDirectory(
    2908             :             m_hTIFF, FILETYPE_REDUCEDIMAGE, nOXSize, nOYSize, nOvBitsPerSample,
    2909         131 :             nPlanarConfig, m_nSamplesPerPixel, nOvrBlockXSize, nOvrBlockYSize,
    2910         131 :             TRUE, nCompression, nPhotometric, m_nSampleFormat, nPredictor,
    2911             :             panRed, panGreen, panBlue, nExtraSamples, panExtraSampleValues,
    2912             :             osMetadata,
    2913         131 :             nOvrJpegQuality >= 0 ? CPLSPrintf("%d", nOvrJpegQuality) : nullptr,
    2914         131 :             CPLSPrintf("%d", m_nJpegTablesMode),
    2915           2 :             osNoData.empty() ? nullptr : osNoData.c_str(),
    2916         131 :             m_anLercAddCompressionAndVersion, m_bWriteCOGLayout);
    2917             : 
    2918         131 :         if (nOverviewOffset == 0)
    2919           0 :             eErr = CE_Failure;
    2920             :         else
    2921         131 :             eErr = RegisterNewOverviewDataset(nOverviewOffset, nOvrJpegQuality,
    2922             :                                               nullptr);
    2923             :     }
    2924             : 
    2925             :     // For directory reloading, so that the chaining to the next directory is
    2926             :     // reloaded, as well as compression parameters.
    2927          71 :     ReloadDirectory();
    2928             : 
    2929          71 :     CPLFree(panExtraSampleValues);
    2930          71 :     panExtraSampleValues = nullptr;
    2931             : 
    2932          71 :     return eErr;
    2933             : }
    2934             : 
    2935             : /************************************************************************/
    2936             : /*                    CreateInternalMaskOverviews()                     */
    2937             : /************************************************************************/
    2938             : 
    2939         274 : CPLErr GTiffDataset::CreateInternalMaskOverviews(int nOvrBlockXSize,
    2940             :                                                  int nOvrBlockYSize)
    2941             : {
    2942         274 :     ScanDirectories();
    2943             : 
    2944             :     /* -------------------------------------------------------------------- */
    2945             :     /*      Create overviews for the mask.                                  */
    2946             :     /* -------------------------------------------------------------------- */
    2947         274 :     CPLErr eErr = CE_None;
    2948             : 
    2949         274 :     if (m_poMaskDS != nullptr && m_poMaskDS->GetRasterCount() == 1)
    2950             :     {
    2951             :         int nMaskOvrCompression;
    2952          43 :         if (strstr(GDALGetMetadataItem(GDALGetDriverByName("GTiff"),
    2953             :                                        GDAL_DMD_CREATIONOPTIONLIST, nullptr),
    2954          43 :                    "<Value>DEFLATE</Value>") != nullptr)
    2955          43 :             nMaskOvrCompression = COMPRESSION_ADOBE_DEFLATE;
    2956             :         else
    2957           0 :             nMaskOvrCompression = COMPRESSION_PACKBITS;
    2958             : 
    2959         115 :         for (auto &poOvrDS : m_apoOverviewDS)
    2960             :         {
    2961          72 :             if (poOvrDS->m_poMaskDS == nullptr)
    2962             :             {
    2963          60 :                 const toff_t nOverviewOffset = GTIFFWriteDirectory(
    2964             :                     m_hTIFF, FILETYPE_REDUCEDIMAGE | FILETYPE_MASK,
    2965          60 :                     poOvrDS->nRasterXSize, poOvrDS->nRasterYSize, 1,
    2966             :                     PLANARCONFIG_CONTIG, 1, nOvrBlockXSize, nOvrBlockYSize,
    2967             :                     TRUE, nMaskOvrCompression, PHOTOMETRIC_MASK,
    2968             :                     SAMPLEFORMAT_UINT, PREDICTOR_NONE, nullptr, nullptr,
    2969             :                     nullptr, 0, nullptr, "", nullptr, nullptr, nullptr, nullptr,
    2970          60 :                     m_bWriteCOGLayout);
    2971             : 
    2972          60 :                 if (nOverviewOffset == 0)
    2973             :                 {
    2974           0 :                     eErr = CE_Failure;
    2975           0 :                     continue;
    2976             :                 }
    2977             : 
    2978         120 :                 auto poMaskODS = std::make_shared<GTiffDataset>();
    2979          60 :                 poMaskODS->eAccess = GA_Update;
    2980          60 :                 poMaskODS->ShareLockWithParentDataset(this);
    2981          60 :                 poMaskODS->m_osFilename = m_osFilename;
    2982          60 :                 if (poMaskODS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF),
    2983             :                                           nOverviewOffset,
    2984          60 :                                           GA_Update) != CE_None)
    2985             :                 {
    2986           0 :                     eErr = CE_Failure;
    2987             :                 }
    2988             :                 else
    2989             :                 {
    2990         120 :                     poMaskODS->m_bPromoteTo8Bits =
    2991          60 :                         CPLTestBool(CPLGetConfigOption(
    2992             :                             "GDAL_TIFF_INTERNAL_MASK_TO_8BIT", "YES"));
    2993          60 :                     poMaskODS->m_poBaseDS = this;
    2994          60 :                     poMaskODS->m_poImageryDS = poOvrDS.get();
    2995          60 :                     poOvrDS->m_poMaskDS = poMaskODS;
    2996          60 :                     m_poMaskDS->m_apoOverviewDS.push_back(std::move(poMaskODS));
    2997             :                 }
    2998             :             }
    2999             :         }
    3000             :     }
    3001             : 
    3002         274 :     ReloadDirectory();
    3003             : 
    3004         274 :     return eErr;
    3005             : }
    3006             : 
    3007             : /************************************************************************/
    3008             : /*                            AddOverviews()                            */
    3009             : /************************************************************************/
    3010             : 
    3011             : CPLErr
    3012          13 : GTiffDataset::AddOverviews(const std::vector<GDALDataset *> &apoSrcOvrDSIn,
    3013             :                            GDALProgressFunc pfnProgress, void *pProgressData,
    3014             :                            CSLConstList papszOptions)
    3015             : {
    3016             :     /* -------------------------------------------------------------------- */
    3017             :     /*      If we don't have read access, then create the overviews         */
    3018             :     /*      externally.                                                     */
    3019             :     /* -------------------------------------------------------------------- */
    3020          13 :     if (GetAccess() != GA_Update)
    3021             :     {
    3022           4 :         CPLDebug("GTiff", "File open for read-only accessing, "
    3023             :                           "creating overviews externally.");
    3024             : 
    3025           4 :         CPLErr eErr = GDALDataset::AddOverviews(apoSrcOvrDSIn, pfnProgress,
    3026             :                                                 pProgressData, papszOptions);
    3027           4 :         if (eErr == CE_None && m_poMaskDS)
    3028             :         {
    3029           0 :             ReportError(
    3030             :                 CE_Warning, CPLE_NotSupported,
    3031             :                 "Building external overviews whereas there is an internal "
    3032             :                 "mask is not fully supported. "
    3033             :                 "The overviews of the non-mask bands will be created, "
    3034             :                 "but not the overviews of the mask band.");
    3035             :         }
    3036           4 :         return eErr;
    3037             :     }
    3038             : 
    3039          18 :     std::vector<GDALDataset *> apoSrcOvrDS = apoSrcOvrDSIn;
    3040             :     // Sort overviews by descending size
    3041           9 :     std::sort(apoSrcOvrDS.begin(), apoSrcOvrDS.end(),
    3042           0 :               [](const GDALDataset *poDS1, const GDALDataset *poDS2)
    3043           0 :               { return poDS1->GetRasterXSize() > poDS2->GetRasterXSize(); });
    3044             : 
    3045           9 :     if (!GDALDefaultOverviews::CheckSrcOverviewsConsistencyWithBase(
    3046             :             this, apoSrcOvrDS))
    3047           5 :         return CE_Failure;
    3048             : 
    3049           4 :     ScanDirectories();
    3050             : 
    3051             :     // Make implicit JPEG overviews invisible, but do not destroy
    3052             :     // them in case they are already used (not sure that the client
    3053             :     // has the right to do that). Behavior maybe undefined in GDAL API.
    3054           4 :     std::swap(m_apoJPEGOverviewDSOld, m_apoJPEGOverviewDS);
    3055           4 :     m_apoJPEGOverviewDS.clear();
    3056             : 
    3057           4 :     FlushDirectory();
    3058             : 
    3059             :     /* -------------------------------------------------------------------- */
    3060             :     /*      If we are averaging bit data to grayscale we need to create     */
    3061             :     /*      8bit overviews.                                                 */
    3062             :     /* -------------------------------------------------------------------- */
    3063           4 :     int nOvBitsPerSample = m_nBitsPerSample;
    3064             : 
    3065             :     /* -------------------------------------------------------------------- */
    3066             :     /*      Do we need some metadata for the overviews?                     */
    3067             :     /* -------------------------------------------------------------------- */
    3068           8 :     CPLString osMetadata;
    3069             : 
    3070           4 :     const bool bIsForMaskBand = nBands == 1 && GetRasterBand(1)->IsMaskBand();
    3071           4 :     GTIFFBuildOverviewMetadata(/* resampling = */ "", this, bIsForMaskBand,
    3072             :                                osMetadata);
    3073             : 
    3074             :     int nCompression;
    3075             :     uint16_t nPlanarConfig;
    3076             :     uint16_t nPredictor;
    3077             :     uint16_t nPhotometric;
    3078             :     int nOvrJpegQuality;
    3079           8 :     std::string osNoData;
    3080           4 :     uint16_t *panExtraSampleValues = nullptr;
    3081           4 :     uint16_t nExtraSamples = 0;
    3082           4 :     if (!GetOverviewParameters(nCompression, nPlanarConfig, nPredictor,
    3083             :                                nPhotometric, nOvrJpegQuality, osNoData,
    3084             :                                panExtraSampleValues, nExtraSamples,
    3085             :                                papszOptions))
    3086             :     {
    3087           0 :         return CE_Failure;
    3088             :     }
    3089             : 
    3090             :     /* -------------------------------------------------------------------- */
    3091             :     /*      Do we have a palette?  If so, create a TIFF compatible version. */
    3092             :     /* -------------------------------------------------------------------- */
    3093           8 :     std::vector<unsigned short> anTRed;
    3094           8 :     std::vector<unsigned short> anTGreen;
    3095           4 :     std::vector<unsigned short> anTBlue;
    3096           4 :     unsigned short *panRed = nullptr;
    3097           4 :     unsigned short *panGreen = nullptr;
    3098           4 :     unsigned short *panBlue = nullptr;
    3099             : 
    3100           4 :     if (nPhotometric == PHOTOMETRIC_PALETTE && m_poColorTable != nullptr)
    3101             :     {
    3102           0 :         if (m_nColorTableMultiplier == 0)
    3103           0 :             m_nColorTableMultiplier = DEFAULT_COLOR_TABLE_MULTIPLIER_257;
    3104             : 
    3105           0 :         CreateTIFFColorTable(m_poColorTable.get(), nOvBitsPerSample,
    3106             :                              m_nColorTableMultiplier, anTRed, anTGreen, anTBlue,
    3107             :                              panRed, panGreen, panBlue);
    3108             :     }
    3109             : 
    3110             :     /* -------------------------------------------------------------------- */
    3111             :     /*      Establish which of the overview levels we already have, and     */
    3112             :     /*      which are new.  We assume that band 1 of the file is            */
    3113             :     /*      representative.                                                 */
    3114             :     /* -------------------------------------------------------------------- */
    3115           4 :     int nOvrBlockXSize = 0;
    3116           4 :     int nOvrBlockYSize = 0;
    3117           4 :     GTIFFGetOverviewBlockSize(GDALRasterBand::ToHandle(GetRasterBand(1)),
    3118             :                               &nOvrBlockXSize, &nOvrBlockYSize, papszOptions,
    3119             :                               "BLOCKSIZE");
    3120             : 
    3121           4 :     CPLErr eErr = CE_None;
    3122           8 :     for (const auto *poSrcOvrDS : apoSrcOvrDS)
    3123             :     {
    3124           4 :         bool bFound = false;
    3125           4 :         for (auto &poOvrDS : m_apoOverviewDS)
    3126             :         {
    3127           4 :             if (poOvrDS->GetRasterXSize() == poSrcOvrDS->GetRasterXSize() &&
    3128           2 :                 poOvrDS->GetRasterYSize() == poSrcOvrDS->GetRasterYSize())
    3129             :             {
    3130           2 :                 bFound = true;
    3131           2 :                 break;
    3132             :             }
    3133             :         }
    3134           4 :         if (!bFound && eErr == CE_None)
    3135             :         {
    3136           2 :             if (m_bLayoutIFDSBeforeData && !m_bKnownIncompatibleEdition &&
    3137           0 :                 !m_bWriteKnownIncompatibleEdition)
    3138             :             {
    3139           0 :                 ReportError(CE_Warning, CPLE_AppDefined,
    3140             :                             "Adding new overviews invalidates the "
    3141             :                             "LAYOUT=IFDS_BEFORE_DATA property");
    3142           0 :                 m_bKnownIncompatibleEdition = true;
    3143           0 :                 m_bWriteKnownIncompatibleEdition = true;
    3144             :             }
    3145             : 
    3146           6 :             const toff_t nOverviewOffset = GTIFFWriteDirectory(
    3147             :                 m_hTIFF, FILETYPE_REDUCEDIMAGE, poSrcOvrDS->GetRasterXSize(),
    3148             :                 poSrcOvrDS->GetRasterYSize(), nOvBitsPerSample, nPlanarConfig,
    3149           2 :                 m_nSamplesPerPixel, nOvrBlockXSize, nOvrBlockYSize, TRUE,
    3150           2 :                 nCompression, nPhotometric, m_nSampleFormat, nPredictor, panRed,
    3151             :                 panGreen, panBlue, nExtraSamples, panExtraSampleValues,
    3152             :                 osMetadata,
    3153           2 :                 nOvrJpegQuality >= 0 ? CPLSPrintf("%d", nOvrJpegQuality)
    3154             :                                      : nullptr,
    3155           2 :                 CPLSPrintf("%d", m_nJpegTablesMode),
    3156           0 :                 osNoData.empty() ? nullptr : osNoData.c_str(),
    3157           2 :                 m_anLercAddCompressionAndVersion, false);
    3158             : 
    3159           2 :             if (nOverviewOffset == 0)
    3160           0 :                 eErr = CE_Failure;
    3161             :             else
    3162           2 :                 eErr = RegisterNewOverviewDataset(
    3163             :                     nOverviewOffset, nOvrJpegQuality, papszOptions);
    3164             :         }
    3165             :     }
    3166             : 
    3167           4 :     CPLFree(panExtraSampleValues);
    3168           4 :     panExtraSampleValues = nullptr;
    3169             : 
    3170           4 :     ReloadDirectory();
    3171             : 
    3172           4 :     if (!pfnProgress)
    3173           2 :         pfnProgress = GDALDummyProgress;
    3174             : 
    3175             :     // almost 0, but not 0 to please Coverity Scan
    3176           4 :     double dfTotalPixels = std::numeric_limits<double>::min();
    3177           8 :     for (const auto *poSrcOvrDS : apoSrcOvrDS)
    3178             :     {
    3179           4 :         dfTotalPixels += static_cast<double>(poSrcOvrDS->GetRasterXSize()) *
    3180           4 :                          poSrcOvrDS->GetRasterYSize();
    3181             :     }
    3182             : 
    3183             :     // Copy source datasets into target overview datasets
    3184           4 :     double dfCurPixels = 0;
    3185           8 :     for (auto *poSrcOvrDS : apoSrcOvrDS)
    3186             :     {
    3187           4 :         GDALDataset *poDstOvrDS = nullptr;
    3188           4 :         for (auto &poOvrDS : m_apoOverviewDS)
    3189             :         {
    3190           8 :             if (poOvrDS->GetRasterXSize() == poSrcOvrDS->GetRasterXSize() &&
    3191           4 :                 poOvrDS->GetRasterYSize() == poSrcOvrDS->GetRasterYSize())
    3192             :             {
    3193           4 :                 poDstOvrDS = poOvrDS.get();
    3194           4 :                 break;
    3195             :             }
    3196             :         }
    3197           4 :         if (eErr == CE_None && poDstOvrDS)
    3198             :         {
    3199             :             const double dfThisPixels =
    3200           4 :                 static_cast<double>(poSrcOvrDS->GetRasterXSize()) *
    3201           4 :                 poSrcOvrDS->GetRasterYSize();
    3202           8 :             void *pScaledProgressData = GDALCreateScaledProgress(
    3203             :                 dfCurPixels / dfTotalPixels,
    3204           4 :                 (dfCurPixels + dfThisPixels) / dfTotalPixels, pfnProgress,
    3205             :                 pProgressData);
    3206           4 :             dfCurPixels += dfThisPixels;
    3207           4 :             eErr = GDALDatasetCopyWholeRaster(GDALDataset::ToHandle(poSrcOvrDS),
    3208             :                                               GDALDataset::ToHandle(poDstOvrDS),
    3209             :                                               nullptr, GDALScaledProgress,
    3210             :                                               pScaledProgressData);
    3211           4 :             GDALDestroyScaledProgress(pScaledProgressData);
    3212             :         }
    3213             :     }
    3214             : 
    3215           4 :     return eErr;
    3216             : }
    3217             : 
    3218             : /************************************************************************/
    3219             : /*                          IBuildOverviews()                           */
    3220             : /************************************************************************/
    3221             : 
    3222         409 : CPLErr GTiffDataset::IBuildOverviews(const char *pszResampling, int nOverviews,
    3223             :                                      const int *panOverviewList, int nBandsIn,
    3224             :                                      const int *panBandList,
    3225             :                                      GDALProgressFunc pfnProgress,
    3226             :                                      void *pProgressData,
    3227             :                                      CSLConstList papszOptions)
    3228             : 
    3229             : {
    3230         409 :     ScanDirectories();
    3231             : 
    3232             :     // Make implicit JPEG overviews invisible, but do not destroy
    3233             :     // them in case they are already used (not sure that the client
    3234             :     // has the right to do that.  Behavior maybe undefined in GDAL API.
    3235         409 :     std::swap(m_apoJPEGOverviewDSOld, m_apoJPEGOverviewDS);
    3236         409 :     m_apoJPEGOverviewDS.clear();
    3237             : 
    3238             :     /* -------------------------------------------------------------------- */
    3239             :     /*      If RRD or external OVR overviews requested, then invoke         */
    3240             :     /*      generic handling.                                               */
    3241             :     /* -------------------------------------------------------------------- */
    3242         409 :     bool bUseGenericHandling = false;
    3243         409 :     bool bUseRRD = false;
    3244         818 :     CPLStringList aosOptions(papszOptions);
    3245             : 
    3246         409 :     const char *pszLocation = CSLFetchNameValue(papszOptions, "LOCATION");
    3247         409 :     if (pszLocation && EQUAL(pszLocation, "EXTERNAL"))
    3248             :     {
    3249           1 :         bUseGenericHandling = true;
    3250             :     }
    3251         408 :     else if (pszLocation && EQUAL(pszLocation, "INTERNAL"))
    3252             :     {
    3253           0 :         if (GetAccess() != GA_Update)
    3254             :         {
    3255           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    3256             :                      "Cannot create internal overviews on file opened in "
    3257             :                      "read-only mode");
    3258           0 :             return CE_Failure;
    3259             :         }
    3260             :     }
    3261         408 :     else if (pszLocation && EQUAL(pszLocation, "RRD"))
    3262             :     {
    3263           3 :         bUseGenericHandling = true;
    3264           3 :         bUseRRD = true;
    3265           3 :         aosOptions.SetNameValue("USE_RRD", "YES");
    3266             :     }
    3267             :     // Legacy
    3268         405 :     else if ((bUseRRD = CPLTestBool(
    3269             :                   CSLFetchNameValueDef(papszOptions, "USE_RRD",
    3270         810 :                                        CPLGetConfigOption("USE_RRD", "NO")))) ||
    3271         405 :              CPLTestBool(CSLFetchNameValueDef(
    3272             :                  papszOptions, "TIFF_USE_OVR",
    3273             :                  CPLGetConfigOption("TIFF_USE_OVR", "NO"))))
    3274             :     {
    3275           0 :         bUseGenericHandling = true;
    3276             :     }
    3277             : 
    3278             :     /* -------------------------------------------------------------------- */
    3279             :     /*      If we don't have read access, then create the overviews         */
    3280             :     /*      externally.                                                     */
    3281             :     /* -------------------------------------------------------------------- */
    3282         409 :     if (GetAccess() != GA_Update)
    3283             :     {
    3284         143 :         CPLDebug("GTiff", "File open for read-only accessing, "
    3285             :                           "creating overviews externally.");
    3286             : 
    3287         143 :         bUseGenericHandling = true;
    3288             :     }
    3289             : 
    3290         409 :     if (bUseGenericHandling)
    3291             :     {
    3292         146 :         if (!m_apoOverviewDS.empty())
    3293             :         {
    3294           0 :             ReportError(CE_Failure, CPLE_NotSupported,
    3295             :                         "Cannot add external overviews when there are already "
    3296             :                         "internal overviews");
    3297           0 :             return CE_Failure;
    3298             :         }
    3299             : 
    3300         146 :         if (!m_bWriteEmptyTiles && !bUseRRD)
    3301             :         {
    3302           1 :             aosOptions.SetNameValue("SPARSE_OK", "YES");
    3303             :         }
    3304             : 
    3305         146 :         CPLErr eErr = GDALDataset::IBuildOverviews(
    3306             :             pszResampling, nOverviews, panOverviewList, nBandsIn, panBandList,
    3307         146 :             pfnProgress, pProgressData, aosOptions);
    3308         146 :         if (eErr == CE_None && m_poMaskDS)
    3309             :         {
    3310           1 :             ReportError(
    3311             :                 CE_Warning, CPLE_NotSupported,
    3312             :                 "Building external overviews whereas there is an internal "
    3313             :                 "mask is not fully supported. "
    3314             :                 "The overviews of the non-mask bands will be created, "
    3315             :                 "but not the overviews of the mask band.");
    3316             :         }
    3317         146 :         return eErr;
    3318             :     }
    3319             : 
    3320             :     /* -------------------------------------------------------------------- */
    3321             :     /*      Our TIFF overview support currently only works safely if all    */
    3322             :     /*      bands are handled at the same time.                             */
    3323             :     /* -------------------------------------------------------------------- */
    3324         263 :     if (nBandsIn != GetRasterCount())
    3325             :     {
    3326           0 :         ReportError(CE_Failure, CPLE_NotSupported,
    3327             :                     "Generation of overviews in TIFF currently only "
    3328             :                     "supported when operating on all bands.  "
    3329             :                     "Operation failed.");
    3330           0 :         return CE_Failure;
    3331             :     }
    3332             : 
    3333             :     /* -------------------------------------------------------------------- */
    3334             :     /*      If zero overviews were requested, we need to clear all          */
    3335             :     /*      existing overviews.                                             */
    3336             :     /* -------------------------------------------------------------------- */
    3337         263 :     if (nOverviews == 0)
    3338             :     {
    3339           8 :         if (m_apoOverviewDS.empty())
    3340           3 :             return GDALDataset::IBuildOverviews(
    3341             :                 pszResampling, nOverviews, panOverviewList, nBandsIn,
    3342           3 :                 panBandList, pfnProgress, pProgressData, papszOptions);
    3343             : 
    3344           5 :         return CleanOverviews();
    3345             :     }
    3346             : 
    3347         255 :     CPLErr eErr = CE_None;
    3348             : 
    3349             :     /* -------------------------------------------------------------------- */
    3350             :     /*      Initialize progress counter.                                    */
    3351             :     /* -------------------------------------------------------------------- */
    3352         255 :     if (!pfnProgress(0.0, nullptr, pProgressData))
    3353             :     {
    3354           0 :         ReportError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    3355           0 :         return CE_Failure;
    3356             :     }
    3357             : 
    3358         255 :     FlushDirectory();
    3359             : 
    3360             :     /* -------------------------------------------------------------------- */
    3361             :     /*      If we are averaging bit data to grayscale we need to create     */
    3362             :     /*      8bit overviews.                                                 */
    3363             :     /* -------------------------------------------------------------------- */
    3364         255 :     int nOvBitsPerSample = m_nBitsPerSample;
    3365             : 
    3366         255 :     if (STARTS_WITH_CI(pszResampling, "AVERAGE_BIT2"))
    3367           2 :         nOvBitsPerSample = 8;
    3368             : 
    3369             :     /* -------------------------------------------------------------------- */
    3370             :     /*      Do we need some metadata for the overviews?                     */
    3371             :     /* -------------------------------------------------------------------- */
    3372         510 :     CPLString osMetadata;
    3373             : 
    3374         255 :     const bool bIsForMaskBand = nBands == 1 && GetRasterBand(1)->IsMaskBand();
    3375         255 :     GTIFFBuildOverviewMetadata(pszResampling, this, bIsForMaskBand, osMetadata);
    3376             : 
    3377             :     int nCompression;
    3378             :     uint16_t nPlanarConfig;
    3379             :     uint16_t nPredictor;
    3380             :     uint16_t nPhotometric;
    3381             :     int nOvrJpegQuality;
    3382         510 :     std::string osNoData;
    3383         255 :     uint16_t *panExtraSampleValues = nullptr;
    3384         255 :     uint16_t nExtraSamples = 0;
    3385         255 :     if (!GetOverviewParameters(nCompression, nPlanarConfig, nPredictor,
    3386             :                                nPhotometric, nOvrJpegQuality, osNoData,
    3387             :                                panExtraSampleValues, nExtraSamples,
    3388             :                                papszOptions))
    3389             :     {
    3390           0 :         return CE_Failure;
    3391             :     }
    3392             : 
    3393             :     /* -------------------------------------------------------------------- */
    3394             :     /*      Do we have a palette?  If so, create a TIFF compatible version. */
    3395             :     /* -------------------------------------------------------------------- */
    3396         510 :     std::vector<unsigned short> anTRed;
    3397         510 :     std::vector<unsigned short> anTGreen;
    3398         510 :     std::vector<unsigned short> anTBlue;
    3399         255 :     unsigned short *panRed = nullptr;
    3400         255 :     unsigned short *panGreen = nullptr;
    3401         255 :     unsigned short *panBlue = nullptr;
    3402             : 
    3403         255 :     if (nPhotometric == PHOTOMETRIC_PALETTE && m_poColorTable != nullptr)
    3404             :     {
    3405          12 :         if (m_nColorTableMultiplier == 0)
    3406           0 :             m_nColorTableMultiplier = DEFAULT_COLOR_TABLE_MULTIPLIER_257;
    3407             : 
    3408          12 :         CreateTIFFColorTable(m_poColorTable.get(), nOvBitsPerSample,
    3409             :                              m_nColorTableMultiplier, anTRed, anTGreen, anTBlue,
    3410             :                              panRed, panGreen, panBlue);
    3411             :     }
    3412             : 
    3413             :     /* -------------------------------------------------------------------- */
    3414             :     /*      Establish which of the overview levels we already have, and     */
    3415             :     /*      which are new.  We assume that band 1 of the file is            */
    3416             :     /*      representative.                                                 */
    3417             :     /* -------------------------------------------------------------------- */
    3418         255 :     int nOvrBlockXSize = 0;
    3419         255 :     int nOvrBlockYSize = 0;
    3420         255 :     GTIFFGetOverviewBlockSize(GDALRasterBand::ToHandle(GetRasterBand(1)),
    3421             :                               &nOvrBlockXSize, &nOvrBlockYSize, papszOptions,
    3422             :                               "BLOCKSIZE");
    3423         510 :     std::vector<bool> abRequireNewOverview(nOverviews, true);
    3424         693 :     for (int i = 0; i < nOverviews && eErr == CE_None; ++i)
    3425             :     {
    3426         770 :         for (auto &poODS : m_apoOverviewDS)
    3427             :         {
    3428             :             const int nOvFactor =
    3429         776 :                 GDALComputeOvFactor(poODS->GetRasterXSize(), GetRasterXSize(),
    3430         388 :                                     poODS->GetRasterYSize(), GetRasterYSize());
    3431             : 
    3432             :             // If we already have a 1x1 overview and this new one would result
    3433             :             // in it too, then don't create it.
    3434         448 :             if (poODS->GetRasterXSize() == 1 && poODS->GetRasterYSize() == 1 &&
    3435         448 :                 DIV_ROUND_UP(GetRasterXSize(), panOverviewList[i]) == 1 &&
    3436          21 :                 DIV_ROUND_UP(GetRasterYSize(), panOverviewList[i]) == 1)
    3437             :             {
    3438          21 :                 abRequireNewOverview[i] = false;
    3439          21 :                 break;
    3440             :             }
    3441             : 
    3442         699 :             if (nOvFactor == panOverviewList[i] ||
    3443         332 :                 nOvFactor == GDALOvLevelAdjust2(panOverviewList[i],
    3444             :                                                 GetRasterXSize(),
    3445             :                                                 GetRasterYSize()))
    3446             :             {
    3447          35 :                 abRequireNewOverview[i] = false;
    3448          35 :                 break;
    3449             :             }
    3450             :         }
    3451             : 
    3452         438 :         if (abRequireNewOverview[i])
    3453             :         {
    3454         382 :             if (m_bLayoutIFDSBeforeData && !m_bKnownIncompatibleEdition &&
    3455           2 :                 !m_bWriteKnownIncompatibleEdition)
    3456             :             {
    3457           2 :                 ReportError(CE_Warning, CPLE_AppDefined,
    3458             :                             "Adding new overviews invalidates the "
    3459             :                             "LAYOUT=IFDS_BEFORE_DATA property");
    3460           2 :                 m_bKnownIncompatibleEdition = true;
    3461           2 :                 m_bWriteKnownIncompatibleEdition = true;
    3462             :             }
    3463             : 
    3464             :             const int nOXSize =
    3465         382 :                 DIV_ROUND_UP(GetRasterXSize(), panOverviewList[i]);
    3466             :             const int nOYSize =
    3467         382 :                 DIV_ROUND_UP(GetRasterYSize(), panOverviewList[i]);
    3468             : 
    3469         764 :             const toff_t nOverviewOffset = GTIFFWriteDirectory(
    3470             :                 m_hTIFF, FILETYPE_REDUCEDIMAGE, nOXSize, nOYSize,
    3471         382 :                 nOvBitsPerSample, nPlanarConfig, m_nSamplesPerPixel,
    3472             :                 nOvrBlockXSize, nOvrBlockYSize, TRUE, nCompression,
    3473         382 :                 nPhotometric, m_nSampleFormat, nPredictor, panRed, panGreen,
    3474             :                 panBlue, nExtraSamples, panExtraSampleValues, osMetadata,
    3475         382 :                 nOvrJpegQuality >= 0 ? CPLSPrintf("%d", nOvrJpegQuality)
    3476             :                                      : nullptr,
    3477         382 :                 CPLSPrintf("%d", m_nJpegTablesMode),
    3478          25 :                 osNoData.empty() ? nullptr : osNoData.c_str(),
    3479         382 :                 m_anLercAddCompressionAndVersion, false);
    3480             : 
    3481         382 :             if (nOverviewOffset == 0)
    3482           0 :                 eErr = CE_Failure;
    3483             :             else
    3484         382 :                 eErr = RegisterNewOverviewDataset(
    3485             :                     nOverviewOffset, nOvrJpegQuality, papszOptions);
    3486             :         }
    3487             :     }
    3488             : 
    3489         255 :     CPLFree(panExtraSampleValues);
    3490         255 :     panExtraSampleValues = nullptr;
    3491             : 
    3492         255 :     ReloadDirectory();
    3493             : 
    3494             :     /* -------------------------------------------------------------------- */
    3495             :     /*      Create overviews for the mask.                                  */
    3496             :     /* -------------------------------------------------------------------- */
    3497         255 :     if (eErr != CE_None)
    3498           0 :         return eErr;
    3499             : 
    3500         255 :     eErr = CreateInternalMaskOverviews(nOvrBlockXSize, nOvrBlockYSize);
    3501             : 
    3502             :     /* -------------------------------------------------------------------- */
    3503             :     /*      Refresh overviews for the mask                                  */
    3504             :     /* -------------------------------------------------------------------- */
    3505             :     const bool bHasInternalMask =
    3506         255 :         m_poMaskDS != nullptr && m_poMaskDS->GetRasterCount() == 1;
    3507             :     const bool bHasExternalMask =
    3508         255 :         !bHasInternalMask && oOvManager.HaveMaskFile();
    3509         255 :     const bool bHasMask = bHasInternalMask || bHasExternalMask;
    3510             : 
    3511         255 :     if (bHasInternalMask)
    3512             :     {
    3513          48 :         std::vector<GDALRasterBandH> ahOverviewBands;
    3514          64 :         for (auto &poOvrDS : m_apoOverviewDS)
    3515             :         {
    3516          40 :             if (poOvrDS->m_poMaskDS != nullptr)
    3517             :             {
    3518          40 :                 ahOverviewBands.push_back(GDALRasterBand::ToHandle(
    3519          40 :                     poOvrDS->m_poMaskDS->GetRasterBand(1)));
    3520             :             }
    3521             :         }
    3522             : 
    3523          48 :         void *pScaledProgressData = GDALCreateScaledProgress(
    3524          24 :             0, 1.0 / (nBands + 1), pfnProgress, pProgressData);
    3525          24 :         eErr = GDALRegenerateOverviewsEx(
    3526          24 :             m_poMaskDS->GetRasterBand(1),
    3527          24 :             static_cast<int>(ahOverviewBands.size()), ahOverviewBands.data(),
    3528             :             pszResampling, GDALScaledProgress, pScaledProgressData,
    3529             :             papszOptions);
    3530          24 :         GDALDestroyScaledProgress(pScaledProgressData);
    3531             :     }
    3532         231 :     else if (bHasExternalMask)
    3533             :     {
    3534           4 :         void *pScaledProgressData = GDALCreateScaledProgress(
    3535           2 :             0, 1.0 / (nBands + 1), pfnProgress, pProgressData);
    3536           2 :         eErr = oOvManager.BuildOverviewsMask(
    3537             :             pszResampling, nOverviews, panOverviewList, GDALScaledProgress,
    3538             :             pScaledProgressData, papszOptions);
    3539           2 :         GDALDestroyScaledProgress(pScaledProgressData);
    3540             :     }
    3541             : 
    3542             :     // If we have an alpha band, we want it to be generated before downsampling
    3543             :     // other bands
    3544         255 :     bool bHasAlphaBand = false;
    3545       66257 :     for (int iBand = 0; iBand < nBands; iBand++)
    3546             :     {
    3547       66002 :         if (papoBands[iBand]->GetColorInterpretation() == GCI_AlphaBand)
    3548          18 :             bHasAlphaBand = true;
    3549             :     }
    3550             : 
    3551             :     /* -------------------------------------------------------------------- */
    3552             :     /*      Refresh old overviews that were listed.                         */
    3553             :     /* -------------------------------------------------------------------- */
    3554         255 :     const auto poColorTable = GetRasterBand(panBandList[0])->GetColorTable();
    3555          21 :     if ((m_nPlanarConfig == PLANARCONFIG_CONTIG || bHasAlphaBand) &&
    3556         236 :         GDALDataTypeIsComplex(
    3557         236 :             GetRasterBand(panBandList[0])->GetRasterDataType()) == FALSE &&
    3558          12 :         (poColorTable == nullptr || STARTS_WITH_CI(pszResampling, "NEAR") ||
    3559         511 :          poColorTable->IsIdentity()) &&
    3560         228 :         (STARTS_WITH_CI(pszResampling, "NEAR") ||
    3561         118 :          EQUAL(pszResampling, "AVERAGE") || EQUAL(pszResampling, "RMS") ||
    3562          48 :          EQUAL(pszResampling, "GAUSS") || EQUAL(pszResampling, "CUBIC") ||
    3563          30 :          EQUAL(pszResampling, "CUBICSPLINE") ||
    3564          29 :          EQUAL(pszResampling, "LANCZOS") || EQUAL(pszResampling, "BILINEAR") ||
    3565          25 :          EQUAL(pszResampling, "MODE")))
    3566             :     {
    3567             :         // In the case of pixel interleaved compressed overviews, we want to
    3568             :         // generate the overviews for all the bands block by block, and not
    3569             :         // band after band, in order to write the block once and not loose
    3570             :         // space in the TIFF file.  We also use that logic for uncompressed
    3571             :         // overviews, since GDALRegenerateOverviewsMultiBand() will be able to
    3572             :         // trigger cascading overview regeneration even in the presence
    3573             :         // of an alpha band.
    3574             : 
    3575         206 :         int nNewOverviews = 0;
    3576             : 
    3577             :         GDALRasterBand ***papapoOverviewBands = static_cast<GDALRasterBand ***>(
    3578         206 :             CPLCalloc(sizeof(void *), nBandsIn));
    3579             :         GDALRasterBand **papoBandList =
    3580         206 :             static_cast<GDALRasterBand **>(CPLCalloc(sizeof(void *), nBandsIn));
    3581       66111 :         for (int iBand = 0; iBand < nBandsIn; ++iBand)
    3582             :         {
    3583       65905 :             GDALRasterBand *poBand = GetRasterBand(panBandList[iBand]);
    3584             : 
    3585       65905 :             papoBandList[iBand] = poBand;
    3586      131810 :             papapoOverviewBands[iBand] = static_cast<GDALRasterBand **>(
    3587       65905 :                 CPLCalloc(sizeof(void *), poBand->GetOverviewCount()));
    3588             : 
    3589       65905 :             int iCurOverview = 0;
    3590             :             std::vector<bool> abAlreadyUsedOverviewBand(
    3591       65905 :                 poBand->GetOverviewCount(), false);
    3592             : 
    3593      132095 :             for (int i = 0; i < nOverviews; ++i)
    3594             :             {
    3595       66649 :                 for (int j = 0; j < poBand->GetOverviewCount(); ++j)
    3596             :                 {
    3597       66634 :                     if (abAlreadyUsedOverviewBand[j])
    3598         458 :                         continue;
    3599             : 
    3600             :                     int nOvFactor;
    3601       66176 :                     GDALRasterBand *poOverview = poBand->GetOverview(j);
    3602             : 
    3603       66176 :                     nOvFactor = GDALComputeOvFactor(
    3604             :                         poOverview->GetXSize(), poBand->GetXSize(),
    3605             :                         poOverview->GetYSize(), poBand->GetYSize());
    3606             : 
    3607       66176 :                     GDALCopyNoDataValue(poOverview, poBand);
    3608             : 
    3609       66177 :                     if (nOvFactor == panOverviewList[i] ||
    3610           1 :                         nOvFactor == GDALOvLevelAdjust2(panOverviewList[i],
    3611             :                                                         poBand->GetXSize(),
    3612             :                                                         poBand->GetYSize()))
    3613             :                     {
    3614       66175 :                         if (iBand == 0)
    3615             :                         {
    3616             :                             const auto osNewResampling =
    3617         664 :                                 GDALGetNormalizedOvrResampling(pszResampling);
    3618             :                             const char *pszExistingResampling =
    3619         332 :                                 poOverview->GetMetadataItem("RESAMPLING");
    3620         664 :                             if (pszExistingResampling &&
    3621         332 :                                 pszExistingResampling != osNewResampling)
    3622             :                             {
    3623           2 :                                 poOverview->SetMetadataItem(
    3624           2 :                                     "RESAMPLING", osNewResampling.c_str());
    3625             :                             }
    3626             :                         }
    3627             : 
    3628       66175 :                         abAlreadyUsedOverviewBand[j] = true;
    3629       66175 :                         CPLAssert(iCurOverview < poBand->GetOverviewCount());
    3630       66175 :                         papapoOverviewBands[iBand][iCurOverview] = poOverview;
    3631       66175 :                         ++iCurOverview;
    3632       66175 :                         break;
    3633             :                     }
    3634             :                 }
    3635             :             }
    3636             : 
    3637       65905 :             if (nNewOverviews == 0)
    3638             :             {
    3639         206 :                 nNewOverviews = iCurOverview;
    3640             :             }
    3641       65699 :             else if (nNewOverviews != iCurOverview)
    3642             :             {
    3643           0 :                 CPLAssert(false);
    3644             :                 return CE_Failure;
    3645             :             }
    3646             :         }
    3647             : 
    3648             :         void *pScaledProgressData =
    3649         206 :             bHasMask ? GDALCreateScaledProgress(1.0 / (nBands + 1), 1.0,
    3650             :                                                 pfnProgress, pProgressData)
    3651         180 :                      : GDALCreateScaledProgress(0.0, 1.0, pfnProgress,
    3652         206 :                                                 pProgressData);
    3653         206 :         GDALRegenerateOverviewsMultiBand(nBandsIn, papoBandList, nNewOverviews,
    3654             :                                          papapoOverviewBands, pszResampling,
    3655             :                                          GDALScaledProgress,
    3656             :                                          pScaledProgressData, papszOptions);
    3657         206 :         GDALDestroyScaledProgress(pScaledProgressData);
    3658             : 
    3659       66111 :         for (int iBand = 0; iBand < nBandsIn; ++iBand)
    3660             :         {
    3661       65905 :             CPLFree(papapoOverviewBands[iBand]);
    3662             :         }
    3663         206 :         CPLFree(papapoOverviewBands);
    3664         206 :         CPLFree(papoBandList);
    3665             :     }
    3666             :     else
    3667             :     {
    3668             :         GDALRasterBand **papoOverviewBands = static_cast<GDALRasterBand **>(
    3669          49 :             CPLCalloc(sizeof(void *), nOverviews));
    3670             : 
    3671          49 :         const int iBandOffset = bHasMask ? 1 : 0;
    3672             : 
    3673         146 :         for (int iBand = 0; iBand < nBandsIn && eErr == CE_None; ++iBand)
    3674             :         {
    3675          97 :             GDALRasterBand *poBand = GetRasterBand(panBandList[iBand]);
    3676          97 :             if (poBand == nullptr)
    3677             :             {
    3678           0 :                 eErr = CE_Failure;
    3679           0 :                 break;
    3680             :             }
    3681             : 
    3682             :             std::vector<bool> abAlreadyUsedOverviewBand(
    3683         194 :                 poBand->GetOverviewCount(), false);
    3684             : 
    3685          97 :             int nNewOverviews = 0;
    3686         290 :             for (int i = 0; i < nOverviews; ++i)
    3687             :             {
    3688         451 :                 for (int j = 0; j < poBand->GetOverviewCount(); ++j)
    3689             :                 {
    3690         433 :                     if (abAlreadyUsedOverviewBand[j])
    3691         257 :                         continue;
    3692             : 
    3693         176 :                     GDALRasterBand *poOverview = poBand->GetOverview(j);
    3694             : 
    3695         176 :                     GDALCopyNoDataValue(poOverview, poBand);
    3696             : 
    3697         176 :                     const int nOvFactor = GDALComputeOvFactor(
    3698             :                         poOverview->GetXSize(), poBand->GetXSize(),
    3699             :                         poOverview->GetYSize(), poBand->GetYSize());
    3700             : 
    3701         177 :                     if (nOvFactor == panOverviewList[i] ||
    3702           1 :                         nOvFactor == GDALOvLevelAdjust2(panOverviewList[i],
    3703             :                                                         poBand->GetXSize(),
    3704             :                                                         poBand->GetYSize()))
    3705             :                     {
    3706         175 :                         if (iBand == 0)
    3707             :                         {
    3708             :                             const auto osNewResampling =
    3709         170 :                                 GDALGetNormalizedOvrResampling(pszResampling);
    3710             :                             const char *pszExistingResampling =
    3711          85 :                                 poOverview->GetMetadataItem("RESAMPLING");
    3712         137 :                             if (pszExistingResampling &&
    3713          52 :                                 pszExistingResampling != osNewResampling)
    3714             :                             {
    3715           1 :                                 poOverview->SetMetadataItem(
    3716           1 :                                     "RESAMPLING", osNewResampling.c_str());
    3717             :                             }
    3718             :                         }
    3719             : 
    3720         175 :                         abAlreadyUsedOverviewBand[j] = true;
    3721         175 :                         CPLAssert(nNewOverviews < poBand->GetOverviewCount());
    3722         175 :                         papoOverviewBands[nNewOverviews++] = poOverview;
    3723         175 :                         break;
    3724             :                     }
    3725             :                 }
    3726             :             }
    3727             : 
    3728         194 :             void *pScaledProgressData = GDALCreateScaledProgress(
    3729          97 :                 (iBand + iBandOffset) /
    3730          97 :                     static_cast<double>(nBandsIn + iBandOffset),
    3731          97 :                 (iBand + iBandOffset + 1) /
    3732          97 :                     static_cast<double>(nBandsIn + iBandOffset),
    3733             :                 pfnProgress, pProgressData);
    3734             : 
    3735          97 :             eErr = GDALRegenerateOverviewsEx(
    3736             :                 poBand, nNewOverviews,
    3737             :                 reinterpret_cast<GDALRasterBandH *>(papoOverviewBands),
    3738             :                 pszResampling, GDALScaledProgress, pScaledProgressData,
    3739             :                 papszOptions);
    3740             : 
    3741          97 :             GDALDestroyScaledProgress(pScaledProgressData);
    3742             :         }
    3743             : 
    3744             :         /* --------------------------------------------------------------------
    3745             :          */
    3746             :         /*      Cleanup */
    3747             :         /* --------------------------------------------------------------------
    3748             :          */
    3749          49 :         CPLFree(papoOverviewBands);
    3750             :     }
    3751             : 
    3752         255 :     pfnProgress(1.0, nullptr, pProgressData);
    3753             : 
    3754         255 :     return eErr;
    3755             : }
    3756             : 
    3757             : /************************************************************************/
    3758             : /*                   GTiffWriteDummyGeokeyDirectory()                   */
    3759             : /************************************************************************/
    3760             : 
    3761        1531 : static void GTiffWriteDummyGeokeyDirectory(TIFF *hTIFF)
    3762             : {
    3763             :     // If we have existing geokeys, try to wipe them
    3764             :     // by writing a dummy geokey directory. (#2546)
    3765        1531 :     uint16_t *panVI = nullptr;
    3766        1531 :     uint16_t nKeyCount = 0;
    3767             : 
    3768        1531 :     if (TIFFGetField(hTIFF, TIFFTAG_GEOKEYDIRECTORY, &nKeyCount, &panVI))
    3769             :     {
    3770          26 :         GUInt16 anGKVersionInfo[4] = {1, 1, 0, 0};
    3771          26 :         double adfDummyDoubleParams[1] = {0.0};
    3772          26 :         TIFFSetField(hTIFF, TIFFTAG_GEOKEYDIRECTORY, 4, anGKVersionInfo);
    3773          26 :         TIFFSetField(hTIFF, TIFFTAG_GEODOUBLEPARAMS, 1, adfDummyDoubleParams);
    3774          26 :         TIFFSetField(hTIFF, TIFFTAG_GEOASCIIPARAMS, "");
    3775             :     }
    3776        1531 : }
    3777             : 
    3778             : /************************************************************************/
    3779             : /*                      IsSRSCompatibleOfGeoTIFF()                      */
    3780             : /************************************************************************/
    3781             : 
    3782        3229 : static bool IsSRSCompatibleOfGeoTIFF(const OGRSpatialReference *poSRS,
    3783             :                                      GTIFFKeysFlavorEnum eGeoTIFFKeysFlavor)
    3784             : {
    3785        3229 :     char *pszWKT = nullptr;
    3786        3229 :     if ((poSRS->IsGeographic() || poSRS->IsProjected()) && !poSRS->IsCompound())
    3787             :     {
    3788        3211 :         const char *pszAuthName = poSRS->GetAuthorityName();
    3789        3211 :         const char *pszAuthCode = poSRS->GetAuthorityCode();
    3790        3211 :         if (pszAuthName && pszAuthCode && EQUAL(pszAuthName, "EPSG"))
    3791        2640 :             return true;
    3792             :     }
    3793             :     OGRErr eErr;
    3794             :     {
    3795        1178 :         CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
    3796        1178 :         if (poSRS->IsDerivedGeographic() ||
    3797         589 :             (poSRS->IsProjected() && !poSRS->IsCompound() &&
    3798          70 :              poSRS->GetAxesCount() == 3))
    3799             :         {
    3800           0 :             eErr = OGRERR_FAILURE;
    3801             :         }
    3802             :         else
    3803             :         {
    3804             :             // Geographic3D CRS can't be exported to WKT1, but are
    3805             :             // valid GeoTIFF 1.1
    3806         589 :             const char *const apszOptions[] = {
    3807         589 :                 poSRS->IsGeographic() ? nullptr : "FORMAT=WKT1", nullptr};
    3808         589 :             eErr = poSRS->exportToWkt(&pszWKT, apszOptions);
    3809         589 :             if (eErr == OGRERR_FAILURE && poSRS->IsProjected() &&
    3810             :                 eGeoTIFFKeysFlavor == GEOTIFF_KEYS_ESRI_PE)
    3811             :             {
    3812           0 :                 CPLFree(pszWKT);
    3813           0 :                 const char *const apszOptionsESRIWKT[] = {"FORMAT=WKT1_ESRI",
    3814             :                                                           nullptr};
    3815           0 :                 eErr = poSRS->exportToWkt(&pszWKT, apszOptionsESRIWKT);
    3816             :             }
    3817             :         }
    3818             :     }
    3819         589 :     const bool bCompatibleOfGeoTIFF =
    3820        1177 :         (eErr == OGRERR_NONE && pszWKT != nullptr &&
    3821         588 :          strstr(pszWKT, "custom_proj4") == nullptr);
    3822         589 :     CPLFree(pszWKT);
    3823         589 :     return bCompatibleOfGeoTIFF;
    3824             : }
    3825             : 
    3826             : /************************************************************************/
    3827             : /*                          WriteGeoTIFFInfo()                          */
    3828             : /************************************************************************/
    3829             : 
    3830        5938 : void GTiffDataset::WriteGeoTIFFInfo()
    3831             : 
    3832             : {
    3833        5938 :     bool bPixelIsPoint = false;
    3834        5938 :     bool bPointGeoIgnore = false;
    3835             : 
    3836             :     const char *pszAreaOrPoint =
    3837        5938 :         GTiffDataset::GetMetadataItem(GDALMD_AREA_OR_POINT);
    3838        5938 :     if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_POINT))
    3839             :     {
    3840          19 :         bPixelIsPoint = true;
    3841             :         bPointGeoIgnore =
    3842          19 :             CPLTestBool(CPLGetConfigOption("GTIFF_POINT_GEO_IGNORE", "FALSE"));
    3843             :     }
    3844             : 
    3845        5938 :     if (m_bForceUnsetGTOrGCPs)
    3846             :     {
    3847          11 :         m_bNeedsRewrite = true;
    3848          11 :         m_bForceUnsetGTOrGCPs = false;
    3849             : 
    3850          11 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOPIXELSCALE);
    3851          11 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOTIEPOINTS);
    3852          11 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOTRANSMATRIX);
    3853             :     }
    3854             : 
    3855        5938 :     if (m_bForceUnsetProjection)
    3856             :     {
    3857           8 :         m_bNeedsRewrite = true;
    3858           8 :         m_bForceUnsetProjection = false;
    3859             : 
    3860           8 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOKEYDIRECTORY);
    3861           8 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEODOUBLEPARAMS);
    3862           8 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOASCIIPARAMS);
    3863             :     }
    3864             : 
    3865             :     /* -------------------------------------------------------------------- */
    3866             :     /*      Write geotransform if valid.                                    */
    3867             :     /* -------------------------------------------------------------------- */
    3868        5938 :     if (m_bGeoTransformValid)
    3869             :     {
    3870        1859 :         m_bNeedsRewrite = true;
    3871             : 
    3872             :         /* --------------------------------------------------------------------
    3873             :          */
    3874             :         /*      Clear old tags to ensure we don't end up with conflicting */
    3875             :         /*      information. (#2625) */
    3876             :         /* --------------------------------------------------------------------
    3877             :          */
    3878        1859 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOPIXELSCALE);
    3879        1859 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOTIEPOINTS);
    3880        1859 :         TIFFUnsetField(m_hTIFF, TIFFTAG_GEOTRANSMATRIX);
    3881             : 
    3882             :         /* --------------------------------------------------------------------
    3883             :          */
    3884             :         /*      Write the transform.  If we have a normal north-up image we */
    3885             :         /*      use the tiepoint plus pixelscale otherwise we use a matrix. */
    3886             :         /* --------------------------------------------------------------------
    3887             :          */
    3888        1859 :         if (m_gt.xrot == 0.0 && m_gt.yrot == 0.0 && m_gt.yscale < 0.0)
    3889             :         {
    3890        1766 :             double dfOffset = 0.0;
    3891        1766 :             if (m_eProfile != GTiffProfile::BASELINE)
    3892             :             {
    3893             :                 // In the case the SRS has a vertical component and we have
    3894             :                 // a single band, encode its scale/offset in the GeoTIFF tags
    3895        1760 :                 int bHasScale = FALSE;
    3896        1760 :                 double dfScale = GetRasterBand(1)->GetScale(&bHasScale);
    3897        1760 :                 int bHasOffset = FALSE;
    3898        1760 :                 dfOffset = GetRasterBand(1)->GetOffset(&bHasOffset);
    3899             :                 const bool bApplyScaleOffset =
    3900        1760 :                     m_oSRS.IsVertical() && GetRasterCount() == 1;
    3901        1760 :                 if (bApplyScaleOffset && !bHasScale)
    3902           0 :                     dfScale = 1.0;
    3903        1760 :                 if (!bApplyScaleOffset || !bHasOffset)
    3904        1757 :                     dfOffset = 0.0;
    3905        1760 :                 const double adfPixelScale[3] = {m_gt.xscale, fabs(m_gt.yscale),
    3906        1760 :                                                  bApplyScaleOffset ? dfScale
    3907        1760 :                                                                    : 0.0};
    3908        1760 :                 TIFFSetField(m_hTIFF, TIFFTAG_GEOPIXELSCALE, 3, adfPixelScale);
    3909             :             }
    3910             : 
    3911        1766 :             double adfTiePoints[6] = {0.0,        0.0,        0.0,
    3912        1766 :                                       m_gt.xorig, m_gt.yorig, dfOffset};
    3913             : 
    3914        1766 :             if (bPixelIsPoint && !bPointGeoIgnore)
    3915             :             {
    3916          15 :                 adfTiePoints[3] += m_gt.xscale * 0.5 + m_gt.xrot * 0.5;
    3917          15 :                 adfTiePoints[4] += m_gt.yrot * 0.5 + m_gt.yscale * 0.5;
    3918             :             }
    3919             : 
    3920        1766 :             if (m_eProfile != GTiffProfile::BASELINE)
    3921        1766 :                 TIFFSetField(m_hTIFF, TIFFTAG_GEOTIEPOINTS, 6, adfTiePoints);
    3922             :         }
    3923             :         else
    3924             :         {
    3925          93 :             double adfMatrix[16] = {};
    3926             : 
    3927          93 :             adfMatrix[0] = m_gt.xscale;
    3928          93 :             adfMatrix[1] = m_gt.xrot;
    3929          93 :             adfMatrix[3] = m_gt.xorig;
    3930          93 :             adfMatrix[4] = m_gt.yrot;
    3931          93 :             adfMatrix[5] = m_gt.yscale;
    3932          93 :             adfMatrix[7] = m_gt.yorig;
    3933          93 :             adfMatrix[15] = 1.0;
    3934             : 
    3935          93 :             if (bPixelIsPoint && !bPointGeoIgnore)
    3936             :             {
    3937           0 :                 adfMatrix[3] += m_gt.xscale * 0.5 + m_gt.xrot * 0.5;
    3938           0 :                 adfMatrix[7] += m_gt.yrot * 0.5 + m_gt.yscale * 0.5;
    3939             :             }
    3940             : 
    3941          93 :             if (m_eProfile != GTiffProfile::BASELINE)
    3942          93 :                 TIFFSetField(m_hTIFF, TIFFTAG_GEOTRANSMATRIX, 16, adfMatrix);
    3943             :         }
    3944             : 
    3945        1859 :         if (m_poBaseDS == nullptr)
    3946             :         {
    3947             :             // Do we need a world file?
    3948        1859 :             if (CPLFetchBool(m_papszCreationOptions, "TFW", false))
    3949           7 :                 GDALWriteWorldFile(m_osFilename.c_str(), "tfw", m_gt.data());
    3950        1852 :             else if (CPLFetchBool(m_papszCreationOptions, "WORLDFILE", false))
    3951           2 :                 GDALWriteWorldFile(m_osFilename.c_str(), "wld", m_gt.data());
    3952             :         }
    3953             :     }
    3954        4092 :     else if (GetGCPCount() > 0 && GetGCPCount() <= knMAX_GCP_COUNT &&
    3955          13 :              m_eProfile != GTiffProfile::BASELINE)
    3956             :     {
    3957          13 :         m_bNeedsRewrite = true;
    3958             : 
    3959             :         double *padfTiePoints = static_cast<double *>(
    3960          13 :             CPLMalloc(6 * sizeof(double) * GetGCPCount()));
    3961             : 
    3962          69 :         for (size_t iGCP = 0; iGCP < m_aoGCPs.size(); ++iGCP)
    3963             :         {
    3964             : 
    3965          56 :             padfTiePoints[iGCP * 6 + 0] = m_aoGCPs[iGCP].Pixel();
    3966          56 :             padfTiePoints[iGCP * 6 + 1] = m_aoGCPs[iGCP].Line();
    3967          56 :             padfTiePoints[iGCP * 6 + 2] = 0;
    3968          56 :             padfTiePoints[iGCP * 6 + 3] = m_aoGCPs[iGCP].X();
    3969          56 :             padfTiePoints[iGCP * 6 + 4] = m_aoGCPs[iGCP].Y();
    3970          56 :             padfTiePoints[iGCP * 6 + 5] = m_aoGCPs[iGCP].Z();
    3971             : 
    3972          56 :             if (bPixelIsPoint && !bPointGeoIgnore)
    3973             :             {
    3974           0 :                 padfTiePoints[iGCP * 6 + 0] += 0.5;
    3975           0 :                 padfTiePoints[iGCP * 6 + 1] += 0.5;
    3976             :             }
    3977             :         }
    3978             : 
    3979          13 :         TIFFSetField(m_hTIFF, TIFFTAG_GEOTIEPOINTS, 6 * GetGCPCount(),
    3980             :                      padfTiePoints);
    3981          13 :         CPLFree(padfTiePoints);
    3982             :     }
    3983             : 
    3984             :     /* -------------------------------------------------------------------- */
    3985             :     /*      Write out projection definition.                                */
    3986             :     /* -------------------------------------------------------------------- */
    3987        5938 :     const bool bHasProjection = !m_oSRS.IsEmpty();
    3988        5938 :     if ((bHasProjection || bPixelIsPoint) &&
    3989        1535 :         m_eProfile != GTiffProfile::BASELINE)
    3990             :     {
    3991        1531 :         m_bNeedsRewrite = true;
    3992             : 
    3993             :         // If we have existing geokeys, try to wipe them
    3994             :         // by writing a dummy geokey directory. (#2546)
    3995        1531 :         GTiffWriteDummyGeokeyDirectory(m_hTIFF);
    3996             : 
    3997        1531 :         GTIF *psGTIF = GTiffDataset::GTIFNew(m_hTIFF);
    3998             : 
    3999             :         // Set according to coordinate system.
    4000        1531 :         if (bHasProjection)
    4001             :         {
    4002        1530 :             if (IsSRSCompatibleOfGeoTIFF(&m_oSRS, m_eGeoTIFFKeysFlavor))
    4003             :             {
    4004        1528 :                 GTIFSetFromOGISDefnEx(psGTIF,
    4005             :                                       OGRSpatialReference::ToHandle(&m_oSRS),
    4006             :                                       m_eGeoTIFFKeysFlavor, m_eGeoTIFFVersion);
    4007             :             }
    4008             :             else
    4009             :             {
    4010           2 :                 GDALPamDataset::SetSpatialRef(&m_oSRS);
    4011             :             }
    4012             :         }
    4013             : 
    4014        1531 :         if (bPixelIsPoint)
    4015             :         {
    4016          19 :             GTIFKeySet(psGTIF, GTRasterTypeGeoKey, TYPE_SHORT, 1,
    4017             :                        RasterPixelIsPoint);
    4018             :         }
    4019             : 
    4020        1531 :         GTIFWriteKeys(psGTIF);
    4021        1531 :         GTIFFree(psGTIF);
    4022             :     }
    4023        5938 : }
    4024             : 
    4025             : /************************************************************************/
    4026             : /*                         AppendMetadataItem()                         */
    4027             : /************************************************************************/
    4028             : 
    4029        3897 : static void AppendMetadataItem(CPLXMLNode **ppsRoot, CPLXMLNode **ppsTail,
    4030             :                                const char *pszKey, const char *pszValue,
    4031             :                                CPLXMLNode *psValueNode, int nBand,
    4032             :                                const char *pszRole, const char *pszDomain)
    4033             : 
    4034             : {
    4035        3897 :     CPLAssert(pszValue || psValueNode);
    4036        3897 :     CPLAssert(!(pszValue && psValueNode));
    4037             : 
    4038             :     /* -------------------------------------------------------------------- */
    4039             :     /*      Create the Item element, and subcomponents.                     */
    4040             :     /* -------------------------------------------------------------------- */
    4041        3897 :     CPLXMLNode *psItem = CPLCreateXMLNode(nullptr, CXT_Element, "Item");
    4042        3897 :     CPLAddXMLAttributeAndValue(psItem, "name", pszKey);
    4043             : 
    4044        3897 :     if (nBand > 0)
    4045             :     {
    4046        1167 :         char szBandId[32] = {};
    4047        1167 :         snprintf(szBandId, sizeof(szBandId), "%d", nBand - 1);
    4048        1167 :         CPLAddXMLAttributeAndValue(psItem, "sample", szBandId);
    4049             :     }
    4050             : 
    4051        3897 :     if (pszRole != nullptr)
    4052         384 :         CPLAddXMLAttributeAndValue(psItem, "role", pszRole);
    4053             : 
    4054        3897 :     if (pszDomain != nullptr && strlen(pszDomain) > 0)
    4055        1012 :         CPLAddXMLAttributeAndValue(psItem, "domain", pszDomain);
    4056             : 
    4057        3897 :     if (pszValue)
    4058             :     {
    4059             :         // Note: this escaping should not normally be done, as the serialization
    4060             :         // of the tree to XML also does it, so we end up width double XML escaping,
    4061             :         // but keep it for backward compatibility.
    4062        3876 :         char *pszEscapedItemValue = CPLEscapeString(pszValue, -1, CPLES_XML);
    4063        3876 :         CPLCreateXMLNode(psItem, CXT_Text, pszEscapedItemValue);
    4064        3876 :         CPLFree(pszEscapedItemValue);
    4065             :     }
    4066             :     else
    4067             :     {
    4068          21 :         CPLAddXMLChild(psItem, psValueNode);
    4069             :     }
    4070             : 
    4071             :     /* -------------------------------------------------------------------- */
    4072             :     /*      Create root, if missing.                                        */
    4073             :     /* -------------------------------------------------------------------- */
    4074        3897 :     if (*ppsRoot == nullptr)
    4075         765 :         *ppsRoot = CPLCreateXMLNode(nullptr, CXT_Element, "GDALMetadata");
    4076             : 
    4077             :     /* -------------------------------------------------------------------- */
    4078             :     /*      Append item to tail.  We keep track of the tail to avoid        */
    4079             :     /*      O(nsquared) time as the list gets longer.                       */
    4080             :     /* -------------------------------------------------------------------- */
    4081        3897 :     if (*ppsTail == nullptr)
    4082         765 :         CPLAddXMLChild(*ppsRoot, psItem);
    4083             :     else
    4084        3132 :         CPLAddXMLSibling(*ppsTail, psItem);
    4085             : 
    4086        3897 :     *ppsTail = psItem;
    4087        3897 : }
    4088             : 
    4089             : /************************************************************************/
    4090             : /*                         AppendMetadataItem()                         */
    4091             : /************************************************************************/
    4092             : 
    4093        3876 : static void AppendMetadataItem(CPLXMLNode **ppsRoot, CPLXMLNode **ppsTail,
    4094             :                                const char *pszKey, const char *pszValue,
    4095             :                                int nBand, const char *pszRole,
    4096             :                                const char *pszDomain)
    4097             : 
    4098             : {
    4099        3876 :     AppendMetadataItem(ppsRoot, ppsTail, pszKey, pszValue, nullptr, nBand,
    4100             :                        pszRole, pszDomain);
    4101        3876 : }
    4102             : 
    4103             : /************************************************************************/
    4104             : /*                          WriteMDMetadata()                           */
    4105             : /************************************************************************/
    4106             : 
    4107      311254 : static void WriteMDMetadata(GDALMultiDomainMetadata *poMDMD, TIFF *hTIFF,
    4108             :                             CPLXMLNode **ppsRoot, CPLXMLNode **ppsTail,
    4109             :                             int nBand, GTiffProfile eProfile)
    4110             : 
    4111             : {
    4112             : 
    4113             :     /* ==================================================================== */
    4114             :     /*      Process each domain.                                            */
    4115             :     /* ==================================================================== */
    4116      311254 :     CSLConstList papszDomainList = poMDMD->GetDomainList();
    4117      319855 :     for (int iDomain = 0; papszDomainList && papszDomainList[iDomain];
    4118             :          ++iDomain)
    4119             :     {
    4120        8601 :         CSLConstList papszMD = poMDMD->GetMetadata(papszDomainList[iDomain]);
    4121        8601 :         bool bIsXMLOrJSON = false;
    4122             : 
    4123        8601 :         if (EQUAL(papszDomainList[iDomain], "IMAGE_STRUCTURE") ||
    4124        2517 :             EQUAL(papszDomainList[iDomain], "DERIVED_SUBDATASETS"))
    4125        6087 :             continue;  // Ignored.
    4126        2514 :         if (EQUAL(papszDomainList[iDomain], "COLOR_PROFILE"))
    4127           3 :             continue;  // Handled elsewhere.
    4128        2511 :         if (EQUAL(papszDomainList[iDomain], MD_DOMAIN_RPC))
    4129           7 :             continue;  // Handled elsewhere.
    4130        2505 :         if (EQUAL(papszDomainList[iDomain], "xml:ESRI") &&
    4131           1 :             CPLTestBool(CPLGetConfigOption("ESRI_XML_PAM", "NO")))
    4132           1 :             continue;  // Handled elsewhere.
    4133        2503 :         if (EQUAL(papszDomainList[iDomain], "xml:XMP"))
    4134           2 :             continue;  // Handled in SetMetadata.
    4135             : 
    4136        2501 :         if (STARTS_WITH_CI(papszDomainList[iDomain], "xml:") ||
    4137        2499 :             STARTS_WITH_CI(papszDomainList[iDomain], "json:"))
    4138             :         {
    4139          12 :             bIsXMLOrJSON = true;
    4140             :         }
    4141             : 
    4142             :         /* --------------------------------------------------------------------
    4143             :          */
    4144             :         /*      Process each item in this domain. */
    4145             :         /* --------------------------------------------------------------------
    4146             :          */
    4147        7631 :         for (int iItem = 0; papszMD && papszMD[iItem]; ++iItem)
    4148             :         {
    4149        5130 :             const char *pszItemValue = nullptr;
    4150        5130 :             char *pszItemName = nullptr;
    4151             : 
    4152        5130 :             if (bIsXMLOrJSON)
    4153             :             {
    4154          11 :                 pszItemName = CPLStrdup("doc");
    4155          11 :                 pszItemValue = papszMD[iItem];
    4156             :             }
    4157             :             else
    4158             :             {
    4159        5119 :                 pszItemValue = CPLParseNameValue(papszMD[iItem], &pszItemName);
    4160        5119 :                 if (pszItemName == nullptr)
    4161             :                 {
    4162          49 :                     CPLDebug("GTiff", "Invalid metadata item : %s",
    4163          49 :                              papszMD[iItem]);
    4164          49 :                     continue;
    4165             :                 }
    4166             :             }
    4167             : 
    4168             :             /* --------------------------------------------------------------------
    4169             :              */
    4170             :             /*      Convert into XML item or handle as a special TIFF tag. */
    4171             :             /* --------------------------------------------------------------------
    4172             :              */
    4173        5081 :             if (strlen(papszDomainList[iDomain]) == 0 && nBand == 0 &&
    4174        3725 :                 (STARTS_WITH_CI(pszItemName, "TIFFTAG_") ||
    4175        3664 :                  (EQUAL(pszItemName, "GEO_METADATA") &&
    4176        3663 :                   eProfile == GTiffProfile::GDALGEOTIFF) ||
    4177        3663 :                  (EQUAL(pszItemName, "TIFF_RSID") &&
    4178             :                   eProfile == GTiffProfile::GDALGEOTIFF)))
    4179             :             {
    4180          63 :                 if (EQUAL(pszItemName, "TIFFTAG_RESOLUTIONUNIT"))
    4181             :                 {
    4182             :                     // ResolutionUnit can't be 0, which is the default if
    4183             :                     // atoi() fails.  Set to 1=Unknown.
    4184           9 :                     int v = atoi(pszItemValue);
    4185           9 :                     if (!v)
    4186           1 :                         v = RESUNIT_NONE;
    4187           9 :                     TIFFSetField(hTIFF, TIFFTAG_RESOLUTIONUNIT, v);
    4188             :                 }
    4189             :                 else
    4190             :                 {
    4191          54 :                     bool bFoundTag = false;
    4192          54 :                     size_t iTag = 0;  // Used after for.
    4193          54 :                     const auto *pasTIFFTags = GTiffDataset::GetTIFFTags();
    4194         286 :                     for (; pasTIFFTags[iTag].pszTagName; ++iTag)
    4195             :                     {
    4196         286 :                         if (EQUAL(pszItemName, pasTIFFTags[iTag].pszTagName))
    4197             :                         {
    4198          54 :                             bFoundTag = true;
    4199          54 :                             break;
    4200             :                         }
    4201             :                     }
    4202             : 
    4203          54 :                     if (bFoundTag &&
    4204          54 :                         pasTIFFTags[iTag].eType == GTIFFTAGTYPE_STRING)
    4205          33 :                         TIFFSetField(hTIFF, pasTIFFTags[iTag].nTagVal,
    4206             :                                      pszItemValue);
    4207          21 :                     else if (bFoundTag &&
    4208          21 :                              pasTIFFTags[iTag].eType == GTIFFTAGTYPE_FLOAT)
    4209          16 :                         TIFFSetField(hTIFF, pasTIFFTags[iTag].nTagVal,
    4210             :                                      CPLAtof(pszItemValue));
    4211           5 :                     else if (bFoundTag &&
    4212           5 :                              pasTIFFTags[iTag].eType == GTIFFTAGTYPE_SHORT)
    4213           4 :                         TIFFSetField(hTIFF, pasTIFFTags[iTag].nTagVal,
    4214             :                                      atoi(pszItemValue));
    4215           1 :                     else if (bFoundTag && pasTIFFTags[iTag].eType ==
    4216             :                                               GTIFFTAGTYPE_BYTE_STRING)
    4217             :                     {
    4218           1 :                         uint32_t nLen =
    4219           1 :                             static_cast<uint32_t>(strlen(pszItemValue));
    4220           1 :                         if (nLen)
    4221             :                         {
    4222           1 :                             TIFFSetField(hTIFF, pasTIFFTags[iTag].nTagVal, nLen,
    4223             :                                          pszItemValue);
    4224           1 :                         }
    4225             :                     }
    4226             :                     else
    4227           0 :                         CPLError(CE_Warning, CPLE_NotSupported,
    4228             :                                  "%s metadata item is unhandled and "
    4229             :                                  "will not be written",
    4230             :                                  pszItemName);
    4231          63 :                 }
    4232             :             }
    4233        5018 :             else if (nBand == 0 && EQUAL(pszItemName, GDALMD_AREA_OR_POINT))
    4234             :             {
    4235             :                 /* Do nothing, handled elsewhere. */;
    4236             :             }
    4237             :             else
    4238             :             {
    4239        3080 :                 AppendMetadataItem(ppsRoot, ppsTail, pszItemName, pszItemValue,
    4240        3080 :                                    nBand, nullptr, papszDomainList[iDomain]);
    4241             :             }
    4242             : 
    4243        5081 :             CPLFree(pszItemName);
    4244             :         }
    4245             : 
    4246             :         /* --------------------------------------------------------------------
    4247             :          */
    4248             :         /*      Remove TIFFTAG_xxxxxx that are already set but no longer in */
    4249             :         /*      the metadata list (#5619) */
    4250             :         /* --------------------------------------------------------------------
    4251             :          */
    4252        2501 :         if (strlen(papszDomainList[iDomain]) == 0 && nBand == 0)
    4253             :         {
    4254        2214 :             const auto *pasTIFFTags = GTiffDataset::GetTIFFTags();
    4255       33210 :             for (size_t iTag = 0; pasTIFFTags[iTag].pszTagName; ++iTag)
    4256             :             {
    4257       30996 :                 uint32_t nCount = 0;
    4258       30996 :                 char *pszText = nullptr;
    4259       30996 :                 int16_t nVal = 0;
    4260       30996 :                 float fVal = 0.0f;
    4261             :                 const char *pszVal =
    4262       30996 :                     CSLFetchNameValue(papszMD, pasTIFFTags[iTag].pszTagName);
    4263       61929 :                 if (pszVal == nullptr &&
    4264       30933 :                     ((pasTIFFTags[iTag].eType == GTIFFTAGTYPE_STRING &&
    4265       17679 :                       TIFFGetField(hTIFF, pasTIFFTags[iTag].nTagVal,
    4266       30925 :                                    &pszText)) ||
    4267       30925 :                      (pasTIFFTags[iTag].eType == GTIFFTAGTYPE_SHORT &&
    4268        6629 :                       TIFFGetField(hTIFF, pasTIFFTags[iTag].nTagVal, &nVal)) ||
    4269       30922 :                      (pasTIFFTags[iTag].eType == GTIFFTAGTYPE_FLOAT &&
    4270        4412 :                       TIFFGetField(hTIFF, pasTIFFTags[iTag].nTagVal, &fVal)) ||
    4271       30921 :                      (pasTIFFTags[iTag].eType == GTIFFTAGTYPE_BYTE_STRING &&
    4272        2213 :                       TIFFGetField(hTIFF, pasTIFFTags[iTag].nTagVal, &nCount,
    4273             :                                    &pszText))))
    4274             :                 {
    4275          13 :                     TIFFUnsetField(hTIFF, pasTIFFTags[iTag].nTagVal);
    4276             :                 }
    4277             :             }
    4278             :         }
    4279             :     }
    4280      311254 : }
    4281             : 
    4282             : /************************************************************************/
    4283             : /*                              WriteRPC()                              */
    4284             : /************************************************************************/
    4285             : 
    4286       10302 : void GTiffDataset::WriteRPC(GDALDataset *poSrcDS, TIFF *l_hTIFF,
    4287             :                             int bSrcIsGeoTIFF, GTiffProfile eProfile,
    4288             :                             const char *pszTIFFFilename,
    4289             :                             CSLConstList papszCreationOptions,
    4290             :                             bool bWriteOnlyInPAMIfNeeded)
    4291             : {
    4292             :     /* -------------------------------------------------------------------- */
    4293             :     /*      Handle RPC data written to TIFF RPCCoefficient tag, RPB file,   */
    4294             :     /*      RPCTEXT file or PAM.                                            */
    4295             :     /* -------------------------------------------------------------------- */
    4296       10302 :     CSLConstList papszRPCMD = poSrcDS->GetMetadata(MD_DOMAIN_RPC);
    4297       10302 :     if (papszRPCMD != nullptr)
    4298             :     {
    4299          32 :         bool bRPCSerializedOtherWay = false;
    4300             : 
    4301          32 :         if (eProfile == GTiffProfile::GDALGEOTIFF)
    4302             :         {
    4303          20 :             if (!bWriteOnlyInPAMIfNeeded)
    4304          11 :                 GTiffDatasetWriteRPCTag(l_hTIFF, papszRPCMD);
    4305          20 :             bRPCSerializedOtherWay = true;
    4306             :         }
    4307             : 
    4308             :         // Write RPB file if explicitly asked, or if a non GDAL specific
    4309             :         // profile is selected and RPCTXT is not asked.
    4310             :         bool bRPBExplicitlyAsked =
    4311          32 :             CPLFetchBool(papszCreationOptions, "RPB", false);
    4312             :         bool bRPBExplicitlyDenied =
    4313          32 :             !CPLFetchBool(papszCreationOptions, "RPB", true);
    4314          44 :         if ((eProfile != GTiffProfile::GDALGEOTIFF &&
    4315          12 :              !CPLFetchBool(papszCreationOptions, "RPCTXT", false) &&
    4316          44 :              !bRPBExplicitlyDenied) ||
    4317             :             bRPBExplicitlyAsked)
    4318             :         {
    4319           8 :             if (!bWriteOnlyInPAMIfNeeded)
    4320           4 :                 GDALWriteRPBFile(pszTIFFFilename, papszRPCMD);
    4321           8 :             bRPCSerializedOtherWay = true;
    4322             :         }
    4323             : 
    4324          32 :         if (CPLFetchBool(papszCreationOptions, "RPCTXT", false))
    4325             :         {
    4326           2 :             if (!bWriteOnlyInPAMIfNeeded)
    4327           1 :                 GDALWriteRPCTXTFile(pszTIFFFilename, papszRPCMD);
    4328           2 :             bRPCSerializedOtherWay = true;
    4329             :         }
    4330             : 
    4331          32 :         if (!bRPCSerializedOtherWay && bWriteOnlyInPAMIfNeeded && bSrcIsGeoTIFF)
    4332           1 :             cpl::down_cast<GTiffDataset *>(poSrcDS)
    4333           1 :                 ->GDALPamDataset::SetMetadata(papszRPCMD, MD_DOMAIN_RPC);
    4334             :     }
    4335       10302 : }
    4336             : 
    4337             : /************************************************************************/
    4338             : /*                           WriteMetadata()                            */
    4339             : /************************************************************************/
    4340             : 
    4341        8164 : bool GTiffDataset::WriteMetadata(GDALDataset *poSrcDS, TIFF *l_hTIFF,
    4342             :                                  bool bSrcIsGeoTIFF, GTiffProfile eProfile,
    4343             :                                  const char *pszTIFFFilename,
    4344             :                                  CSLConstList papszCreationOptions,
    4345             :                                  bool bExcludeRPBandIMGFileWriting)
    4346             : 
    4347             : {
    4348             :     /* -------------------------------------------------------------------- */
    4349             :     /*      Convert all the remaining metadata into a simple XML            */
    4350             :     /*      format.                                                         */
    4351             :     /* -------------------------------------------------------------------- */
    4352        8164 :     CPLXMLNode *psRoot = nullptr;
    4353        8164 :     CPLXMLNode *psTail = nullptr;
    4354             : 
    4355             :     const char *pszCopySrcMDD =
    4356        8164 :         CSLFetchNameValueDef(papszCreationOptions, "COPY_SRC_MDD", "AUTO");
    4357             :     char **papszSrcMDD =
    4358        8164 :         CSLFetchNameValueMultiple(papszCreationOptions, "SRC_MDD");
    4359             : 
    4360             :     GTiffDataset *poSrcDSGTiff =
    4361        8164 :         bSrcIsGeoTIFF ? cpl::down_cast<GTiffDataset *>(poSrcDS) : nullptr;
    4362             : 
    4363        8164 :     if (poSrcDSGTiff)
    4364             :     {
    4365        5999 :         WriteMDMetadata(&poSrcDSGTiff->m_oGTiffMDMD, l_hTIFF, &psRoot, &psTail,
    4366             :                         0, eProfile);
    4367             :     }
    4368             :     else
    4369             :     {
    4370        2165 :         if (EQUAL(pszCopySrcMDD, "AUTO") || CPLTestBool(pszCopySrcMDD) ||
    4371             :             papszSrcMDD)
    4372             :         {
    4373        4324 :             GDALMultiDomainMetadata l_oMDMD;
    4374             :             {
    4375        2162 :                 CSLConstList papszMD = poSrcDS->GetMetadata();
    4376        2166 :                 if (CSLCount(papszMD) > 0 &&
    4377           4 :                     (!papszSrcMDD || CSLFindString(papszSrcMDD, "") >= 0 ||
    4378           2 :                      CSLFindString(papszSrcMDD, "_DEFAULT_") >= 0))
    4379             :                 {
    4380        1644 :                     l_oMDMD.SetMetadata(papszMD);
    4381             :                 }
    4382             :             }
    4383             : 
    4384        2162 :             if (EQUAL(pszCopySrcMDD, "AUTO") && !papszSrcMDD)
    4385             :             {
    4386             :                 // Propagate ISIS3 or VICAR metadata
    4387        6459 :                 for (const char *pszMDD : {"json:ISIS3", "json:VICAR"})
    4388             :                 {
    4389        4306 :                     CSLConstList papszMD = poSrcDS->GetMetadata(pszMDD);
    4390        4306 :                     if (papszMD)
    4391             :                     {
    4392           5 :                         l_oMDMD.SetMetadata(papszMD, pszMDD);
    4393             :                     }
    4394             :                 }
    4395             :             }
    4396             : 
    4397        2162 :             if ((!EQUAL(pszCopySrcMDD, "AUTO") && CPLTestBool(pszCopySrcMDD)) ||
    4398             :                 papszSrcMDD)
    4399             :             {
    4400           9 :                 char **papszDomainList = poSrcDS->GetMetadataDomainList();
    4401          39 :                 for (CSLConstList papszIter = papszDomainList;
    4402          39 :                      papszIter && *papszIter; ++papszIter)
    4403             :                 {
    4404          30 :                     const char *pszDomain = *papszIter;
    4405          46 :                     if (pszDomain[0] != 0 &&
    4406          16 :                         (!papszSrcMDD ||
    4407          16 :                          CSLFindString(papszSrcMDD, pszDomain) >= 0))
    4408             :                     {
    4409          12 :                         l_oMDMD.SetMetadata(poSrcDS->GetMetadata(pszDomain),
    4410             :                                             pszDomain);
    4411             :                     }
    4412             :                 }
    4413           9 :                 CSLDestroy(papszDomainList);
    4414             :             }
    4415             : 
    4416        2162 :             WriteMDMetadata(&l_oMDMD, l_hTIFF, &psRoot, &psTail, 0, eProfile);
    4417             :         }
    4418             :     }
    4419             : 
    4420        8164 :     if (!bExcludeRPBandIMGFileWriting &&
    4421        5993 :         (!poSrcDSGTiff || poSrcDSGTiff->m_poBaseDS == nullptr))
    4422             :     {
    4423        8153 :         WriteRPC(poSrcDS, l_hTIFF, bSrcIsGeoTIFF, eProfile, pszTIFFFilename,
    4424             :                  papszCreationOptions);
    4425             : 
    4426             :         /* ------------------------------------------------------------------ */
    4427             :         /*      Handle metadata data written to an IMD file. */
    4428             :         /* ------------------------------------------------------------------ */
    4429        8153 :         CSLConstList papszIMDMD = poSrcDS->GetMetadata(MD_DOMAIN_IMD);
    4430        8153 :         if (papszIMDMD != nullptr)
    4431             :         {
    4432          20 :             GDALWriteIMDFile(pszTIFFFilename, papszIMDMD);
    4433             :         }
    4434             :     }
    4435             : 
    4436        8164 :     uint16_t nPhotometric = 0;
    4437        8164 :     if (!TIFFGetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, &(nPhotometric)))
    4438           1 :         nPhotometric = PHOTOMETRIC_MINISBLACK;
    4439             : 
    4440        8164 :     const bool bStandardColorInterp = GTIFFIsStandardColorInterpretation(
    4441             :         GDALDataset::ToHandle(poSrcDS), nPhotometric, papszCreationOptions);
    4442             : 
    4443             :     /* -------------------------------------------------------------------- */
    4444             :     /*      We also need to address band specific metadata, and special     */
    4445             :     /*      "role" metadata.                                                */
    4446             :     /* -------------------------------------------------------------------- */
    4447      316259 :     for (int nBand = 1; nBand <= poSrcDS->GetRasterCount(); ++nBand)
    4448             :     {
    4449      308095 :         GDALRasterBand *poBand = poSrcDS->GetRasterBand(nBand);
    4450             : 
    4451      308095 :         if (bSrcIsGeoTIFF)
    4452             :         {
    4453             :             GTiffRasterBand *poSrcBandGTiff =
    4454      303001 :                 cpl::down_cast<GTiffRasterBand *>(poBand);
    4455      303001 :             assert(poSrcBandGTiff);
    4456      303001 :             WriteMDMetadata(&poSrcBandGTiff->m_oGTiffMDMD, l_hTIFF, &psRoot,
    4457             :                             &psTail, nBand, eProfile);
    4458             :         }
    4459             :         else
    4460             :         {
    4461       10188 :             GDALMultiDomainMetadata l_oMDMD;
    4462        5094 :             bool bOMDMDSet = false;
    4463             : 
    4464        5094 :             if (EQUAL(pszCopySrcMDD, "AUTO") && !papszSrcMDD)
    4465             :             {
    4466       15246 :                 for (const char *pszDomain : {"", "IMAGERY"})
    4467             :                 {
    4468       10164 :                     if (CSLConstList papszMD = poBand->GetMetadata(pszDomain))
    4469             :                     {
    4470          90 :                         if (papszMD[0])
    4471             :                         {
    4472          90 :                             bOMDMDSet = true;
    4473          90 :                             l_oMDMD.SetMetadata(papszMD, pszDomain);
    4474             :                         }
    4475             :                     }
    4476        5082 :                 }
    4477             :             }
    4478          12 :             else if (CPLTestBool(pszCopySrcMDD) || papszSrcMDD)
    4479             :             {
    4480           9 :                 char **papszDomainList = poBand->GetMetadataDomainList();
    4481           3 :                 for (const char *pszDomain :
    4482          15 :                      cpl::Iterate(CSLConstList(papszDomainList)))
    4483             :                 {
    4484           9 :                     if (pszDomain[0] != 0 &&
    4485           5 :                         !EQUAL(pszDomain, "IMAGE_STRUCTURE") &&
    4486           2 :                         (!papszSrcMDD ||
    4487           2 :                          CSLFindString(papszSrcMDD, pszDomain) >= 0))
    4488             :                     {
    4489           2 :                         bOMDMDSet = true;
    4490           2 :                         l_oMDMD.SetMetadata(poBand->GetMetadata(pszDomain),
    4491             :                                             pszDomain);
    4492             :                     }
    4493             :                 }
    4494           9 :                 CSLDestroy(papszDomainList);
    4495             :             }
    4496             : 
    4497        5094 :             if (bOMDMDSet)
    4498             :             {
    4499          92 :                 WriteMDMetadata(&l_oMDMD, l_hTIFF, &psRoot, &psTail, nBand,
    4500             :                                 eProfile);
    4501             :             }
    4502             :         }
    4503             : 
    4504      308095 :         const double dfOffset = poBand->GetOffset();
    4505      308095 :         const double dfScale = poBand->GetScale();
    4506      308095 :         bool bGeoTIFFScaleOffsetInZ = false;
    4507      308095 :         GDALGeoTransform gt;
    4508             :         // Check if we have already encoded scale/offset in the GeoTIFF tags
    4509      314310 :         if (poSrcDS->GetGeoTransform(gt) == CE_None && gt.xrot == 0.0 &&
    4510        6199 :             gt.yrot == 0.0 && gt.yscale < 0.0 && poSrcDS->GetSpatialRef() &&
    4511      314317 :             poSrcDS->GetSpatialRef()->IsVertical() &&
    4512           7 :             poSrcDS->GetRasterCount() == 1)
    4513             :         {
    4514           7 :             bGeoTIFFScaleOffsetInZ = true;
    4515             :         }
    4516             : 
    4517      308095 :         if ((dfOffset != 0.0 || dfScale != 1.0) && !bGeoTIFFScaleOffsetInZ)
    4518             :         {
    4519          25 :             char szValue[128] = {};
    4520             : 
    4521          25 :             CPLsnprintf(szValue, sizeof(szValue), "%.17g", dfOffset);
    4522          25 :             AppendMetadataItem(&psRoot, &psTail, "OFFSET", szValue, nBand,
    4523             :                                "offset", "");
    4524          25 :             CPLsnprintf(szValue, sizeof(szValue), "%.17g", dfScale);
    4525          25 :             AppendMetadataItem(&psRoot, &psTail, "SCALE", szValue, nBand,
    4526             :                                "scale", "");
    4527             :         }
    4528             : 
    4529      308095 :         const char *pszUnitType = poBand->GetUnitType();
    4530      308095 :         if (pszUnitType != nullptr && pszUnitType[0] != '\0')
    4531             :         {
    4532          40 :             bool bWriteUnit = true;
    4533          40 :             auto poSRS = poSrcDS->GetSpatialRef();
    4534          40 :             if (poSRS && poSRS->IsCompound())
    4535             :             {
    4536           2 :                 const char *pszVertUnit = nullptr;
    4537           2 :                 poSRS->GetTargetLinearUnits("COMPD_CS|VERT_CS", &pszVertUnit);
    4538           2 :                 if (pszVertUnit && EQUAL(pszVertUnit, pszUnitType))
    4539             :                 {
    4540           2 :                     bWriteUnit = false;
    4541             :                 }
    4542             :             }
    4543          40 :             if (bWriteUnit)
    4544             :             {
    4545          38 :                 AppendMetadataItem(&psRoot, &psTail, "UNITTYPE", pszUnitType,
    4546             :                                    nBand, "unittype", "");
    4547             :             }
    4548             :         }
    4549             : 
    4550      308095 :         if (strlen(poBand->GetDescription()) > 0)
    4551             :         {
    4552          25 :             AppendMetadataItem(&psRoot, &psTail, "DESCRIPTION",
    4553          25 :                                poBand->GetDescription(), nBand, "description",
    4554             :                                "");
    4555             :         }
    4556             : 
    4557      308312 :         if (!bStandardColorInterp &&
    4558         217 :             !(nBand <= 3 && EQUAL(CSLFetchNameValueDef(papszCreationOptions,
    4559             :                                                        "PHOTOMETRIC", ""),
    4560             :                                   "RGB")))
    4561             :         {
    4562         250 :             AppendMetadataItem(&psRoot, &psTail, "COLORINTERP",
    4563             :                                GDALGetColorInterpretationName(
    4564         250 :                                    poBand->GetColorInterpretation()),
    4565             :                                nBand, "colorinterp", "");
    4566             :         }
    4567             :     }
    4568             : 
    4569        8164 :     CSLDestroy(papszSrcMDD);
    4570             : 
    4571             :     const char *pszTilingSchemeName =
    4572        8164 :         CSLFetchNameValue(papszCreationOptions, "@TILING_SCHEME_NAME");
    4573        8164 :     if (pszTilingSchemeName)
    4574             :     {
    4575          23 :         AppendMetadataItem(&psRoot, &psTail, "NAME", pszTilingSchemeName, 0,
    4576             :                            nullptr, "TILING_SCHEME");
    4577             : 
    4578          23 :         const char *pszZoomLevel = CSLFetchNameValue(
    4579             :             papszCreationOptions, "@TILING_SCHEME_ZOOM_LEVEL");
    4580          23 :         if (pszZoomLevel)
    4581             :         {
    4582          23 :             AppendMetadataItem(&psRoot, &psTail, "ZOOM_LEVEL", pszZoomLevel, 0,
    4583             :                                nullptr, "TILING_SCHEME");
    4584             :         }
    4585             : 
    4586          23 :         const char *pszAlignedLevels = CSLFetchNameValue(
    4587             :             papszCreationOptions, "@TILING_SCHEME_ALIGNED_LEVELS");
    4588          23 :         if (pszAlignedLevels)
    4589             :         {
    4590           4 :             AppendMetadataItem(&psRoot, &psTail, "ALIGNED_LEVELS",
    4591             :                                pszAlignedLevels, 0, nullptr, "TILING_SCHEME");
    4592             :         }
    4593             :     }
    4594             : 
    4595        8164 :     if (const char *pszOverviewResampling =
    4596        8164 :             CSLFetchNameValue(papszCreationOptions, "@OVERVIEW_RESAMPLING"))
    4597             :     {
    4598          41 :         AppendMetadataItem(&psRoot, &psTail, "OVERVIEW_RESAMPLING",
    4599             :                            pszOverviewResampling, 0, nullptr,
    4600             :                            "IMAGE_STRUCTURE");
    4601             :     }
    4602             : 
    4603             :     /* -------------------------------------------------------------------- */
    4604             :     /*      Write information about some codecs.                            */
    4605             :     /* -------------------------------------------------------------------- */
    4606        8164 :     if (CPLTestBool(
    4607             :             CPLGetConfigOption("GTIFF_WRITE_IMAGE_STRUCTURE_METADATA", "YES")))
    4608             :     {
    4609             :         const char *pszTileInterleave =
    4610        8159 :             CSLFetchNameValue(papszCreationOptions, "@TILE_INTERLEAVE");
    4611        8159 :         if (pszTileInterleave && CPLTestBool(pszTileInterleave))
    4612             :         {
    4613           7 :             AppendMetadataItem(&psRoot, &psTail, "INTERLEAVE", "TILE", 0,
    4614             :                                nullptr, "IMAGE_STRUCTURE");
    4615             :         }
    4616             : 
    4617             :         const char *pszCompress =
    4618        8159 :             CSLFetchNameValue(papszCreationOptions, "COMPRESS");
    4619        8159 :         if (pszCompress && EQUAL(pszCompress, "WEBP"))
    4620             :         {
    4621          31 :             if (GTiffGetWebPLossless(papszCreationOptions))
    4622             :             {
    4623           6 :                 AppendMetadataItem(&psRoot, &psTail,
    4624             :                                    "COMPRESSION_REVERSIBILITY", "LOSSLESS", 0,
    4625             :                                    nullptr, "IMAGE_STRUCTURE");
    4626             :             }
    4627             :             else
    4628             :             {
    4629          25 :                 AppendMetadataItem(
    4630             :                     &psRoot, &psTail, "WEBP_LEVEL",
    4631          25 :                     CPLSPrintf("%d", GTiffGetWebPLevel(papszCreationOptions)),
    4632             :                     0, nullptr, "IMAGE_STRUCTURE");
    4633             :             }
    4634             :         }
    4635        8128 :         else if (pszCompress && STARTS_WITH_CI(pszCompress, "LERC"))
    4636             :         {
    4637             :             const double dfMaxZError =
    4638          97 :                 GTiffGetLERCMaxZError(papszCreationOptions);
    4639             :             const double dfMaxZErrorOverview =
    4640          97 :                 GTiffGetLERCMaxZErrorOverview(papszCreationOptions);
    4641          97 :             if (dfMaxZError == 0.0 && dfMaxZErrorOverview == 0.0)
    4642             :             {
    4643          83 :                 AppendMetadataItem(&psRoot, &psTail,
    4644             :                                    "COMPRESSION_REVERSIBILITY", "LOSSLESS", 0,
    4645             :                                    nullptr, "IMAGE_STRUCTURE");
    4646             :             }
    4647             :             else
    4648             :             {
    4649          14 :                 AppendMetadataItem(&psRoot, &psTail, "MAX_Z_ERROR",
    4650             :                                    CSLFetchNameValueDef(papszCreationOptions,
    4651             :                                                         "MAX_Z_ERROR", ""),
    4652             :                                    0, nullptr, "IMAGE_STRUCTURE");
    4653          14 :                 if (dfMaxZError != dfMaxZErrorOverview)
    4654             :                 {
    4655           3 :                     AppendMetadataItem(
    4656             :                         &psRoot, &psTail, "MAX_Z_ERROR_OVERVIEW",
    4657             :                         CSLFetchNameValueDef(papszCreationOptions,
    4658             :                                              "MAX_Z_ERROR_OVERVIEW", ""),
    4659             :                         0, nullptr, "IMAGE_STRUCTURE");
    4660             :                 }
    4661          97 :             }
    4662             :         }
    4663             : #if HAVE_JXL
    4664        8031 :         else if (pszCompress && EQUAL(pszCompress, "JXL"))
    4665             :         {
    4666         101 :             float fDistance = 0.0f;
    4667         101 :             if (GTiffGetJXLLossless(papszCreationOptions))
    4668             :             {
    4669          82 :                 AppendMetadataItem(&psRoot, &psTail,
    4670             :                                    "COMPRESSION_REVERSIBILITY", "LOSSLESS", 0,
    4671             :                                    nullptr, "IMAGE_STRUCTURE");
    4672             :             }
    4673             :             else
    4674             :             {
    4675          19 :                 fDistance = GTiffGetJXLDistance(papszCreationOptions);
    4676          19 :                 AppendMetadataItem(
    4677             :                     &psRoot, &psTail, "JXL_DISTANCE",
    4678             :                     CPLSPrintf("%f", static_cast<double>(fDistance)), 0,
    4679             :                     nullptr, "IMAGE_STRUCTURE");
    4680             :             }
    4681             :             const float fAlphaDistance =
    4682         101 :                 GTiffGetJXLAlphaDistance(papszCreationOptions);
    4683         101 :             if (fAlphaDistance >= 0.0f && fAlphaDistance != fDistance)
    4684             :             {
    4685           2 :                 AppendMetadataItem(
    4686             :                     &psRoot, &psTail, "JXL_ALPHA_DISTANCE",
    4687             :                     CPLSPrintf("%f", static_cast<double>(fAlphaDistance)), 0,
    4688             :                     nullptr, "IMAGE_STRUCTURE");
    4689             :             }
    4690         101 :             AppendMetadataItem(
    4691             :                 &psRoot, &psTail, "JXL_EFFORT",
    4692             :                 CPLSPrintf("%d", GTiffGetJXLEffort(papszCreationOptions)), 0,
    4693             :                 nullptr, "IMAGE_STRUCTURE");
    4694             :         }
    4695             : #endif
    4696             :     }
    4697             : 
    4698        8164 :     if (!CPLTestBool(CPLGetConfigOption("GTIFF_WRITE_RAT_TO_PAM", "NO")))
    4699             :     {
    4700      316253 :         for (int nBand = 1; nBand <= poSrcDS->GetRasterCount(); ++nBand)
    4701             :         {
    4702      308092 :             GDALRasterAttributeTable *poRAT = nullptr;
    4703      308092 :             if (poSrcDSGTiff)
    4704             :             {
    4705      302999 :                 auto poBand = cpl::down_cast<GTiffRasterBand *>(
    4706             :                     poSrcDSGTiff->GetRasterBand(nBand));
    4707             :                 // Scenario of https://github.com/OSGeo/gdal/issues/13930
    4708             :                 // Do not try to fetch the RAT from auxiliary files if creating
    4709             :                 // a new GeoTIFF file
    4710      302999 :                 if (poBand->m_bRATSet)
    4711         106 :                     poRAT = poBand->GetDefaultRAT();
    4712             :             }
    4713             :             else
    4714             :             {
    4715        5093 :                 poRAT = poSrcDS->GetRasterBand(nBand)->GetDefaultRAT();
    4716             :             }
    4717      308092 :             if (poRAT)
    4718             :             {
    4719          23 :                 auto psSerializedRAT = poRAT->Serialize();
    4720          23 :                 if (psSerializedRAT)
    4721             :                 {
    4722          21 :                     AppendMetadataItem(
    4723             :                         &psRoot, &psTail, DEFAULT_RASTER_ATTRIBUTE_TABLE,
    4724             :                         nullptr, psSerializedRAT, nBand, RAT_ROLE, nullptr);
    4725             :                 }
    4726             :             }
    4727             :         }
    4728             :     }
    4729             : 
    4730             :     /* -------------------------------------------------------------------- */
    4731             :     /*      Write out the generic XML metadata if there is any.             */
    4732             :     /* -------------------------------------------------------------------- */
    4733        8164 :     if (psRoot != nullptr)
    4734             :     {
    4735         765 :         bool bRet = true;
    4736             : 
    4737         765 :         if (eProfile == GTiffProfile::GDALGEOTIFF)
    4738             :         {
    4739         748 :             char *pszXML_MD = CPLSerializeXMLTree(psRoot);
    4740         748 :             TIFFSetField(l_hTIFF, TIFFTAG_GDAL_METADATA, pszXML_MD);
    4741         748 :             CPLFree(pszXML_MD);
    4742             :         }
    4743             :         else
    4744             :         {
    4745          17 :             if (bSrcIsGeoTIFF)
    4746          11 :                 cpl::down_cast<GTiffDataset *>(poSrcDS)->PushMetadataToPam();
    4747             :             else
    4748           6 :                 bRet = false;
    4749             :         }
    4750             : 
    4751         765 :         CPLDestroyXMLNode(psRoot);
    4752             : 
    4753         765 :         return bRet;
    4754             :     }
    4755             : 
    4756             :     // If we have no more metadata but it existed before,
    4757             :     // remove the GDAL_METADATA tag.
    4758        7399 :     if (eProfile == GTiffProfile::GDALGEOTIFF)
    4759             :     {
    4760        7375 :         char *pszText = nullptr;
    4761        7375 :         if (TIFFGetField(l_hTIFF, TIFFTAG_GDAL_METADATA, &pszText))
    4762             :         {
    4763           7 :             TIFFUnsetField(l_hTIFF, TIFFTAG_GDAL_METADATA);
    4764             :         }
    4765             :     }
    4766             : 
    4767        7399 :     return true;
    4768             : }
    4769             : 
    4770             : /************************************************************************/
    4771             : /*                         PushMetadataToPam()                          */
    4772             : /*                                                                      */
    4773             : /*      When producing a strict profile TIFF or if our aggregate        */
    4774             : /*      metadata is too big for a single tiff tag we may end up         */
    4775             : /*      needing to write it via the PAM mechanisms.  This method        */
    4776             : /*      copies all the appropriate metadata into the PAM level          */
    4777             : /*      metadata object but with special care to avoid copying          */
    4778             : /*      metadata handled in other ways in TIFF format.                  */
    4779             : /************************************************************************/
    4780             : 
    4781          17 : void GTiffDataset::PushMetadataToPam()
    4782             : 
    4783             : {
    4784          17 :     if (GetPamFlags() & GPF_DISABLED)
    4785           0 :         return;
    4786             : 
    4787          17 :     const bool bStandardColorInterp = GTIFFIsStandardColorInterpretation(
    4788          17 :         GDALDataset::ToHandle(this), m_nPhotometric, m_papszCreationOptions);
    4789             : 
    4790          55 :     for (int nBand = 0; nBand <= GetRasterCount(); ++nBand)
    4791             :     {
    4792          38 :         GDALMultiDomainMetadata *poSrcMDMD = nullptr;
    4793          38 :         GTiffRasterBand *poBand = nullptr;
    4794             : 
    4795          38 :         if (nBand == 0)
    4796             :         {
    4797          17 :             poSrcMDMD = &(this->m_oGTiffMDMD);
    4798             :         }
    4799             :         else
    4800             :         {
    4801          21 :             poBand = cpl::down_cast<GTiffRasterBand *>(GetRasterBand(nBand));
    4802          21 :             poSrcMDMD = &(poBand->m_oGTiffMDMD);
    4803             :         }
    4804             : 
    4805             :         /* --------------------------------------------------------------------
    4806             :          */
    4807             :         /*      Loop over the available domains. */
    4808             :         /* --------------------------------------------------------------------
    4809             :          */
    4810          38 :         CSLConstList papszDomainList = poSrcMDMD->GetDomainList();
    4811          74 :         for (int iDomain = 0; papszDomainList && papszDomainList[iDomain];
    4812             :              ++iDomain)
    4813             :         {
    4814          36 :             char **papszMD = poSrcMDMD->GetMetadata(papszDomainList[iDomain]);
    4815             : 
    4816          36 :             if (EQUAL(papszDomainList[iDomain], MD_DOMAIN_RPC) ||
    4817          36 :                 EQUAL(papszDomainList[iDomain], MD_DOMAIN_IMD) ||
    4818          36 :                 EQUAL(papszDomainList[iDomain], "_temporary_") ||
    4819          36 :                 EQUAL(papszDomainList[iDomain], "IMAGE_STRUCTURE") ||
    4820          19 :                 EQUAL(papszDomainList[iDomain], "COLOR_PROFILE"))
    4821          17 :                 continue;
    4822             : 
    4823          19 :             papszMD = CSLDuplicate(papszMD);
    4824             : 
    4825          69 :             for (int i = CSLCount(papszMD) - 1; i >= 0; --i)
    4826             :             {
    4827          50 :                 if (STARTS_WITH_CI(papszMD[i], "TIFFTAG_") ||
    4828          50 :                     EQUALN(papszMD[i], GDALMD_AREA_OR_POINT,
    4829             :                            strlen(GDALMD_AREA_OR_POINT)))
    4830           4 :                     papszMD = CSLRemoveStrings(papszMD, i, 1, nullptr);
    4831             :             }
    4832             : 
    4833          19 :             if (!poBand)
    4834          10 :                 GDALPamDataset::SetMetadata(papszMD, papszDomainList[iDomain]);
    4835             :             else
    4836           9 :                 poBand->GDALPamRasterBand::SetMetadata(
    4837           9 :                     papszMD, papszDomainList[iDomain]);
    4838             : 
    4839          19 :             CSLDestroy(papszMD);
    4840             :         }
    4841             : 
    4842             :         /* --------------------------------------------------------------------
    4843             :          */
    4844             :         /*      Handle some "special domain" stuff. */
    4845             :         /* --------------------------------------------------------------------
    4846             :          */
    4847          38 :         if (poBand != nullptr)
    4848             :         {
    4849          21 :             poBand->GDALPamRasterBand::SetOffset(poBand->GetOffset());
    4850          21 :             poBand->GDALPamRasterBand::SetScale(poBand->GetScale());
    4851          21 :             poBand->GDALPamRasterBand::SetUnitType(poBand->GetUnitType());
    4852          21 :             poBand->GDALPamRasterBand::SetDescription(poBand->GetDescription());
    4853          21 :             if (!bStandardColorInterp)
    4854             :             {
    4855           3 :                 poBand->GDALPamRasterBand::SetColorInterpretation(
    4856           3 :                     poBand->GetColorInterpretation());
    4857             :             }
    4858             :         }
    4859             :     }
    4860          17 :     MarkPamDirty();
    4861             : }
    4862             : 
    4863             : /************************************************************************/
    4864             : /*                          WriteNoDataValue()                          */
    4865             : /************************************************************************/
    4866             : 
    4867         532 : void GTiffDataset::WriteNoDataValue(TIFF *hTIFF, double dfNoData)
    4868             : 
    4869             : {
    4870        1064 :     CPLString osVal(GTiffFormatGDALNoDataTagValue(dfNoData));
    4871         532 :     TIFFSetField(hTIFF, TIFFTAG_GDAL_NODATA, osVal.c_str());
    4872         532 : }
    4873             : 
    4874           5 : void GTiffDataset::WriteNoDataValue(TIFF *hTIFF, int64_t nNoData)
    4875             : 
    4876             : {
    4877           5 :     TIFFSetField(hTIFF, TIFFTAG_GDAL_NODATA,
    4878             :                  CPLSPrintf(CPL_FRMT_GIB, static_cast<GIntBig>(nNoData)));
    4879           5 : }
    4880             : 
    4881           5 : void GTiffDataset::WriteNoDataValue(TIFF *hTIFF, uint64_t nNoData)
    4882             : 
    4883             : {
    4884           5 :     TIFFSetField(hTIFF, TIFFTAG_GDAL_NODATA,
    4885             :                  CPLSPrintf(CPL_FRMT_GUIB, static_cast<GUIntBig>(nNoData)));
    4886           5 : }
    4887             : 
    4888             : /************************************************************************/
    4889             : /*                          UnsetNoDataValue()                          */
    4890             : /************************************************************************/
    4891             : 
    4892          16 : void GTiffDataset::UnsetNoDataValue(TIFF *l_hTIFF)
    4893             : 
    4894             : {
    4895          16 :     TIFFUnsetField(l_hTIFF, TIFFTAG_GDAL_NODATA);
    4896          16 : }
    4897             : 
    4898             : /************************************************************************/
    4899             : /*                             SaveICCProfile()                         */
    4900             : /*                                                                      */
    4901             : /*      Save ICC Profile or colorimetric data into file                 */
    4902             : /* pDS:                                                                 */
    4903             : /*      Dataset that contains the metadata with the ICC or colorimetric */
    4904             : /*      data. If this argument is specified, all other arguments are    */
    4905             : /*      ignored. Set them to NULL or 0.                                 */
    4906             : /* hTIFF:                                                               */
    4907             : /*      Pointer to TIFF handle. Only needed if pDS is NULL or           */
    4908             : /*      pDS->m_hTIFF is NULL.                                             */
    4909             : /* papszParamList:                                                       */
    4910             : /*      Options containing the ICC profile or colorimetric metadata.    */
    4911             : /*      Ignored if pDS is not NULL.                                     */
    4912             : /* nBitsPerSample:                                                      */
    4913             : /*      Bits per sample. Ignored if pDS is not NULL.                    */
    4914             : /************************************************************************/
    4915             : 
    4916        9909 : void GTiffDataset::SaveICCProfile(GTiffDataset *pDS, TIFF *l_hTIFF,
    4917             :                                   CSLConstList papszParamList,
    4918             :                                   uint32_t l_nBitsPerSample)
    4919             : {
    4920        9909 :     if ((pDS != nullptr) && (pDS->eAccess != GA_Update))
    4921           0 :         return;
    4922             : 
    4923        9909 :     if (l_hTIFF == nullptr)
    4924             :     {
    4925           2 :         if (pDS == nullptr)
    4926           0 :             return;
    4927             : 
    4928           2 :         l_hTIFF = pDS->m_hTIFF;
    4929           2 :         if (l_hTIFF == nullptr)
    4930           0 :             return;
    4931             :     }
    4932             : 
    4933        9909 :     if ((papszParamList == nullptr) && (pDS == nullptr))
    4934        4925 :         return;
    4935             : 
    4936             :     const char *pszICCProfile =
    4937             :         (pDS != nullptr)
    4938        4984 :             ? pDS->GetMetadataItem("SOURCE_ICC_PROFILE", "COLOR_PROFILE")
    4939        4982 :             : CSLFetchNameValue(papszParamList, "SOURCE_ICC_PROFILE");
    4940        4984 :     if (pszICCProfile != nullptr)
    4941             :     {
    4942           8 :         char *pEmbedBuffer = CPLStrdup(pszICCProfile);
    4943             :         int32_t nEmbedLen =
    4944           8 :             CPLBase64DecodeInPlace(reinterpret_cast<GByte *>(pEmbedBuffer));
    4945             : 
    4946           8 :         TIFFSetField(l_hTIFF, TIFFTAG_ICCPROFILE, nEmbedLen, pEmbedBuffer);
    4947             : 
    4948           8 :         CPLFree(pEmbedBuffer);
    4949             :     }
    4950             :     else
    4951             :     {
    4952             :         // Output colorimetric data.
    4953        4976 :         float pCHR[6] = {};     // Primaries.
    4954        4976 :         uint16_t pTXR[6] = {};  // Transfer range.
    4955        4976 :         const char *pszCHRNames[] = {"SOURCE_PRIMARIES_RED",
    4956             :                                      "SOURCE_PRIMARIES_GREEN",
    4957             :                                      "SOURCE_PRIMARIES_BLUE"};
    4958        4976 :         const char *pszTXRNames[] = {"TIFFTAG_TRANSFERRANGE_BLACK",
    4959             :                                      "TIFFTAG_TRANSFERRANGE_WHITE"};
    4960             : 
    4961             :         // Output chromacities.
    4962        4976 :         bool bOutputCHR = true;
    4963        4991 :         for (int i = 0; i < 3 && bOutputCHR; ++i)
    4964             :         {
    4965             :             const char *pszColorProfile =
    4966             :                 (pDS != nullptr)
    4967        4986 :                     ? pDS->GetMetadataItem(pszCHRNames[i], "COLOR_PROFILE")
    4968        4983 :                     : CSLFetchNameValue(papszParamList, pszCHRNames[i]);
    4969        4986 :             if (pszColorProfile == nullptr)
    4970             :             {
    4971        4971 :                 bOutputCHR = false;
    4972        4971 :                 break;
    4973             :             }
    4974             : 
    4975             :             const CPLStringList aosTokens(CSLTokenizeString2(
    4976             :                 pszColorProfile, ",",
    4977             :                 CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES |
    4978          15 :                     CSLT_STRIPENDSPACES));
    4979             : 
    4980          15 :             if (aosTokens.size() != 3)
    4981             :             {
    4982           0 :                 bOutputCHR = false;
    4983           0 :                 break;
    4984             :             }
    4985             : 
    4986          60 :             for (int j = 0; j < 3; ++j)
    4987             :             {
    4988          45 :                 float v = static_cast<float>(CPLAtof(aosTokens[j]));
    4989             : 
    4990          45 :                 if (j == 2)
    4991             :                 {
    4992             :                     // Last term of xyY color must be 1.0.
    4993          15 :                     if (v != 1.0f)
    4994             :                     {
    4995           0 :                         bOutputCHR = false;
    4996           0 :                         break;
    4997             :                     }
    4998             :                 }
    4999             :                 else
    5000             :                 {
    5001          30 :                     pCHR[i * 2 + j] = v;
    5002             :                 }
    5003             :             }
    5004             :         }
    5005             : 
    5006        4976 :         if (bOutputCHR)
    5007             :         {
    5008           5 :             TIFFSetField(l_hTIFF, TIFFTAG_PRIMARYCHROMATICITIES, pCHR);
    5009             :         }
    5010             : 
    5011             :         // Output whitepoint.
    5012             :         const char *pszSourceWhitePoint =
    5013             :             (pDS != nullptr)
    5014        4976 :                 ? pDS->GetMetadataItem("SOURCE_WHITEPOINT", "COLOR_PROFILE")
    5015        4975 :                 : CSLFetchNameValue(papszParamList, "SOURCE_WHITEPOINT");
    5016        4976 :         if (pszSourceWhitePoint != nullptr)
    5017             :         {
    5018             :             const CPLStringList aosTokens(CSLTokenizeString2(
    5019             :                 pszSourceWhitePoint, ",",
    5020             :                 CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES |
    5021          10 :                     CSLT_STRIPENDSPACES));
    5022             : 
    5023           5 :             bool bOutputWhitepoint = true;
    5024           5 :             float pWP[2] = {0.0f, 0.0f};  // Whitepoint
    5025           5 :             if (aosTokens.size() != 3)
    5026             :             {
    5027           0 :                 bOutputWhitepoint = false;
    5028             :             }
    5029             :             else
    5030             :             {
    5031          20 :                 for (int j = 0; j < 3; ++j)
    5032             :                 {
    5033          15 :                     const float v = static_cast<float>(CPLAtof(aosTokens[j]));
    5034             : 
    5035          15 :                     if (j == 2)
    5036             :                     {
    5037             :                         // Last term of xyY color must be 1.0.
    5038           5 :                         if (v != 1.0f)
    5039             :                         {
    5040           0 :                             bOutputWhitepoint = false;
    5041           0 :                             break;
    5042             :                         }
    5043             :                     }
    5044             :                     else
    5045             :                     {
    5046          10 :                         pWP[j] = v;
    5047             :                     }
    5048             :                 }
    5049             :             }
    5050             : 
    5051           5 :             if (bOutputWhitepoint)
    5052             :             {
    5053           5 :                 TIFFSetField(l_hTIFF, TIFFTAG_WHITEPOINT, pWP);
    5054             :             }
    5055             :         }
    5056             : 
    5057             :         // Set transfer function metadata.
    5058             :         char const *pszTFRed =
    5059             :             (pDS != nullptr)
    5060        4976 :                 ? pDS->GetMetadataItem("TIFFTAG_TRANSFERFUNCTION_RED",
    5061             :                                        "COLOR_PROFILE")
    5062        4975 :                 : CSLFetchNameValue(papszParamList,
    5063        4976 :                                     "TIFFTAG_TRANSFERFUNCTION_RED");
    5064             : 
    5065             :         char const *pszTFGreen =
    5066             :             (pDS != nullptr)
    5067        4976 :                 ? pDS->GetMetadataItem("TIFFTAG_TRANSFERFUNCTION_GREEN",
    5068             :                                        "COLOR_PROFILE")
    5069        4975 :                 : CSLFetchNameValue(papszParamList,
    5070        4976 :                                     "TIFFTAG_TRANSFERFUNCTION_GREEN");
    5071             : 
    5072             :         char const *pszTFBlue =
    5073             :             (pDS != nullptr)
    5074        4976 :                 ? pDS->GetMetadataItem("TIFFTAG_TRANSFERFUNCTION_BLUE",
    5075             :                                        "COLOR_PROFILE")
    5076        4975 :                 : CSLFetchNameValue(papszParamList,
    5077        4976 :                                     "TIFFTAG_TRANSFERFUNCTION_BLUE");
    5078             : 
    5079        4976 :         if ((pszTFRed != nullptr) && (pszTFGreen != nullptr) &&
    5080             :             (pszTFBlue != nullptr))
    5081             :         {
    5082             :             // Get length of table.
    5083           4 :             const int nTransferFunctionLength =
    5084           4 :                 1 << ((pDS != nullptr) ? pDS->m_nBitsPerSample
    5085             :                                        : l_nBitsPerSample);
    5086             : 
    5087             :             const CPLStringList aosTokensRed(CSLTokenizeString2(
    5088             :                 pszTFRed, ",",
    5089             :                 CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES |
    5090           8 :                     CSLT_STRIPENDSPACES));
    5091             :             const CPLStringList aosTokensGreen(CSLTokenizeString2(
    5092             :                 pszTFGreen, ",",
    5093             :                 CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES |
    5094           8 :                     CSLT_STRIPENDSPACES));
    5095             :             const CPLStringList aosTokensBlue(CSLTokenizeString2(
    5096             :                 pszTFBlue, ",",
    5097             :                 CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES |
    5098           8 :                     CSLT_STRIPENDSPACES));
    5099             : 
    5100           4 :             if ((aosTokensRed.size() == nTransferFunctionLength) &&
    5101           8 :                 (aosTokensGreen.size() == nTransferFunctionLength) &&
    5102           4 :                 (aosTokensBlue.size() == nTransferFunctionLength))
    5103             :             {
    5104             :                 std::vector<uint16_t> anTransferFuncRed(
    5105           8 :                     nTransferFunctionLength);
    5106             :                 std::vector<uint16_t> anTransferFuncGreen(
    5107           8 :                     nTransferFunctionLength);
    5108             :                 std::vector<uint16_t> anTransferFuncBlue(
    5109           8 :                     nTransferFunctionLength);
    5110             : 
    5111             :                 // Convert our table in string format into int16_t format.
    5112        1028 :                 for (int i = 0; i < nTransferFunctionLength; ++i)
    5113             :                 {
    5114        2048 :                     anTransferFuncRed[i] =
    5115        1024 :                         static_cast<uint16_t>(atoi(aosTokensRed[i]));
    5116        2048 :                     anTransferFuncGreen[i] =
    5117        1024 :                         static_cast<uint16_t>(atoi(aosTokensGreen[i]));
    5118        1024 :                     anTransferFuncBlue[i] =
    5119        1024 :                         static_cast<uint16_t>(atoi(aosTokensBlue[i]));
    5120             :                 }
    5121             : 
    5122           4 :                 TIFFSetField(
    5123             :                     l_hTIFF, TIFFTAG_TRANSFERFUNCTION, anTransferFuncRed.data(),
    5124             :                     anTransferFuncGreen.data(), anTransferFuncBlue.data());
    5125             :             }
    5126             :         }
    5127             : 
    5128             :         // Output transfer range.
    5129        4976 :         bool bOutputTransferRange = true;
    5130        4976 :         for (int i = 0; (i < 2) && bOutputTransferRange; ++i)
    5131             :         {
    5132             :             const char *pszTXRVal =
    5133             :                 (pDS != nullptr)
    5134        4976 :                     ? pDS->GetMetadataItem(pszTXRNames[i], "COLOR_PROFILE")
    5135        4975 :                     : CSLFetchNameValue(papszParamList, pszTXRNames[i]);
    5136        4976 :             if (pszTXRVal == nullptr)
    5137             :             {
    5138        4976 :                 bOutputTransferRange = false;
    5139        4976 :                 break;
    5140             :             }
    5141             : 
    5142             :             const CPLStringList aosTokens(CSLTokenizeString2(
    5143             :                 pszTXRVal, ",",
    5144             :                 CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES |
    5145           0 :                     CSLT_STRIPENDSPACES));
    5146             : 
    5147           0 :             if (aosTokens.size() != 3)
    5148             :             {
    5149           0 :                 bOutputTransferRange = false;
    5150           0 :                 break;
    5151             :             }
    5152             : 
    5153           0 :             for (int j = 0; j < 3; ++j)
    5154             :             {
    5155           0 :                 pTXR[i + j * 2] = static_cast<uint16_t>(atoi(aosTokens[j]));
    5156             :             }
    5157             :         }
    5158             : 
    5159        4976 :         if (bOutputTransferRange)
    5160             :         {
    5161           0 :             const int TIFFTAG_TRANSFERRANGE = 0x0156;
    5162           0 :             TIFFSetField(l_hTIFF, TIFFTAG_TRANSFERRANGE, pTXR);
    5163             :         }
    5164             :     }
    5165             : }
    5166             : 
    5167       17913 : static signed char GTiffGetLZMAPreset(CSLConstList papszOptions)
    5168             : {
    5169       17913 :     int nLZMAPreset = -1;
    5170       17913 :     const char *pszValue = CSLFetchNameValue(papszOptions, "LZMA_PRESET");
    5171       17913 :     if (pszValue != nullptr)
    5172             :     {
    5173          20 :         nLZMAPreset = atoi(pszValue);
    5174          20 :         if (!(nLZMAPreset >= 0 && nLZMAPreset <= 9))
    5175             :         {
    5176           0 :             CPLError(CE_Warning, CPLE_IllegalArg,
    5177             :                      "LZMA_PRESET=%s value not recognised, ignoring.",
    5178             :                      pszValue);
    5179           0 :             nLZMAPreset = -1;
    5180             :         }
    5181             :     }
    5182       17913 :     return static_cast<signed char>(nLZMAPreset);
    5183             : }
    5184             : 
    5185       17913 : static signed char GTiffGetZSTDPreset(CSLConstList papszOptions)
    5186             : {
    5187       17913 :     int nZSTDLevel = -1;
    5188       17913 :     const char *pszValue = CSLFetchNameValue(papszOptions, "ZSTD_LEVEL");
    5189       17913 :     if (pszValue != nullptr)
    5190             :     {
    5191          24 :         nZSTDLevel = atoi(pszValue);
    5192          24 :         if (!(nZSTDLevel >= 1 && nZSTDLevel <= 22))
    5193             :         {
    5194           0 :             CPLError(CE_Warning, CPLE_IllegalArg,
    5195             :                      "ZSTD_LEVEL=%s value not recognised, ignoring.", pszValue);
    5196           0 :             nZSTDLevel = -1;
    5197             :         }
    5198             :     }
    5199       17913 :     return static_cast<signed char>(nZSTDLevel);
    5200             : }
    5201             : 
    5202       17913 : static signed char GTiffGetZLevel(CSLConstList papszOptions)
    5203             : {
    5204       17913 :     int nZLevel = -1;
    5205       17913 :     const char *pszValue = CSLFetchNameValue(papszOptions, "ZLEVEL");
    5206       17913 :     if (pszValue != nullptr)
    5207             :     {
    5208          44 :         nZLevel = atoi(pszValue);
    5209             : #ifdef TIFFTAG_DEFLATE_SUBCODEC
    5210          44 :         constexpr int nMaxLevel = 12;
    5211             : #ifndef LIBDEFLATE_SUPPORT
    5212             :         if (nZLevel > 9 && nZLevel <= nMaxLevel)
    5213             :         {
    5214             :             CPLDebug("GTiff",
    5215             :                      "ZLEVEL=%d not supported in a non-libdeflate enabled "
    5216             :                      "libtiff build. Capping to 9",
    5217             :                      nZLevel);
    5218             :             nZLevel = 9;
    5219             :         }
    5220             : #endif
    5221             : #else
    5222             :         constexpr int nMaxLevel = 9;
    5223             : #endif
    5224          44 :         if (nZLevel < 1 || nZLevel > nMaxLevel)
    5225             :         {
    5226           0 :             CPLError(CE_Warning, CPLE_IllegalArg,
    5227             :                      "ZLEVEL=%s value not recognised, ignoring.", pszValue);
    5228           0 :             nZLevel = -1;
    5229             :         }
    5230             :     }
    5231       17913 :     return static_cast<signed char>(nZLevel);
    5232             : }
    5233             : 
    5234       17913 : static signed char GTiffGetJpegQuality(CSLConstList papszOptions)
    5235             : {
    5236       17913 :     int nJpegQuality = -1;
    5237       17913 :     const char *pszValue = CSLFetchNameValue(papszOptions, "JPEG_QUALITY");
    5238       17913 :     if (pszValue != nullptr)
    5239             :     {
    5240        1939 :         nJpegQuality = atoi(pszValue);
    5241        1939 :         if (nJpegQuality < 1 || nJpegQuality > 100)
    5242             :         {
    5243           0 :             CPLError(CE_Warning, CPLE_IllegalArg,
    5244             :                      "JPEG_QUALITY=%s value not recognised, ignoring.",
    5245             :                      pszValue);
    5246           0 :             nJpegQuality = -1;
    5247             :         }
    5248             :     }
    5249       17913 :     return static_cast<signed char>(nJpegQuality);
    5250             : }
    5251             : 
    5252       17913 : static signed char GTiffGetJpegTablesMode(CSLConstList papszOptions)
    5253             : {
    5254       17913 :     return static_cast<signed char>(atoi(
    5255             :         CSLFetchNameValueDef(papszOptions, "JPEGTABLESMODE",
    5256       17913 :                              CPLSPrintf("%d", knGTIFFJpegTablesModeDefault))));
    5257             : }
    5258             : 
    5259             : /************************************************************************/
    5260             : /*                        GetDiscardLsbOption()                         */
    5261             : /************************************************************************/
    5262             : 
    5263        7945 : static GTiffDataset::MaskOffset *GetDiscardLsbOption(TIFF *hTIFF,
    5264             :                                                      CSLConstList papszOptions)
    5265             : {
    5266        7945 :     const char *pszBits = CSLFetchNameValue(papszOptions, "DISCARD_LSB");
    5267        7945 :     if (pszBits == nullptr)
    5268        7823 :         return nullptr;
    5269             : 
    5270         122 :     uint16_t nPhotometric = 0;
    5271         122 :     TIFFGetFieldDefaulted(hTIFF, TIFFTAG_PHOTOMETRIC, &nPhotometric);
    5272             : 
    5273         122 :     uint16_t nBitsPerSample = 0;
    5274         122 :     if (!TIFFGetField(hTIFF, TIFFTAG_BITSPERSAMPLE, &nBitsPerSample))
    5275           0 :         nBitsPerSample = 1;
    5276             : 
    5277         122 :     uint16_t nSamplesPerPixel = 0;
    5278         122 :     if (!TIFFGetField(hTIFF, TIFFTAG_SAMPLESPERPIXEL, &nSamplesPerPixel))
    5279           0 :         nSamplesPerPixel = 1;
    5280             : 
    5281         122 :     uint16_t nSampleFormat = 0;
    5282         122 :     if (!TIFFGetField(hTIFF, TIFFTAG_SAMPLEFORMAT, &nSampleFormat))
    5283           0 :         nSampleFormat = SAMPLEFORMAT_UINT;
    5284             : 
    5285         122 :     if (nPhotometric == PHOTOMETRIC_PALETTE)
    5286             :     {
    5287           1 :         CPLError(CE_Warning, CPLE_AppDefined,
    5288             :                  "DISCARD_LSB ignored on a paletted image");
    5289           1 :         return nullptr;
    5290             :     }
    5291         121 :     if (!(nBitsPerSample == 8 || nBitsPerSample == 16 || nBitsPerSample == 32 ||
    5292          13 :           nBitsPerSample == 64))
    5293             :     {
    5294           1 :         CPLError(CE_Warning, CPLE_AppDefined,
    5295             :                  "DISCARD_LSB ignored on non 8, 16, 32 or 64 bits images");
    5296           1 :         return nullptr;
    5297             :     }
    5298             : 
    5299         240 :     const CPLStringList aosTokens(CSLTokenizeString2(pszBits, ",", 0));
    5300         120 :     const int nTokens = aosTokens.size();
    5301         120 :     GTiffDataset::MaskOffset *panMaskOffsetLsb = nullptr;
    5302         120 :     if (nTokens == 1 || nTokens == nSamplesPerPixel)
    5303             :     {
    5304             :         panMaskOffsetLsb = static_cast<GTiffDataset::MaskOffset *>(
    5305         119 :             CPLCalloc(nSamplesPerPixel, sizeof(GTiffDataset::MaskOffset)));
    5306         374 :         for (int i = 0; i < nSamplesPerPixel; ++i)
    5307             :         {
    5308         255 :             const int nBits = atoi(aosTokens[nTokens == 1 ? 0 : i]);
    5309         510 :             const int nMaxBits = (nSampleFormat == SAMPLEFORMAT_IEEEFP)
    5310         510 :                                      ? ((nBitsPerSample == 16)   ? 11 - 1
    5311          78 :                                         : (nBitsPerSample == 32) ? 23 - 1
    5312          26 :                                         : (nBitsPerSample == 64) ? 53 - 1
    5313             :                                                                  : 0)
    5314         203 :                                  : nSampleFormat == SAMPLEFORMAT_INT
    5315         203 :                                      ? nBitsPerSample - 2
    5316         119 :                                      : nBitsPerSample - 1;
    5317             : 
    5318         255 :             if (nBits < 0 || nBits > nMaxBits)
    5319             :             {
    5320           0 :                 CPLError(
    5321             :                     CE_Warning, CPLE_AppDefined,
    5322             :                     "DISCARD_LSB ignored: values should be in [0,%d] range",
    5323             :                     nMaxBits);
    5324           0 :                 VSIFree(panMaskOffsetLsb);
    5325           0 :                 return nullptr;
    5326             :             }
    5327         255 :             panMaskOffsetLsb[i].nMask =
    5328         255 :                 ~((static_cast<uint64_t>(1) << nBits) - 1);
    5329         255 :             if (nBits > 1)
    5330             :             {
    5331         249 :                 panMaskOffsetLsb[i].nRoundUpBitTest = static_cast<uint64_t>(1)
    5332         249 :                                                       << (nBits - 1);
    5333             :             }
    5334         119 :         }
    5335             :     }
    5336             :     else
    5337             :     {
    5338           1 :         CPLError(CE_Warning, CPLE_AppDefined,
    5339             :                  "DISCARD_LSB ignored: wrong number of components");
    5340             :     }
    5341         120 :     return panMaskOffsetLsb;
    5342             : }
    5343             : 
    5344        7945 : void GTiffDataset::GetDiscardLsbOption(CSLConstList papszOptions)
    5345             : {
    5346        7945 :     m_panMaskOffsetLsb = ::GetDiscardLsbOption(m_hTIFF, papszOptions);
    5347        7945 : }
    5348             : 
    5349             : /************************************************************************/
    5350             : /*                             GetProfile()                             */
    5351             : /************************************************************************/
    5352             : 
    5353       17964 : static GTiffProfile GetProfile(const char *pszProfile)
    5354             : {
    5355       17964 :     GTiffProfile eProfile = GTiffProfile::GDALGEOTIFF;
    5356       17964 :     if (pszProfile != nullptr)
    5357             :     {
    5358          70 :         if (EQUAL(pszProfile, szPROFILE_BASELINE))
    5359          50 :             eProfile = GTiffProfile::BASELINE;
    5360          20 :         else if (EQUAL(pszProfile, szPROFILE_GeoTIFF))
    5361          18 :             eProfile = GTiffProfile::GEOTIFF;
    5362           2 :         else if (!EQUAL(pszProfile, szPROFILE_GDALGeoTIFF))
    5363             :         {
    5364           0 :             CPLError(CE_Warning, CPLE_NotSupported,
    5365             :                      "Unsupported value for PROFILE: %s", pszProfile);
    5366             :         }
    5367             :     }
    5368       17964 :     return eProfile;
    5369             : }
    5370             : 
    5371             : /************************************************************************/
    5372             : /*                            GTiffCreate()                             */
    5373             : /*                                                                      */
    5374             : /*      Shared functionality between GTiffDataset::Create() and         */
    5375             : /*      GTiffCreateCopy() for creating TIFF file based on a set of      */
    5376             : /*      options and a configuration.                                    */
    5377             : /************************************************************************/
    5378             : 
    5379        9988 : TIFF *GTiffDataset::CreateLL(const char *pszFilename, int nXSize, int nYSize,
    5380             :                              int l_nBands, GDALDataType eType,
    5381             :                              double dfExtraSpaceForOverviews,
    5382             :                              int nColorTableMultiplier,
    5383             :                              CSLConstList papszParamList, VSILFILE **pfpL,
    5384             :                              CPLString &l_osTmpFilename, bool bCreateCopy,
    5385             :                              bool &bTileInterleavingOut)
    5386             : 
    5387             : {
    5388        9988 :     bTileInterleavingOut = false;
    5389             : 
    5390        9988 :     GTiffOneTimeInit();
    5391             : 
    5392             :     /* -------------------------------------------------------------------- */
    5393             :     /*      Blow on a few errors.                                           */
    5394             :     /* -------------------------------------------------------------------- */
    5395        9988 :     if (nXSize < 1 || nYSize < 1 || l_nBands < 1)
    5396             :     {
    5397           2 :         ReportError(
    5398             :             pszFilename, CE_Failure, CPLE_AppDefined,
    5399             :             "Attempt to create %dx%dx%d TIFF file, but width, height and bands "
    5400             :             "must be positive.",
    5401             :             nXSize, nYSize, l_nBands);
    5402             : 
    5403           2 :         return nullptr;
    5404             :     }
    5405             : 
    5406        9986 :     if (l_nBands > 65535)
    5407             :     {
    5408           1 :         ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
    5409             :                     "Attempt to create %dx%dx%d TIFF file, but bands "
    5410             :                     "must be lesser or equal to 65535.",
    5411             :                     nXSize, nYSize, l_nBands);
    5412             : 
    5413           1 :         return nullptr;
    5414             :     }
    5415             : 
    5416             :     /* -------------------------------------------------------------------- */
    5417             :     /*      Setup values based on options.                                  */
    5418             :     /* -------------------------------------------------------------------- */
    5419             :     const GTiffProfile eProfile =
    5420        9985 :         GetProfile(CSLFetchNameValue(papszParamList, "PROFILE"));
    5421             : 
    5422        9985 :     const bool bTiled = CPLFetchBool(papszParamList, "TILED", false);
    5423             : 
    5424        9985 :     int l_nBlockXSize = 0;
    5425        9985 :     if (const char *pszValue = CSLFetchNameValue(papszParamList, "BLOCKXSIZE"))
    5426             :     {
    5427         473 :         l_nBlockXSize = atoi(pszValue);
    5428         473 :         if (l_nBlockXSize < 0)
    5429             :         {
    5430           0 :             ReportError(pszFilename, CE_Failure, CPLE_IllegalArg,
    5431             :                         "Invalid value for BLOCKXSIZE");
    5432           0 :             return nullptr;
    5433             :         }
    5434         473 :         if (!bTiled)
    5435             :         {
    5436           9 :             ReportError(pszFilename, CE_Warning, CPLE_IllegalArg,
    5437             :                         "BLOCKXSIZE can only be used with TILED=YES");
    5438             :         }
    5439         464 :         else if (l_nBlockXSize % 16 != 0)
    5440             :         {
    5441           1 :             ReportError(pszFilename, CE_Failure, CPLE_IllegalArg,
    5442             :                         "BLOCKXSIZE must be a multiple of 16");
    5443           1 :             return nullptr;
    5444             :         }
    5445             :     }
    5446             : 
    5447        9984 :     int l_nBlockYSize = 0;
    5448        9984 :     if (const char *pszValue = CSLFetchNameValue(papszParamList, "BLOCKYSIZE"))
    5449             :     {
    5450        2584 :         l_nBlockYSize = atoi(pszValue);
    5451        2584 :         if (l_nBlockYSize < 0)
    5452             :         {
    5453           0 :             ReportError(pszFilename, CE_Failure, CPLE_IllegalArg,
    5454             :                         "Invalid value for BLOCKYSIZE");
    5455           0 :             return nullptr;
    5456             :         }
    5457        2584 :         if (bTiled && (l_nBlockYSize % 16 != 0))
    5458             :         {
    5459           2 :             ReportError(pszFilename, CE_Failure, CPLE_IllegalArg,
    5460             :                         "BLOCKYSIZE must be a multiple of 16");
    5461           2 :             return nullptr;
    5462             :         }
    5463             :     }
    5464             : 
    5465        9982 :     if (bTiled)
    5466             :     {
    5467         822 :         if (l_nBlockXSize == 0)
    5468         360 :             l_nBlockXSize = 256;
    5469             : 
    5470         822 :         if (l_nBlockYSize == 0)
    5471         360 :             l_nBlockYSize = 256;
    5472             :     }
    5473             : 
    5474        9982 :     int nPlanar = 0;
    5475             : 
    5476             :     // Hidden @TILE_INTERLEAVE=YES parameter used by the COG driver
    5477        9982 :     if (bCreateCopy && CPLTestBool(CSLFetchNameValueDef(
    5478             :                            papszParamList, "@TILE_INTERLEAVE", "NO")))
    5479             :     {
    5480           7 :         bTileInterleavingOut = true;
    5481           7 :         nPlanar = PLANARCONFIG_SEPARATE;
    5482             :     }
    5483             :     else
    5484             :     {
    5485        9975 :         if (const char *pszValue =
    5486        9975 :                 CSLFetchNameValue(papszParamList, "INTERLEAVE"))
    5487             :         {
    5488        1581 :             if (EQUAL(pszValue, "PIXEL"))
    5489             :             {
    5490         409 :                 nPlanar = PLANARCONFIG_CONTIG;
    5491             :             }
    5492        1172 :             else if (EQUAL(pszValue, "BAND"))
    5493             :             {
    5494        1171 :                 nPlanar = PLANARCONFIG_SEPARATE;
    5495             :             }
    5496             :             else
    5497             :             {
    5498           1 :                 ReportError(
    5499             :                     pszFilename, CE_Failure, CPLE_IllegalArg,
    5500             :                     "INTERLEAVE=%s unsupported, value must be PIXEL or BAND.",
    5501             :                     pszValue);
    5502           1 :                 return nullptr;
    5503             :             }
    5504             :         }
    5505             :         else
    5506             :         {
    5507        8394 :             nPlanar = PLANARCONFIG_CONTIG;
    5508             :         }
    5509             :     }
    5510             : 
    5511        9981 :     int l_nCompression = COMPRESSION_NONE;
    5512        9981 :     if (const char *pszValue = CSLFetchNameValue(papszParamList, "COMPRESS"))
    5513             :     {
    5514        3361 :         l_nCompression = GTIFFGetCompressionMethod(pszValue, "COMPRESS");
    5515        3361 :         if (l_nCompression < 0)
    5516           0 :             return nullptr;
    5517             :     }
    5518             : 
    5519        9981 :     constexpr int JPEG_MAX_DIMENSION = 65500;  // Defined in jpeglib.h
    5520        9981 :     constexpr int WEBP_MAX_DIMENSION = 16383;
    5521             : 
    5522             :     const struct
    5523             :     {
    5524             :         int nCodecID;
    5525             :         const char *pszCodecName;
    5526             :         int nMaxDim;
    5527        9981 :     } asLimitations[] = {
    5528             :         {COMPRESSION_JPEG, "JPEG", JPEG_MAX_DIMENSION},
    5529             :         {COMPRESSION_WEBP, "WEBP", WEBP_MAX_DIMENSION},
    5530             :     };
    5531             : 
    5532       29931 :     for (const auto &sLimitation : asLimitations)
    5533             :     {
    5534       19958 :         if (l_nCompression == sLimitation.nCodecID && !bTiled &&
    5535        2074 :             nXSize > sLimitation.nMaxDim)
    5536             :         {
    5537           2 :             ReportError(
    5538             :                 pszFilename, CE_Failure, CPLE_IllegalArg,
    5539             :                 "COMPRESS=%s is only compatible with un-tiled images whose "
    5540             :                 "width is lesser or equal to %d pixels. "
    5541             :                 "To overcome this limitation, set the TILED=YES creation "
    5542             :                 "option.",
    5543           2 :                 sLimitation.pszCodecName, sLimitation.nMaxDim);
    5544           2 :             return nullptr;
    5545             :         }
    5546       19956 :         else if (l_nCompression == sLimitation.nCodecID && bTiled &&
    5547          52 :                  l_nBlockXSize > sLimitation.nMaxDim)
    5548             :         {
    5549           2 :             ReportError(
    5550             :                 pszFilename, CE_Failure, CPLE_IllegalArg,
    5551             :                 "COMPRESS=%s is only compatible with tiled images whose "
    5552             :                 "BLOCKXSIZE is lesser or equal to %d pixels.",
    5553           2 :                 sLimitation.pszCodecName, sLimitation.nMaxDim);
    5554           2 :             return nullptr;
    5555             :         }
    5556       19954 :         else if (l_nCompression == sLimitation.nCodecID &&
    5557        2122 :                  l_nBlockYSize > sLimitation.nMaxDim)
    5558             :         {
    5559           4 :             ReportError(pszFilename, CE_Failure, CPLE_IllegalArg,
    5560             :                         "COMPRESS=%s is only compatible with images whose "
    5561             :                         "BLOCKYSIZE is lesser or equal to %d pixels. "
    5562             :                         "To overcome this limitation, set the TILED=YES "
    5563             :                         "creation option",
    5564           4 :                         sLimitation.pszCodecName, sLimitation.nMaxDim);
    5565           4 :             return nullptr;
    5566             :         }
    5567             :     }
    5568             : 
    5569             :     /* -------------------------------------------------------------------- */
    5570             :     /*      How many bits per sample?  We have a special case if NBITS      */
    5571             :     /*      specified for GDT_UInt8, GDT_UInt16, GDT_UInt32.                 */
    5572             :     /* -------------------------------------------------------------------- */
    5573        9973 :     int l_nBitsPerSample = GDALGetDataTypeSizeBits(eType);
    5574        9973 :     if (CSLFetchNameValue(papszParamList, "NBITS") != nullptr)
    5575             :     {
    5576        1758 :         int nMinBits = 0;
    5577        1758 :         int nMaxBits = 0;
    5578        1758 :         l_nBitsPerSample = atoi(CSLFetchNameValue(papszParamList, "NBITS"));
    5579        1758 :         if (eType == GDT_UInt8)
    5580             :         {
    5581         527 :             nMinBits = 1;
    5582         527 :             nMaxBits = 8;
    5583             :         }
    5584        1231 :         else if (eType == GDT_UInt16)
    5585             :         {
    5586        1213 :             nMinBits = 9;
    5587        1213 :             nMaxBits = 16;
    5588             :         }
    5589          18 :         else if (eType == GDT_UInt32)
    5590             :         {
    5591          14 :             nMinBits = 17;
    5592          14 :             nMaxBits = 32;
    5593             :         }
    5594           4 :         else if (eType == GDT_Float32)
    5595             :         {
    5596           4 :             if (l_nBitsPerSample != 16 && l_nBitsPerSample != 32)
    5597             :             {
    5598           1 :                 ReportError(pszFilename, CE_Warning, CPLE_NotSupported,
    5599             :                             "Only NBITS=16 is supported for data type Float32");
    5600           1 :                 l_nBitsPerSample = GDALGetDataTypeSizeBits(eType);
    5601             :             }
    5602             :         }
    5603             :         else
    5604             :         {
    5605           0 :             ReportError(pszFilename, CE_Warning, CPLE_NotSupported,
    5606             :                         "NBITS is not supported for data type %s",
    5607             :                         GDALGetDataTypeName(eType));
    5608           0 :             l_nBitsPerSample = GDALGetDataTypeSizeBits(eType);
    5609             :         }
    5610             : 
    5611        1758 :         if (nMinBits != 0)
    5612             :         {
    5613        1754 :             if (l_nBitsPerSample < nMinBits)
    5614             :             {
    5615           2 :                 ReportError(
    5616             :                     pszFilename, CE_Warning, CPLE_AppDefined,
    5617             :                     "NBITS=%d is invalid for data type %s. Using NBITS=%d",
    5618             :                     l_nBitsPerSample, GDALGetDataTypeName(eType), nMinBits);
    5619           2 :                 l_nBitsPerSample = nMinBits;
    5620             :             }
    5621        1752 :             else if (l_nBitsPerSample > nMaxBits)
    5622             :             {
    5623           3 :                 ReportError(
    5624             :                     pszFilename, CE_Warning, CPLE_AppDefined,
    5625             :                     "NBITS=%d is invalid for data type %s. Using NBITS=%d",
    5626             :                     l_nBitsPerSample, GDALGetDataTypeName(eType), nMaxBits);
    5627           3 :                 l_nBitsPerSample = nMaxBits;
    5628             :             }
    5629             :         }
    5630             :     }
    5631             : 
    5632             : #ifdef HAVE_JXL
    5633        9973 :     if ((l_nCompression == COMPRESSION_JXL ||
    5634         106 :          l_nCompression == COMPRESSION_JXL_DNG_1_7) &&
    5635         105 :         eType != GDT_Float16 && eType != GDT_Float32)
    5636             :     {
    5637             :         // Reflects tif_jxl's GetJXLDataType()
    5638          85 :         if (eType != GDT_UInt8 && eType != GDT_UInt16)
    5639             :         {
    5640           1 :             ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    5641             :                         "Data type %s not supported for JXL compression. Only "
    5642             :                         "Byte, UInt16, Float16, Float32 are supported",
    5643             :                         GDALGetDataTypeName(eType));
    5644           2 :             return nullptr;
    5645             :         }
    5646             : 
    5647             :         const struct
    5648             :         {
    5649             :             GDALDataType eDT;
    5650             :             int nBitsPerSample;
    5651          84 :         } asSupportedDTBitsPerSample[] = {
    5652             :             {GDT_UInt8, 8},
    5653             :             {GDT_UInt16, 16},
    5654             :         };
    5655             : 
    5656         250 :         for (const auto &sSupportedDTBitsPerSample : asSupportedDTBitsPerSample)
    5657             :         {
    5658         167 :             if (eType == sSupportedDTBitsPerSample.eDT &&
    5659          84 :                 l_nBitsPerSample != sSupportedDTBitsPerSample.nBitsPerSample)
    5660             :             {
    5661           1 :                 ReportError(
    5662             :                     pszFilename, CE_Failure, CPLE_NotSupported,
    5663             :                     "Bits per sample=%d not supported for JXL compression. "
    5664             :                     "Only %d is supported for %s data type.",
    5665           1 :                     l_nBitsPerSample, sSupportedDTBitsPerSample.nBitsPerSample,
    5666             :                     GDALGetDataTypeName(eType));
    5667           1 :                 return nullptr;
    5668             :             }
    5669             :         }
    5670             :     }
    5671             : #endif
    5672             : 
    5673        9971 :     int nPredictor = PREDICTOR_NONE;
    5674        9971 :     const char *pszPredictor = CSLFetchNameValue(papszParamList, "PREDICTOR");
    5675        9971 :     if (pszPredictor)
    5676             :     {
    5677          31 :         nPredictor = atoi(pszPredictor);
    5678             :     }
    5679             : 
    5680        9971 :     if (nPredictor != PREDICTOR_NONE &&
    5681          18 :         l_nCompression != COMPRESSION_ADOBE_DEFLATE &&
    5682           2 :         l_nCompression != COMPRESSION_LZW &&
    5683           2 :         l_nCompression != COMPRESSION_LZMA &&
    5684             :         l_nCompression != COMPRESSION_ZSTD)
    5685             :     {
    5686           1 :         ReportError(pszFilename, CE_Warning, CPLE_NotSupported,
    5687             :                     "PREDICTOR option is ignored for COMPRESS=%s. "
    5688             :                     "Only valid for DEFLATE, LZW, LZMA or ZSTD",
    5689             :                     CSLFetchNameValueDef(papszParamList, "COMPRESS", "NONE"));
    5690             :     }
    5691             : 
    5692             :     // Do early checks as libtiff will only error out when starting to write.
    5693       10000 :     else if (nPredictor != PREDICTOR_NONE &&
    5694          30 :              CPLTestBool(
    5695             :                  CPLGetConfigOption("GDAL_GTIFF_PREDICTOR_CHECKS", "YES")))
    5696             :     {
    5697             : #if (TIFFLIB_VERSION > 20210416) || defined(INTERNAL_LIBTIFF)
    5698             : #define HAVE_PREDICTOR_2_FOR_64BIT
    5699             : #endif
    5700          30 :         if (nPredictor == 2)
    5701             :         {
    5702          24 :             if (l_nBitsPerSample != 8 && l_nBitsPerSample != 16 &&
    5703             :                 l_nBitsPerSample != 32
    5704             : #ifdef HAVE_PREDICTOR_2_FOR_64BIT
    5705           2 :                 && l_nBitsPerSample != 64
    5706             : #endif
    5707             :             )
    5708             :             {
    5709             : #if !defined(HAVE_PREDICTOR_2_FOR_64BIT)
    5710             :                 if (l_nBitsPerSample == 64)
    5711             :                 {
    5712             :                     ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
    5713             :                                 "PREDICTOR=2 is supported on 64 bit samples "
    5714             :                                 "starting with libtiff > 4.3.0.");
    5715             :                 }
    5716             :                 else
    5717             : #endif
    5718             :                 {
    5719           2 :                     const int nBITSHint = (l_nBitsPerSample < 8)    ? 8
    5720           1 :                                           : (l_nBitsPerSample < 16) ? 16
    5721           0 :                                           : (l_nBitsPerSample < 32) ? 32
    5722             :                                                                     : 64;
    5723           1 :                     ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
    5724             : #ifdef HAVE_PREDICTOR_2_FOR_64BIT
    5725             :                                 "PREDICTOR=2 is only supported with 8/16/32/64 "
    5726             :                                 "bit samples. You can specify the NBITS=%d "
    5727             :                                 "creation option to promote to the closest "
    5728             :                                 "supported bits per sample value.",
    5729             : #else
    5730             :                                 "PREDICTOR=2 is only supported with 8/16/32 "
    5731             :                                 "bit samples. You can specify the NBITS=%d "
    5732             :                                 "creation option to promote to the closest "
    5733             :                                 "supported bits per sample value.",
    5734             : #endif
    5735             :                                 nBITSHint);
    5736             :                 }
    5737           1 :                 return nullptr;
    5738             :             }
    5739             :         }
    5740           6 :         else if (nPredictor == 3)
    5741             :         {
    5742           5 :             if (eType != GDT_Float16 && eType != GDT_Float32 &&
    5743             :                 eType != GDT_Float64)
    5744             :             {
    5745           1 :                 ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
    5746             :                             "PREDICTOR=3 is only supported with Float16, "
    5747             :                             "Float32 or Float64.");
    5748           1 :                 return nullptr;
    5749             :             }
    5750             :         }
    5751             :         else
    5752             :         {
    5753           1 :             ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
    5754             :                         "PREDICTOR=%s is not supported.", pszPredictor);
    5755           1 :             return nullptr;
    5756             :         }
    5757             :     }
    5758             : 
    5759        9968 :     const int l_nZLevel = GTiffGetZLevel(papszParamList);
    5760        9968 :     const int l_nLZMAPreset = GTiffGetLZMAPreset(papszParamList);
    5761        9968 :     const int l_nZSTDLevel = GTiffGetZSTDPreset(papszParamList);
    5762        9968 :     const int l_nWebPLevel = GTiffGetWebPLevel(papszParamList);
    5763        9968 :     const bool l_bWebPLossless = GTiffGetWebPLossless(papszParamList);
    5764        9968 :     const int l_nJpegQuality = GTiffGetJpegQuality(papszParamList);
    5765        9968 :     const int l_nJpegTablesMode = GTiffGetJpegTablesMode(papszParamList);
    5766        9968 :     const double l_dfMaxZError = GTiffGetLERCMaxZError(papszParamList);
    5767             : #if HAVE_JXL
    5768        9968 :     bool bJXLLosslessSpecified = false;
    5769             :     const bool l_bJXLLossless =
    5770        9968 :         GTiffGetJXLLossless(papszParamList, &bJXLLosslessSpecified);
    5771        9968 :     const uint32_t l_nJXLEffort = GTiffGetJXLEffort(papszParamList);
    5772        9968 :     bool bJXLDistanceSpecified = false;
    5773             :     const float l_fJXLDistance =
    5774        9968 :         GTiffGetJXLDistance(papszParamList, &bJXLDistanceSpecified);
    5775        9968 :     if (bJXLDistanceSpecified && l_bJXLLossless)
    5776             :     {
    5777           1 :         ReportError(pszFilename, CE_Warning, CPLE_AppDefined,
    5778             :                     "JXL_DISTANCE creation option is ignored, given %s "
    5779             :                     "JXL_LOSSLESS=YES",
    5780             :                     bJXLLosslessSpecified ? "(explicit)" : "(implicit)");
    5781             :     }
    5782        9968 :     bool bJXLAlphaDistanceSpecified = false;
    5783             :     const float l_fJXLAlphaDistance =
    5784        9968 :         GTiffGetJXLAlphaDistance(papszParamList, &bJXLAlphaDistanceSpecified);
    5785        9968 :     if (bJXLAlphaDistanceSpecified && l_bJXLLossless)
    5786             :     {
    5787           1 :         ReportError(pszFilename, CE_Warning, CPLE_AppDefined,
    5788             :                     "JXL_ALPHA_DISTANCE creation option is ignored, given %s "
    5789             :                     "JXL_LOSSLESS=YES",
    5790             :                     bJXLLosslessSpecified ? "(explicit)" : "(implicit)");
    5791             :     }
    5792             : #endif
    5793             :     /* -------------------------------------------------------------------- */
    5794             :     /*      Streaming related code                                          */
    5795             :     /* -------------------------------------------------------------------- */
    5796       19936 :     const CPLString osOriFilename(pszFilename);
    5797       19936 :     bool bStreaming = strcmp(pszFilename, "/vsistdout/") == 0 ||
    5798        9968 :                       CPLFetchBool(papszParamList, "STREAMABLE_OUTPUT", false);
    5799             : #ifdef S_ISFIFO
    5800        9968 :     if (!bStreaming)
    5801             :     {
    5802             :         VSIStatBufL sStat;
    5803        9956 :         if (VSIStatExL(pszFilename, &sStat,
    5804       10835 :                        VSI_STAT_EXISTS_FLAG | VSI_STAT_NATURE_FLAG) == 0 &&
    5805         879 :             S_ISFIFO(sStat.st_mode))
    5806             :         {
    5807           0 :             bStreaming = true;
    5808             :         }
    5809             :     }
    5810             : #endif
    5811        9968 :     if (bStreaming && !EQUAL("NONE", CSLFetchNameValueDef(papszParamList,
    5812             :                                                           "COMPRESS", "NONE")))
    5813             :     {
    5814           1 :         ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    5815             :                     "Streaming only supported to uncompressed TIFF");
    5816           1 :         return nullptr;
    5817             :     }
    5818        9967 :     if (bStreaming && CPLFetchBool(papszParamList, "SPARSE_OK", false))
    5819             :     {
    5820           1 :         ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    5821             :                     "Streaming not supported with SPARSE_OK");
    5822           1 :         return nullptr;
    5823             :     }
    5824             :     const bool bCopySrcOverviews =
    5825        9966 :         CPLFetchBool(papszParamList, "COPY_SRC_OVERVIEWS", false);
    5826        9966 :     if (bStreaming && bCopySrcOverviews)
    5827             :     {
    5828           1 :         ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    5829             :                     "Streaming not supported with COPY_SRC_OVERVIEWS");
    5830           1 :         return nullptr;
    5831             :     }
    5832        9965 :     if (bStreaming)
    5833             :     {
    5834           9 :         l_osTmpFilename = VSIMemGenerateHiddenFilename("vsistdout.tif");
    5835           9 :         pszFilename = l_osTmpFilename.c_str();
    5836             :     }
    5837             : 
    5838             :     /* -------------------------------------------------------------------- */
    5839             :     /*      Compute the uncompressed size.                                  */
    5840             :     /* -------------------------------------------------------------------- */
    5841        9965 :     const unsigned nTileXCount =
    5842        9965 :         bTiled ? DIV_ROUND_UP(nXSize, l_nBlockXSize) : 0;
    5843        9965 :     const unsigned nTileYCount =
    5844        9965 :         bTiled ? DIV_ROUND_UP(nYSize, l_nBlockYSize) : 0;
    5845             :     const double dfUncompressedImageSize =
    5846        9965 :         (bTiled ? (static_cast<double>(nTileXCount) * nTileYCount *
    5847         818 :                    l_nBlockXSize * l_nBlockYSize)
    5848        9147 :                 : (nXSize * static_cast<double>(nYSize))) *
    5849        9965 :             l_nBands * GDALGetDataTypeSizeBytes(eType) +
    5850        9965 :         dfExtraSpaceForOverviews;
    5851             : 
    5852             :     /* -------------------------------------------------------------------- */
    5853             :     /*      Should the file be created as a bigtiff file?                   */
    5854             :     /* -------------------------------------------------------------------- */
    5855        9965 :     const char *pszBIGTIFF = CSLFetchNameValue(papszParamList, "BIGTIFF");
    5856             : 
    5857        9965 :     if (pszBIGTIFF == nullptr)
    5858        9518 :         pszBIGTIFF = "IF_NEEDED";
    5859             : 
    5860        9965 :     bool bCreateBigTIFF = false;
    5861        9965 :     if (EQUAL(pszBIGTIFF, "IF_NEEDED"))
    5862             :     {
    5863        9519 :         if (l_nCompression == COMPRESSION_NONE &&
    5864             :             dfUncompressedImageSize > 4200000000.0)
    5865          17 :             bCreateBigTIFF = true;
    5866             :     }
    5867         446 :     else if (EQUAL(pszBIGTIFF, "IF_SAFER"))
    5868             :     {
    5869         425 :         if (dfUncompressedImageSize > 2000000000.0)
    5870           1 :             bCreateBigTIFF = true;
    5871             :     }
    5872             :     else
    5873             :     {
    5874          21 :         bCreateBigTIFF = CPLTestBool(pszBIGTIFF);
    5875          21 :         if (!bCreateBigTIFF && l_nCompression == COMPRESSION_NONE &&
    5876             :             dfUncompressedImageSize > 4200000000.0)
    5877             :         {
    5878           2 :             ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    5879             :                         "The TIFF file will be larger than 4GB, so BigTIFF is "
    5880             :                         "necessary.  Creation failed.");
    5881           2 :             return nullptr;
    5882             :         }
    5883             :     }
    5884             : 
    5885        9963 :     if (bCreateBigTIFF)
    5886          35 :         CPLDebug("GTiff", "File being created as a BigTIFF.");
    5887             : 
    5888             :     /* -------------------------------------------------------------------- */
    5889             :     /*      Sanity check.                                                   */
    5890             :     /* -------------------------------------------------------------------- */
    5891        9963 :     if (bTiled)
    5892             :     {
    5893             :         // libtiff implementation limitation
    5894         818 :         if (nTileXCount > 0x80000000U / (bCreateBigTIFF ? 8 : 4) / nTileYCount)
    5895             :         {
    5896           3 :             ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    5897             :                         "File too large regarding tile size. This would result "
    5898             :                         "in a file with tile arrays larger than 2GB");
    5899           3 :             return nullptr;
    5900             :         }
    5901             :     }
    5902             : 
    5903             :     /* -------------------------------------------------------------------- */
    5904             :     /*      Check free space (only for big, non sparse)                     */
    5905             :     /* -------------------------------------------------------------------- */
    5906        9960 :     const double dfLikelyFloorOfFinalSize =
    5907             :         l_nCompression == COMPRESSION_NONE
    5908        9960 :             ? dfUncompressedImageSize
    5909             :             :
    5910             :             /* For compressed, we target 1% as the most optimistic reduction factor! */
    5911             :             0.01 * dfUncompressedImageSize;
    5912        9982 :     if (dfLikelyFloorOfFinalSize >= 1e9 &&
    5913          22 :         !CPLFetchBool(papszParamList, "SPARSE_OK", false) &&
    5914           5 :         osOriFilename != "/vsistdout/" &&
    5915        9987 :         osOriFilename != "/vsistdout_redirect/" &&
    5916           5 :         CPLTestBool(CPLGetConfigOption("CHECK_DISK_FREE_SPACE", "TRUE")))
    5917             :     {
    5918             :         const GIntBig nFreeDiskSpace =
    5919           4 :             VSIGetDiskFreeSpace(CPLGetDirnameSafe(pszFilename).c_str());
    5920           4 :         if (nFreeDiskSpace >= 0 && nFreeDiskSpace < dfLikelyFloorOfFinalSize)
    5921             :         {
    5922           6 :             ReportError(
    5923             :                 pszFilename, CE_Failure, CPLE_FileIO,
    5924             :                 "Free disk space available is %s, "
    5925             :                 "whereas %s are %s necessary. "
    5926             :                 "You can disable this check by defining the "
    5927             :                 "CHECK_DISK_FREE_SPACE configuration option to FALSE.",
    5928           4 :                 CPLFormatReadableFileSize(static_cast<uint64_t>(nFreeDiskSpace))
    5929             :                     .c_str(),
    5930           4 :                 CPLFormatReadableFileSize(dfLikelyFloorOfFinalSize).c_str(),
    5931             :                 l_nCompression == COMPRESSION_NONE
    5932             :                     ? "at least"
    5933             :                     : "likely at least (probably more)");
    5934           2 :             return nullptr;
    5935             :         }
    5936             :     }
    5937             : 
    5938             :     /* -------------------------------------------------------------------- */
    5939             :     /*      Check if the user wishes a particular endianness                */
    5940             :     /* -------------------------------------------------------------------- */
    5941             : 
    5942        9958 :     int eEndianness = ENDIANNESS_NATIVE;
    5943        9958 :     const char *pszEndianness = CSLFetchNameValue(papszParamList, "ENDIANNESS");
    5944        9958 :     if (pszEndianness == nullptr)
    5945        9895 :         pszEndianness = CPLGetConfigOption("GDAL_TIFF_ENDIANNESS", nullptr);
    5946        9958 :     if (pszEndianness != nullptr)
    5947             :     {
    5948         123 :         if (EQUAL(pszEndianness, "LITTLE"))
    5949             :         {
    5950          36 :             eEndianness = ENDIANNESS_LITTLE;
    5951             :         }
    5952          87 :         else if (EQUAL(pszEndianness, "BIG"))
    5953             :         {
    5954           1 :             eEndianness = ENDIANNESS_BIG;
    5955             :         }
    5956          86 :         else if (EQUAL(pszEndianness, "INVERTED"))
    5957             :         {
    5958             : #ifdef CPL_LSB
    5959          82 :             eEndianness = ENDIANNESS_BIG;
    5960             : #else
    5961             :             eEndianness = ENDIANNESS_LITTLE;
    5962             : #endif
    5963             :         }
    5964           4 :         else if (!EQUAL(pszEndianness, "NATIVE"))
    5965             :         {
    5966           1 :             ReportError(pszFilename, CE_Warning, CPLE_NotSupported,
    5967             :                         "ENDIANNESS=%s not supported. Defaulting to NATIVE",
    5968             :                         pszEndianness);
    5969             :         }
    5970             :     }
    5971             : 
    5972             :     /* -------------------------------------------------------------------- */
    5973             :     /*      Try opening the dataset.                                        */
    5974             :     /* -------------------------------------------------------------------- */
    5975             : 
    5976             :     const bool bAppend =
    5977        9958 :         CPLFetchBool(papszParamList, "APPEND_SUBDATASET", false);
    5978             : 
    5979        9958 :     char szOpeningFlag[5] = {};
    5980        9958 :     strcpy(szOpeningFlag, bAppend ? "r+" : "w+");
    5981        9958 :     if (bCreateBigTIFF)
    5982          32 :         strcat(szOpeningFlag, "8");
    5983        9958 :     if (eEndianness == ENDIANNESS_BIG)
    5984          83 :         strcat(szOpeningFlag, "b");
    5985        9875 :     else if (eEndianness == ENDIANNESS_LITTLE)
    5986          36 :         strcat(szOpeningFlag, "l");
    5987             : 
    5988        9958 :     VSIErrorReset();
    5989        9958 :     const bool bOnlyVisibleAtCloseTime = CPLTestBool(CSLFetchNameValueDef(
    5990             :         papszParamList, "@CREATE_ONLY_VISIBLE_AT_CLOSE_TIME", "NO"));
    5991        9958 :     const bool bSuppressASAP = CPLTestBool(
    5992             :         CSLFetchNameValueDef(papszParamList, "@SUPPRESS_ASAP", "NO"));
    5993             :     auto l_fpL =
    5994        9958 :         (bOnlyVisibleAtCloseTime || bSuppressASAP) && !bAppend
    5995       10028 :             ? VSIFileManager::GetHandler(pszFilename)
    5996         140 :                   ->CreateOnlyVisibleAtCloseTime(pszFilename, true, nullptr)
    5997          70 :                   .release()
    5998       19846 :             : VSIFilesystemHandler::OpenStatic(pszFilename,
    5999             :                                                bAppend ? "r+b" : "w+b", true)
    6000        9958 :                   .release();
    6001        9958 :     if (l_fpL == nullptr)
    6002             :     {
    6003          21 :         VSIToCPLErrorWithMsg(CE_Failure, CPLE_OpenFailed,
    6004          42 :                              std::string("Attempt to create new tiff file `")
    6005          21 :                                  .append(pszFilename)
    6006          21 :                                  .append("' failed")
    6007             :                                  .c_str());
    6008          21 :         return nullptr;
    6009             :     }
    6010             : 
    6011        9937 :     if (bSuppressASAP)
    6012             :     {
    6013          40 :         l_fpL->CancelCreation();
    6014             :     }
    6015             : 
    6016        9937 :     TIFF *l_hTIFF = VSI_TIFFOpen(pszFilename, szOpeningFlag, l_fpL);
    6017        9937 :     if (l_hTIFF == nullptr)
    6018             :     {
    6019           2 :         if (CPLGetLastErrorNo() == 0)
    6020           0 :             CPLError(CE_Failure, CPLE_OpenFailed,
    6021             :                      "Attempt to create new tiff file `%s' "
    6022             :                      "failed in XTIFFOpen().",
    6023             :                      pszFilename);
    6024           2 :         l_fpL->CancelCreation();
    6025           2 :         CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    6026           2 :         return nullptr;
    6027             :     }
    6028             : 
    6029        9935 :     if (bAppend)
    6030             :     {
    6031             : #if !(defined(INTERNAL_LIBTIFF) || TIFFLIB_VERSION > 20240911)
    6032             :         // This is a bit of a hack to cause (*tif->tif_cleanup)(tif); to be
    6033             :         // called. See https://trac.osgeo.org/gdal/ticket/2055
    6034             :         // Fixed in libtiff > 4.7.0
    6035             :         TIFFSetField(l_hTIFF, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
    6036             :         TIFFFreeDirectory(l_hTIFF);
    6037             : #endif
    6038           6 :         TIFFCreateDirectory(l_hTIFF);
    6039             :     }
    6040             : 
    6041             :     /* -------------------------------------------------------------------- */
    6042             :     /*      Do we have a custom pixel type (just used for signed byte now). */
    6043             :     /* -------------------------------------------------------------------- */
    6044        9935 :     const char *pszPixelType = CSLFetchNameValue(papszParamList, "PIXELTYPE");
    6045        9935 :     if (pszPixelType == nullptr)
    6046        9927 :         pszPixelType = "";
    6047        9935 :     if (eType == GDT_UInt8 && EQUAL(pszPixelType, "SIGNEDBYTE"))
    6048             :     {
    6049           8 :         CPLError(CE_Warning, CPLE_AppDefined,
    6050             :                  "Using PIXELTYPE=SIGNEDBYTE with Byte data type is deprecated "
    6051             :                  "(but still works). "
    6052             :                  "Using Int8 data type instead is now recommended.");
    6053             :     }
    6054             : 
    6055             :     /* -------------------------------------------------------------------- */
    6056             :     /*      Setup some standard flags.                                      */
    6057             :     /* -------------------------------------------------------------------- */
    6058        9935 :     TIFFSetField(l_hTIFF, TIFFTAG_IMAGEWIDTH, nXSize);
    6059        9935 :     TIFFSetField(l_hTIFF, TIFFTAG_IMAGELENGTH, nYSize);
    6060        9935 :     TIFFSetField(l_hTIFF, TIFFTAG_BITSPERSAMPLE, l_nBitsPerSample);
    6061             : 
    6062        9935 :     uint16_t l_nSampleFormat = 0;
    6063        9935 :     if ((eType == GDT_UInt8 && EQUAL(pszPixelType, "SIGNEDBYTE")) ||
    6064        9786 :         eType == GDT_Int8 || eType == GDT_Int16 || eType == GDT_Int32 ||
    6065             :         eType == GDT_Int64)
    6066         808 :         l_nSampleFormat = SAMPLEFORMAT_INT;
    6067        9127 :     else if (eType == GDT_CInt16 || eType == GDT_CInt32)
    6068         363 :         l_nSampleFormat = SAMPLEFORMAT_COMPLEXINT;
    6069        8764 :     else if (eType == GDT_Float16 || eType == GDT_Float32 ||
    6070             :              eType == GDT_Float64)
    6071        1170 :         l_nSampleFormat = SAMPLEFORMAT_IEEEFP;
    6072        7594 :     else if (eType == GDT_CFloat16 || eType == GDT_CFloat32 ||
    6073             :              eType == GDT_CFloat64)
    6074         471 :         l_nSampleFormat = SAMPLEFORMAT_COMPLEXIEEEFP;
    6075             :     else
    6076        7123 :         l_nSampleFormat = SAMPLEFORMAT_UINT;
    6077             : 
    6078        9935 :     TIFFSetField(l_hTIFF, TIFFTAG_SAMPLEFORMAT, l_nSampleFormat);
    6079        9935 :     TIFFSetField(l_hTIFF, TIFFTAG_SAMPLESPERPIXEL, l_nBands);
    6080        9935 :     TIFFSetField(l_hTIFF, TIFFTAG_PLANARCONFIG, nPlanar);
    6081             : 
    6082             :     /* -------------------------------------------------------------------- */
    6083             :     /*      Setup Photometric Interpretation. Take this value from the user */
    6084             :     /*      passed option or guess correct value otherwise.                 */
    6085             :     /* -------------------------------------------------------------------- */
    6086        9935 :     int nSamplesAccountedFor = 1;
    6087        9935 :     bool bForceColorTable = false;
    6088             : 
    6089        9935 :     if (const char *pszValue = CSLFetchNameValue(papszParamList, "PHOTOMETRIC"))
    6090             :     {
    6091        1913 :         if (EQUAL(pszValue, "MINISBLACK"))
    6092          14 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
    6093        1899 :         else if (EQUAL(pszValue, "MINISWHITE"))
    6094             :         {
    6095           2 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISWHITE);
    6096             :         }
    6097        1897 :         else if (EQUAL(pszValue, "PALETTE"))
    6098             :         {
    6099           5 :             if (eType == GDT_UInt8 || eType == GDT_UInt16)
    6100             :             {
    6101           4 :                 TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
    6102           4 :                 nSamplesAccountedFor = 1;
    6103           4 :                 bForceColorTable = true;
    6104             :             }
    6105             :             else
    6106             :             {
    6107           1 :                 ReportError(
    6108             :                     pszFilename, CE_Warning, CPLE_AppDefined,
    6109             :                     "PHOTOMETRIC=PALETTE only compatible with Byte or UInt16");
    6110             :             }
    6111             :         }
    6112        1892 :         else if (EQUAL(pszValue, "RGB"))
    6113             :         {
    6114        1152 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
    6115        1152 :             nSamplesAccountedFor = 3;
    6116             :         }
    6117         740 :         else if (EQUAL(pszValue, "CMYK"))
    6118             :         {
    6119          10 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_SEPARATED);
    6120          10 :             nSamplesAccountedFor = 4;
    6121             :         }
    6122         730 :         else if (EQUAL(pszValue, "YCBCR"))
    6123             :         {
    6124             :             // Because of subsampling, setting YCBCR without JPEG compression
    6125             :             // leads to a crash currently. Would need to make
    6126             :             // GTiffRasterBand::IWriteBlock() aware of subsampling so that it
    6127             :             // doesn't overrun buffer size returned by libtiff.
    6128         729 :             if (l_nCompression != COMPRESSION_JPEG)
    6129             :             {
    6130           1 :                 ReportError(
    6131             :                     pszFilename, CE_Failure, CPLE_NotSupported,
    6132             :                     "Currently, PHOTOMETRIC=YCBCR requires COMPRESS=JPEG");
    6133           1 :                 XTIFFClose(l_hTIFF);
    6134           1 :                 l_fpL->CancelCreation();
    6135           1 :                 CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    6136           1 :                 return nullptr;
    6137             :             }
    6138             : 
    6139         728 :             if (nPlanar == PLANARCONFIG_SEPARATE)
    6140             :             {
    6141           1 :                 ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    6142             :                             "PHOTOMETRIC=YCBCR requires INTERLEAVE=PIXEL");
    6143           1 :                 XTIFFClose(l_hTIFF);
    6144           1 :                 l_fpL->CancelCreation();
    6145           1 :                 CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    6146           1 :                 return nullptr;
    6147             :             }
    6148             : 
    6149             :             // YCBCR strictly requires 3 bands. Not less, not more Issue an
    6150             :             // explicit error message as libtiff one is a bit cryptic:
    6151             :             // TIFFVStripSize64:Invalid td_samplesperpixel value.
    6152         727 :             if (l_nBands != 3)
    6153             :             {
    6154           1 :                 ReportError(
    6155             :                     pszFilename, CE_Failure, CPLE_NotSupported,
    6156             :                     "PHOTOMETRIC=YCBCR not supported on a %d-band raster: "
    6157             :                     "only compatible with 3-band (RGB) rasters",
    6158             :                     l_nBands);
    6159           1 :                 XTIFFClose(l_hTIFF);
    6160           1 :                 l_fpL->CancelCreation();
    6161           1 :                 CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    6162           1 :                 return nullptr;
    6163             :             }
    6164             : 
    6165         726 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
    6166         726 :             nSamplesAccountedFor = 3;
    6167             : 
    6168             :             // Explicitly register the subsampling so that JPEGFixupTags
    6169             :             // is a no-op (helps for cloud optimized geotiffs)
    6170         726 :             TIFFSetField(l_hTIFF, TIFFTAG_YCBCRSUBSAMPLING, 2, 2);
    6171             :         }
    6172           1 :         else if (EQUAL(pszValue, "CIELAB"))
    6173             :         {
    6174           0 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_CIELAB);
    6175           0 :             nSamplesAccountedFor = 3;
    6176             :         }
    6177           1 :         else if (EQUAL(pszValue, "ICCLAB"))
    6178             :         {
    6179           0 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_ICCLAB);
    6180           0 :             nSamplesAccountedFor = 3;
    6181             :         }
    6182           1 :         else if (EQUAL(pszValue, "ITULAB"))
    6183             :         {
    6184           0 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_ITULAB);
    6185           0 :             nSamplesAccountedFor = 3;
    6186             :         }
    6187             :         else
    6188             :         {
    6189           1 :             ReportError(pszFilename, CE_Warning, CPLE_IllegalArg,
    6190             :                         "PHOTOMETRIC=%s value not recognised, ignoring.  "
    6191             :                         "Set the Photometric Interpretation as MINISBLACK.",
    6192             :                         pszValue);
    6193           1 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
    6194             :         }
    6195             : 
    6196        1910 :         if (l_nBands < nSamplesAccountedFor)
    6197             :         {
    6198           1 :             ReportError(pszFilename, CE_Warning, CPLE_IllegalArg,
    6199             :                         "PHOTOMETRIC=%s value does not correspond to number "
    6200             :                         "of bands (%d), ignoring.  "
    6201             :                         "Set the Photometric Interpretation as MINISBLACK.",
    6202             :                         pszValue, l_nBands);
    6203           1 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
    6204             :         }
    6205             :     }
    6206             :     else
    6207             :     {
    6208             :         // If image contains 3 or 4 bands and datatype is Byte then we will
    6209             :         // assume it is RGB. In all other cases assume it is MINISBLACK.
    6210        8022 :         if (l_nBands == 3 && eType == GDT_UInt8)
    6211             :         {
    6212         323 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
    6213         323 :             nSamplesAccountedFor = 3;
    6214             :         }
    6215        7699 :         else if (l_nBands == 4 && eType == GDT_UInt8)
    6216             :         {
    6217             :             uint16_t v[1] = {
    6218         723 :                 GTiffGetAlphaValue(CSLFetchNameValue(papszParamList, "ALPHA"),
    6219         723 :                                    DEFAULT_ALPHA_TYPE)};
    6220             : 
    6221         723 :             TIFFSetField(l_hTIFF, TIFFTAG_EXTRASAMPLES, 1, v);
    6222         723 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
    6223         723 :             nSamplesAccountedFor = 4;
    6224             :         }
    6225             :         else
    6226             :         {
    6227        6976 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
    6228        6976 :             nSamplesAccountedFor = 1;
    6229             :         }
    6230             :     }
    6231             : 
    6232             :     /* -------------------------------------------------------------------- */
    6233             :     /*      If there are extra samples, we need to mark them with an        */
    6234             :     /*      appropriate extrasamples definition here.                       */
    6235             :     /* -------------------------------------------------------------------- */
    6236        9932 :     if (l_nBands > nSamplesAccountedFor)
    6237             :     {
    6238        1389 :         const int nExtraSamples = l_nBands - nSamplesAccountedFor;
    6239             : 
    6240             :         uint16_t *v = static_cast<uint16_t *>(
    6241        1389 :             CPLMalloc(sizeof(uint16_t) * nExtraSamples));
    6242             : 
    6243        1389 :         v[0] = GTiffGetAlphaValue(CSLFetchNameValue(papszParamList, "ALPHA"),
    6244             :                                   EXTRASAMPLE_UNSPECIFIED);
    6245             : 
    6246      297700 :         for (int i = 1; i < nExtraSamples; ++i)
    6247      296311 :             v[i] = EXTRASAMPLE_UNSPECIFIED;
    6248             : 
    6249        1389 :         TIFFSetField(l_hTIFF, TIFFTAG_EXTRASAMPLES, nExtraSamples, v);
    6250             : 
    6251        1389 :         CPLFree(v);
    6252             :     }
    6253             : 
    6254             :     // Set the ICC color profile.
    6255        9932 :     if (eProfile != GTiffProfile::BASELINE)
    6256             :     {
    6257        9907 :         SaveICCProfile(nullptr, l_hTIFF, papszParamList, l_nBitsPerSample);
    6258             :     }
    6259             : 
    6260             :     // Set the compression method before asking the default strip size
    6261             :     // This is useful when translating to a JPEG-In-TIFF file where
    6262             :     // the default strip size is 8 or 16 depending on the photometric value.
    6263        9932 :     TIFFSetField(l_hTIFF, TIFFTAG_COMPRESSION, l_nCompression);
    6264             : 
    6265        9932 :     if (l_nCompression == COMPRESSION_LERC)
    6266             :     {
    6267             :         const char *pszCompress =
    6268          97 :             CSLFetchNameValueDef(papszParamList, "COMPRESS", "");
    6269          97 :         if (EQUAL(pszCompress, "LERC_DEFLATE"))
    6270             :         {
    6271          16 :             TIFFSetField(l_hTIFF, TIFFTAG_LERC_ADD_COMPRESSION,
    6272             :                          LERC_ADD_COMPRESSION_DEFLATE);
    6273             :         }
    6274          81 :         else if (EQUAL(pszCompress, "LERC_ZSTD"))
    6275             :         {
    6276          14 :             if (TIFFSetField(l_hTIFF, TIFFTAG_LERC_ADD_COMPRESSION,
    6277          14 :                              LERC_ADD_COMPRESSION_ZSTD) != 1)
    6278             :             {
    6279           0 :                 XTIFFClose(l_hTIFF);
    6280           0 :                 l_fpL->CancelCreation();
    6281           0 :                 CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    6282           0 :                 return nullptr;
    6283             :             }
    6284             :         }
    6285             :     }
    6286             :     // TODO later: take into account LERC version
    6287             : 
    6288             :     /* -------------------------------------------------------------------- */
    6289             :     /*      Setup tiling/stripping flags.                                   */
    6290             :     /* -------------------------------------------------------------------- */
    6291        9932 :     if (bTiled)
    6292             :     {
    6293        1616 :         if (!TIFFSetField(l_hTIFF, TIFFTAG_TILEWIDTH, l_nBlockXSize) ||
    6294         808 :             !TIFFSetField(l_hTIFF, TIFFTAG_TILELENGTH, l_nBlockYSize))
    6295             :         {
    6296           0 :             XTIFFClose(l_hTIFF);
    6297           0 :             l_fpL->CancelCreation();
    6298           0 :             CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    6299           0 :             return nullptr;
    6300             :         }
    6301             :     }
    6302             :     else
    6303             :     {
    6304        9124 :         const uint32_t l_nRowsPerStrip = std::min(
    6305             :             nYSize, l_nBlockYSize == 0
    6306        9124 :                         ? static_cast<int>(TIFFDefaultStripSize(l_hTIFF, 0))
    6307        9124 :                         : l_nBlockYSize);
    6308             : 
    6309        9124 :         TIFFSetField(l_hTIFF, TIFFTAG_ROWSPERSTRIP, l_nRowsPerStrip);
    6310             :     }
    6311             : 
    6312             :     /* -------------------------------------------------------------------- */
    6313             :     /*      Set compression related tags.                                   */
    6314             :     /* -------------------------------------------------------------------- */
    6315        9932 :     if (GTIFFSupportsPredictor(l_nCompression))
    6316         980 :         TIFFSetField(l_hTIFF, TIFFTAG_PREDICTOR, nPredictor);
    6317        9932 :     if (l_nCompression == COMPRESSION_ADOBE_DEFLATE ||
    6318             :         l_nCompression == COMPRESSION_LERC)
    6319             :     {
    6320         280 :         GTiffSetDeflateSubCodec(l_hTIFF);
    6321             : 
    6322         280 :         if (l_nZLevel != -1)
    6323          22 :             TIFFSetField(l_hTIFF, TIFFTAG_ZIPQUALITY, l_nZLevel);
    6324             :     }
    6325        9932 :     if (l_nCompression == COMPRESSION_JPEG && l_nJpegQuality != -1)
    6326        1905 :         TIFFSetField(l_hTIFF, TIFFTAG_JPEGQUALITY, l_nJpegQuality);
    6327        9932 :     if (l_nCompression == COMPRESSION_LZMA && l_nLZMAPreset != -1)
    6328          10 :         TIFFSetField(l_hTIFF, TIFFTAG_LZMAPRESET, l_nLZMAPreset);
    6329        9932 :     if ((l_nCompression == COMPRESSION_ZSTD ||
    6330         201 :          l_nCompression == COMPRESSION_LERC) &&
    6331             :         l_nZSTDLevel != -1)
    6332          12 :         TIFFSetField(l_hTIFF, TIFFTAG_ZSTD_LEVEL, l_nZSTDLevel);
    6333        9932 :     if (l_nCompression == COMPRESSION_LERC)
    6334             :     {
    6335          97 :         TIFFSetField(l_hTIFF, TIFFTAG_LERC_MAXZERROR, l_dfMaxZError);
    6336             :     }
    6337             : #if HAVE_JXL
    6338        9932 :     if (l_nCompression == COMPRESSION_JXL ||
    6339             :         l_nCompression == COMPRESSION_JXL_DNG_1_7)
    6340             :     {
    6341         104 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_LOSSYNESS,
    6342             :                      l_bJXLLossless ? JXL_LOSSLESS : JXL_LOSSY);
    6343         104 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_EFFORT, l_nJXLEffort);
    6344         104 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_DISTANCE,
    6345             :                      static_cast<double>(l_fJXLDistance));
    6346         104 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_ALPHA_DISTANCE,
    6347             :                      static_cast<double>(l_fJXLAlphaDistance));
    6348             :     }
    6349             : #endif
    6350        9932 :     if (l_nCompression == COMPRESSION_WEBP)
    6351          33 :         TIFFSetField(l_hTIFF, TIFFTAG_WEBP_LEVEL, l_nWebPLevel);
    6352        9932 :     if (l_nCompression == COMPRESSION_WEBP && l_bWebPLossless)
    6353           7 :         TIFFSetField(l_hTIFF, TIFFTAG_WEBP_LOSSLESS, 1);
    6354             : 
    6355        9932 :     if (l_nCompression == COMPRESSION_JPEG)
    6356        2083 :         TIFFSetField(l_hTIFF, TIFFTAG_JPEGTABLESMODE, l_nJpegTablesMode);
    6357             : 
    6358             :     /* -------------------------------------------------------------------- */
    6359             :     /*      If we forced production of a file with photometric=palette,     */
    6360             :     /*      we need to push out a default color table.                      */
    6361             :     /* -------------------------------------------------------------------- */
    6362        9932 :     if (bForceColorTable)
    6363             :     {
    6364           4 :         const int nColors = eType == GDT_UInt8 ? 256 : 65536;
    6365             : 
    6366             :         unsigned short *panTRed = static_cast<unsigned short *>(
    6367           4 :             CPLMalloc(sizeof(unsigned short) * nColors));
    6368             :         unsigned short *panTGreen = static_cast<unsigned short *>(
    6369           4 :             CPLMalloc(sizeof(unsigned short) * nColors));
    6370             :         unsigned short *panTBlue = static_cast<unsigned short *>(
    6371           4 :             CPLMalloc(sizeof(unsigned short) * nColors));
    6372             : 
    6373        1028 :         for (int iColor = 0; iColor < nColors; ++iColor)
    6374             :         {
    6375        1024 :             if (eType == GDT_UInt8)
    6376             :             {
    6377        1024 :                 panTRed[iColor] = GTiffDataset::ClampCTEntry(
    6378             :                     iColor, 1, iColor, nColorTableMultiplier);
    6379        1024 :                 panTGreen[iColor] = GTiffDataset::ClampCTEntry(
    6380             :                     iColor, 2, iColor, nColorTableMultiplier);
    6381        1024 :                 panTBlue[iColor] = GTiffDataset::ClampCTEntry(
    6382             :                     iColor, 3, iColor, nColorTableMultiplier);
    6383             :             }
    6384             :             else
    6385             :             {
    6386           0 :                 panTRed[iColor] = static_cast<unsigned short>(iColor);
    6387           0 :                 panTGreen[iColor] = static_cast<unsigned short>(iColor);
    6388           0 :                 panTBlue[iColor] = static_cast<unsigned short>(iColor);
    6389             :             }
    6390             :         }
    6391             : 
    6392           4 :         TIFFSetField(l_hTIFF, TIFFTAG_COLORMAP, panTRed, panTGreen, panTBlue);
    6393             : 
    6394           4 :         CPLFree(panTRed);
    6395           4 :         CPLFree(panTGreen);
    6396           4 :         CPLFree(panTBlue);
    6397             :     }
    6398             : 
    6399             :     // This trick
    6400             :     // creates a temporary in-memory file and fetches its JPEG tables so that
    6401             :     // we can directly set them, before tif_jpeg.c compute them at the first
    6402             :     // strip/tile writing, which is too late, since we have already crystalized
    6403             :     // the directory. This way we avoid a directory rewriting.
    6404       12015 :     if (l_nCompression == COMPRESSION_JPEG &&
    6405        2083 :         CPLTestBool(
    6406             :             CSLFetchNameValueDef(papszParamList, "WRITE_JPEGTABLE_TAG", "YES")))
    6407             :     {
    6408        1014 :         GTiffWriteJPEGTables(
    6409             :             l_hTIFF, CSLFetchNameValue(papszParamList, "PHOTOMETRIC"),
    6410             :             CSLFetchNameValue(papszParamList, "JPEG_QUALITY"),
    6411             :             CSLFetchNameValue(papszParamList, "JPEGTABLESMODE"));
    6412             :     }
    6413             : 
    6414        9932 :     *pfpL = l_fpL;
    6415             : 
    6416        9932 :     return l_hTIFF;
    6417             : }
    6418             : 
    6419             : /************************************************************************/
    6420             : /*                            GuessJPEGQuality()                        */
    6421             : /*                                                                      */
    6422             : /*      Guess JPEG quality from JPEGTABLES tag.                         */
    6423             : /************************************************************************/
    6424             : 
    6425        3841 : static const GByte *GTIFFFindNextTable(const GByte *paby, GByte byMarker,
    6426             :                                        int nLen, int *pnLenTable)
    6427             : {
    6428        7949 :     for (int i = 0; i + 1 < nLen;)
    6429             :     {
    6430        7949 :         if (paby[i] != 0xFF)
    6431           0 :             return nullptr;
    6432        7949 :         ++i;
    6433        7949 :         if (paby[i] == 0xD8)
    6434             :         {
    6435        3111 :             ++i;
    6436        3111 :             continue;
    6437             :         }
    6438        4838 :         if (i + 2 >= nLen)
    6439         829 :             return nullptr;
    6440        4009 :         int nMarkerLen = paby[i + 1] * 256 + paby[i + 2];
    6441        4009 :         if (i + 1 + nMarkerLen >= nLen)
    6442           0 :             return nullptr;
    6443        4009 :         if (paby[i] == byMarker)
    6444             :         {
    6445        3012 :             if (pnLenTable)
    6446        2470 :                 *pnLenTable = nMarkerLen;
    6447        3012 :             return paby + i + 1;
    6448             :         }
    6449         997 :         i += 1 + nMarkerLen;
    6450             :     }
    6451           0 :     return nullptr;
    6452             : }
    6453             : 
    6454             : constexpr GByte MARKER_HUFFMAN_TABLE = 0xC4;
    6455             : constexpr GByte MARKER_QUANT_TABLE = 0xDB;
    6456             : 
    6457             : // We assume that if there are several quantization tables, they are
    6458             : // in the same order. Which is a reasonable assumption for updating
    6459             : // a file generated by ourselves.
    6460         904 : static bool GTIFFQuantizationTablesEqual(const GByte *paby1, int nLen1,
    6461             :                                          const GByte *paby2, int nLen2)
    6462             : {
    6463         904 :     bool bFound = false;
    6464             :     while (true)
    6465             :     {
    6466         945 :         int nLenTable1 = 0;
    6467         945 :         int nLenTable2 = 0;
    6468             :         const GByte *paby1New =
    6469         945 :             GTIFFFindNextTable(paby1, MARKER_QUANT_TABLE, nLen1, &nLenTable1);
    6470             :         const GByte *paby2New =
    6471         945 :             GTIFFFindNextTable(paby2, MARKER_QUANT_TABLE, nLen2, &nLenTable2);
    6472         945 :         if (paby1New == nullptr && paby2New == nullptr)
    6473         904 :             return bFound;
    6474         911 :         if (paby1New == nullptr || paby2New == nullptr)
    6475           0 :             return false;
    6476         911 :         if (nLenTable1 != nLenTable2)
    6477         207 :             return false;
    6478         704 :         if (memcmp(paby1New, paby2New, nLenTable1) != 0)
    6479         663 :             return false;
    6480          41 :         paby1New += nLenTable1;
    6481          41 :         paby2New += nLenTable2;
    6482          41 :         nLen1 -= static_cast<int>(paby1New - paby1);
    6483          41 :         nLen2 -= static_cast<int>(paby2New - paby2);
    6484          41 :         paby1 = paby1New;
    6485          41 :         paby2 = paby2New;
    6486          41 :         bFound = true;
    6487          41 :     }
    6488             : }
    6489             : 
    6490             : // Guess the JPEG quality by comparing against the MD5Sum of precomputed
    6491             : // quantization tables
    6492         407 : static int GuessJPEGQualityFromMD5(const uint8_t md5JPEGQuantTable[][16],
    6493             :                                    const GByte *const pabyJPEGTable,
    6494             :                                    int nJPEGTableSize)
    6495             : {
    6496         407 :     int nRemainingLen = nJPEGTableSize;
    6497         407 :     const GByte *pabyCur = pabyJPEGTable;
    6498             : 
    6499             :     struct CPLMD5Context context;
    6500         407 :     CPLMD5Init(&context);
    6501             : 
    6502             :     while (true)
    6503             :     {
    6504        1055 :         int nLenTable = 0;
    6505        1055 :         const GByte *pabyNew = GTIFFFindNextTable(pabyCur, MARKER_QUANT_TABLE,
    6506             :                                                   nRemainingLen, &nLenTable);
    6507        1055 :         if (pabyNew == nullptr)
    6508         407 :             break;
    6509         648 :         CPLMD5Update(&context, pabyNew, nLenTable);
    6510         648 :         pabyNew += nLenTable;
    6511         648 :         nRemainingLen -= static_cast<int>(pabyNew - pabyCur);
    6512         648 :         pabyCur = pabyNew;
    6513         648 :     }
    6514             : 
    6515             :     GByte digest[16];
    6516         407 :     CPLMD5Final(digest, &context);
    6517             : 
    6518       28696 :     for (int i = 0; i < 100; i++)
    6519             :     {
    6520       28693 :         if (memcmp(md5JPEGQuantTable[i], digest, 16) == 0)
    6521             :         {
    6522         404 :             return i + 1;
    6523             :         }
    6524             :     }
    6525           3 :     return -1;
    6526             : }
    6527             : 
    6528         462 : int GTiffDataset::GuessJPEGQuality(bool &bOutHasQuantizationTable,
    6529             :                                    bool &bOutHasHuffmanTable)
    6530             : {
    6531         462 :     CPLAssert(m_nCompression == COMPRESSION_JPEG);
    6532         462 :     uint32_t nJPEGTableSize = 0;
    6533         462 :     void *pJPEGTable = nullptr;
    6534         462 :     if (!TIFFGetField(m_hTIFF, TIFFTAG_JPEGTABLES, &nJPEGTableSize,
    6535             :                       &pJPEGTable))
    6536             :     {
    6537          14 :         bOutHasQuantizationTable = false;
    6538          14 :         bOutHasHuffmanTable = false;
    6539          14 :         return -1;
    6540             :     }
    6541             : 
    6542         448 :     bOutHasQuantizationTable =
    6543         448 :         GTIFFFindNextTable(static_cast<const GByte *>(pJPEGTable),
    6544             :                            MARKER_QUANT_TABLE, nJPEGTableSize,
    6545         448 :                            nullptr) != nullptr;
    6546         448 :     bOutHasHuffmanTable =
    6547         448 :         GTIFFFindNextTable(static_cast<const GByte *>(pJPEGTable),
    6548             :                            MARKER_HUFFMAN_TABLE, nJPEGTableSize,
    6549         448 :                            nullptr) != nullptr;
    6550         448 :     if (!bOutHasQuantizationTable)
    6551           7 :         return -1;
    6552             : 
    6553         441 :     if ((nBands == 1 && m_nBitsPerSample == 8) ||
    6554         381 :         (nBands == 3 && m_nBitsPerSample == 8 &&
    6555         335 :          m_nPhotometric == PHOTOMETRIC_RGB) ||
    6556         287 :         (nBands == 4 && m_nBitsPerSample == 8 &&
    6557          27 :          m_nPhotometric == PHOTOMETRIC_SEPARATED))
    6558             :     {
    6559         166 :         return GuessJPEGQualityFromMD5(md5JPEGQuantTable_generic_8bit,
    6560             :                                        static_cast<const GByte *>(pJPEGTable),
    6561         166 :                                        static_cast<int>(nJPEGTableSize));
    6562             :     }
    6563             : 
    6564         275 :     if (nBands == 3 && m_nBitsPerSample == 8 &&
    6565         241 :         m_nPhotometric == PHOTOMETRIC_YCBCR)
    6566             :     {
    6567             :         int nRet =
    6568         241 :             GuessJPEGQualityFromMD5(md5JPEGQuantTable_3_YCBCR_8bit,
    6569             :                                     static_cast<const GByte *>(pJPEGTable),
    6570             :                                     static_cast<int>(nJPEGTableSize));
    6571         241 :         if (nRet < 0)
    6572             :         {
    6573             :             // libjpeg 9e has modified the YCbCr quantization tables.
    6574             :             nRet =
    6575           0 :                 GuessJPEGQualityFromMD5(md5JPEGQuantTable_3_YCBCR_8bit_jpeg9e,
    6576             :                                         static_cast<const GByte *>(pJPEGTable),
    6577             :                                         static_cast<int>(nJPEGTableSize));
    6578             :         }
    6579         241 :         return nRet;
    6580             :     }
    6581             : 
    6582          34 :     char **papszLocalParameters = nullptr;
    6583             :     papszLocalParameters =
    6584          34 :         CSLSetNameValue(papszLocalParameters, "COMPRESS", "JPEG");
    6585          34 :     if (m_nPhotometric == PHOTOMETRIC_YCBCR)
    6586             :         papszLocalParameters =
    6587           7 :             CSLSetNameValue(papszLocalParameters, "PHOTOMETRIC", "YCBCR");
    6588          27 :     else if (m_nPhotometric == PHOTOMETRIC_SEPARATED)
    6589             :         papszLocalParameters =
    6590           0 :             CSLSetNameValue(papszLocalParameters, "PHOTOMETRIC", "CMYK");
    6591             :     papszLocalParameters =
    6592          34 :         CSLSetNameValue(papszLocalParameters, "BLOCKYSIZE", "16");
    6593          34 :     if (m_nBitsPerSample == 12)
    6594             :         papszLocalParameters =
    6595          16 :             CSLSetNameValue(papszLocalParameters, "NBITS", "12");
    6596             : 
    6597             :     const CPLString osTmpFilenameIn(
    6598          34 :         VSIMemGenerateHiddenFilename("gtiffdataset_guess_jpeg_quality_tmp"));
    6599             : 
    6600          34 :     int nRet = -1;
    6601         938 :     for (int nQuality = 0; nQuality <= 100 && nRet < 0; ++nQuality)
    6602             :     {
    6603         904 :         VSILFILE *fpTmp = nullptr;
    6604         904 :         if (nQuality == 0)
    6605             :             papszLocalParameters =
    6606          34 :                 CSLSetNameValue(papszLocalParameters, "JPEG_QUALITY", "75");
    6607             :         else
    6608             :             papszLocalParameters =
    6609         870 :                 CSLSetNameValue(papszLocalParameters, "JPEG_QUALITY",
    6610             :                                 CPLSPrintf("%d", nQuality));
    6611             : 
    6612         904 :         CPLPushErrorHandler(CPLQuietErrorHandler);
    6613         904 :         CPLString osTmp;
    6614             :         bool bTileInterleaving;
    6615        1808 :         TIFF *hTIFFTmp = CreateLL(
    6616         904 :             osTmpFilenameIn, 16, 16, (nBands <= 4) ? nBands : 1,
    6617             :             GetRasterBand(1)->GetRasterDataType(), 0.0, 0, papszLocalParameters,
    6618             :             &fpTmp, osTmp, /* bCreateCopy=*/false, bTileInterleaving);
    6619         904 :         CPLPopErrorHandler();
    6620         904 :         if (!hTIFFTmp)
    6621             :         {
    6622           0 :             break;
    6623             :         }
    6624             : 
    6625         904 :         TIFFWriteCheck(hTIFFTmp, FALSE, "CreateLL");
    6626         904 :         TIFFWriteDirectory(hTIFFTmp);
    6627         904 :         TIFFSetDirectory(hTIFFTmp, 0);
    6628             :         // Now reset jpegcolormode.
    6629        1196 :         if (m_nPhotometric == PHOTOMETRIC_YCBCR &&
    6630         292 :             CPLTestBool(CPLGetConfigOption("CONVERT_YCBCR_TO_RGB", "YES")))
    6631             :         {
    6632         292 :             TIFFSetField(hTIFFTmp, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
    6633             :         }
    6634             : 
    6635         904 :         GByte abyZeroData[(16 * 16 * 4 * 3) / 2] = {};
    6636         904 :         const int nBlockSize =
    6637         904 :             (16 * 16 * ((nBands <= 4) ? nBands : 1) * m_nBitsPerSample) / 8;
    6638         904 :         TIFFWriteEncodedStrip(hTIFFTmp, 0, abyZeroData, nBlockSize);
    6639             : 
    6640         904 :         uint32_t nJPEGTableSizeTry = 0;
    6641         904 :         void *pJPEGTableTry = nullptr;
    6642         904 :         if (TIFFGetField(hTIFFTmp, TIFFTAG_JPEGTABLES, &nJPEGTableSizeTry,
    6643         904 :                          &pJPEGTableTry))
    6644             :         {
    6645         904 :             if (GTIFFQuantizationTablesEqual(
    6646             :                     static_cast<GByte *>(pJPEGTable), nJPEGTableSize,
    6647             :                     static_cast<GByte *>(pJPEGTableTry), nJPEGTableSizeTry))
    6648             :             {
    6649          34 :                 nRet = (nQuality == 0) ? 75 : nQuality;
    6650             :             }
    6651             :         }
    6652             : 
    6653         904 :         XTIFFClose(hTIFFTmp);
    6654         904 :         CPL_IGNORE_RET_VAL(VSIFCloseL(fpTmp));
    6655             :     }
    6656             : 
    6657          34 :     CSLDestroy(papszLocalParameters);
    6658          34 :     VSIUnlink(osTmpFilenameIn);
    6659             : 
    6660          34 :     return nRet;
    6661             : }
    6662             : 
    6663             : /************************************************************************/
    6664             : /*                SetJPEGQualityAndTablesModeFromFile()                 */
    6665             : /************************************************************************/
    6666             : 
    6667         161 : void GTiffDataset::SetJPEGQualityAndTablesModeFromFile(
    6668             :     int nQuality, bool bHasQuantizationTable, bool bHasHuffmanTable)
    6669             : {
    6670         161 :     if (nQuality > 0)
    6671             :     {
    6672         154 :         CPLDebug("GTiff", "Guessed JPEG quality to be %d", nQuality);
    6673         154 :         m_nJpegQuality = static_cast<signed char>(nQuality);
    6674         154 :         TIFFSetField(m_hTIFF, TIFFTAG_JPEGQUALITY, nQuality);
    6675             : 
    6676             :         // This means we will use the quantization tables from the
    6677             :         // JpegTables tag.
    6678         154 :         m_nJpegTablesMode = JPEGTABLESMODE_QUANT;
    6679             :     }
    6680             :     else
    6681             :     {
    6682           7 :         uint32_t nJPEGTableSize = 0;
    6683           7 :         void *pJPEGTable = nullptr;
    6684           7 :         if (!TIFFGetField(m_hTIFF, TIFFTAG_JPEGTABLES, &nJPEGTableSize,
    6685             :                           &pJPEGTable))
    6686             :         {
    6687           4 :             toff_t *panByteCounts = nullptr;
    6688           8 :             const int nBlockCount = m_nPlanarConfig == PLANARCONFIG_SEPARATE
    6689           4 :                                         ? m_nBlocksPerBand * nBands
    6690             :                                         : m_nBlocksPerBand;
    6691           4 :             if (TIFFIsTiled(m_hTIFF))
    6692           1 :                 TIFFGetField(m_hTIFF, TIFFTAG_TILEBYTECOUNTS, &panByteCounts);
    6693             :             else
    6694           3 :                 TIFFGetField(m_hTIFF, TIFFTAG_STRIPBYTECOUNTS, &panByteCounts);
    6695             : 
    6696           4 :             bool bFoundNonEmptyBlock = false;
    6697           4 :             if (panByteCounts != nullptr)
    6698             :             {
    6699          56 :                 for (int iBlock = 0; iBlock < nBlockCount; ++iBlock)
    6700             :                 {
    6701          53 :                     if (panByteCounts[iBlock] != 0)
    6702             :                     {
    6703           1 :                         bFoundNonEmptyBlock = true;
    6704           1 :                         break;
    6705             :                     }
    6706             :                 }
    6707             :             }
    6708           4 :             if (bFoundNonEmptyBlock)
    6709             :             {
    6710           1 :                 CPLDebug("GTiff", "Could not guess JPEG quality. "
    6711             :                                   "JPEG tables are missing, so going in "
    6712             :                                   "TIFFTAG_JPEGTABLESMODE = 0/2 mode");
    6713             :                 // Write quantization tables in each strile.
    6714           1 :                 m_nJpegTablesMode = 0;
    6715             :             }
    6716             :         }
    6717             :         else
    6718             :         {
    6719           3 :             if (bHasQuantizationTable)
    6720             :             {
    6721             :                 // FIXME in libtiff: this is likely going to cause issues
    6722             :                 // since libtiff will reuse in each strile the number of
    6723             :                 // the global quantization table, which is invalid.
    6724           1 :                 CPLDebug("GTiff",
    6725             :                          "Could not guess JPEG quality although JPEG "
    6726             :                          "quantization tables are present, so going in "
    6727             :                          "TIFFTAG_JPEGTABLESMODE = 0/2 mode");
    6728             :             }
    6729             :             else
    6730             :             {
    6731           2 :                 CPLDebug("GTiff",
    6732             :                          "Could not guess JPEG quality since JPEG "
    6733             :                          "quantization tables are not present, so going in "
    6734             :                          "TIFFTAG_JPEGTABLESMODE = 0/2 mode");
    6735             :             }
    6736             : 
    6737             :             // Write quantization tables in each strile.
    6738           3 :             m_nJpegTablesMode = 0;
    6739             :         }
    6740             :     }
    6741         161 :     if (bHasHuffmanTable)
    6742             :     {
    6743             :         // If there are Huffman tables in header use them, otherwise
    6744             :         // if we use optimized tables, libtiff will currently reuse
    6745             :         // the number of the Huffman tables of the header for the
    6746             :         // optimized version of each strile, which is illegal.
    6747          23 :         m_nJpegTablesMode |= JPEGTABLESMODE_HUFF;
    6748             :     }
    6749         161 :     if (m_nJpegTablesMode >= 0)
    6750         159 :         TIFFSetField(m_hTIFF, TIFFTAG_JPEGTABLESMODE, m_nJpegTablesMode);
    6751         161 : }
    6752             : 
    6753             : /************************************************************************/
    6754             : /*                               Create()                               */
    6755             : /*                                                                      */
    6756             : /*      Create a new GeoTIFF or TIFF file.                              */
    6757             : /************************************************************************/
    6758             : 
    6759        5831 : GDALDataset *GTiffDataset::Create(const char *pszFilename, int nXSize,
    6760             :                                   int nYSize, int l_nBands, GDALDataType eType,
    6761             :                                   CSLConstList papszParamList)
    6762             : 
    6763             : {
    6764        5831 :     VSILFILE *l_fpL = nullptr;
    6765       11662 :     CPLString l_osTmpFilename;
    6766             : 
    6767             :     const int nColorTableMultiplier = std::max(
    6768       11662 :         1,
    6769       11662 :         std::min(257,
    6770        5831 :                  atoi(CSLFetchNameValueDef(
    6771             :                      papszParamList, "COLOR_TABLE_MULTIPLIER",
    6772        5831 :                      CPLSPrintf("%d", DEFAULT_COLOR_TABLE_MULTIPLIER_257)))));
    6773             : 
    6774             :     /* -------------------------------------------------------------------- */
    6775             :     /*      Create the underlying TIFF file.                                */
    6776             :     /* -------------------------------------------------------------------- */
    6777             :     bool bTileInterleaving;
    6778             :     TIFF *l_hTIFF =
    6779        5831 :         CreateLL(pszFilename, nXSize, nYSize, l_nBands, eType, 0,
    6780             :                  nColorTableMultiplier, papszParamList, &l_fpL, l_osTmpFilename,
    6781             :                  /* bCreateCopy=*/false, bTileInterleaving);
    6782        5831 :     const bool bStreaming = !l_osTmpFilename.empty();
    6783             : 
    6784        5831 :     if (l_hTIFF == nullptr)
    6785          38 :         return nullptr;
    6786             : 
    6787             :     /* -------------------------------------------------------------------- */
    6788             :     /*      Create the new GTiffDataset object.                             */
    6789             :     /* -------------------------------------------------------------------- */
    6790       11586 :     auto poDS = std::make_unique<GTiffDataset>();
    6791        5793 :     poDS->m_hTIFF = l_hTIFF;
    6792        5793 :     poDS->m_fpL = l_fpL;
    6793        5793 :     const bool bSuppressASAP = CPLTestBool(
    6794             :         CSLFetchNameValueDef(papszParamList, "@SUPPRESS_ASAP", "NO"));
    6795        5793 :     if (bSuppressASAP)
    6796          36 :         poDS->MarkSuppressOnClose();
    6797        5793 :     if (bStreaming)
    6798             :     {
    6799           4 :         poDS->m_bStreamingOut = true;
    6800           4 :         poDS->m_pszTmpFilename = CPLStrdup(l_osTmpFilename);
    6801           4 :         poDS->m_fpToWrite = VSIFOpenL(pszFilename, "wb");
    6802           4 :         if (poDS->m_fpToWrite == nullptr)
    6803             :         {
    6804           1 :             VSIUnlink(l_osTmpFilename);
    6805           1 :             return nullptr;
    6806             :         }
    6807             :     }
    6808        5792 :     poDS->nRasterXSize = nXSize;
    6809        5792 :     poDS->nRasterYSize = nYSize;
    6810        5792 :     poDS->eAccess = GA_Update;
    6811             : 
    6812             :     // This will avoid GTiffDataset::GetSiblingFiles() to trigger a directory
    6813             :     // listing, which is potentially costly and only makes sense when opening
    6814             :     // new files, not creating new ones. Helps for scenario like
    6815             :     // https://github.com/OSGeo/gdal/issues/13930
    6816        5792 :     poDS->m_bHasGotSiblingFiles = true;
    6817             : 
    6818        5792 :     poDS->m_nColorTableMultiplier = nColorTableMultiplier;
    6819             : 
    6820        5792 :     poDS->m_bCrystalized = false;
    6821        5792 :     poDS->m_nSamplesPerPixel = static_cast<uint16_t>(l_nBands);
    6822        5792 :     poDS->m_osFilename = pszFilename;
    6823             : 
    6824             :     // Don't try to load external metadata files (#6597).
    6825        5792 :     poDS->m_bIMDRPCMetadataLoaded = true;
    6826             : 
    6827             :     // Avoid premature crystalization that will cause directory re-writing if
    6828             :     // GetProjectionRef() or GetGeoTransform() are called on the newly created
    6829             :     // GeoTIFF.
    6830        5792 :     poDS->m_bLookedForProjection = true;
    6831             : 
    6832        5792 :     TIFFGetField(l_hTIFF, TIFFTAG_SAMPLEFORMAT, &(poDS->m_nSampleFormat));
    6833        5792 :     TIFFGetField(l_hTIFF, TIFFTAG_PLANARCONFIG, &(poDS->m_nPlanarConfig));
    6834             :     // Weird that we need this, but otherwise we get a Valgrind warning on
    6835             :     // tiff_write_124.
    6836        5792 :     if (!TIFFGetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, &(poDS->m_nPhotometric)))
    6837           1 :         poDS->m_nPhotometric = PHOTOMETRIC_MINISBLACK;
    6838        5792 :     TIFFGetField(l_hTIFF, TIFFTAG_BITSPERSAMPLE, &(poDS->m_nBitsPerSample));
    6839        5792 :     TIFFGetField(l_hTIFF, TIFFTAG_COMPRESSION, &(poDS->m_nCompression));
    6840             : 
    6841        5792 :     if (TIFFIsTiled(l_hTIFF))
    6842             :     {
    6843         407 :         TIFFGetField(l_hTIFF, TIFFTAG_TILEWIDTH, &(poDS->m_nBlockXSize));
    6844         407 :         TIFFGetField(l_hTIFF, TIFFTAG_TILELENGTH, &(poDS->m_nBlockYSize));
    6845             :     }
    6846             :     else
    6847             :     {
    6848        5385 :         if (!TIFFGetField(l_hTIFF, TIFFTAG_ROWSPERSTRIP,
    6849        5385 :                           &(poDS->m_nRowsPerStrip)))
    6850           0 :             poDS->m_nRowsPerStrip = 1;  // Dummy value.
    6851             : 
    6852        5385 :         poDS->m_nBlockXSize = nXSize;
    6853       10770 :         poDS->m_nBlockYSize =
    6854        5385 :             std::min(static_cast<int>(poDS->m_nRowsPerStrip), nYSize);
    6855             :     }
    6856             : 
    6857        5792 :     if (!poDS->ComputeBlocksPerColRowAndBand(l_nBands))
    6858             :     {
    6859           0 :         poDS->m_fpL->CancelCreation();
    6860           0 :         return nullptr;
    6861             :     }
    6862             : 
    6863        5792 :     poDS->m_eProfile = GetProfile(CSLFetchNameValue(papszParamList, "PROFILE"));
    6864             : 
    6865             :     /* -------------------------------------------------------------------- */
    6866             :     /*      YCbCr JPEG compressed images should be translated on the fly    */
    6867             :     /*      to RGB by libtiff/libjpeg unless specifically requested         */
    6868             :     /*      otherwise.                                                      */
    6869             :     /* -------------------------------------------------------------------- */
    6870        5792 :     if (poDS->m_nCompression == COMPRESSION_JPEG &&
    6871        5813 :         poDS->m_nPhotometric == PHOTOMETRIC_YCBCR &&
    6872          21 :         CPLTestBool(CPLGetConfigOption("CONVERT_YCBCR_TO_RGB", "YES")))
    6873             :     {
    6874          21 :         int nColorMode = 0;
    6875             : 
    6876          21 :         poDS->SetMetadataItem("SOURCE_COLOR_SPACE", "YCbCr", "IMAGE_STRUCTURE");
    6877          42 :         if (!TIFFGetField(l_hTIFF, TIFFTAG_JPEGCOLORMODE, &nColorMode) ||
    6878          21 :             nColorMode != JPEGCOLORMODE_RGB)
    6879          21 :             TIFFSetField(l_hTIFF, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
    6880             :     }
    6881             : 
    6882        5792 :     if (poDS->m_nCompression == COMPRESSION_LERC)
    6883             :     {
    6884          26 :         uint32_t nLercParamCount = 0;
    6885          26 :         uint32_t *panLercParams = nullptr;
    6886          26 :         if (TIFFGetField(l_hTIFF, TIFFTAG_LERC_PARAMETERS, &nLercParamCount,
    6887          52 :                          &panLercParams) &&
    6888          26 :             nLercParamCount == 2)
    6889             :         {
    6890          26 :             memcpy(poDS->m_anLercAddCompressionAndVersion, panLercParams,
    6891             :                    sizeof(poDS->m_anLercAddCompressionAndVersion));
    6892             :         }
    6893             :     }
    6894             : 
    6895             :     /* -------------------------------------------------------------------- */
    6896             :     /*      Read palette back as a color table if it has one.               */
    6897             :     /* -------------------------------------------------------------------- */
    6898        5792 :     unsigned short *panRed = nullptr;
    6899        5792 :     unsigned short *panGreen = nullptr;
    6900        5792 :     unsigned short *panBlue = nullptr;
    6901             : 
    6902        5796 :     if (poDS->m_nPhotometric == PHOTOMETRIC_PALETTE &&
    6903           4 :         TIFFGetField(l_hTIFF, TIFFTAG_COLORMAP, &panRed, &panGreen, &panBlue))
    6904             :     {
    6905             : 
    6906           4 :         poDS->m_poColorTable = std::make_unique<GDALColorTable>();
    6907             : 
    6908           4 :         const int nColorCount = 1 << poDS->m_nBitsPerSample;
    6909             : 
    6910        1028 :         for (int iColor = nColorCount - 1; iColor >= 0; iColor--)
    6911             :         {
    6912        1024 :             const GDALColorEntry oEntry = {
    6913        1024 :                 static_cast<short>(panRed[iColor] / nColorTableMultiplier),
    6914        1024 :                 static_cast<short>(panGreen[iColor] / nColorTableMultiplier),
    6915        1024 :                 static_cast<short>(panBlue[iColor] / nColorTableMultiplier),
    6916        1024 :                 static_cast<short>(255)};
    6917             : 
    6918        1024 :             poDS->m_poColorTable->SetColorEntry(iColor, &oEntry);
    6919             :         }
    6920             :     }
    6921             : 
    6922             :     /* -------------------------------------------------------------------- */
    6923             :     /*      Do we want to ensure all blocks get written out on close to     */
    6924             :     /*      avoid sparse files?                                             */
    6925             :     /* -------------------------------------------------------------------- */
    6926        5792 :     if (!CPLFetchBool(papszParamList, "SPARSE_OK", false))
    6927        5682 :         poDS->m_bFillEmptyTilesAtClosing = true;
    6928             : 
    6929        5792 :     poDS->m_bWriteEmptyTiles =
    6930        6618 :         bStreaming || (poDS->m_nCompression != COMPRESSION_NONE &&
    6931         826 :                        poDS->m_bFillEmptyTilesAtClosing);
    6932             :     // Only required for people writing non-compressed striped files in the
    6933             :     // right order and wanting all tstrips to be written in the same order
    6934             :     // so that the end result can be memory mapped without knowledge of each
    6935             :     // strip offset.
    6936        5792 :     if (CPLTestBool(CSLFetchNameValueDef(
    6937       11584 :             papszParamList, "WRITE_EMPTY_TILES_SYNCHRONOUSLY", "FALSE")) ||
    6938        5792 :         CPLTestBool(CSLFetchNameValueDef(
    6939             :             papszParamList, "@WRITE_EMPTY_TILES_SYNCHRONOUSLY", "FALSE")))
    6940             :     {
    6941          26 :         poDS->m_bWriteEmptyTiles = true;
    6942             :     }
    6943             : 
    6944             :     /* -------------------------------------------------------------------- */
    6945             :     /*      Preserve creation options for consulting later (for instance    */
    6946             :     /*      to decide if a TFW file should be written).                     */
    6947             :     /* -------------------------------------------------------------------- */
    6948        5792 :     poDS->m_papszCreationOptions = CSLDuplicate(papszParamList);
    6949             : 
    6950        5792 :     poDS->m_nZLevel = GTiffGetZLevel(papszParamList);
    6951        5792 :     poDS->m_nLZMAPreset = GTiffGetLZMAPreset(papszParamList);
    6952        5792 :     poDS->m_nZSTDLevel = GTiffGetZSTDPreset(papszParamList);
    6953        5792 :     poDS->m_nWebPLevel = GTiffGetWebPLevel(papszParamList);
    6954        5792 :     poDS->m_bWebPLossless = GTiffGetWebPLossless(papszParamList);
    6955        5794 :     if (poDS->m_nWebPLevel != 100 && poDS->m_bWebPLossless &&
    6956           2 :         CSLFetchNameValue(papszParamList, "WEBP_LEVEL"))
    6957             :     {
    6958           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    6959             :                  "WEBP_LEVEL is specified, but WEBP_LOSSLESS=YES. "
    6960             :                  "WEBP_LEVEL will be ignored.");
    6961             :     }
    6962        5792 :     poDS->m_nJpegQuality = GTiffGetJpegQuality(papszParamList);
    6963        5792 :     poDS->m_nJpegTablesMode = GTiffGetJpegTablesMode(papszParamList);
    6964        5792 :     poDS->m_dfMaxZError = GTiffGetLERCMaxZError(papszParamList);
    6965        5792 :     poDS->m_dfMaxZErrorOverview = GTiffGetLERCMaxZErrorOverview(papszParamList);
    6966             : #if HAVE_JXL
    6967        5792 :     poDS->m_bJXLLossless = GTiffGetJXLLossless(papszParamList);
    6968        5792 :     poDS->m_nJXLEffort = GTiffGetJXLEffort(papszParamList);
    6969        5792 :     poDS->m_fJXLDistance = GTiffGetJXLDistance(papszParamList);
    6970        5792 :     poDS->m_fJXLAlphaDistance = GTiffGetJXLAlphaDistance(papszParamList);
    6971             : #endif
    6972        5792 :     poDS->InitCreationOrOpenOptions(true, papszParamList);
    6973             : 
    6974             :     /* -------------------------------------------------------------------- */
    6975             :     /*      Create band information objects.                                */
    6976             :     /* -------------------------------------------------------------------- */
    6977      308457 :     for (int iBand = 0; iBand < l_nBands; ++iBand)
    6978             :     {
    6979      371895 :         if (poDS->m_nBitsPerSample == 8 || poDS->m_nBitsPerSample == 16 ||
    6980      372147 :             poDS->m_nBitsPerSample == 32 || poDS->m_nBitsPerSample == 64 ||
    6981         252 :             poDS->m_nBitsPerSample == 128)
    6982             :         {
    6983      605178 :             poDS->SetBand(iBand + 1, std::make_unique<GTiffRasterBand>(
    6984      605178 :                                          poDS.get(), iBand + 1));
    6985             :         }
    6986             :         else
    6987             :         {
    6988         152 :             poDS->SetBand(iBand + 1, std::make_unique<GTiffOddBitsBand>(
    6989          76 :                                          poDS.get(), iBand + 1));
    6990         152 :             poDS->GetRasterBand(iBand + 1)->SetMetadataItem(
    6991         152 :                 "NBITS", CPLString().Printf("%d", poDS->m_nBitsPerSample),
    6992          76 :                 "IMAGE_STRUCTURE");
    6993             :         }
    6994             :     }
    6995             : 
    6996        5792 :     poDS->GetDiscardLsbOption(papszParamList);
    6997             : 
    6998        5792 :     if (poDS->m_nPlanarConfig == PLANARCONFIG_CONTIG && l_nBands != 1)
    6999         851 :         poDS->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
    7000             :     else
    7001        4941 :         poDS->SetMetadataItem("INTERLEAVE", "BAND", "IMAGE_STRUCTURE");
    7002             : 
    7003        5792 :     poDS->oOvManager.Initialize(poDS.get(), pszFilename);
    7004             : 
    7005        5792 :     return poDS.release();
    7006             : }
    7007             : 
    7008             : /************************************************************************/
    7009             : /*                         CopyImageryAndMask()                         */
    7010             : /************************************************************************/
    7011             : 
    7012         354 : CPLErr GTiffDataset::CopyImageryAndMask(GTiffDataset *poDstDS,
    7013             :                                         GDALDataset *poSrcDS,
    7014             :                                         GDALRasterBand *poSrcMaskBand,
    7015             :                                         GDALProgressFunc pfnProgress,
    7016             :                                         void *pProgressData)
    7017             : {
    7018         354 :     CPLErr eErr = CE_None;
    7019             : 
    7020         354 :     const auto eType = poDstDS->GetRasterBand(1)->GetRasterDataType();
    7021         354 :     const int nDataTypeSize = GDALGetDataTypeSizeBytes(eType);
    7022         354 :     const int l_nBands = poDstDS->GetRasterCount();
    7023             :     GByte *pBlockBuffer = static_cast<GByte *>(
    7024         354 :         VSI_MALLOC3_VERBOSE(poDstDS->m_nBlockXSize, poDstDS->m_nBlockYSize,
    7025             :                             cpl::fits_on<int>(l_nBands * nDataTypeSize)));
    7026         354 :     if (pBlockBuffer == nullptr)
    7027             :     {
    7028           0 :         eErr = CE_Failure;
    7029             :     }
    7030         354 :     const int nYSize = poDstDS->nRasterYSize;
    7031         354 :     const int nXSize = poDstDS->nRasterXSize;
    7032             :     const bool bIsOddBand =
    7033         354 :         dynamic_cast<GTiffOddBitsBand *>(poDstDS->GetRasterBand(1)) != nullptr;
    7034             : 
    7035         354 :     if (poDstDS->m_poMaskDS)
    7036             :     {
    7037          59 :         CPLAssert(poDstDS->m_poMaskDS->m_nBlockXSize == poDstDS->m_nBlockXSize);
    7038          59 :         CPLAssert(poDstDS->m_poMaskDS->m_nBlockYSize == poDstDS->m_nBlockYSize);
    7039             :     }
    7040             : 
    7041         354 :     if (poDstDS->m_nPlanarConfig == PLANARCONFIG_SEPARATE &&
    7042          58 :         !poDstDS->m_bTileInterleave)
    7043             :     {
    7044          45 :         int iBlock = 0;
    7045          45 :         const int nBlocks = poDstDS->m_nBlocksPerBand *
    7046          45 :                             (l_nBands + (poDstDS->m_poMaskDS ? 1 : 0));
    7047         195 :         for (int i = 0; eErr == CE_None && i < l_nBands; i++)
    7048             :         {
    7049         345 :             for (int iY = 0; iY < nYSize && eErr == CE_None;
    7050         195 :                  iY = ((nYSize - iY < poDstDS->m_nBlockYSize)
    7051         195 :                            ? nYSize
    7052          59 :                            : iY + poDstDS->m_nBlockYSize))
    7053             :             {
    7054             :                 const int nReqYSize =
    7055         195 :                     std::min(nYSize - iY, poDstDS->m_nBlockYSize);
    7056         495 :                 for (int iX = 0; iX < nXSize && eErr == CE_None;
    7057         300 :                      iX = ((nXSize - iX < poDstDS->m_nBlockXSize)
    7058         300 :                                ? nXSize
    7059         155 :                                : iX + poDstDS->m_nBlockXSize))
    7060             :                 {
    7061             :                     const int nReqXSize =
    7062         300 :                         std::min(nXSize - iX, poDstDS->m_nBlockXSize);
    7063         300 :                     if (nReqXSize < poDstDS->m_nBlockXSize ||
    7064         155 :                         nReqYSize < poDstDS->m_nBlockYSize)
    7065             :                     {
    7066         190 :                         memset(pBlockBuffer, 0,
    7067         190 :                                static_cast<size_t>(poDstDS->m_nBlockXSize) *
    7068         190 :                                    poDstDS->m_nBlockYSize * nDataTypeSize);
    7069             :                     }
    7070         300 :                     eErr = poSrcDS->GetRasterBand(i + 1)->RasterIO(
    7071             :                         GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
    7072             :                         nReqXSize, nReqYSize, eType, nDataTypeSize,
    7073         300 :                         static_cast<GSpacing>(nDataTypeSize) *
    7074         300 :                             poDstDS->m_nBlockXSize,
    7075             :                         nullptr);
    7076         300 :                     if (eErr == CE_None)
    7077             :                     {
    7078         300 :                         eErr = poDstDS->WriteEncodedTileOrStrip(
    7079             :                             iBlock, pBlockBuffer, false);
    7080             :                     }
    7081             : 
    7082         300 :                     iBlock++;
    7083         600 :                     if (pfnProgress &&
    7084         300 :                         !pfnProgress(static_cast<double>(iBlock) / nBlocks,
    7085             :                                      nullptr, pProgressData))
    7086             :                     {
    7087           0 :                         eErr = CE_Failure;
    7088             :                     }
    7089             : 
    7090         300 :                     if (poDstDS->m_bWriteError)
    7091           0 :                         eErr = CE_Failure;
    7092             :                 }
    7093             :             }
    7094             :         }
    7095          45 :         if (poDstDS->m_poMaskDS && eErr == CE_None)
    7096             :         {
    7097           6 :             int iBlockMask = 0;
    7098          17 :             for (int iY = 0, nYBlock = 0; iY < nYSize && eErr == CE_None;
    7099          11 :                  iY = ((nYSize - iY < poDstDS->m_nBlockYSize)
    7100          11 :                            ? nYSize
    7101           5 :                            : iY + poDstDS->m_nBlockYSize),
    7102             :                      nYBlock++)
    7103             :             {
    7104             :                 const int nReqYSize =
    7105          11 :                     std::min(nYSize - iY, poDstDS->m_nBlockYSize);
    7106          49 :                 for (int iX = 0, nXBlock = 0; iX < nXSize && eErr == CE_None;
    7107          38 :                      iX = ((nXSize - iX < poDstDS->m_nBlockXSize)
    7108          38 :                                ? nXSize
    7109          30 :                                : iX + poDstDS->m_nBlockXSize),
    7110             :                          nXBlock++)
    7111             :                 {
    7112             :                     const int nReqXSize =
    7113          38 :                         std::min(nXSize - iX, poDstDS->m_nBlockXSize);
    7114          38 :                     if (nReqXSize < poDstDS->m_nBlockXSize ||
    7115          30 :                         nReqYSize < poDstDS->m_nBlockYSize)
    7116             :                     {
    7117          16 :                         memset(pBlockBuffer, 0,
    7118          16 :                                static_cast<size_t>(poDstDS->m_nBlockXSize) *
    7119          16 :                                    poDstDS->m_nBlockYSize);
    7120             :                     }
    7121          76 :                     eErr = poSrcMaskBand->RasterIO(
    7122             :                         GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
    7123             :                         nReqXSize, nReqYSize, GDT_UInt8, 1,
    7124          38 :                         poDstDS->m_nBlockXSize, nullptr);
    7125          38 :                     if (eErr == CE_None)
    7126             :                     {
    7127             :                         // Avoid any attempt to load from disk
    7128          38 :                         poDstDS->m_poMaskDS->m_nLoadedBlock = iBlockMask;
    7129             :                         eErr =
    7130          38 :                             poDstDS->m_poMaskDS->GetRasterBand(1)->WriteBlock(
    7131             :                                 nXBlock, nYBlock, pBlockBuffer);
    7132          38 :                         if (eErr == CE_None)
    7133          38 :                             eErr = poDstDS->m_poMaskDS->FlushBlockBuf();
    7134             :                     }
    7135             : 
    7136          38 :                     iBlockMask++;
    7137          76 :                     if (pfnProgress &&
    7138          38 :                         !pfnProgress(static_cast<double>(iBlock + iBlockMask) /
    7139             :                                          nBlocks,
    7140             :                                      nullptr, pProgressData))
    7141             :                     {
    7142           0 :                         eErr = CE_Failure;
    7143             :                     }
    7144             : 
    7145          38 :                     if (poDstDS->m_poMaskDS->m_bWriteError)
    7146           0 :                         eErr = CE_Failure;
    7147             :                 }
    7148             :             }
    7149          45 :         }
    7150             :     }
    7151             :     else
    7152             :     {
    7153         309 :         int iBlock = 0;
    7154         309 :         const int nBlocks = poDstDS->m_nBlocksPerBand;
    7155        7127 :         for (int iY = 0, nYBlock = 0; iY < nYSize && eErr == CE_None;
    7156        6818 :              iY = ((nYSize - iY < poDstDS->m_nBlockYSize)
    7157        6818 :                        ? nYSize
    7158        6584 :                        : iY + poDstDS->m_nBlockYSize),
    7159             :                  nYBlock++)
    7160             :         {
    7161        6818 :             const int nReqYSize = std::min(nYSize - iY, poDstDS->m_nBlockYSize);
    7162       26645 :             for (int iX = 0, nXBlock = 0; iX < nXSize && eErr == CE_None;
    7163       19827 :                  iX = ((nXSize - iX < poDstDS->m_nBlockXSize)
    7164       19827 :                            ? nXSize
    7165       19506 :                            : iX + poDstDS->m_nBlockXSize),
    7166             :                      nXBlock++)
    7167             :             {
    7168             :                 const int nReqXSize =
    7169       19827 :                     std::min(nXSize - iX, poDstDS->m_nBlockXSize);
    7170       19827 :                 if (nReqXSize < poDstDS->m_nBlockXSize ||
    7171       19506 :                     nReqYSize < poDstDS->m_nBlockYSize)
    7172             :                 {
    7173         507 :                     memset(pBlockBuffer, 0,
    7174         507 :                            static_cast<size_t>(poDstDS->m_nBlockXSize) *
    7175         507 :                                poDstDS->m_nBlockYSize * l_nBands *
    7176         507 :                                nDataTypeSize);
    7177             :                 }
    7178             : 
    7179       19827 :                 if (poDstDS->m_bTileInterleave)
    7180             :                 {
    7181         114 :                     eErr = poSrcDS->RasterIO(
    7182             :                         GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
    7183             :                         nReqXSize, nReqYSize, eType, l_nBands, nullptr,
    7184             :                         nDataTypeSize,
    7185          57 :                         static_cast<GSpacing>(nDataTypeSize) *
    7186          57 :                             poDstDS->m_nBlockXSize,
    7187          57 :                         static_cast<GSpacing>(nDataTypeSize) *
    7188          57 :                             poDstDS->m_nBlockXSize * poDstDS->m_nBlockYSize,
    7189             :                         nullptr);
    7190          57 :                     if (eErr == CE_None)
    7191             :                     {
    7192         228 :                         for (int i = 0; eErr == CE_None && i < l_nBands; i++)
    7193             :                         {
    7194         171 :                             eErr = poDstDS->WriteEncodedTileOrStrip(
    7195         171 :                                 iBlock + i * poDstDS->m_nBlocksPerBand,
    7196         171 :                                 pBlockBuffer + static_cast<size_t>(i) *
    7197         171 :                                                    poDstDS->m_nBlockXSize *
    7198         171 :                                                    poDstDS->m_nBlockYSize *
    7199         171 :                                                    nDataTypeSize,
    7200             :                                 false);
    7201             :                         }
    7202             :                     }
    7203             :                 }
    7204       19770 :                 else if (!bIsOddBand)
    7205             :                 {
    7206       39418 :                     eErr = poSrcDS->RasterIO(
    7207             :                         GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
    7208             :                         nReqXSize, nReqYSize, eType, l_nBands, nullptr,
    7209       19709 :                         static_cast<GSpacing>(nDataTypeSize) * l_nBands,
    7210       19709 :                         static_cast<GSpacing>(nDataTypeSize) * l_nBands *
    7211       19709 :                             poDstDS->m_nBlockXSize,
    7212             :                         nDataTypeSize, nullptr);
    7213       19709 :                     if (eErr == CE_None)
    7214             :                     {
    7215       19708 :                         eErr = poDstDS->WriteEncodedTileOrStrip(
    7216             :                             iBlock, pBlockBuffer, false);
    7217             :                     }
    7218             :                 }
    7219             :                 else
    7220             :                 {
    7221             :                     // In the odd bit case, this is a bit messy to ensure
    7222             :                     // the strile gets written synchronously.
    7223             :                     // We load the content of the n-1 bands in the cache,
    7224             :                     // and for the last band we invoke WriteBlock() directly
    7225             :                     // We also force FlushBlockBuf()
    7226         122 :                     std::vector<GDALRasterBlock *> apoLockedBlocks;
    7227          91 :                     for (int i = 0; eErr == CE_None && i < l_nBands - 1; i++)
    7228             :                     {
    7229             :                         auto poBlock =
    7230          30 :                             poDstDS->GetRasterBand(i + 1)->GetLockedBlockRef(
    7231          30 :                                 nXBlock, nYBlock, TRUE);
    7232          30 :                         if (poBlock)
    7233             :                         {
    7234          60 :                             eErr = poSrcDS->GetRasterBand(i + 1)->RasterIO(
    7235             :                                 GF_Read, iX, iY, nReqXSize, nReqYSize,
    7236             :                                 poBlock->GetDataRef(), nReqXSize, nReqYSize,
    7237             :                                 eType, nDataTypeSize,
    7238          30 :                                 static_cast<GSpacing>(nDataTypeSize) *
    7239          30 :                                     poDstDS->m_nBlockXSize,
    7240             :                                 nullptr);
    7241          30 :                             poBlock->MarkDirty();
    7242          30 :                             apoLockedBlocks.emplace_back(poBlock);
    7243             :                         }
    7244             :                         else
    7245             :                         {
    7246           0 :                             eErr = CE_Failure;
    7247             :                         }
    7248             :                     }
    7249          61 :                     if (eErr == CE_None)
    7250             :                     {
    7251         122 :                         eErr = poSrcDS->GetRasterBand(l_nBands)->RasterIO(
    7252             :                             GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
    7253             :                             nReqXSize, nReqYSize, eType, nDataTypeSize,
    7254          61 :                             static_cast<GSpacing>(nDataTypeSize) *
    7255          61 :                                 poDstDS->m_nBlockXSize,
    7256             :                             nullptr);
    7257             :                     }
    7258          61 :                     if (eErr == CE_None)
    7259             :                     {
    7260             :                         // Avoid any attempt to load from disk
    7261          61 :                         poDstDS->m_nLoadedBlock = iBlock;
    7262          61 :                         eErr = poDstDS->GetRasterBand(l_nBands)->WriteBlock(
    7263             :                             nXBlock, nYBlock, pBlockBuffer);
    7264          61 :                         if (eErr == CE_None)
    7265          61 :                             eErr = poDstDS->FlushBlockBuf();
    7266             :                     }
    7267          91 :                     for (auto poBlock : apoLockedBlocks)
    7268             :                     {
    7269          30 :                         poBlock->MarkClean();
    7270          30 :                         poBlock->DropLock();
    7271             :                     }
    7272             :                 }
    7273             : 
    7274       19827 :                 if (eErr == CE_None && poDstDS->m_poMaskDS)
    7275             :                 {
    7276        4664 :                     if (nReqXSize < poDstDS->m_nBlockXSize ||
    7277        4621 :                         nReqYSize < poDstDS->m_nBlockYSize)
    7278             :                     {
    7279          81 :                         memset(pBlockBuffer, 0,
    7280          81 :                                static_cast<size_t>(poDstDS->m_nBlockXSize) *
    7281          81 :                                    poDstDS->m_nBlockYSize);
    7282             :                     }
    7283        9328 :                     eErr = poSrcMaskBand->RasterIO(
    7284             :                         GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
    7285             :                         nReqXSize, nReqYSize, GDT_UInt8, 1,
    7286        4664 :                         poDstDS->m_nBlockXSize, nullptr);
    7287        4664 :                     if (eErr == CE_None)
    7288             :                     {
    7289             :                         // Avoid any attempt to load from disk
    7290        4664 :                         poDstDS->m_poMaskDS->m_nLoadedBlock = iBlock;
    7291             :                         eErr =
    7292        4664 :                             poDstDS->m_poMaskDS->GetRasterBand(1)->WriteBlock(
    7293             :                                 nXBlock, nYBlock, pBlockBuffer);
    7294        4664 :                         if (eErr == CE_None)
    7295        4664 :                             eErr = poDstDS->m_poMaskDS->FlushBlockBuf();
    7296             :                     }
    7297             :                 }
    7298       19827 :                 if (poDstDS->m_bWriteError)
    7299           6 :                     eErr = CE_Failure;
    7300             : 
    7301       19827 :                 iBlock++;
    7302       39654 :                 if (pfnProgress &&
    7303       19827 :                     !pfnProgress(static_cast<double>(iBlock) / nBlocks, nullptr,
    7304             :                                  pProgressData))
    7305             :                 {
    7306           0 :                     eErr = CE_Failure;
    7307             :                 }
    7308             :             }
    7309             :         }
    7310             :     }
    7311             : 
    7312         354 :     poDstDS->FlushCache(false);  // mostly to wait for thread completion
    7313         354 :     VSIFree(pBlockBuffer);
    7314             : 
    7315         354 :     return eErr;
    7316             : }
    7317             : 
    7318             : /************************************************************************/
    7319             : /*                             CreateCopy()                             */
    7320             : /************************************************************************/
    7321             : 
    7322        2189 : GDALDataset *GTiffDataset::CreateCopy(const char *pszFilename,
    7323             :                                       GDALDataset *poSrcDS, int bStrict,
    7324             :                                       CSLConstList papszOptions,
    7325             :                                       GDALProgressFunc pfnProgress,
    7326             :                                       void *pProgressData)
    7327             : 
    7328             : {
    7329        2189 :     if (poSrcDS->GetRasterCount() == 0)
    7330             :     {
    7331           2 :         ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
    7332             :                     "Unable to export GeoTIFF files with zero bands.");
    7333           2 :         return nullptr;
    7334             :     }
    7335             : 
    7336        2187 :     GDALRasterBand *const poPBand = poSrcDS->GetRasterBand(1);
    7337        2187 :     GDALDataType eType = poPBand->GetRasterDataType();
    7338             : 
    7339             :     /* -------------------------------------------------------------------- */
    7340             :     /*      Check, whether all bands in input dataset has the same type.    */
    7341             :     /* -------------------------------------------------------------------- */
    7342        2187 :     const int l_nBands = poSrcDS->GetRasterCount();
    7343        5120 :     for (int iBand = 2; iBand <= l_nBands; ++iBand)
    7344             :     {
    7345        2933 :         if (eType != poSrcDS->GetRasterBand(iBand)->GetRasterDataType())
    7346             :         {
    7347           0 :             if (bStrict)
    7348             :             {
    7349           0 :                 ReportError(
    7350             :                     pszFilename, CE_Failure, CPLE_AppDefined,
    7351             :                     "Unable to export GeoTIFF file with different datatypes "
    7352             :                     "per different bands. All bands should have the same "
    7353             :                     "types in TIFF.");
    7354           0 :                 return nullptr;
    7355             :             }
    7356             :             else
    7357             :             {
    7358           0 :                 ReportError(
    7359             :                     pszFilename, CE_Warning, CPLE_AppDefined,
    7360             :                     "Unable to export GeoTIFF file with different datatypes "
    7361             :                     "per different bands. All bands should have the same "
    7362             :                     "types in TIFF.");
    7363             :             }
    7364             :         }
    7365             :     }
    7366             : 
    7367             :     /* -------------------------------------------------------------------- */
    7368             :     /*      Capture the profile.                                            */
    7369             :     /* -------------------------------------------------------------------- */
    7370             :     const GTiffProfile eProfile =
    7371        2187 :         GetProfile(CSLFetchNameValue(papszOptions, "PROFILE"));
    7372             : 
    7373        2187 :     const bool bGeoTIFF = eProfile != GTiffProfile::BASELINE;
    7374             : 
    7375             :     /* -------------------------------------------------------------------- */
    7376             :     /*      Special handling for NBITS.  Copy from band metadata if found.  */
    7377             :     /* -------------------------------------------------------------------- */
    7378        2187 :     char **papszCreateOptions = CSLDuplicate(papszOptions);
    7379             : 
    7380        2187 :     if (poPBand->GetMetadataItem("NBITS", "IMAGE_STRUCTURE") != nullptr &&
    7381        2204 :         atoi(poPBand->GetMetadataItem("NBITS", "IMAGE_STRUCTURE")) > 0 &&
    7382          17 :         CSLFetchNameValue(papszCreateOptions, "NBITS") == nullptr)
    7383             :     {
    7384           3 :         papszCreateOptions = CSLSetNameValue(
    7385             :             papszCreateOptions, "NBITS",
    7386           3 :             poPBand->GetMetadataItem("NBITS", "IMAGE_STRUCTURE"));
    7387             :     }
    7388             : 
    7389        2187 :     if (CSLFetchNameValue(papszOptions, "PIXELTYPE") == nullptr &&
    7390             :         eType == GDT_UInt8)
    7391             :     {
    7392        1812 :         poPBand->EnablePixelTypeSignedByteWarning(false);
    7393             :         const char *pszPixelType =
    7394        1812 :             poPBand->GetMetadataItem("PIXELTYPE", "IMAGE_STRUCTURE");
    7395        1812 :         poPBand->EnablePixelTypeSignedByteWarning(true);
    7396        1812 :         if (pszPixelType)
    7397             :         {
    7398           1 :             papszCreateOptions =
    7399           1 :                 CSLSetNameValue(papszCreateOptions, "PIXELTYPE", pszPixelType);
    7400             :         }
    7401             :     }
    7402             : 
    7403             :     /* -------------------------------------------------------------------- */
    7404             :     /*      Color profile.  Copy from band metadata if found.              */
    7405             :     /* -------------------------------------------------------------------- */
    7406        2187 :     if (bGeoTIFF)
    7407             :     {
    7408        2170 :         const char *pszOptionsMD[] = {"SOURCE_ICC_PROFILE",
    7409             :                                       "SOURCE_PRIMARIES_RED",
    7410             :                                       "SOURCE_PRIMARIES_GREEN",
    7411             :                                       "SOURCE_PRIMARIES_BLUE",
    7412             :                                       "SOURCE_WHITEPOINT",
    7413             :                                       "TIFFTAG_TRANSFERFUNCTION_RED",
    7414             :                                       "TIFFTAG_TRANSFERFUNCTION_GREEN",
    7415             :                                       "TIFFTAG_TRANSFERFUNCTION_BLUE",
    7416             :                                       "TIFFTAG_TRANSFERRANGE_BLACK",
    7417             :                                       "TIFFTAG_TRANSFERRANGE_WHITE",
    7418             :                                       nullptr};
    7419             : 
    7420             :         // Copy all the tags.  Options will override tags in the source.
    7421        2170 :         int i = 0;
    7422       23850 :         while (pszOptionsMD[i] != nullptr)
    7423             :         {
    7424             :             char const *pszMD =
    7425       21682 :                 CSLFetchNameValue(papszOptions, pszOptionsMD[i]);
    7426       21682 :             if (pszMD == nullptr)
    7427             :                 pszMD =
    7428       21674 :                     poSrcDS->GetMetadataItem(pszOptionsMD[i], "COLOR_PROFILE");
    7429             : 
    7430       21682 :             if ((pszMD != nullptr) && !EQUAL(pszMD, ""))
    7431             :             {
    7432          16 :                 papszCreateOptions =
    7433          16 :                     CSLSetNameValue(papszCreateOptions, pszOptionsMD[i], pszMD);
    7434             : 
    7435             :                 // If an ICC profile exists, other tags are not needed.
    7436          16 :                 if (EQUAL(pszOptionsMD[i], "SOURCE_ICC_PROFILE"))
    7437           2 :                     break;
    7438             :             }
    7439             : 
    7440       21680 :             ++i;
    7441             :         }
    7442             :     }
    7443             : 
    7444        2187 :     double dfExtraSpaceForOverviews = 0;
    7445             :     const bool bCopySrcOverviews =
    7446        2187 :         CPLFetchBool(papszCreateOptions, "COPY_SRC_OVERVIEWS", false);
    7447        2187 :     std::unique_ptr<GDALDataset> poOvrDS;
    7448        2187 :     int nSrcOverviews = 0;
    7449        2187 :     if (bCopySrcOverviews)
    7450             :     {
    7451             :         const char *pszOvrDS =
    7452         233 :             CSLFetchNameValue(papszCreateOptions, "@OVERVIEW_DATASET");
    7453         233 :         if (pszOvrDS)
    7454             :         {
    7455             :             // Empty string is used by COG driver to indicate that we want
    7456             :             // to ignore source overviews.
    7457          39 :             if (!EQUAL(pszOvrDS, ""))
    7458             :             {
    7459          37 :                 poOvrDS.reset(GDALDataset::Open(pszOvrDS));
    7460          37 :                 if (!poOvrDS)
    7461             :                 {
    7462           0 :                     CSLDestroy(papszCreateOptions);
    7463           0 :                     return nullptr;
    7464             :                 }
    7465          37 :                 if (poOvrDS->GetRasterCount() != l_nBands)
    7466             :                 {
    7467           0 :                     CSLDestroy(papszCreateOptions);
    7468           0 :                     return nullptr;
    7469             :                 }
    7470          37 :                 nSrcOverviews =
    7471          37 :                     poOvrDS->GetRasterBand(1)->GetOverviewCount() + 1;
    7472             :             }
    7473             :         }
    7474             :         else
    7475             :         {
    7476         194 :             nSrcOverviews = poSrcDS->GetRasterBand(1)->GetOverviewCount();
    7477             :         }
    7478             : 
    7479             :         // Limit number of overviews if specified
    7480             :         const char *pszOverviewCount =
    7481         233 :             CSLFetchNameValue(papszCreateOptions, "@OVERVIEW_COUNT");
    7482         233 :         if (pszOverviewCount)
    7483           8 :             nSrcOverviews =
    7484           8 :                 std::max(0, std::min(nSrcOverviews, atoi(pszOverviewCount)));
    7485             : 
    7486         233 :         if (nSrcOverviews)
    7487             :         {
    7488         208 :             for (int j = 1; j <= l_nBands; ++j)
    7489             :             {
    7490             :                 const int nOtherBandOverviewCount =
    7491         136 :                     poOvrDS ? poOvrDS->GetRasterBand(j)->GetOverviewCount() + 1
    7492         200 :                             : poSrcDS->GetRasterBand(j)->GetOverviewCount();
    7493         136 :                 if (nOtherBandOverviewCount < nSrcOverviews)
    7494             :                 {
    7495           1 :                     ReportError(
    7496             :                         pszFilename, CE_Failure, CPLE_NotSupported,
    7497             :                         "COPY_SRC_OVERVIEWS cannot be used when the bands have "
    7498             :                         "not the same number of overview levels.");
    7499           1 :                     CSLDestroy(papszCreateOptions);
    7500           1 :                     return nullptr;
    7501             :                 }
    7502         395 :                 for (int i = 0; i < nSrcOverviews; ++i)
    7503             :                 {
    7504             :                     GDALRasterBand *poOvrBand =
    7505             :                         poOvrDS
    7506         361 :                             ? (i == 0 ? poOvrDS->GetRasterBand(j)
    7507         198 :                                       : poOvrDS->GetRasterBand(j)->GetOverview(
    7508          99 :                                             i - 1))
    7509         353 :                             : poSrcDS->GetRasterBand(j)->GetOverview(i);
    7510         262 :                     if (poOvrBand == nullptr)
    7511             :                     {
    7512           1 :                         ReportError(
    7513             :                             pszFilename, CE_Failure, CPLE_NotSupported,
    7514             :                             "COPY_SRC_OVERVIEWS cannot be used when one "
    7515             :                             "overview band is NULL.");
    7516           1 :                         CSLDestroy(papszCreateOptions);
    7517           1 :                         return nullptr;
    7518             :                     }
    7519             :                     GDALRasterBand *poOvrFirstBand =
    7520             :                         poOvrDS
    7521         360 :                             ? (i == 0 ? poOvrDS->GetRasterBand(1)
    7522         198 :                                       : poOvrDS->GetRasterBand(1)->GetOverview(
    7523          99 :                                             i - 1))
    7524         351 :                             : poSrcDS->GetRasterBand(1)->GetOverview(i);
    7525         521 :                     if (poOvrBand->GetXSize() != poOvrFirstBand->GetXSize() ||
    7526         260 :                         poOvrBand->GetYSize() != poOvrFirstBand->GetYSize())
    7527             :                     {
    7528           1 :                         ReportError(
    7529             :                             pszFilename, CE_Failure, CPLE_NotSupported,
    7530             :                             "COPY_SRC_OVERVIEWS cannot be used when the "
    7531             :                             "overview bands have not the same dimensions "
    7532             :                             "among bands.");
    7533           1 :                         CSLDestroy(papszCreateOptions);
    7534           1 :                         return nullptr;
    7535             :                     }
    7536             :                 }
    7537             :             }
    7538             : 
    7539         205 :             for (int i = 0; i < nSrcOverviews; ++i)
    7540             :             {
    7541             :                 GDALRasterBand *poOvrFirstBand =
    7542             :                     poOvrDS
    7543         211 :                         ? (i == 0
    7544          78 :                                ? poOvrDS->GetRasterBand(1)
    7545          41 :                                : poOvrDS->GetRasterBand(1)->GetOverview(i - 1))
    7546         188 :                         : poSrcDS->GetRasterBand(1)->GetOverview(i);
    7547         133 :                 dfExtraSpaceForOverviews +=
    7548         133 :                     static_cast<double>(poOvrFirstBand->GetXSize()) *
    7549         133 :                     poOvrFirstBand->GetYSize();
    7550             :             }
    7551          72 :             dfExtraSpaceForOverviews *=
    7552          72 :                 l_nBands * GDALGetDataTypeSizeBytes(eType);
    7553             :         }
    7554             :         else
    7555             :         {
    7556         158 :             CPLDebug("GTiff", "No source overviews to copy");
    7557             :         }
    7558             :     }
    7559             : 
    7560             : /* -------------------------------------------------------------------- */
    7561             : /*      Should we use optimized way of copying from an input JPEG       */
    7562             : /*      dataset?                                                        */
    7563             : /* -------------------------------------------------------------------- */
    7564             : 
    7565             : // TODO(schwehr): Refactor bDirectCopyFromJPEG to be a const.
    7566             : #if defined(HAVE_LIBJPEG) || defined(JPEG_DIRECT_COPY)
    7567        2184 :     bool bDirectCopyFromJPEG = false;
    7568             : #endif
    7569             : 
    7570             :     // Note: JPEG_DIRECT_COPY is not defined by default, because it is mainly
    7571             :     // useful for debugging purposes.
    7572             : #ifdef JPEG_DIRECT_COPY
    7573             :     if (CPLFetchBool(papszCreateOptions, "JPEG_DIRECT_COPY", false) &&
    7574             :         GTIFF_CanDirectCopyFromJPEG(poSrcDS, papszCreateOptions))
    7575             :     {
    7576             :         CPLDebug("GTiff", "Using special direct copy mode from a JPEG dataset");
    7577             : 
    7578             :         bDirectCopyFromJPEG = true;
    7579             :     }
    7580             : #endif
    7581             : 
    7582             : #ifdef HAVE_LIBJPEG
    7583        2184 :     bool bCopyFromJPEG = false;
    7584             : 
    7585             :     // When CreateCopy'ing() from a JPEG dataset, and asking for COMPRESS=JPEG,
    7586             :     // use DCT coefficients (unless other options are incompatible, like
    7587             :     // strip/tile dimensions, specifying JPEG_QUALITY option, incompatible
    7588             :     // PHOTOMETRIC with the source colorspace, etc.) to avoid the lossy steps
    7589             :     // involved by decompression/recompression.
    7590        4368 :     if (!bDirectCopyFromJPEG &&
    7591        2184 :         GTIFF_CanCopyFromJPEG(poSrcDS, papszCreateOptions))
    7592             :     {
    7593          12 :         CPLDebug("GTiff", "Using special copy mode from a JPEG dataset");
    7594             : 
    7595          12 :         bCopyFromJPEG = true;
    7596             :     }
    7597             : #endif
    7598             : 
    7599             :     /* -------------------------------------------------------------------- */
    7600             :     /*      If the source is RGB, then set the PHOTOMETRIC=RGB value        */
    7601             :     /* -------------------------------------------------------------------- */
    7602             : 
    7603             :     const bool bForcePhotometric =
    7604        2184 :         CSLFetchNameValue(papszOptions, "PHOTOMETRIC") != nullptr;
    7605             : 
    7606        1231 :     if (l_nBands >= 3 && !bForcePhotometric &&
    7607             : #ifdef HAVE_LIBJPEG
    7608        1193 :         !bCopyFromJPEG &&
    7609             : #endif
    7610        1187 :         poSrcDS->GetRasterBand(1)->GetColorInterpretation() == GCI_RedBand &&
    7611        4490 :         poSrcDS->GetRasterBand(2)->GetColorInterpretation() == GCI_GreenBand &&
    7612        1075 :         poSrcDS->GetRasterBand(3)->GetColorInterpretation() == GCI_BlueBand)
    7613             :     {
    7614        1069 :         papszCreateOptions =
    7615        1069 :             CSLSetNameValue(papszCreateOptions, "PHOTOMETRIC", "RGB");
    7616             :     }
    7617             : 
    7618             :     /* -------------------------------------------------------------------- */
    7619             :     /*      Create the file.                                                */
    7620             :     /* -------------------------------------------------------------------- */
    7621        2184 :     VSILFILE *l_fpL = nullptr;
    7622        4368 :     CPLString l_osTmpFilename;
    7623             : 
    7624        2184 :     const int nXSize = poSrcDS->GetRasterXSize();
    7625        2184 :     const int nYSize = poSrcDS->GetRasterYSize();
    7626             : 
    7627             :     const int nColorTableMultiplier = std::max(
    7628        4368 :         1,
    7629        4368 :         std::min(257,
    7630        2184 :                  atoi(CSLFetchNameValueDef(
    7631             :                      papszOptions, "COLOR_TABLE_MULTIPLIER",
    7632        2184 :                      CPLSPrintf("%d", DEFAULT_COLOR_TABLE_MULTIPLIER_257)))));
    7633             : 
    7634        2184 :     bool bTileInterleaving = false;
    7635        2184 :     TIFF *l_hTIFF = CreateLL(pszFilename, nXSize, nYSize, l_nBands, eType,
    7636             :                              dfExtraSpaceForOverviews, nColorTableMultiplier,
    7637             :                              papszCreateOptions, &l_fpL, l_osTmpFilename,
    7638             :                              /* bCreateCopy = */ true, bTileInterleaving);
    7639        2184 :     const bool bStreaming = !l_osTmpFilename.empty();
    7640             : 
    7641        2184 :     CSLDestroy(papszCreateOptions);
    7642        2184 :     papszCreateOptions = nullptr;
    7643             : 
    7644        2184 :     if (l_hTIFF == nullptr)
    7645             :     {
    7646          18 :         if (bStreaming)
    7647           0 :             VSIUnlink(l_osTmpFilename);
    7648          18 :         return nullptr;
    7649             :     }
    7650             : 
    7651        2166 :     uint16_t l_nPlanarConfig = 0;
    7652        2166 :     TIFFGetField(l_hTIFF, TIFFTAG_PLANARCONFIG, &l_nPlanarConfig);
    7653             : 
    7654        2166 :     uint16_t l_nCompression = 0;
    7655             : 
    7656        2166 :     if (!TIFFGetField(l_hTIFF, TIFFTAG_COMPRESSION, &(l_nCompression)))
    7657           0 :         l_nCompression = COMPRESSION_NONE;
    7658             : 
    7659             :     /* -------------------------------------------------------------------- */
    7660             :     /*      Set the alpha channel if we find one.                           */
    7661             :     /* -------------------------------------------------------------------- */
    7662        2166 :     uint16_t *extraSamples = nullptr;
    7663        2166 :     uint16_t nExtraSamples = 0;
    7664        2166 :     if (TIFFGetField(l_hTIFF, TIFFTAG_EXTRASAMPLES, &nExtraSamples,
    7665        2431 :                      &extraSamples) &&
    7666         265 :         nExtraSamples > 0)
    7667             :     {
    7668             :         // We need to allocate a new array as (current) libtiff
    7669             :         // versions will not like that we reuse the array we got from
    7670             :         // TIFFGetField().
    7671             :         uint16_t *pasNewExtraSamples = static_cast<uint16_t *>(
    7672         265 :             CPLMalloc(nExtraSamples * sizeof(uint16_t)));
    7673         265 :         memcpy(pasNewExtraSamples, extraSamples,
    7674         265 :                nExtraSamples * sizeof(uint16_t));
    7675         265 :         const char *pszAlpha = CPLGetConfigOption(
    7676             :             "GTIFF_ALPHA", CSLFetchNameValue(papszOptions, "ALPHA"));
    7677             :         const uint16_t nAlpha =
    7678         265 :             GTiffGetAlphaValue(pszAlpha, DEFAULT_ALPHA_TYPE);
    7679         265 :         const int nBaseSamples = l_nBands - nExtraSamples;
    7680         895 :         for (int iExtraBand = nBaseSamples + 1; iExtraBand <= l_nBands;
    7681             :              iExtraBand++)
    7682             :         {
    7683         630 :             if (poSrcDS->GetRasterBand(iExtraBand)->GetColorInterpretation() ==
    7684             :                 GCI_AlphaBand)
    7685             :             {
    7686         145 :                 pasNewExtraSamples[iExtraBand - nBaseSamples - 1] = nAlpha;
    7687         145 :                 if (!pszAlpha)
    7688             :                 {
    7689             :                     // Use the ALPHA metadata item from the source band, when
    7690             :                     // present, if no explicit ALPHA creation option
    7691         286 :                     pasNewExtraSamples[iExtraBand - nBaseSamples - 1] =
    7692         143 :                         GTiffGetAlphaValue(
    7693         143 :                             poSrcDS->GetRasterBand(iExtraBand)
    7694         143 :                                 ->GetMetadataItem("ALPHA", "IMAGE_STRUCTURE"),
    7695             :                             nAlpha);
    7696             :                 }
    7697             :             }
    7698             :         }
    7699         265 :         TIFFSetField(l_hTIFF, TIFFTAG_EXTRASAMPLES, nExtraSamples,
    7700             :                      pasNewExtraSamples);
    7701             : 
    7702         265 :         CPLFree(pasNewExtraSamples);
    7703             :     }
    7704             : 
    7705             :     /* -------------------------------------------------------------------- */
    7706             :     /*      If the output is jpeg compressed, and the input is RGB make     */
    7707             :     /*      sure we note that.                                              */
    7708             :     /* -------------------------------------------------------------------- */
    7709             : 
    7710        2166 :     if (l_nCompression == COMPRESSION_JPEG)
    7711             :     {
    7712         134 :         if (l_nBands >= 3 &&
    7713          58 :             (poSrcDS->GetRasterBand(1)->GetColorInterpretation() ==
    7714           0 :              GCI_YCbCr_YBand) &&
    7715           0 :             (poSrcDS->GetRasterBand(2)->GetColorInterpretation() ==
    7716         134 :              GCI_YCbCr_CbBand) &&
    7717           0 :             (poSrcDS->GetRasterBand(3)->GetColorInterpretation() ==
    7718             :              GCI_YCbCr_CrBand))
    7719             :         {
    7720             :             // Do nothing.
    7721             :         }
    7722             :         else
    7723             :         {
    7724             :             // Assume RGB if it is not explicitly YCbCr.
    7725          76 :             CPLDebug("GTiff", "Setting JPEGCOLORMODE_RGB");
    7726          76 :             TIFFSetField(l_hTIFF, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
    7727             :         }
    7728             :     }
    7729             : 
    7730             :     /* -------------------------------------------------------------------- */
    7731             :     /*      Does the source image consist of one band, with a palette?      */
    7732             :     /*      If so, copy over.                                               */
    7733             :     /* -------------------------------------------------------------------- */
    7734        1317 :     if ((l_nBands == 1 || l_nBands == 2) &&
    7735        3483 :         poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
    7736             :         eType == GDT_UInt8)
    7737             :     {
    7738          21 :         unsigned short anTRed[256] = {0};
    7739          21 :         unsigned short anTGreen[256] = {0};
    7740          21 :         unsigned short anTBlue[256] = {0};
    7741          21 :         GDALColorTable *poCT = poSrcDS->GetRasterBand(1)->GetColorTable();
    7742             : 
    7743        5397 :         for (int iColor = 0; iColor < 256; ++iColor)
    7744             :         {
    7745        5376 :             if (iColor < poCT->GetColorEntryCount())
    7746             :             {
    7747        4241 :                 GDALColorEntry sRGB = {0, 0, 0, 0};
    7748             : 
    7749        4241 :                 poCT->GetColorEntryAsRGB(iColor, &sRGB);
    7750             : 
    7751        8482 :                 anTRed[iColor] = GTiffDataset::ClampCTEntry(
    7752        4241 :                     iColor, 1, sRGB.c1, nColorTableMultiplier);
    7753        8482 :                 anTGreen[iColor] = GTiffDataset::ClampCTEntry(
    7754        4241 :                     iColor, 2, sRGB.c2, nColorTableMultiplier);
    7755        4241 :                 anTBlue[iColor] = GTiffDataset::ClampCTEntry(
    7756        4241 :                     iColor, 3, sRGB.c3, nColorTableMultiplier);
    7757             :             }
    7758             :             else
    7759             :             {
    7760        1135 :                 anTRed[iColor] = 0;
    7761        1135 :                 anTGreen[iColor] = 0;
    7762        1135 :                 anTBlue[iColor] = 0;
    7763             :             }
    7764             :         }
    7765             : 
    7766          21 :         if (!bForcePhotometric)
    7767          21 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
    7768          21 :         TIFFSetField(l_hTIFF, TIFFTAG_COLORMAP, anTRed, anTGreen, anTBlue);
    7769             :     }
    7770        1316 :     else if ((l_nBands == 1 || l_nBands == 2) &&
    7771        3461 :              poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
    7772             :              eType == GDT_UInt16)
    7773             :     {
    7774             :         unsigned short *panTRed = static_cast<unsigned short *>(
    7775           1 :             CPLMalloc(65536 * sizeof(unsigned short)));
    7776             :         unsigned short *panTGreen = static_cast<unsigned short *>(
    7777           1 :             CPLMalloc(65536 * sizeof(unsigned short)));
    7778             :         unsigned short *panTBlue = static_cast<unsigned short *>(
    7779           1 :             CPLMalloc(65536 * sizeof(unsigned short)));
    7780             : 
    7781           1 :         GDALColorTable *poCT = poSrcDS->GetRasterBand(1)->GetColorTable();
    7782             : 
    7783       65537 :         for (int iColor = 0; iColor < 65536; ++iColor)
    7784             :         {
    7785       65536 :             if (iColor < poCT->GetColorEntryCount())
    7786             :             {
    7787       65536 :                 GDALColorEntry sRGB = {0, 0, 0, 0};
    7788             : 
    7789       65536 :                 poCT->GetColorEntryAsRGB(iColor, &sRGB);
    7790             : 
    7791      131072 :                 panTRed[iColor] = GTiffDataset::ClampCTEntry(
    7792       65536 :                     iColor, 1, sRGB.c1, nColorTableMultiplier);
    7793      131072 :                 panTGreen[iColor] = GTiffDataset::ClampCTEntry(
    7794       65536 :                     iColor, 2, sRGB.c2, nColorTableMultiplier);
    7795       65536 :                 panTBlue[iColor] = GTiffDataset::ClampCTEntry(
    7796       65536 :                     iColor, 3, sRGB.c3, nColorTableMultiplier);
    7797             :             }
    7798             :             else
    7799             :             {
    7800           0 :                 panTRed[iColor] = 0;
    7801           0 :                 panTGreen[iColor] = 0;
    7802           0 :                 panTBlue[iColor] = 0;
    7803             :             }
    7804             :         }
    7805             : 
    7806           1 :         if (!bForcePhotometric)
    7807           1 :             TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
    7808           1 :         TIFFSetField(l_hTIFF, TIFFTAG_COLORMAP, panTRed, panTGreen, panTBlue);
    7809             : 
    7810           1 :         CPLFree(panTRed);
    7811           1 :         CPLFree(panTGreen);
    7812           1 :         CPLFree(panTBlue);
    7813             :     }
    7814        2144 :     else if (poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr)
    7815           1 :         ReportError(
    7816             :             pszFilename, CE_Failure, CPLE_AppDefined,
    7817             :             "Unable to export color table to GeoTIFF file.  Color tables "
    7818             :             "can only be written to 1 band or 2 bands Byte or "
    7819             :             "UInt16 GeoTIFF files.");
    7820             : 
    7821        2166 :     if (l_nCompression == COMPRESSION_JPEG)
    7822             :     {
    7823          76 :         uint16_t l_nPhotometric = 0;
    7824          76 :         TIFFGetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, &l_nPhotometric);
    7825             :         // Check done in tif_jpeg.c later, but not with a very clear error
    7826             :         // message
    7827          76 :         if (l_nPhotometric == PHOTOMETRIC_PALETTE)
    7828             :         {
    7829           1 :             ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
    7830             :                         "JPEG compression not supported with paletted image");
    7831           1 :             XTIFFClose(l_hTIFF);
    7832           1 :             VSIUnlink(l_osTmpFilename);
    7833           1 :             CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    7834           1 :             return nullptr;
    7835             :         }
    7836             :     }
    7837             : 
    7838        2252 :     if (l_nBands == 2 &&
    7839        2165 :         poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
    7840           0 :         (eType == GDT_UInt8 || eType == GDT_UInt16))
    7841             :     {
    7842           1 :         uint16_t v[1] = {EXTRASAMPLE_UNASSALPHA};
    7843             : 
    7844           1 :         TIFFSetField(l_hTIFF, TIFFTAG_EXTRASAMPLES, 1, v);
    7845             :     }
    7846             : 
    7847        2165 :     const int nMaskFlags = poSrcDS->GetRasterBand(1)->GetMaskFlags();
    7848        2165 :     bool bCreateMask = false;
    7849        4330 :     CPLString osHiddenStructuralMD;
    7850             :     const char *pszInterleave =
    7851        2165 :         CSLFetchNameValueDef(papszOptions, "INTERLEAVE", "PIXEL");
    7852        2392 :     if (bCopySrcOverviews &&
    7853         227 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "TILED", "NO")))
    7854             :     {
    7855         215 :         osHiddenStructuralMD += "LAYOUT=IFDS_BEFORE_DATA\n";
    7856         215 :         osHiddenStructuralMD += "BLOCK_ORDER=ROW_MAJOR\n";
    7857         215 :         osHiddenStructuralMD += "BLOCK_LEADER=SIZE_AS_UINT4\n";
    7858         215 :         osHiddenStructuralMD += "BLOCK_TRAILER=LAST_4_BYTES_REPEATED\n";
    7859         215 :         if (l_nBands > 1 && !EQUAL(pszInterleave, "PIXEL"))
    7860             :         {
    7861          21 :             osHiddenStructuralMD += "INTERLEAVE=";
    7862          21 :             osHiddenStructuralMD += CPLString(pszInterleave).toupper();
    7863          21 :             osHiddenStructuralMD += "\n";
    7864             :         }
    7865             :         osHiddenStructuralMD +=
    7866         215 :             "KNOWN_INCOMPATIBLE_EDITION=NO\n ";  // Final space intended, so
    7867             :                                                  // this can be replaced by YES
    7868             :     }
    7869        2165 :     if (!(nMaskFlags & (GMF_ALL_VALID | GMF_ALPHA | GMF_NODATA)) &&
    7870          42 :         (nMaskFlags & GMF_PER_DATASET) && !bStreaming)
    7871             :     {
    7872          38 :         bCreateMask = true;
    7873          38 :         if (GTiffDataset::MustCreateInternalMask() &&
    7874          38 :             !osHiddenStructuralMD.empty() && EQUAL(pszInterleave, "PIXEL"))
    7875             :         {
    7876          21 :             osHiddenStructuralMD += "MASK_INTERLEAVED_WITH_IMAGERY=YES\n";
    7877             :         }
    7878             :     }
    7879        2380 :     if (!osHiddenStructuralMD.empty() &&
    7880         215 :         CPLTestBool(CPLGetConfigOption("GTIFF_WRITE_COG_GHOST_AREA", "YES")))
    7881             :     {
    7882         214 :         const int nHiddenMDSize = static_cast<int>(osHiddenStructuralMD.size());
    7883             :         osHiddenStructuralMD =
    7884         214 :             CPLOPrintf("GDAL_STRUCTURAL_METADATA_SIZE=%06d bytes\n",
    7885         428 :                        nHiddenMDSize) +
    7886         214 :             osHiddenStructuralMD;
    7887         214 :         VSI_TIFFWrite(l_hTIFF, osHiddenStructuralMD.c_str(),
    7888             :                       osHiddenStructuralMD.size());
    7889             :     }
    7890             : 
    7891             :     // FIXME? libtiff writes extended tags in the order they are specified
    7892             :     // and not in increasing order.
    7893             : 
    7894             :     /* -------------------------------------------------------------------- */
    7895             :     /*      Transfer some TIFF specific metadata, if available.             */
    7896             :     /*      The return value will tell us if we need to try again later with*/
    7897             :     /*      PAM because the profile doesn't allow to write some metadata    */
    7898             :     /*      as TIFF tag                                                     */
    7899             :     /* -------------------------------------------------------------------- */
    7900        2165 :     const bool bHasWrittenMDInGeotiffTAG = GTiffDataset::WriteMetadata(
    7901             :         poSrcDS, l_hTIFF, false, eProfile, pszFilename, papszOptions);
    7902             : 
    7903             :     /* -------------------------------------------------------------------- */
    7904             :     /*      Write NoData value, if exist.                                   */
    7905             :     /* -------------------------------------------------------------------- */
    7906        2165 :     if (eProfile == GTiffProfile::GDALGEOTIFF)
    7907             :     {
    7908        2144 :         int bSuccess = FALSE;
    7909        2144 :         GDALRasterBand *poFirstBand = poSrcDS->GetRasterBand(1);
    7910        2144 :         if (poFirstBand->GetRasterDataType() == GDT_Int64)
    7911             :         {
    7912           4 :             const auto nNoData = poFirstBand->GetNoDataValueAsInt64(&bSuccess);
    7913           4 :             if (bSuccess)
    7914           1 :                 GTiffDataset::WriteNoDataValue(l_hTIFF, nNoData);
    7915             :         }
    7916        2140 :         else if (poFirstBand->GetRasterDataType() == GDT_UInt64)
    7917             :         {
    7918           4 :             const auto nNoData = poFirstBand->GetNoDataValueAsUInt64(&bSuccess);
    7919           4 :             if (bSuccess)
    7920           1 :                 GTiffDataset::WriteNoDataValue(l_hTIFF, nNoData);
    7921             :         }
    7922             :         else
    7923             :         {
    7924        2136 :             const auto dfNoData = poFirstBand->GetNoDataValue(&bSuccess);
    7925        2136 :             if (bSuccess)
    7926         150 :                 GTiffDataset::WriteNoDataValue(l_hTIFF, dfNoData);
    7927             :         }
    7928             :     }
    7929             : 
    7930             :     /* -------------------------------------------------------------------- */
    7931             :     /*      Are we addressing PixelIsPoint mode?                            */
    7932             :     /* -------------------------------------------------------------------- */
    7933        2165 :     bool bPixelIsPoint = false;
    7934        2165 :     bool bPointGeoIgnore = false;
    7935             : 
    7936        3642 :     if (poSrcDS->GetMetadataItem(GDALMD_AREA_OR_POINT) &&
    7937        1477 :         EQUAL(poSrcDS->GetMetadataItem(GDALMD_AREA_OR_POINT), GDALMD_AOP_POINT))
    7938             :     {
    7939          10 :         bPixelIsPoint = true;
    7940             :         bPointGeoIgnore =
    7941          10 :             CPLTestBool(CPLGetConfigOption("GTIFF_POINT_GEO_IGNORE", "FALSE"));
    7942             :     }
    7943             : 
    7944             :     /* -------------------------------------------------------------------- */
    7945             :     /*      Write affine transform if it is meaningful.                     */
    7946             :     /* -------------------------------------------------------------------- */
    7947        2165 :     const OGRSpatialReference *l_poSRS = nullptr;
    7948        2165 :     GDALGeoTransform l_gt;
    7949        2165 :     if (poSrcDS->GetGeoTransform(l_gt) == CE_None)
    7950             :     {
    7951        1726 :         if (bGeoTIFF)
    7952             :         {
    7953        1721 :             l_poSRS = poSrcDS->GetSpatialRef();
    7954             : 
    7955        1721 :             if (l_gt.xrot == 0.0 && l_gt.yrot == 0.0 && l_gt.yscale < 0.0)
    7956             :             {
    7957        1713 :                 double dfOffset = 0.0;
    7958             :                 {
    7959             :                     // In the case the SRS has a vertical component and we have
    7960             :                     // a single band, encode its scale/offset in the GeoTIFF
    7961             :                     // tags
    7962        1713 :                     int bHasScale = FALSE;
    7963             :                     double dfScale =
    7964        1713 :                         poSrcDS->GetRasterBand(1)->GetScale(&bHasScale);
    7965        1713 :                     int bHasOffset = FALSE;
    7966             :                     dfOffset =
    7967        1713 :                         poSrcDS->GetRasterBand(1)->GetOffset(&bHasOffset);
    7968             :                     const bool bApplyScaleOffset =
    7969        1717 :                         l_poSRS && l_poSRS->IsVertical() &&
    7970           4 :                         poSrcDS->GetRasterCount() == 1;
    7971        1713 :                     if (bApplyScaleOffset && !bHasScale)
    7972           0 :                         dfScale = 1.0;
    7973        1713 :                     if (!bApplyScaleOffset || !bHasOffset)
    7974        1709 :                         dfOffset = 0.0;
    7975             :                     const double adfPixelScale[3] = {
    7976        1713 :                         l_gt.xscale, fabs(l_gt.yscale),
    7977        1713 :                         bApplyScaleOffset ? dfScale : 0.0};
    7978             : 
    7979        1713 :                     TIFFSetField(l_hTIFF, TIFFTAG_GEOPIXELSCALE, 3,
    7980             :                                  adfPixelScale);
    7981             :                 }
    7982             : 
    7983        1713 :                 double adfTiePoints[6] = {0.0,        0.0,        0.0,
    7984        1713 :                                           l_gt.xorig, l_gt.yorig, dfOffset};
    7985             : 
    7986        1713 :                 if (bPixelIsPoint && !bPointGeoIgnore)
    7987             :                 {
    7988           6 :                     adfTiePoints[3] += l_gt.xscale * 0.5 + l_gt.xrot * 0.5;
    7989           6 :                     adfTiePoints[4] += l_gt.yrot * 0.5 + l_gt.yscale * 0.5;
    7990             :                 }
    7991             : 
    7992        1713 :                 TIFFSetField(l_hTIFF, TIFFTAG_GEOTIEPOINTS, 6, adfTiePoints);
    7993             :             }
    7994             :             else
    7995             :             {
    7996           8 :                 double adfMatrix[16] = {0.0};
    7997             : 
    7998           8 :                 adfMatrix[0] = l_gt.xscale;
    7999           8 :                 adfMatrix[1] = l_gt.xrot;
    8000           8 :                 adfMatrix[3] = l_gt.xorig;
    8001           8 :                 adfMatrix[4] = l_gt.yrot;
    8002           8 :                 adfMatrix[5] = l_gt.yscale;
    8003           8 :                 adfMatrix[7] = l_gt.yorig;
    8004           8 :                 adfMatrix[15] = 1.0;
    8005             : 
    8006           8 :                 if (bPixelIsPoint && !bPointGeoIgnore)
    8007             :                 {
    8008           0 :                     adfMatrix[3] += l_gt.xscale * 0.5 + l_gt.xrot * 0.5;
    8009           0 :                     adfMatrix[7] += l_gt.yrot * 0.5 + l_gt.yscale * 0.5;
    8010             :                 }
    8011             : 
    8012           8 :                 TIFFSetField(l_hTIFF, TIFFTAG_GEOTRANSMATRIX, 16, adfMatrix);
    8013             :             }
    8014             :         }
    8015             : 
    8016             :         /* --------------------------------------------------------------------
    8017             :          */
    8018             :         /*      Do we need a TFW file? */
    8019             :         /* --------------------------------------------------------------------
    8020             :          */
    8021        1726 :         if (CPLFetchBool(papszOptions, "TFW", false))
    8022           2 :             GDALWriteWorldFile(pszFilename, "tfw", l_gt.data());
    8023        1724 :         else if (CPLFetchBool(papszOptions, "WORLDFILE", false))
    8024           1 :             GDALWriteWorldFile(pszFilename, "wld", l_gt.data());
    8025             :     }
    8026             : 
    8027             :     /* -------------------------------------------------------------------- */
    8028             :     /*      Otherwise write tiepoints if they are available.                */
    8029             :     /* -------------------------------------------------------------------- */
    8030         439 :     else if (poSrcDS->GetGCPCount() > 0 && bGeoTIFF)
    8031             :     {
    8032          11 :         const GDAL_GCP *pasGCPs = poSrcDS->GetGCPs();
    8033             :         double *padfTiePoints = static_cast<double *>(
    8034          11 :             CPLMalloc(6 * sizeof(double) * poSrcDS->GetGCPCount()));
    8035             : 
    8036          55 :         for (int iGCP = 0; iGCP < poSrcDS->GetGCPCount(); ++iGCP)
    8037             :         {
    8038             : 
    8039          44 :             padfTiePoints[iGCP * 6 + 0] = pasGCPs[iGCP].dfGCPPixel;
    8040          44 :             padfTiePoints[iGCP * 6 + 1] = pasGCPs[iGCP].dfGCPLine;
    8041          44 :             padfTiePoints[iGCP * 6 + 2] = 0;
    8042          44 :             padfTiePoints[iGCP * 6 + 3] = pasGCPs[iGCP].dfGCPX;
    8043          44 :             padfTiePoints[iGCP * 6 + 4] = pasGCPs[iGCP].dfGCPY;
    8044          44 :             padfTiePoints[iGCP * 6 + 5] = pasGCPs[iGCP].dfGCPZ;
    8045             : 
    8046          44 :             if (bPixelIsPoint && !bPointGeoIgnore)
    8047             :             {
    8048           4 :                 padfTiePoints[iGCP * 6 + 0] -= 0.5;
    8049           4 :                 padfTiePoints[iGCP * 6 + 1] -= 0.5;
    8050             :             }
    8051             :         }
    8052             : 
    8053          11 :         TIFFSetField(l_hTIFF, TIFFTAG_GEOTIEPOINTS, 6 * poSrcDS->GetGCPCount(),
    8054             :                      padfTiePoints);
    8055          11 :         CPLFree(padfTiePoints);
    8056             : 
    8057          11 :         l_poSRS = poSrcDS->GetGCPSpatialRef();
    8058             : 
    8059          22 :         if (CPLFetchBool(papszOptions, "TFW", false) ||
    8060          11 :             CPLFetchBool(papszOptions, "WORLDFILE", false))
    8061             :         {
    8062           0 :             ReportError(
    8063             :                 pszFilename, CE_Warning, CPLE_AppDefined,
    8064             :                 "TFW=ON or WORLDFILE=ON creation options are ignored when "
    8065             :                 "GCPs are available");
    8066             :         }
    8067             :     }
    8068             :     else
    8069             :     {
    8070         428 :         l_poSRS = poSrcDS->GetSpatialRef();
    8071             :     }
    8072             : 
    8073             :     /* -------------------------------------------------------------------- */
    8074             :     /*      Copy xml:XMP data                                               */
    8075             :     /* -------------------------------------------------------------------- */
    8076        2165 :     CSLConstList papszXMP = poSrcDS->GetMetadata("xml:XMP");
    8077        2165 :     if (papszXMP != nullptr && *papszXMP != nullptr)
    8078             :     {
    8079           9 :         int nTagSize = static_cast<int>(strlen(*papszXMP));
    8080           9 :         TIFFSetField(l_hTIFF, TIFFTAG_XMLPACKET, nTagSize, *papszXMP);
    8081             :     }
    8082             : 
    8083             :     /* -------------------------------------------------------------------- */
    8084             :     /*      Write the projection information, if possible.                  */
    8085             :     /* -------------------------------------------------------------------- */
    8086        2165 :     const bool bHasProjection = l_poSRS != nullptr;
    8087        2165 :     bool bExportSRSToPAM = false;
    8088        2165 :     if ((bHasProjection || bPixelIsPoint) && bGeoTIFF)
    8089             :     {
    8090        1699 :         GTIF *psGTIF = GTiffDataset::GTIFNew(l_hTIFF);
    8091             : 
    8092        1699 :         if (bHasProjection)
    8093             :         {
    8094        1699 :             const auto eGeoTIFFKeysFlavor = GetGTIFFKeysFlavor(papszOptions);
    8095        1699 :             if (IsSRSCompatibleOfGeoTIFF(l_poSRS, eGeoTIFFKeysFlavor))
    8096             :             {
    8097        1699 :                 GTIFSetFromOGISDefnEx(
    8098             :                     psGTIF,
    8099             :                     OGRSpatialReference::ToHandle(
    8100             :                         const_cast<OGRSpatialReference *>(l_poSRS)),
    8101             :                     eGeoTIFFKeysFlavor, GetGeoTIFFVersion(papszOptions));
    8102             :             }
    8103             :             else
    8104             :             {
    8105           0 :                 bExportSRSToPAM = true;
    8106             :             }
    8107             :         }
    8108             : 
    8109        1699 :         if (bPixelIsPoint)
    8110             :         {
    8111          10 :             GTIFKeySet(psGTIF, GTRasterTypeGeoKey, TYPE_SHORT, 1,
    8112             :                        RasterPixelIsPoint);
    8113             :         }
    8114             : 
    8115        1699 :         GTIFWriteKeys(psGTIF);
    8116        1699 :         GTIFFree(psGTIF);
    8117             :     }
    8118             : 
    8119        2165 :     bool l_bDontReloadFirstBlock = false;
    8120             : 
    8121             : #ifdef HAVE_LIBJPEG
    8122        2165 :     if (bCopyFromJPEG)
    8123             :     {
    8124          12 :         GTIFF_CopyFromJPEG_WriteAdditionalTags(l_hTIFF, poSrcDS);
    8125             :     }
    8126             : #endif
    8127             : 
    8128             :     /* -------------------------------------------------------------------- */
    8129             :     /*      Cleanup                                                         */
    8130             :     /* -------------------------------------------------------------------- */
    8131        2165 :     if (bCopySrcOverviews)
    8132             :     {
    8133         227 :         TIFFDeferStrileArrayWriting(l_hTIFF);
    8134             :     }
    8135        2165 :     TIFFWriteCheck(l_hTIFF, TIFFIsTiled(l_hTIFF), "GTiffCreateCopy()");
    8136        2165 :     TIFFWriteDirectory(l_hTIFF);
    8137        2165 :     if (bStreaming)
    8138             :     {
    8139             :         // We need to write twice the directory to be sure that custom
    8140             :         // TIFF tags are correctly sorted and that padding bytes have been
    8141             :         // added.
    8142           5 :         TIFFSetDirectory(l_hTIFF, 0);
    8143           5 :         TIFFWriteDirectory(l_hTIFF);
    8144             : 
    8145           5 :         if (VSIFSeekL(l_fpL, 0, SEEK_END) != 0)
    8146           0 :             ReportError(pszFilename, CE_Failure, CPLE_FileIO, "Cannot seek");
    8147           5 :         const int nSize = static_cast<int>(VSIFTellL(l_fpL));
    8148             : 
    8149           5 :         vsi_l_offset nDataLength = 0;
    8150           5 :         VSIGetMemFileBuffer(l_osTmpFilename, &nDataLength, FALSE);
    8151           5 :         TIFFSetDirectory(l_hTIFF, 0);
    8152           5 :         GTiffFillStreamableOffsetAndCount(l_hTIFF, nSize);
    8153           5 :         TIFFWriteDirectory(l_hTIFF);
    8154             :     }
    8155        2165 :     const auto nDirCount = TIFFNumberOfDirectories(l_hTIFF);
    8156        2165 :     if (nDirCount >= 1)
    8157             :     {
    8158        2158 :         TIFFSetDirectory(l_hTIFF, static_cast<tdir_t>(nDirCount - 1));
    8159             :     }
    8160        2165 :     const toff_t l_nDirOffset = TIFFCurrentDirOffset(l_hTIFF);
    8161        2165 :     TIFFFlush(l_hTIFF);
    8162        2165 :     XTIFFClose(l_hTIFF);
    8163             : 
    8164        2165 :     VSIFSeekL(l_fpL, 0, SEEK_SET);
    8165             : 
    8166             :     // fpStreaming will assigned to the instance and not closed here.
    8167        2165 :     VSILFILE *fpStreaming = nullptr;
    8168        2165 :     if (bStreaming)
    8169             :     {
    8170           5 :         vsi_l_offset nDataLength = 0;
    8171             :         void *pabyBuffer =
    8172           5 :             VSIGetMemFileBuffer(l_osTmpFilename, &nDataLength, FALSE);
    8173           5 :         fpStreaming = VSIFOpenL(pszFilename, "wb");
    8174           5 :         if (fpStreaming == nullptr)
    8175             :         {
    8176           1 :             VSIUnlink(l_osTmpFilename);
    8177           1 :             CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    8178           1 :             return nullptr;
    8179             :         }
    8180           4 :         if (static_cast<vsi_l_offset>(VSIFWriteL(pabyBuffer, 1,
    8181             :                                                  static_cast<int>(nDataLength),
    8182           4 :                                                  fpStreaming)) != nDataLength)
    8183             :         {
    8184           0 :             ReportError(pszFilename, CE_Failure, CPLE_FileIO,
    8185             :                         "Could not write %d bytes",
    8186             :                         static_cast<int>(nDataLength));
    8187           0 :             CPL_IGNORE_RET_VAL(VSIFCloseL(fpStreaming));
    8188           0 :             VSIUnlink(l_osTmpFilename);
    8189           0 :             CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    8190           0 :             return nullptr;
    8191             :         }
    8192             :     }
    8193             : 
    8194             :     /* -------------------------------------------------------------------- */
    8195             :     /*      Re-open as a dataset and copy over missing metadata using       */
    8196             :     /*      PAM facilities.                                                 */
    8197             :     /* -------------------------------------------------------------------- */
    8198        2164 :     l_hTIFF = VSI_TIFFOpen(bStreaming ? l_osTmpFilename.c_str() : pszFilename,
    8199             :                            "r+", l_fpL);
    8200        2164 :     if (l_hTIFF == nullptr)
    8201             :     {
    8202          11 :         if (bStreaming)
    8203           0 :             VSIUnlink(l_osTmpFilename);
    8204          11 :         l_fpL->CancelCreation();
    8205          11 :         CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
    8206          11 :         return nullptr;
    8207             :     }
    8208             : 
    8209             :     /* -------------------------------------------------------------------- */
    8210             :     /*      Create a corresponding GDALDataset.                             */
    8211             :     /* -------------------------------------------------------------------- */
    8212        4306 :     auto poDS = std::make_unique<GTiffDataset>();
    8213             :     const bool bSuppressASAP =
    8214        2153 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "@SUPPRESS_ASAP", "NO"));
    8215        2153 :     if (bSuppressASAP)
    8216           4 :         poDS->MarkSuppressOnClose();
    8217        2153 :     poDS->SetDescription(pszFilename);
    8218        2153 :     poDS->eAccess = GA_Update;
    8219        2153 :     poDS->m_osFilename = pszFilename;
    8220        2153 :     poDS->m_fpL = l_fpL;
    8221        2153 :     poDS->m_bIMDRPCMetadataLoaded = true;
    8222        2153 :     poDS->m_nColorTableMultiplier = nColorTableMultiplier;
    8223        2153 :     poDS->m_bTileInterleave = bTileInterleaving;
    8224             : 
    8225        2153 :     if (bTileInterleaving)
    8226             :     {
    8227           7 :         poDS->m_oGTiffMDMD.SetMetadataItem("INTERLEAVE", "TILE",
    8228             :                                            "IMAGE_STRUCTURE");
    8229             :     }
    8230             : 
    8231        2153 :     const bool bAppend = CPLFetchBool(papszOptions, "APPEND_SUBDATASET", false);
    8232        4305 :     if (poDS->OpenOffset(l_hTIFF,
    8233        2152 :                          bAppend ? l_nDirOffset : TIFFCurrentDirOffset(l_hTIFF),
    8234             :                          GA_Update,
    8235             :                          false,  // bAllowRGBAInterface
    8236             :                          true    // bReadGeoTransform
    8237        2153 :                          ) != CE_None)
    8238             :     {
    8239           0 :         l_fpL->CancelCreation();
    8240           0 :         poDS.reset();
    8241           0 :         if (bStreaming)
    8242           0 :             VSIUnlink(l_osTmpFilename);
    8243           0 :         return nullptr;
    8244             :     }
    8245             : 
    8246             :     // Legacy... Patch back GDT_Int8 type to GDT_UInt8 if the user used
    8247             :     // PIXELTYPE=SIGNEDBYTE
    8248        2153 :     const char *pszPixelType = CSLFetchNameValue(papszOptions, "PIXELTYPE");
    8249        2153 :     if (pszPixelType == nullptr)
    8250        2148 :         pszPixelType = "";
    8251        2153 :     if (eType == GDT_UInt8 && EQUAL(pszPixelType, "SIGNEDBYTE"))
    8252             :     {
    8253          10 :         for (int i = 0; i < poDS->nBands; ++i)
    8254             :         {
    8255           5 :             auto poBand = static_cast<GTiffRasterBand *>(poDS->papoBands[i]);
    8256           5 :             poBand->eDataType = GDT_UInt8;
    8257           5 :             poBand->EnablePixelTypeSignedByteWarning(false);
    8258           5 :             poBand->SetMetadataItem("PIXELTYPE", "SIGNEDBYTE",
    8259             :                                     "IMAGE_STRUCTURE");
    8260           5 :             poBand->EnablePixelTypeSignedByteWarning(true);
    8261             :         }
    8262             :     }
    8263             : 
    8264        2153 :     poDS->oOvManager.Initialize(poDS.get(), pszFilename);
    8265             : 
    8266        2153 :     if (bStreaming)
    8267             :     {
    8268           4 :         VSIUnlink(l_osTmpFilename);
    8269           4 :         poDS->m_fpToWrite = fpStreaming;
    8270             :     }
    8271        2153 :     poDS->m_eProfile = eProfile;
    8272             : 
    8273        2153 :     int nCloneInfoFlags = GCIF_PAM_DEFAULT & ~GCIF_MASK;
    8274             : 
    8275             :     // If we explicitly asked not to tag the alpha band as such, do not
    8276             :     // reintroduce this alpha color interpretation in PAM.
    8277        2153 :     if (poSrcDS->GetRasterBand(l_nBands)->GetColorInterpretation() ==
    8278        2281 :             GCI_AlphaBand &&
    8279         128 :         GTiffGetAlphaValue(
    8280             :             CPLGetConfigOption("GTIFF_ALPHA",
    8281             :                                CSLFetchNameValue(papszOptions, "ALPHA")),
    8282             :             DEFAULT_ALPHA_TYPE) == EXTRASAMPLE_UNSPECIFIED)
    8283             :     {
    8284           1 :         nCloneInfoFlags &= ~GCIF_COLORINTERP;
    8285             :     }
    8286             :     // Ignore source band color interpretation if requesting PHOTOMETRIC=RGB
    8287        3380 :     else if (l_nBands >= 3 &&
    8288        1228 :              EQUAL(CSLFetchNameValueDef(papszOptions, "PHOTOMETRIC", ""),
    8289             :                    "RGB"))
    8290             :     {
    8291          28 :         for (int i = 1; i <= 3; i++)
    8292             :         {
    8293          21 :             poDS->GetRasterBand(i)->SetColorInterpretation(
    8294          21 :                 static_cast<GDALColorInterp>(GCI_RedBand + (i - 1)));
    8295             :         }
    8296           7 :         nCloneInfoFlags &= ~GCIF_COLORINTERP;
    8297           9 :         if (!(l_nBands == 4 &&
    8298           2 :               CSLFetchNameValue(papszOptions, "ALPHA") != nullptr))
    8299             :         {
    8300          15 :             for (int i = 4; i <= l_nBands; i++)
    8301             :             {
    8302          18 :                 poDS->GetRasterBand(i)->SetColorInterpretation(
    8303           9 :                     poSrcDS->GetRasterBand(i)->GetColorInterpretation());
    8304             :             }
    8305             :         }
    8306             :     }
    8307             : 
    8308             :     CPLString osOldGTIFF_REPORT_COMPD_CSVal(
    8309        4306 :         CPLGetConfigOption("GTIFF_REPORT_COMPD_CS", ""));
    8310        2153 :     CPLSetThreadLocalConfigOption("GTIFF_REPORT_COMPD_CS", "YES");
    8311        2153 :     poDS->CloneInfo(poSrcDS, nCloneInfoFlags);
    8312        2153 :     CPLSetThreadLocalConfigOption("GTIFF_REPORT_COMPD_CS",
    8313        2153 :                                   osOldGTIFF_REPORT_COMPD_CSVal.empty()
    8314             :                                       ? nullptr
    8315           0 :                                       : osOldGTIFF_REPORT_COMPD_CSVal.c_str());
    8316             : 
    8317        2170 :     if ((!bGeoTIFF || bExportSRSToPAM) &&
    8318          17 :         (poDS->GetPamFlags() & GPF_DISABLED) == 0)
    8319             :     {
    8320             :         // Copy georeferencing info to PAM if the profile is not GeoTIFF
    8321          16 :         poDS->GDALPamDataset::SetSpatialRef(poDS->GetSpatialRef());
    8322          16 :         GDALGeoTransform gt;
    8323          16 :         if (poDS->GetGeoTransform(gt) == CE_None)
    8324             :         {
    8325           5 :             poDS->GDALPamDataset::SetGeoTransform(gt);
    8326             :         }
    8327          16 :         poDS->GDALPamDataset::SetGCPs(poDS->GetGCPCount(), poDS->GetGCPs(),
    8328             :                                       poDS->GetGCPSpatialRef());
    8329             :     }
    8330             : 
    8331        2153 :     poDS->m_papszCreationOptions = CSLDuplicate(papszOptions);
    8332        2153 :     poDS->m_bDontReloadFirstBlock = l_bDontReloadFirstBlock;
    8333             : 
    8334             :     /* -------------------------------------------------------------------- */
    8335             :     /*      CloneInfo() does not merge metadata, it just replaces it        */
    8336             :     /*      totally.  So we have to merge it.                               */
    8337             :     /* -------------------------------------------------------------------- */
    8338             : 
    8339        2153 :     CSLConstList papszSRC_MD = poSrcDS->GetMetadata();
    8340        2153 :     char **papszDST_MD = CSLDuplicate(poDS->GetMetadata());
    8341             : 
    8342        2153 :     papszDST_MD = CSLMerge(papszDST_MD, papszSRC_MD);
    8343             : 
    8344        2153 :     poDS->SetMetadata(papszDST_MD);
    8345        2153 :     CSLDestroy(papszDST_MD);
    8346             : 
    8347             :     // Depending on the PHOTOMETRIC tag, the TIFF file may not have the same
    8348             :     // band count as the source. Will fail later in GDALDatasetCopyWholeRaster
    8349             :     // anyway.
    8350        7233 :     for (int nBand = 1;
    8351        7233 :          nBand <= std::min(poDS->GetRasterCount(), poSrcDS->GetRasterCount());
    8352             :          ++nBand)
    8353             :     {
    8354        5080 :         GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand(nBand);
    8355        5080 :         GDALRasterBand *poDstBand = poDS->GetRasterBand(nBand);
    8356        5080 :         papszSRC_MD = poSrcBand->GetMetadata();
    8357        5080 :         papszDST_MD = CSLDuplicate(poDstBand->GetMetadata());
    8358             : 
    8359        5080 :         papszDST_MD = CSLMerge(papszDST_MD, papszSRC_MD);
    8360             : 
    8361        5080 :         poDstBand->SetMetadata(papszDST_MD);
    8362        5080 :         CSLDestroy(papszDST_MD);
    8363             : 
    8364        5080 :         char **papszCatNames = poSrcBand->GetCategoryNames();
    8365        5080 :         if (nullptr != papszCatNames)
    8366           0 :             poDstBand->SetCategoryNames(papszCatNames);
    8367             :     }
    8368             : 
    8369        2153 :     l_hTIFF = static_cast<TIFF *>(poDS->GetInternalHandle("TIFF_HANDLE"));
    8370             : 
    8371             :     /* -------------------------------------------------------------------- */
    8372             :     /*      Handle forcing xml:ESRI data to be written to PAM.              */
    8373             :     /* -------------------------------------------------------------------- */
    8374        2153 :     if (CPLTestBool(CPLGetConfigOption("ESRI_XML_PAM", "NO")))
    8375             :     {
    8376           1 :         CSLConstList papszESRIMD = poSrcDS->GetMetadata("xml:ESRI");
    8377           1 :         if (papszESRIMD)
    8378             :         {
    8379           1 :             poDS->SetMetadata(papszESRIMD, "xml:ESRI");
    8380             :         }
    8381             :     }
    8382             : 
    8383             :     /* -------------------------------------------------------------------- */
    8384             :     /*      Second chance: now that we have a PAM dataset, it is possible   */
    8385             :     /*      to write metadata that we could not write as a TIFF tag.        */
    8386             :     /* -------------------------------------------------------------------- */
    8387        2153 :     if (!bHasWrittenMDInGeotiffTAG && !bStreaming)
    8388             :     {
    8389           6 :         GTiffDataset::WriteMetadata(
    8390           6 :             poDS.get(), l_hTIFF, true, eProfile, pszFilename, papszOptions,
    8391             :             true /* don't write RPC and IMD file again */);
    8392             :     }
    8393             : 
    8394        2153 :     if (!bStreaming)
    8395        2149 :         GTiffDataset::WriteRPC(poDS.get(), l_hTIFF, true, eProfile, pszFilename,
    8396             :                                papszOptions,
    8397             :                                true /* write only in PAM AND if needed */);
    8398             : 
    8399        2153 :     poDS->m_bWriteCOGLayout = bCopySrcOverviews;
    8400             : 
    8401             :     // To avoid unnecessary directory rewriting.
    8402        2153 :     poDS->m_bMetadataChanged = false;
    8403        2153 :     poDS->m_bGeoTIFFInfoChanged = false;
    8404        2153 :     poDS->m_bNoDataChanged = false;
    8405        2153 :     poDS->m_bForceUnsetGTOrGCPs = false;
    8406        2153 :     poDS->m_bForceUnsetProjection = false;
    8407        2153 :     poDS->m_bStreamingOut = bStreaming;
    8408             : 
    8409             :     // Don't try to load external metadata files (#6597).
    8410        2153 :     poDS->m_bIMDRPCMetadataLoaded = true;
    8411             : 
    8412             :     // We must re-set the compression level at this point, since it has been
    8413             :     // lost a few lines above when closing the newly create TIFF file The
    8414             :     // TIFFTAG_ZIPQUALITY & TIFFTAG_JPEGQUALITY are not store in the TIFF file.
    8415             :     // They are just TIFF session parameters.
    8416             : 
    8417        2153 :     poDS->m_nZLevel = GTiffGetZLevel(papszOptions);
    8418        2153 :     poDS->m_nLZMAPreset = GTiffGetLZMAPreset(papszOptions);
    8419        2153 :     poDS->m_nZSTDLevel = GTiffGetZSTDPreset(papszOptions);
    8420        2153 :     poDS->m_nWebPLevel = GTiffGetWebPLevel(papszOptions);
    8421        2153 :     poDS->m_bWebPLossless = GTiffGetWebPLossless(papszOptions);
    8422        2156 :     if (poDS->m_nWebPLevel != 100 && poDS->m_bWebPLossless &&
    8423           3 :         CSLFetchNameValue(papszOptions, "WEBP_LEVEL"))
    8424             :     {
    8425           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    8426             :                  "WEBP_LEVEL is specified, but WEBP_LOSSLESS=YES. "
    8427             :                  "WEBP_LEVEL will be ignored.");
    8428             :     }
    8429        2153 :     poDS->m_nJpegQuality = GTiffGetJpegQuality(papszOptions);
    8430        2153 :     poDS->m_nJpegTablesMode = GTiffGetJpegTablesMode(papszOptions);
    8431        2153 :     poDS->GetDiscardLsbOption(papszOptions);
    8432        2153 :     poDS->m_dfMaxZError = GTiffGetLERCMaxZError(papszOptions);
    8433        2153 :     poDS->m_dfMaxZErrorOverview = GTiffGetLERCMaxZErrorOverview(papszOptions);
    8434             : #if HAVE_JXL
    8435        2153 :     poDS->m_bJXLLossless = GTiffGetJXLLossless(papszOptions);
    8436        2153 :     poDS->m_nJXLEffort = GTiffGetJXLEffort(papszOptions);
    8437        2153 :     poDS->m_fJXLDistance = GTiffGetJXLDistance(papszOptions);
    8438        2153 :     poDS->m_fJXLAlphaDistance = GTiffGetJXLAlphaDistance(papszOptions);
    8439             : #endif
    8440        2153 :     poDS->InitCreationOrOpenOptions(true, papszOptions);
    8441             : 
    8442        2153 :     if (l_nCompression == COMPRESSION_ADOBE_DEFLATE ||
    8443        2125 :         l_nCompression == COMPRESSION_LERC)
    8444             :     {
    8445          99 :         GTiffSetDeflateSubCodec(l_hTIFF);
    8446             : 
    8447          99 :         if (poDS->m_nZLevel != -1)
    8448             :         {
    8449          12 :             TIFFSetField(l_hTIFF, TIFFTAG_ZIPQUALITY, poDS->m_nZLevel);
    8450             :         }
    8451             :     }
    8452        2153 :     if (l_nCompression == COMPRESSION_JPEG)
    8453             :     {
    8454          75 :         if (poDS->m_nJpegQuality != -1)
    8455             :         {
    8456           9 :             TIFFSetField(l_hTIFF, TIFFTAG_JPEGQUALITY, poDS->m_nJpegQuality);
    8457             :         }
    8458          75 :         TIFFSetField(l_hTIFF, TIFFTAG_JPEGTABLESMODE, poDS->m_nJpegTablesMode);
    8459             :     }
    8460        2153 :     if (l_nCompression == COMPRESSION_LZMA)
    8461             :     {
    8462           7 :         if (poDS->m_nLZMAPreset != -1)
    8463             :         {
    8464           6 :             TIFFSetField(l_hTIFF, TIFFTAG_LZMAPRESET, poDS->m_nLZMAPreset);
    8465             :         }
    8466             :     }
    8467        2153 :     if (l_nCompression == COMPRESSION_ZSTD ||
    8468        2133 :         l_nCompression == COMPRESSION_LERC)
    8469             :     {
    8470          91 :         if (poDS->m_nZSTDLevel != -1)
    8471             :         {
    8472           8 :             TIFFSetField(l_hTIFF, TIFFTAG_ZSTD_LEVEL, poDS->m_nZSTDLevel);
    8473             :         }
    8474             :     }
    8475        2153 :     if (l_nCompression == COMPRESSION_LERC)
    8476             :     {
    8477          71 :         TIFFSetField(l_hTIFF, TIFFTAG_LERC_MAXZERROR, poDS->m_dfMaxZError);
    8478             :     }
    8479             : #if HAVE_JXL
    8480        2153 :     if (l_nCompression == COMPRESSION_JXL ||
    8481        2153 :         l_nCompression == COMPRESSION_JXL_DNG_1_7)
    8482             :     {
    8483          91 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_LOSSYNESS,
    8484          91 :                      poDS->m_bJXLLossless ? JXL_LOSSLESS : JXL_LOSSY);
    8485          91 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_EFFORT, poDS->m_nJXLEffort);
    8486          91 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_DISTANCE,
    8487          91 :                      static_cast<double>(poDS->m_fJXLDistance));
    8488          91 :         TIFFSetField(l_hTIFF, TIFFTAG_JXL_ALPHA_DISTANCE,
    8489          91 :                      static_cast<double>(poDS->m_fJXLAlphaDistance));
    8490             :     }
    8491             : #endif
    8492        2153 :     if (l_nCompression == COMPRESSION_WEBP)
    8493             :     {
    8494          14 :         if (poDS->m_nWebPLevel != -1)
    8495             :         {
    8496          14 :             TIFFSetField(l_hTIFF, TIFFTAG_WEBP_LEVEL, poDS->m_nWebPLevel);
    8497             :         }
    8498             : 
    8499          14 :         if (poDS->m_bWebPLossless)
    8500             :         {
    8501           5 :             TIFFSetField(l_hTIFF, TIFFTAG_WEBP_LOSSLESS, poDS->m_bWebPLossless);
    8502             :         }
    8503             :     }
    8504             : 
    8505             :     /* -------------------------------------------------------------------- */
    8506             :     /*      Do we want to ensure all blocks get written out on close to     */
    8507             :     /*      avoid sparse files?                                             */
    8508             :     /* -------------------------------------------------------------------- */
    8509        2153 :     if (!CPLFetchBool(papszOptions, "SPARSE_OK", false))
    8510        2125 :         poDS->m_bFillEmptyTilesAtClosing = true;
    8511             : 
    8512        2153 :     poDS->m_bWriteEmptyTiles =
    8513        4083 :         (bCopySrcOverviews && poDS->m_bFillEmptyTilesAtClosing) || bStreaming ||
    8514        1930 :         (poDS->m_nCompression != COMPRESSION_NONE &&
    8515         317 :          poDS->m_bFillEmptyTilesAtClosing);
    8516             :     // Only required for people writing non-compressed striped files in the
    8517             :     // rightorder and wanting all tstrips to be written in the same order
    8518             :     // so that the end result can be memory mapped without knowledge of each
    8519             :     // strip offset
    8520        2153 :     if (CPLTestBool(CSLFetchNameValueDef(
    8521        4306 :             papszOptions, "WRITE_EMPTY_TILES_SYNCHRONOUSLY", "FALSE")) ||
    8522        2153 :         CPLTestBool(CSLFetchNameValueDef(
    8523             :             papszOptions, "@WRITE_EMPTY_TILES_SYNCHRONOUSLY", "FALSE")))
    8524             :     {
    8525           0 :         poDS->m_bWriteEmptyTiles = true;
    8526             :     }
    8527             : 
    8528             :     // Precreate (internal) mask, so that the IBuildOverviews() below
    8529             :     // has a chance to create also the overviews of the mask.
    8530        2153 :     CPLErr eErr = CE_None;
    8531             : 
    8532        2153 :     if (bCreateMask)
    8533             :     {
    8534          38 :         eErr = poDS->CreateMaskBand(nMaskFlags);
    8535          38 :         if (poDS->m_poMaskDS)
    8536             :         {
    8537          37 :             poDS->m_poMaskDS->m_bFillEmptyTilesAtClosing =
    8538          37 :                 poDS->m_bFillEmptyTilesAtClosing;
    8539          37 :             poDS->m_poMaskDS->m_bWriteEmptyTiles = poDS->m_bWriteEmptyTiles;
    8540             :         }
    8541             :     }
    8542             : 
    8543             :     /* -------------------------------------------------------------------- */
    8544             :     /*      Create and then copy existing overviews if requested            */
    8545             :     /*  We do it such that all the IFDs are at the beginning of the file,   */
    8546             :     /*  and that the imagery data for the smallest overview is written      */
    8547             :     /*  first, that way the file is more usable when embedded in a          */
    8548             :     /*  compressed stream.                                                  */
    8549             :     /* -------------------------------------------------------------------- */
    8550             : 
    8551             :     // For scaled progress due to overview copying.
    8552        2153 :     const int nBandsWidthMask = l_nBands + (bCreateMask ? 1 : 0);
    8553        2153 :     double dfTotalPixels =
    8554        2153 :         static_cast<double>(nXSize) * nYSize * nBandsWidthMask;
    8555        2153 :     double dfCurPixels = 0;
    8556             : 
    8557        2153 :     if (eErr == CE_None && bCopySrcOverviews)
    8558             :     {
    8559           0 :         std::unique_ptr<GDALDataset> poMaskOvrDS;
    8560             :         const char *pszMaskOvrDS =
    8561         224 :             CSLFetchNameValue(papszOptions, "@MASK_OVERVIEW_DATASET");
    8562         224 :         if (pszMaskOvrDS)
    8563             :         {
    8564           6 :             poMaskOvrDS.reset(GDALDataset::Open(pszMaskOvrDS));
    8565           6 :             if (!poMaskOvrDS)
    8566             :             {
    8567           0 :                 l_fpL->CancelCreation();
    8568           0 :                 return nullptr;
    8569             :             }
    8570           6 :             if (poMaskOvrDS->GetRasterCount() != 1)
    8571             :             {
    8572           0 :                 l_fpL->CancelCreation();
    8573           0 :                 return nullptr;
    8574             :             }
    8575             :         }
    8576         224 :         if (nSrcOverviews)
    8577             :         {
    8578          71 :             eErr = poDS->CreateOverviewsFromSrcOverviews(poSrcDS, poOvrDS.get(),
    8579             :                                                          nSrcOverviews);
    8580             : 
    8581         207 :             if (eErr == CE_None &&
    8582          71 :                 (poMaskOvrDS != nullptr ||
    8583          65 :                  (poSrcDS->GetRasterBand(1)->GetOverview(0) &&
    8584          35 :                   poSrcDS->GetRasterBand(1)->GetOverview(0)->GetMaskFlags() ==
    8585             :                       GMF_PER_DATASET)))
    8586             :             {
    8587          19 :                 int nOvrBlockXSize = 0;
    8588          19 :                 int nOvrBlockYSize = 0;
    8589          19 :                 GTIFFGetOverviewBlockSize(
    8590          19 :                     GDALRasterBand::ToHandle(poDS->GetRasterBand(1)),
    8591             :                     &nOvrBlockXSize, &nOvrBlockYSize, nullptr, nullptr);
    8592          19 :                 eErr = poDS->CreateInternalMaskOverviews(nOvrBlockXSize,
    8593             :                                                          nOvrBlockYSize);
    8594             :             }
    8595             :         }
    8596             : 
    8597         224 :         TIFFForceStrileArrayWriting(poDS->m_hTIFF);
    8598             : 
    8599         224 :         if (poDS->m_poMaskDS)
    8600             :         {
    8601          27 :             TIFFForceStrileArrayWriting(poDS->m_poMaskDS->m_hTIFF);
    8602             :         }
    8603             : 
    8604         355 :         for (auto &poIterOvrDS : poDS->m_apoOverviewDS)
    8605             :         {
    8606         131 :             TIFFForceStrileArrayWriting(poIterOvrDS->m_hTIFF);
    8607             : 
    8608         131 :             if (poIterOvrDS->m_poMaskDS)
    8609             :             {
    8610          32 :                 TIFFForceStrileArrayWriting(poIterOvrDS->m_poMaskDS->m_hTIFF);
    8611             :             }
    8612             :         }
    8613             : 
    8614         224 :         if (eErr == CE_None && nSrcOverviews)
    8615             :         {
    8616          71 :             if (poDS->m_apoOverviewDS.size() !=
    8617          71 :                 static_cast<size_t>(nSrcOverviews))
    8618             :             {
    8619           0 :                 ReportError(
    8620             :                     pszFilename, CE_Failure, CPLE_AppDefined,
    8621             :                     "Did only manage to instantiate %d overview levels, "
    8622             :                     "whereas source contains %d",
    8623           0 :                     static_cast<int>(poDS->m_apoOverviewDS.size()),
    8624             :                     nSrcOverviews);
    8625           0 :                 eErr = CE_Failure;
    8626             :             }
    8627             : 
    8628         202 :             for (int i = 0; eErr == CE_None && i < nSrcOverviews; ++i)
    8629             :             {
    8630             :                 GDALRasterBand *poOvrBand =
    8631             :                     poOvrDS
    8632         207 :                         ? (i == 0
    8633          76 :                                ? poOvrDS->GetRasterBand(1)
    8634          40 :                                : poOvrDS->GetRasterBand(1)->GetOverview(i - 1))
    8635         186 :                         : poSrcDS->GetRasterBand(1)->GetOverview(i);
    8636             :                 const double dfOvrPixels =
    8637         131 :                     static_cast<double>(poOvrBand->GetXSize()) *
    8638         131 :                     poOvrBand->GetYSize();
    8639         131 :                 dfTotalPixels += dfOvrPixels * l_nBands;
    8640         244 :                 if (poOvrBand->GetMaskFlags() == GMF_PER_DATASET ||
    8641         113 :                     poMaskOvrDS != nullptr)
    8642             :                 {
    8643          32 :                     dfTotalPixels += dfOvrPixels;
    8644             :                 }
    8645          99 :                 else if (i == 0 && poDS->GetRasterBand(1)->GetMaskFlags() ==
    8646             :                                        GMF_PER_DATASET)
    8647             :                 {
    8648           1 :                     ReportError(pszFilename, CE_Warning, CPLE_AppDefined,
    8649             :                                 "Source dataset has a mask band on full "
    8650             :                                 "resolution, overviews on the regular bands, "
    8651             :                                 "but lacks overviews on the mask band.");
    8652             :                 }
    8653             :             }
    8654             : 
    8655             :             // Now copy the imagery.
    8656             :             // Begin with the smallest overview.
    8657          71 :             for (int iOvrLevel = nSrcOverviews - 1;
    8658         201 :                  eErr == CE_None && iOvrLevel >= 0; --iOvrLevel)
    8659             :             {
    8660         130 :                 auto poDstDS = poDS->m_apoOverviewDS[iOvrLevel].get();
    8661             : 
    8662             :                 // Create a fake dataset with the source overview level so that
    8663             :                 // GDALDatasetCopyWholeRaster can cope with it.
    8664             :                 GDALDataset *poSrcOvrDS =
    8665             :                     poOvrDS
    8666         170 :                         ? (iOvrLevel == 0 ? poOvrDS.get()
    8667          40 :                                           : GDALCreateOverviewDataset(
    8668             :                                                 poOvrDS.get(), iOvrLevel - 1,
    8669             :                                                 /* bThisLevelOnly = */ true))
    8670          54 :                         : GDALCreateOverviewDataset(
    8671             :                               poSrcDS, iOvrLevel,
    8672         130 :                               /* bThisLevelOnly = */ true);
    8673             :                 GDALRasterBand *poSrcOvrBand =
    8674         206 :                     poOvrDS ? (iOvrLevel == 0
    8675          76 :                                    ? poOvrDS->GetRasterBand(1)
    8676          80 :                                    : poOvrDS->GetRasterBand(1)->GetOverview(
    8677          40 :                                          iOvrLevel - 1))
    8678         184 :                             : poSrcDS->GetRasterBand(1)->GetOverview(iOvrLevel);
    8679             :                 double dfNextCurPixels =
    8680             :                     dfCurPixels +
    8681         130 :                     static_cast<double>(poSrcOvrBand->GetXSize()) *
    8682         130 :                         poSrcOvrBand->GetYSize() * l_nBands;
    8683             : 
    8684         130 :                 poDstDS->m_bBlockOrderRowMajor = true;
    8685         130 :                 poDstDS->m_bLeaderSizeAsUInt4 = true;
    8686         130 :                 poDstDS->m_bTrailerRepeatedLast4BytesRepeated = true;
    8687         130 :                 poDstDS->m_bFillEmptyTilesAtClosing =
    8688         130 :                     poDS->m_bFillEmptyTilesAtClosing;
    8689         130 :                 poDstDS->m_bWriteEmptyTiles = poDS->m_bWriteEmptyTiles;
    8690         130 :                 poDstDS->m_bTileInterleave = poDS->m_bTileInterleave;
    8691         130 :                 GDALRasterBand *poSrcMaskBand = nullptr;
    8692         130 :                 if (poDstDS->m_poMaskDS)
    8693             :                 {
    8694          32 :                     poDstDS->m_poMaskDS->m_bBlockOrderRowMajor = true;
    8695          32 :                     poDstDS->m_poMaskDS->m_bLeaderSizeAsUInt4 = true;
    8696          32 :                     poDstDS->m_poMaskDS->m_bTrailerRepeatedLast4BytesRepeated =
    8697             :                         true;
    8698          64 :                     poDstDS->m_poMaskDS->m_bFillEmptyTilesAtClosing =
    8699          32 :                         poDS->m_bFillEmptyTilesAtClosing;
    8700          64 :                     poDstDS->m_poMaskDS->m_bWriteEmptyTiles =
    8701          32 :                         poDS->m_bWriteEmptyTiles;
    8702             : 
    8703          32 :                     poSrcMaskBand =
    8704             :                         poMaskOvrDS
    8705          46 :                             ? (iOvrLevel == 0
    8706          14 :                                    ? poMaskOvrDS->GetRasterBand(1)
    8707          16 :                                    : poMaskOvrDS->GetRasterBand(1)->GetOverview(
    8708           8 :                                          iOvrLevel - 1))
    8709          50 :                             : poSrcOvrBand->GetMaskBand();
    8710             :                 }
    8711             : 
    8712         130 :                 if (poDstDS->m_poMaskDS)
    8713             :                 {
    8714          32 :                     dfNextCurPixels +=
    8715          32 :                         static_cast<double>(poSrcOvrBand->GetXSize()) *
    8716          32 :                         poSrcOvrBand->GetYSize();
    8717             :                 }
    8718             :                 void *pScaledData =
    8719         130 :                     GDALCreateScaledProgress(dfCurPixels / dfTotalPixels,
    8720             :                                              dfNextCurPixels / dfTotalPixels,
    8721             :                                              pfnProgress, pProgressData);
    8722             : 
    8723         130 :                 eErr = CopyImageryAndMask(poDstDS, poSrcOvrDS, poSrcMaskBand,
    8724             :                                           GDALScaledProgress, pScaledData);
    8725             : 
    8726         130 :                 dfCurPixels = dfNextCurPixels;
    8727         130 :                 GDALDestroyScaledProgress(pScaledData);
    8728             : 
    8729         130 :                 if (poSrcOvrDS != poOvrDS.get())
    8730          94 :                     delete poSrcOvrDS;
    8731         130 :                 poSrcOvrDS = nullptr;
    8732             :             }
    8733             :         }
    8734             :     }
    8735             : 
    8736             :     /* -------------------------------------------------------------------- */
    8737             :     /*      Copy actual imagery.                                            */
    8738             :     /* -------------------------------------------------------------------- */
    8739        2153 :     double dfNextCurPixels =
    8740        2153 :         dfCurPixels + static_cast<double>(nXSize) * nYSize * l_nBands;
    8741        2153 :     void *pScaledData = GDALCreateScaledProgress(
    8742             :         dfCurPixels / dfTotalPixels, dfNextCurPixels / dfTotalPixels,
    8743             :         pfnProgress, pProgressData);
    8744             : 
    8745             : #if defined(HAVE_LIBJPEG) || defined(JPEG_DIRECT_COPY)
    8746        2153 :     bool bTryCopy = true;
    8747             : #endif
    8748             : 
    8749             : #ifdef HAVE_LIBJPEG
    8750        2153 :     if (bCopyFromJPEG)
    8751             :     {
    8752          12 :         eErr = GTIFF_CopyFromJPEG(poDS.get(), poSrcDS, pfnProgress,
    8753             :                                   pProgressData, bTryCopy);
    8754             : 
    8755             :         // In case of failure in the decompression step, try normal copy.
    8756          12 :         if (bTryCopy)
    8757           0 :             eErr = CE_None;
    8758             :     }
    8759             : #endif
    8760             : 
    8761             : #ifdef JPEG_DIRECT_COPY
    8762             :     if (bDirectCopyFromJPEG)
    8763             :     {
    8764             :         eErr = GTIFF_DirectCopyFromJPEG(poDS.get(), poSrcDS, pfnProgress,
    8765             :                                         pProgressData, bTryCopy);
    8766             : 
    8767             :         // In case of failure in the reading step, try normal copy.
    8768             :         if (bTryCopy)
    8769             :             eErr = CE_None;
    8770             :     }
    8771             : #endif
    8772             : 
    8773        2153 :     bool bWriteMask = true;
    8774        2153 :     if (
    8775             : #if defined(HAVE_LIBJPEG) || defined(JPEG_DIRECT_COPY)
    8776        4294 :         bTryCopy &&
    8777             : #endif
    8778        2141 :         (poDS->m_bTreatAsSplit || poDS->m_bTreatAsSplitBitmap))
    8779             :     {
    8780             :         // For split bands, we use TIFFWriteScanline() interface.
    8781           9 :         CPLAssert(poDS->m_nBitsPerSample == 8 || poDS->m_nBitsPerSample == 1);
    8782             : 
    8783           9 :         if (poDS->m_nPlanarConfig == PLANARCONFIG_CONTIG && poDS->nBands > 1)
    8784             :         {
    8785             :             GByte *pabyScanline = static_cast<GByte *>(
    8786           3 :                 VSI_MALLOC_VERBOSE(TIFFScanlineSize(l_hTIFF)));
    8787           3 :             if (pabyScanline == nullptr)
    8788           0 :                 eErr = CE_Failure;
    8789        9052 :             for (int j = 0; j < nYSize && eErr == CE_None; ++j)
    8790             :             {
    8791       18098 :                 eErr = poSrcDS->RasterIO(GF_Read, 0, j, nXSize, 1, pabyScanline,
    8792             :                                          nXSize, 1, GDT_UInt8, l_nBands,
    8793        9049 :                                          nullptr, poDS->nBands, 0, 1, nullptr);
    8794       18098 :                 if (eErr == CE_None &&
    8795        9049 :                     TIFFWriteScanline(l_hTIFF, pabyScanline, j, 0) == -1)
    8796             :                 {
    8797           0 :                     ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
    8798             :                                 "TIFFWriteScanline() failed.");
    8799           0 :                     eErr = CE_Failure;
    8800             :                 }
    8801        9049 :                 if (!GDALScaledProgress((j + 1) * 1.0 / nYSize, nullptr,
    8802             :                                         pScaledData))
    8803           0 :                     eErr = CE_Failure;
    8804             :             }
    8805           3 :             CPLFree(pabyScanline);
    8806             :         }
    8807             :         else
    8808             :         {
    8809             :             GByte *pabyScanline =
    8810           6 :                 static_cast<GByte *>(VSI_MALLOC_VERBOSE(nXSize));
    8811           6 :             if (pabyScanline == nullptr)
    8812           0 :                 eErr = CE_Failure;
    8813             :             else
    8814           6 :                 eErr = CE_None;
    8815          14 :             for (int iBand = 1; iBand <= l_nBands && eErr == CE_None; ++iBand)
    8816             :             {
    8817       48211 :                 for (int j = 0; j < nYSize && eErr == CE_None; ++j)
    8818             :                 {
    8819       48203 :                     eErr = poSrcDS->GetRasterBand(iBand)->RasterIO(
    8820             :                         GF_Read, 0, j, nXSize, 1, pabyScanline, nXSize, 1,
    8821             :                         GDT_UInt8, 0, 0, nullptr);
    8822       48203 :                     if (poDS->m_bTreatAsSplitBitmap)
    8823             :                     {
    8824     7225210 :                         for (int i = 0; i < nXSize; ++i)
    8825             :                         {
    8826     7216010 :                             const GByte byVal = pabyScanline[i];
    8827     7216010 :                             if ((i & 0x7) == 0)
    8828      902001 :                                 pabyScanline[i >> 3] = 0;
    8829     7216010 :                             if (byVal)
    8830     7097220 :                                 pabyScanline[i >> 3] |= 0x80 >> (i & 0x7);
    8831             :                         }
    8832             :                     }
    8833       96406 :                     if (eErr == CE_None &&
    8834       48203 :                         TIFFWriteScanline(l_hTIFF, pabyScanline, j,
    8835       48203 :                                           static_cast<uint16_t>(iBand - 1)) ==
    8836             :                             -1)
    8837             :                     {
    8838           0 :                         ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
    8839             :                                     "TIFFWriteScanline() failed.");
    8840           0 :                         eErr = CE_Failure;
    8841             :                     }
    8842       48203 :                     if (!GDALScaledProgress((j + 1 + (iBand - 1) * nYSize) *
    8843       48203 :                                                 1.0 / (l_nBands * nYSize),
    8844             :                                             nullptr, pScaledData))
    8845           0 :                         eErr = CE_Failure;
    8846             :                 }
    8847             :             }
    8848           6 :             CPLFree(pabyScanline);
    8849             :         }
    8850             : 
    8851             :         // Necessary to be able to read the file without re-opening.
    8852           9 :         TIFFSizeProc pfnSizeProc = TIFFGetSizeProc(l_hTIFF);
    8853             : 
    8854           9 :         TIFFFlushData(l_hTIFF);
    8855             : 
    8856           9 :         toff_t nNewDirOffset = pfnSizeProc(TIFFClientdata(l_hTIFF));
    8857           9 :         if ((nNewDirOffset % 2) == 1)
    8858           5 :             ++nNewDirOffset;
    8859             : 
    8860           9 :         TIFFFlush(l_hTIFF);
    8861             : 
    8862           9 :         if (poDS->m_nDirOffset != TIFFCurrentDirOffset(l_hTIFF))
    8863             :         {
    8864           0 :             poDS->m_nDirOffset = nNewDirOffset;
    8865           0 :             CPLDebug("GTiff", "directory moved during flush.");
    8866             :         }
    8867             :     }
    8868        2144 :     else if (
    8869             : #if defined(HAVE_LIBJPEG) || defined(JPEG_DIRECT_COPY)
    8870        2132 :         bTryCopy &&
    8871             : #endif
    8872             :         eErr == CE_None)
    8873             :     {
    8874        2131 :         const char *papszCopyWholeRasterOptions[3] = {nullptr, nullptr,
    8875             :                                                       nullptr};
    8876        2131 :         int iNextOption = 0;
    8877        2131 :         papszCopyWholeRasterOptions[iNextOption++] = "SKIP_HOLES=YES";
    8878        2131 :         if (l_nCompression != COMPRESSION_NONE)
    8879             :         {
    8880         506 :             papszCopyWholeRasterOptions[iNextOption++] = "COMPRESSED=YES";
    8881             :         }
    8882             : 
    8883             :         // For streaming with separate, we really want that bands are written
    8884             :         // after each other, even if the source is pixel interleaved.
    8885        1625 :         else if (bStreaming && poDS->m_nPlanarConfig == PLANARCONFIG_SEPARATE)
    8886             :         {
    8887           1 :             papszCopyWholeRasterOptions[iNextOption++] = "INTERLEAVE=BAND";
    8888             :         }
    8889             : 
    8890        2131 :         if (bCopySrcOverviews || bTileInterleaving)
    8891             :         {
    8892         224 :             poDS->m_bBlockOrderRowMajor = true;
    8893         224 :             poDS->m_bLeaderSizeAsUInt4 = bCopySrcOverviews;
    8894         224 :             poDS->m_bTrailerRepeatedLast4BytesRepeated = bCopySrcOverviews;
    8895         224 :             if (poDS->m_poMaskDS)
    8896             :             {
    8897          27 :                 poDS->m_poMaskDS->m_bBlockOrderRowMajor = true;
    8898          27 :                 poDS->m_poMaskDS->m_bLeaderSizeAsUInt4 = bCopySrcOverviews;
    8899          27 :                 poDS->m_poMaskDS->m_bTrailerRepeatedLast4BytesRepeated =
    8900             :                     bCopySrcOverviews;
    8901          27 :                 GDALDestroyScaledProgress(pScaledData);
    8902             :                 pScaledData =
    8903          27 :                     GDALCreateScaledProgress(dfCurPixels / dfTotalPixels, 1.0,
    8904             :                                              pfnProgress, pProgressData);
    8905             :             }
    8906             : 
    8907         224 :             eErr = CopyImageryAndMask(poDS.get(), poSrcDS,
    8908         224 :                                       poSrcDS->GetRasterBand(1)->GetMaskBand(),
    8909             :                                       GDALScaledProgress, pScaledData);
    8910         224 :             if (poDS->m_poMaskDS)
    8911             :             {
    8912          27 :                 bWriteMask = false;
    8913             :             }
    8914             :         }
    8915             :         else
    8916             :         {
    8917        1907 :             eErr = GDALDatasetCopyWholeRaster(GDALDataset::ToHandle(poSrcDS),
    8918        1907 :                                               GDALDataset::ToHandle(poDS.get()),
    8919             :                                               papszCopyWholeRasterOptions,
    8920             :                                               GDALScaledProgress, pScaledData);
    8921             :         }
    8922             :     }
    8923             : 
    8924        2153 :     GDALDestroyScaledProgress(pScaledData);
    8925             : 
    8926        2153 :     if (eErr == CE_None && !bStreaming && bWriteMask)
    8927             :     {
    8928        2104 :         pScaledData = GDALCreateScaledProgress(dfNextCurPixels / dfTotalPixels,
    8929             :                                                1.0, pfnProgress, pProgressData);
    8930        2104 :         if (poDS->m_poMaskDS)
    8931             :         {
    8932          10 :             const char *l_papszOptions[2] = {"COMPRESSED=YES", nullptr};
    8933          10 :             eErr = GDALRasterBandCopyWholeRaster(
    8934          10 :                 poSrcDS->GetRasterBand(1)->GetMaskBand(),
    8935          10 :                 poDS->GetRasterBand(1)->GetMaskBand(),
    8936             :                 const_cast<char **>(l_papszOptions), GDALScaledProgress,
    8937             :                 pScaledData);
    8938             :         }
    8939             :         else
    8940             :         {
    8941        2094 :             eErr = GDALDriver::DefaultCopyMasks(poSrcDS, poDS.get(), bStrict,
    8942             :                                                 nullptr, GDALScaledProgress,
    8943             :                                                 pScaledData);
    8944             :         }
    8945        2104 :         GDALDestroyScaledProgress(pScaledData);
    8946             :     }
    8947             : 
    8948        2153 :     poDS->m_bWriteCOGLayout = false;
    8949             : 
    8950        4288 :     if (eErr == CE_None &&
    8951        2135 :         CPLTestBool(CSLFetchNameValueDef(poDS->m_papszCreationOptions,
    8952             :                                          "@FLUSHCACHE", "NO")))
    8953             :     {
    8954         175 :         if (poDS->FlushCache(false) != CE_None)
    8955             :         {
    8956           0 :             eErr = CE_Failure;
    8957             :         }
    8958             :     }
    8959             : 
    8960        2153 :     if (eErr == CE_Failure)
    8961             :     {
    8962          18 :         if (CPLTestBool(CPLGetConfigOption("GTIFF_DELETE_ON_ERROR", "YES")))
    8963             :         {
    8964          17 :             l_fpL->CancelCreation();
    8965          17 :             poDS.reset();
    8966             : 
    8967          17 :             if (!bStreaming)
    8968             :             {
    8969             :                 // Should really delete more carefully.
    8970          17 :                 VSIUnlink(pszFilename);
    8971             :             }
    8972             :         }
    8973             :         else
    8974             :         {
    8975           1 :             poDS.reset();
    8976             :         }
    8977             :     }
    8978             : 
    8979        2153 :     return poDS.release();
    8980             : }
    8981             : 
    8982             : /************************************************************************/
    8983             : /*                           SetSpatialRef()                            */
    8984             : /************************************************************************/
    8985             : 
    8986        1534 : CPLErr GTiffDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
    8987             : 
    8988             : {
    8989        1534 :     if (m_bStreamingOut && m_bCrystalized)
    8990             :     {
    8991           1 :         ReportError(CE_Failure, CPLE_NotSupported,
    8992             :                     "Cannot modify projection at that point in "
    8993             :                     "a streamed output file");
    8994           1 :         return CE_Failure;
    8995             :     }
    8996             : 
    8997        1533 :     LoadGeoreferencingAndPamIfNeeded();
    8998        1533 :     LookForProjection();
    8999             : 
    9000        1533 :     CPLErr eErr = CE_None;
    9001        1533 :     if (eAccess == GA_Update)
    9002             :     {
    9003        1535 :         if ((m_eProfile == GTiffProfile::BASELINE) &&
    9004           7 :             (GetPamFlags() & GPF_DISABLED) == 0)
    9005             :         {
    9006           7 :             eErr = GDALPamDataset::SetSpatialRef(poSRS);
    9007             :         }
    9008             :         else
    9009             :         {
    9010        1521 :             if (GDALPamDataset::GetSpatialRef() != nullptr)
    9011             :             {
    9012             :                 // Cancel any existing SRS from PAM file.
    9013           1 :                 GDALPamDataset::SetSpatialRef(nullptr);
    9014             :             }
    9015        1521 :             m_bGeoTIFFInfoChanged = true;
    9016             :         }
    9017             :     }
    9018             :     else
    9019             :     {
    9020           5 :         CPLDebug("GTIFF", "SetSpatialRef() goes to PAM instead of TIFF tags");
    9021           5 :         eErr = GDALPamDataset::SetSpatialRef(poSRS);
    9022             :     }
    9023             : 
    9024        1533 :     if (eErr == CE_None)
    9025             :     {
    9026        1533 :         if (poSRS == nullptr || poSRS->IsEmpty())
    9027             :         {
    9028          14 :             if (!m_oSRS.IsEmpty())
    9029             :             {
    9030           4 :                 m_bForceUnsetProjection = true;
    9031             :             }
    9032          14 :             m_oSRS.Clear();
    9033             :         }
    9034             :         else
    9035             :         {
    9036        1519 :             m_oSRS = *poSRS;
    9037        1519 :             m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    9038             :         }
    9039             :     }
    9040             : 
    9041        1533 :     return eErr;
    9042             : }
    9043             : 
    9044             : /************************************************************************/
    9045             : /*                          SetGeoTransform()                           */
    9046             : /************************************************************************/
    9047             : 
    9048        1862 : CPLErr GTiffDataset::SetGeoTransform(const GDALGeoTransform &gt)
    9049             : 
    9050             : {
    9051        1862 :     if (m_bStreamingOut && m_bCrystalized)
    9052             :     {
    9053           1 :         ReportError(CE_Failure, CPLE_NotSupported,
    9054             :                     "Cannot modify geotransform at that point in a "
    9055             :                     "streamed output file");
    9056           1 :         return CE_Failure;
    9057             :     }
    9058             : 
    9059        1861 :     LoadGeoreferencingAndPamIfNeeded();
    9060             : 
    9061        1861 :     CPLErr eErr = CE_None;
    9062        1861 :     if (eAccess == GA_Update)
    9063             :     {
    9064        1855 :         if (!m_aoGCPs.empty())
    9065             :         {
    9066           1 :             ReportError(CE_Warning, CPLE_AppDefined,
    9067             :                         "GCPs previously set are going to be cleared "
    9068             :                         "due to the setting of a geotransform.");
    9069           1 :             m_bForceUnsetGTOrGCPs = true;
    9070           1 :             m_aoGCPs.clear();
    9071             :         }
    9072        1854 :         else if (gt.xorig == 0.0 && gt.xscale == 0.0 && gt.xrot == 0.0 &&
    9073           2 :                  gt.yorig == 0.0 && gt.yrot == 0.0 && gt.yscale == 0.0)
    9074             :         {
    9075           2 :             if (m_bGeoTransformValid)
    9076             :             {
    9077           2 :                 m_bForceUnsetGTOrGCPs = true;
    9078           2 :                 m_bGeoTIFFInfoChanged = true;
    9079             :             }
    9080           2 :             m_bGeoTransformValid = false;
    9081           2 :             m_gt = gt;
    9082           2 :             return CE_None;
    9083             :         }
    9084             : 
    9085        3715 :         if ((m_eProfile == GTiffProfile::BASELINE) &&
    9086           9 :             !CPLFetchBool(m_papszCreationOptions, "TFW", false) &&
    9087        1867 :             !CPLFetchBool(m_papszCreationOptions, "WORLDFILE", false) &&
    9088           5 :             (GetPamFlags() & GPF_DISABLED) == 0)
    9089             :         {
    9090           5 :             eErr = GDALPamDataset::SetGeoTransform(gt);
    9091             :         }
    9092             :         else
    9093             :         {
    9094             :             // Cancel any existing geotransform from PAM file.
    9095        1848 :             GDALPamDataset::DeleteGeoTransform();
    9096        1848 :             m_bGeoTIFFInfoChanged = true;
    9097             :         }
    9098             :     }
    9099             :     else
    9100             :     {
    9101           6 :         CPLDebug("GTIFF", "SetGeoTransform() goes to PAM instead of TIFF tags");
    9102           6 :         eErr = GDALPamDataset::SetGeoTransform(gt);
    9103             :     }
    9104             : 
    9105        1859 :     if (eErr == CE_None)
    9106             :     {
    9107        1859 :         m_gt = gt;
    9108        1859 :         m_bGeoTransformValid = true;
    9109             :     }
    9110             : 
    9111        1859 :     return eErr;
    9112             : }
    9113             : 
    9114             : /************************************************************************/
    9115             : /*                              SetGCPs()                               */
    9116             : /************************************************************************/
    9117             : 
    9118          22 : CPLErr GTiffDataset::SetGCPs(int nGCPCountIn, const GDAL_GCP *pasGCPListIn,
    9119             :                              const OGRSpatialReference *poGCPSRS)
    9120             : {
    9121          22 :     CPLErr eErr = CE_None;
    9122          22 :     LoadGeoreferencingAndPamIfNeeded();
    9123          22 :     LookForProjection();
    9124             : 
    9125          22 :     if (eAccess == GA_Update)
    9126             :     {
    9127          20 :         if (!m_aoGCPs.empty() && nGCPCountIn == 0)
    9128             :         {
    9129           3 :             m_bForceUnsetGTOrGCPs = true;
    9130             :         }
    9131          17 :         else if (nGCPCountIn > 0 && m_bGeoTransformValid)
    9132             :         {
    9133           5 :             ReportError(CE_Warning, CPLE_AppDefined,
    9134             :                         "A geotransform previously set is going to be cleared "
    9135             :                         "due to the setting of GCPs.");
    9136           5 :             m_gt = GDALGeoTransform();
    9137           5 :             m_bGeoTransformValid = false;
    9138           5 :             m_bForceUnsetGTOrGCPs = true;
    9139             :         }
    9140          20 :         if ((m_eProfile == GTiffProfile::BASELINE) &&
    9141           0 :             (GetPamFlags() & GPF_DISABLED) == 0)
    9142             :         {
    9143           0 :             eErr = GDALPamDataset::SetGCPs(nGCPCountIn, pasGCPListIn, poGCPSRS);
    9144             :         }
    9145             :         else
    9146             :         {
    9147          20 :             if (nGCPCountIn > knMAX_GCP_COUNT)
    9148             :             {
    9149           2 :                 if (GDALPamDataset::GetGCPCount() == 0 && !m_aoGCPs.empty())
    9150             :                 {
    9151           1 :                     m_bForceUnsetGTOrGCPs = true;
    9152             :                 }
    9153           2 :                 ReportError(CE_Warning, CPLE_AppDefined,
    9154             :                             "Trying to write %d GCPs, whereas the maximum "
    9155             :                             "supported in GeoTIFF tag is %d. "
    9156             :                             "Falling back to writing them to PAM",
    9157             :                             nGCPCountIn, knMAX_GCP_COUNT);
    9158           2 :                 eErr = GDALPamDataset::SetGCPs(nGCPCountIn, pasGCPListIn,
    9159             :                                                poGCPSRS);
    9160             :             }
    9161          18 :             else if (GDALPamDataset::GetGCPCount() > 0)
    9162             :             {
    9163             :                 // Cancel any existing GCPs from PAM file.
    9164           1 :                 GDALPamDataset::SetGCPs(
    9165             :                     0, nullptr,
    9166             :                     static_cast<const OGRSpatialReference *>(nullptr));
    9167             :             }
    9168          20 :             m_bGeoTIFFInfoChanged = true;
    9169             :         }
    9170             :     }
    9171             :     else
    9172             :     {
    9173           2 :         CPLDebug("GTIFF", "SetGCPs() goes to PAM instead of TIFF tags");
    9174           2 :         eErr = GDALPamDataset::SetGCPs(nGCPCountIn, pasGCPListIn, poGCPSRS);
    9175             :     }
    9176             : 
    9177          22 :     if (eErr == CE_None)
    9178             :     {
    9179          22 :         if (poGCPSRS == nullptr || poGCPSRS->IsEmpty())
    9180             :         {
    9181          11 :             if (!m_oSRS.IsEmpty())
    9182             :             {
    9183           5 :                 m_bForceUnsetProjection = true;
    9184             :             }
    9185          11 :             m_oSRS.Clear();
    9186             :         }
    9187             :         else
    9188             :         {
    9189          11 :             m_oSRS = *poGCPSRS;
    9190          11 :             m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    9191             :         }
    9192             : 
    9193          22 :         m_aoGCPs = gdal::GCP::fromC(pasGCPListIn, nGCPCountIn);
    9194             :     }
    9195             : 
    9196          22 :     return eErr;
    9197             : }
    9198             : 
    9199             : /************************************************************************/
    9200             : /*                            SetMetadata()                             */
    9201             : /************************************************************************/
    9202        2747 : CPLErr GTiffDataset::SetMetadata(CSLConstList papszMD, const char *pszDomain)
    9203             : 
    9204             : {
    9205        2747 :     LoadGeoreferencingAndPamIfNeeded();
    9206             : 
    9207        2747 :     if (m_bStreamingOut && m_bCrystalized)
    9208             :     {
    9209           1 :         ReportError(
    9210             :             CE_Failure, CPLE_NotSupported,
    9211             :             "Cannot modify metadata at that point in a streamed output file");
    9212           1 :         return CE_Failure;
    9213             :     }
    9214             : 
    9215        2746 :     if (pszDomain && EQUAL(pszDomain, "json:ISIS3"))
    9216             :     {
    9217           5 :         m_oISIS3Metadata.Deinit();
    9218           5 :         m_oMapISIS3MetadataItems.clear();
    9219             :     }
    9220             : 
    9221        2746 :     CPLErr eErr = CE_None;
    9222        2746 :     if (eAccess == GA_Update)
    9223             :     {
    9224        2743 :         if (pszDomain != nullptr && EQUAL(pszDomain, MD_DOMAIN_RPC))
    9225             :         {
    9226             :             // So that a subsequent GetMetadata() wouldn't override our new
    9227             :             // values
    9228          22 :             LoadMetadata();
    9229          22 :             m_bForceUnsetRPC = (CSLCount(papszMD) == 0);
    9230             :         }
    9231             : 
    9232        2743 :         if ((papszMD != nullptr) && (pszDomain != nullptr) &&
    9233        1903 :             EQUAL(pszDomain, "COLOR_PROFILE"))
    9234             :         {
    9235           0 :             m_bColorProfileMetadataChanged = true;
    9236             :         }
    9237        2743 :         else if (pszDomain == nullptr || !EQUAL(pszDomain, "_temporary_"))
    9238             :         {
    9239        2743 :             m_bMetadataChanged = true;
    9240             :             // Cancel any existing metadata from PAM file.
    9241        2743 :             if (GDALPamDataset::GetMetadata(pszDomain) != nullptr)
    9242           1 :                 GDALPamDataset::SetMetadata(nullptr, pszDomain);
    9243             :         }
    9244             : 
    9245        5450 :         if ((pszDomain == nullptr || EQUAL(pszDomain, "")) &&
    9246        2707 :             CSLFetchNameValue(papszMD, GDALMD_AREA_OR_POINT) != nullptr)
    9247             :         {
    9248        2072 :             const char *pszPrevValue = GetMetadataItem(GDALMD_AREA_OR_POINT);
    9249             :             const char *pszNewValue =
    9250        2072 :                 CSLFetchNameValue(papszMD, GDALMD_AREA_OR_POINT);
    9251        2072 :             if (pszPrevValue == nullptr || pszNewValue == nullptr ||
    9252        1645 :                 !EQUAL(pszPrevValue, pszNewValue))
    9253             :             {
    9254         431 :                 LookForProjection();
    9255         431 :                 m_bGeoTIFFInfoChanged = true;
    9256             :             }
    9257             :         }
    9258             : 
    9259        2743 :         if (pszDomain != nullptr && EQUAL(pszDomain, "xml:XMP"))
    9260             :         {
    9261           2 :             if (papszMD != nullptr && *papszMD != nullptr)
    9262             :             {
    9263           1 :                 int nTagSize = static_cast<int>(strlen(*papszMD));
    9264           1 :                 TIFFSetField(m_hTIFF, TIFFTAG_XMLPACKET, nTagSize, *papszMD);
    9265             :             }
    9266             :             else
    9267             :             {
    9268           1 :                 TIFFUnsetField(m_hTIFF, TIFFTAG_XMLPACKET);
    9269             :             }
    9270             :         }
    9271             :     }
    9272             :     else
    9273             :     {
    9274           3 :         CPLDebug(
    9275             :             "GTIFF",
    9276             :             "GTiffDataset::SetMetadata() goes to PAM instead of TIFF tags");
    9277           3 :         eErr = GDALPamDataset::SetMetadata(papszMD, pszDomain);
    9278             :     }
    9279             : 
    9280        2746 :     if (eErr == CE_None)
    9281             :     {
    9282        2746 :         eErr = m_oGTiffMDMD.SetMetadata(papszMD, pszDomain);
    9283             :     }
    9284        2746 :     return eErr;
    9285             : }
    9286             : 
    9287             : /************************************************************************/
    9288             : /*                          SetMetadataItem()                           */
    9289             : /************************************************************************/
    9290             : 
    9291        5922 : CPLErr GTiffDataset::SetMetadataItem(const char *pszName, const char *pszValue,
    9292             :                                      const char *pszDomain)
    9293             : 
    9294             : {
    9295        5922 :     LoadGeoreferencingAndPamIfNeeded();
    9296             : 
    9297        5922 :     if (m_bStreamingOut && m_bCrystalized)
    9298             :     {
    9299           1 :         ReportError(
    9300             :             CE_Failure, CPLE_NotSupported,
    9301             :             "Cannot modify metadata at that point in a streamed output file");
    9302           1 :         return CE_Failure;
    9303             :     }
    9304             : 
    9305        5921 :     if (pszDomain && EQUAL(pszDomain, "json:ISIS3"))
    9306             :     {
    9307           1 :         ReportError(CE_Failure, CPLE_NotSupported,
    9308             :                     "Updating part of json:ISIS3 is not supported. "
    9309             :                     "Use SetMetadata() instead");
    9310           1 :         return CE_Failure;
    9311             :     }
    9312             : 
    9313        5920 :     CPLErr eErr = CE_None;
    9314        5920 :     if (eAccess == GA_Update)
    9315             :     {
    9316        5913 :         if ((pszDomain != nullptr) && EQUAL(pszDomain, "COLOR_PROFILE"))
    9317             :         {
    9318           8 :             m_bColorProfileMetadataChanged = true;
    9319             :         }
    9320        5905 :         else if (pszDomain == nullptr || !EQUAL(pszDomain, "_temporary_"))
    9321             :         {
    9322        5905 :             m_bMetadataChanged = true;
    9323             :             // Cancel any existing metadata from PAM file.
    9324        5905 :             if (GDALPamDataset::GetMetadataItem(pszName, pszDomain) != nullptr)
    9325           1 :                 GDALPamDataset::SetMetadataItem(pszName, nullptr, pszDomain);
    9326             :         }
    9327             : 
    9328        5913 :         if ((pszDomain == nullptr || EQUAL(pszDomain, "")) &&
    9329          84 :             pszName != nullptr && EQUAL(pszName, GDALMD_AREA_OR_POINT))
    9330             :         {
    9331           7 :             LookForProjection();
    9332           7 :             m_bGeoTIFFInfoChanged = true;
    9333             :         }
    9334             :     }
    9335             :     else
    9336             :     {
    9337           7 :         CPLDebug(
    9338             :             "GTIFF",
    9339             :             "GTiffDataset::SetMetadataItem() goes to PAM instead of TIFF tags");
    9340           7 :         eErr = GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    9341             :     }
    9342             : 
    9343        5920 :     if (eErr == CE_None)
    9344             :     {
    9345        5920 :         eErr = m_oGTiffMDMD.SetMetadataItem(pszName, pszValue, pszDomain);
    9346             :     }
    9347             : 
    9348        5920 :     return eErr;
    9349             : }
    9350             : 
    9351             : /************************************************************************/
    9352             : /*                           CreateMaskBand()                           */
    9353             : /************************************************************************/
    9354             : 
    9355         100 : CPLErr GTiffDataset::CreateMaskBand(int nFlagsIn)
    9356             : {
    9357         100 :     ScanDirectories();
    9358             : 
    9359         100 :     if (m_poMaskDS != nullptr)
    9360             :     {
    9361           1 :         ReportError(CE_Failure, CPLE_AppDefined,
    9362             :                     "This TIFF dataset already has an internal mask band");
    9363           1 :         return CE_Failure;
    9364             :     }
    9365          99 :     else if (MustCreateInternalMask())
    9366             :     {
    9367          86 :         if (nFlagsIn != GMF_PER_DATASET)
    9368             :         {
    9369           1 :             ReportError(CE_Failure, CPLE_AppDefined,
    9370             :                         "The only flag value supported for internal mask is "
    9371             :                         "GMF_PER_DATASET");
    9372           1 :             return CE_Failure;
    9373             :         }
    9374             : 
    9375          85 :         int l_nCompression = COMPRESSION_PACKBITS;
    9376          85 :         if (strstr(GDALGetMetadataItem(GDALGetDriverByName("GTiff"),
    9377             :                                        GDAL_DMD_CREATIONOPTIONLIST, nullptr),
    9378          85 :                    "<Value>DEFLATE</Value>") != nullptr)
    9379          85 :             l_nCompression = COMPRESSION_ADOBE_DEFLATE;
    9380             : 
    9381             :         /* --------------------------------------------------------------------
    9382             :          */
    9383             :         /*      If we don't have read access, then create the mask externally.
    9384             :          */
    9385             :         /* --------------------------------------------------------------------
    9386             :          */
    9387          85 :         if (GetAccess() != GA_Update)
    9388             :         {
    9389           1 :             ReportError(CE_Warning, CPLE_AppDefined,
    9390             :                         "File open for read-only accessing, "
    9391             :                         "creating mask externally.");
    9392             : 
    9393           1 :             return GDALPamDataset::CreateMaskBand(nFlagsIn);
    9394             :         }
    9395             : 
    9396          84 :         if (m_bLayoutIFDSBeforeData && !m_bKnownIncompatibleEdition &&
    9397           0 :             !m_bWriteKnownIncompatibleEdition)
    9398             :         {
    9399           0 :             ReportError(CE_Warning, CPLE_AppDefined,
    9400             :                         "Adding a mask invalidates the "
    9401             :                         "LAYOUT=IFDS_BEFORE_DATA property");
    9402           0 :             m_bKnownIncompatibleEdition = true;
    9403           0 :             m_bWriteKnownIncompatibleEdition = true;
    9404             :         }
    9405             : 
    9406          84 :         bool bIsOverview = false;
    9407          84 :         uint32_t nSubType = 0;
    9408          84 :         if (TIFFGetField(m_hTIFF, TIFFTAG_SUBFILETYPE, &nSubType))
    9409             :         {
    9410           8 :             bIsOverview = (nSubType & FILETYPE_REDUCEDIMAGE) != 0;
    9411             : 
    9412           8 :             if ((nSubType & FILETYPE_MASK) != 0)
    9413             :             {
    9414           0 :                 ReportError(CE_Failure, CPLE_AppDefined,
    9415             :                             "Cannot create a mask on a TIFF mask IFD !");
    9416           0 :                 return CE_Failure;
    9417             :             }
    9418             :         }
    9419             : 
    9420          84 :         const int bIsTiled = TIFFIsTiled(m_hTIFF);
    9421             : 
    9422          84 :         FlushDirectory();
    9423             : 
    9424          84 :         const toff_t nOffset = GTIFFWriteDirectory(
    9425             :             m_hTIFF,
    9426             :             bIsOverview ? FILETYPE_REDUCEDIMAGE | FILETYPE_MASK : FILETYPE_MASK,
    9427             :             nRasterXSize, nRasterYSize, 1, PLANARCONFIG_CONTIG, 1,
    9428             :             m_nBlockXSize, m_nBlockYSize, bIsTiled, l_nCompression,
    9429             :             PHOTOMETRIC_MASK, PREDICTOR_NONE, SAMPLEFORMAT_UINT, nullptr,
    9430             :             nullptr, nullptr, 0, nullptr, "", nullptr, nullptr, nullptr,
    9431          84 :             nullptr, m_bWriteCOGLayout);
    9432             : 
    9433          84 :         ReloadDirectory();
    9434             : 
    9435          84 :         if (nOffset == 0)
    9436           0 :             return CE_Failure;
    9437             : 
    9438          84 :         m_poMaskDS = std::make_shared<GTiffDataset>();
    9439          84 :         m_poMaskDS->eAccess = GA_Update;
    9440          84 :         m_poMaskDS->m_poBaseDS = this;
    9441          84 :         m_poMaskDS->m_poImageryDS = this;
    9442          84 :         m_poMaskDS->ShareLockWithParentDataset(this);
    9443          84 :         m_poMaskDS->m_osFilename = m_osFilename;
    9444          84 :         m_poMaskDS->m_bPromoteTo8Bits = CPLTestBool(
    9445             :             CPLGetConfigOption("GDAL_TIFF_INTERNAL_MASK_TO_8BIT", "YES"));
    9446          84 :         return m_poMaskDS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF), nOffset,
    9447          84 :                                       GA_Update);
    9448             :     }
    9449             : 
    9450          13 :     return GDALPamDataset::CreateMaskBand(nFlagsIn);
    9451             : }
    9452             : 
    9453             : /************************************************************************/
    9454             : /*                       MustCreateInternalMask()                       */
    9455             : /************************************************************************/
    9456             : 
    9457         137 : bool GTiffDataset::MustCreateInternalMask()
    9458             : {
    9459         137 :     return CPLTestBool(CPLGetConfigOption("GDAL_TIFF_INTERNAL_MASK", "YES"));
    9460             : }
    9461             : 
    9462             : /************************************************************************/
    9463             : /*                           CreateMaskBand()                           */
    9464             : /************************************************************************/
    9465             : 
    9466          29 : CPLErr GTiffRasterBand::CreateMaskBand(int nFlagsIn)
    9467             : {
    9468          29 :     m_poGDS->ScanDirectories();
    9469             : 
    9470          29 :     if (m_poGDS->m_poMaskDS != nullptr)
    9471             :     {
    9472           5 :         ReportError(CE_Failure, CPLE_AppDefined,
    9473             :                     "This TIFF dataset already has an internal mask band");
    9474           5 :         return CE_Failure;
    9475             :     }
    9476             : 
    9477             :     const char *pszGDAL_TIFF_INTERNAL_MASK =
    9478          24 :         CPLGetConfigOption("GDAL_TIFF_INTERNAL_MASK", nullptr);
    9479          27 :     if ((pszGDAL_TIFF_INTERNAL_MASK &&
    9480          24 :          CPLTestBool(pszGDAL_TIFF_INTERNAL_MASK)) ||
    9481             :         nFlagsIn == GMF_PER_DATASET)
    9482             :     {
    9483          16 :         return m_poGDS->CreateMaskBand(nFlagsIn);
    9484             :     }
    9485             : 
    9486           8 :     return GDALPamRasterBand::CreateMaskBand(nFlagsIn);
    9487             : }
    9488             : 
    9489             : /************************************************************************/
    9490             : /*                            ClampCTEntry()                            */
    9491             : /************************************************************************/
    9492             : 
    9493      236415 : /* static */ unsigned short GTiffDataset::ClampCTEntry(int iColor, int iComp,
    9494             :                                                        int nCTEntryVal,
    9495             :                                                        int nMultFactor)
    9496             : {
    9497      236415 :     const int nVal = nCTEntryVal * nMultFactor;
    9498      236415 :     if (nVal < 0)
    9499             :     {
    9500           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9501             :                  "Color table entry [%d][%d] = %d, clamped to 0", iColor, iComp,
    9502             :                  nCTEntryVal);
    9503           0 :         return 0;
    9504             :     }
    9505      236415 :     if (nVal > 65535)
    9506             :     {
    9507           2 :         CPLError(CE_Warning, CPLE_AppDefined,
    9508             :                  "Color table entry [%d][%d] = %d, clamped to 65535", iColor,
    9509             :                  iComp, nCTEntryVal);
    9510           2 :         return 65535;
    9511             :     }
    9512      236413 :     return static_cast<unsigned short>(nVal);
    9513             : }

Generated by: LCOV version 1.14