Coverage Report

Created: 2025-08-28 06:57

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