Coverage Report

Created: 2025-12-31 06:48

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