Coverage Report

Created: 2025-06-13 06:29

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