LCOV - code coverage report
Current view: top level - frmts/gtiff - gtiffdataset_write.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 3750 4091 91.7 %
Date: 2025-05-31 00:00:17 Functions: 108 136 79.4 %

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

Generated by: LCOV version 1.14