Coverage Report

Created: 2026-07-25 06:50

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