Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: GeoTIFF Driver
4 : * Purpose: Write/set operations on GTiffDataset
5 : * Author: Frank Warmerdam, warmerdam@pobox.com
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 1998, 2002, Frank Warmerdam <warmerdam@pobox.com>
9 : * Copyright (c) 2007-2015, Even Rouault <even dot rouault at spatialys dot com>
10 : *
11 : * SPDX-License-Identifier: MIT
12 : ****************************************************************************/
13 :
14 : #include "gtiffdataset.h"
15 : #include "gtiffrasterband.h"
16 : #include "gtiffoddbitsband.h"
17 : #include "gtiffjpegoverviewds.h"
18 :
19 : #include <cassert>
20 : #include <cerrno>
21 :
22 : #include <algorithm>
23 : #include <cmath>
24 : #include <limits>
25 : #include <memory>
26 : #include <mutex>
27 : #include <set>
28 : #include <string>
29 : #include <tuple>
30 : #include <utility>
31 :
32 : #include "cpl_error.h"
33 : #include "cpl_error_internal.h" // CPLErrorHandlerAccumulatorStruct
34 : #include "cpl_float.h"
35 : #include "cpl_md5.h"
36 : #include "cpl_vsi.h"
37 : #include "cpl_vsi_virtual.h"
38 : #include "cpl_worker_thread_pool.h"
39 : #include "fetchbufferdirectio.h"
40 : #include "gdal_mdreader.h" // GDALWriteRPCTXTFile()
41 : #include "gdal_priv.h"
42 : #include "gdal_priv_templates.hpp" // GDALIsValueInRange<>
43 : #include "gdal_thread_pool.h" // GDALGetGlobalThreadPool()
44 : #include "geovalues.h" // RasterPixelIsPoint
45 : #include "gt_jpeg_copy.h"
46 : #include "gt_overview.h" // GTIFFBuildOverviewMetadata()
47 : #include "quant_table_md5sum.h"
48 : #include "quant_table_md5sum_jpeg9e.h"
49 : #include "tif_jxl.h"
50 : #include "tifvsi.h"
51 : #include "xtiffio.h"
52 :
53 : #if LIFFLIB_VERSION > 20230908 || defined(INTERNAL_LIBTIFF)
54 : /* libtiff < 4.6.1 doesn't generate a LERC mask for multi-band contig configuration */
55 : #define LIBTIFF_MULTIBAND_LERC_NAN_OK
56 : #endif
57 :
58 : static const int knGTIFFJpegTablesModeDefault = JPEGTABLESMODE_QUANT;
59 :
60 : static constexpr const char szPROFILE_BASELINE[] = "BASELINE";
61 : static constexpr const char szPROFILE_GeoTIFF[] = "GeoTIFF";
62 : static constexpr const char szPROFILE_GDALGeoTIFF[] = "GDALGeoTIFF";
63 :
64 : // Due to libgeotiff/xtiff.c declaring TIFFTAG_GEOTIEPOINTS with field_readcount
65 : // and field_writecount == -1 == TIFF_VARIABLE, we are limited to writing
66 : // 65535 values in that tag. That could potentially be overcome by changing the tag
67 : // declaration to using TIFF_VARIABLE2 where the count is a uint32_t.
68 : constexpr int knMAX_GCP_COUNT =
69 : static_cast<int>(std::numeric_limits<uint16_t>::max() / 6);
70 :
71 : enum
72 : {
73 : ENDIANNESS_NATIVE,
74 : ENDIANNESS_LITTLE,
75 : ENDIANNESS_BIG
76 : };
77 :
78 17720 : static signed char GTiffGetWebPLevel(CSLConstList papszOptions)
79 : {
80 17720 : int nWebPLevel = DEFAULT_WEBP_LEVEL;
81 17720 : const char *pszValue = CSLFetchNameValue(papszOptions, "WEBP_LEVEL");
82 17720 : if (pszValue != nullptr)
83 : {
84 51 : nWebPLevel = atoi(pszValue);
85 51 : if (!(nWebPLevel >= 1 && nWebPLevel <= 100))
86 : {
87 0 : CPLError(CE_Warning, CPLE_IllegalArg,
88 : "WEBP_LEVEL=%s value not recognised, ignoring.", pszValue);
89 0 : nWebPLevel = DEFAULT_WEBP_LEVEL;
90 : }
91 : }
92 17720 : return static_cast<signed char>(nWebPLevel);
93 : }
94 :
95 17726 : static bool GTiffGetWebPLossless(CSLConstList papszOptions)
96 : {
97 17726 : return CPLFetchBool(papszOptions, "WEBP_LOSSLESS", false);
98 : }
99 :
100 17792 : static double GTiffGetLERCMaxZError(CSLConstList papszOptions)
101 : {
102 17792 : return CPLAtof(CSLFetchNameValueDef(papszOptions, "MAX_Z_ERROR", "0.0"));
103 : }
104 :
105 7933 : static double GTiffGetLERCMaxZErrorOverview(CSLConstList papszOptions)
106 : {
107 7933 : return CPLAtof(CSLFetchNameValueDef(
108 : papszOptions, "MAX_Z_ERROR_OVERVIEW",
109 7933 : CSLFetchNameValueDef(papszOptions, "MAX_Z_ERROR", "0.0")));
110 : }
111 :
112 : #if HAVE_JXL
113 17796 : static bool GTiffGetJXLLossless(CSLConstList papszOptions,
114 : bool *pbIsSpecified = nullptr)
115 : {
116 17796 : const char *pszVal = CSLFetchNameValue(papszOptions, "JXL_LOSSLESS");
117 17796 : if (pbIsSpecified)
118 9859 : *pbIsSpecified = pszVal != nullptr;
119 17796 : return pszVal == nullptr || CPLTestBool(pszVal);
120 : }
121 :
122 17796 : static uint32_t GTiffGetJXLEffort(CSLConstList papszOptions)
123 : {
124 17796 : return atoi(CSLFetchNameValueDef(papszOptions, "JXL_EFFORT", "5"));
125 : }
126 :
127 17714 : static float GTiffGetJXLDistance(CSLConstList papszOptions,
128 : bool *pbIsSpecified = nullptr)
129 : {
130 17714 : const char *pszVal = CSLFetchNameValue(papszOptions, "JXL_DISTANCE");
131 17714 : if (pbIsSpecified)
132 9859 : *pbIsSpecified = pszVal != nullptr;
133 17714 : return pszVal == nullptr ? 1.0f : static_cast<float>(CPLAtof(pszVal));
134 : }
135 :
136 17796 : static float GTiffGetJXLAlphaDistance(CSLConstList papszOptions,
137 : bool *pbIsSpecified = nullptr)
138 : {
139 17796 : const char *pszVal = CSLFetchNameValue(papszOptions, "JXL_ALPHA_DISTANCE");
140 17796 : if (pbIsSpecified)
141 9859 : *pbIsSpecified = pszVal != nullptr;
142 17796 : return pszVal == nullptr ? -1.0f : static_cast<float>(CPLAtof(pszVal));
143 : }
144 :
145 : #endif
146 :
147 : /************************************************************************/
148 : /* FillEmptyTiles() */
149 : /************************************************************************/
150 :
151 8116 : CPLErr GTiffDataset::FillEmptyTiles()
152 :
153 : {
154 : /* -------------------------------------------------------------------- */
155 : /* How many blocks are there in this file? */
156 : /* -------------------------------------------------------------------- */
157 16232 : const int nBlockCount = m_nPlanarConfig == PLANARCONFIG_SEPARATE
158 8116 : ? m_nBlocksPerBand * nBands
159 : : m_nBlocksPerBand;
160 :
161 : /* -------------------------------------------------------------------- */
162 : /* Fetch block maps. */
163 : /* -------------------------------------------------------------------- */
164 8116 : toff_t *panByteCounts = nullptr;
165 :
166 8116 : if (TIFFIsTiled(m_hTIFF))
167 1127 : TIFFGetField(m_hTIFF, TIFFTAG_TILEBYTECOUNTS, &panByteCounts);
168 : else
169 6989 : TIFFGetField(m_hTIFF, TIFFTAG_STRIPBYTECOUNTS, &panByteCounts);
170 :
171 8116 : if (panByteCounts == nullptr)
172 : {
173 : // Got here with libtiff 3.9.3 and tiff_write_8 test.
174 0 : ReportError(CE_Failure, CPLE_AppDefined,
175 : "FillEmptyTiles() failed because panByteCounts == NULL");
176 0 : return CE_Failure;
177 : }
178 :
179 : /* -------------------------------------------------------------------- */
180 : /* Prepare a blank data buffer to write for uninitialized blocks. */
181 : /* -------------------------------------------------------------------- */
182 : const GPtrDiff_t nBlockBytes =
183 8116 : TIFFIsTiled(m_hTIFF) ? static_cast<GPtrDiff_t>(TIFFTileSize(m_hTIFF))
184 6989 : : static_cast<GPtrDiff_t>(TIFFStripSize(m_hTIFF));
185 :
186 8116 : GByte *pabyData = static_cast<GByte *>(VSI_CALLOC_VERBOSE(nBlockBytes, 1));
187 8116 : if (pabyData == nullptr)
188 : {
189 0 : return CE_Failure;
190 : }
191 :
192 : // Force tiles completely filled with the nodata value to be written.
193 8116 : m_bWriteEmptyTiles = true;
194 :
195 : /* -------------------------------------------------------------------- */
196 : /* If set, fill data buffer with no data value. */
197 : /* -------------------------------------------------------------------- */
198 8116 : if ((m_bNoDataSet && m_dfNoDataValue != 0.0) ||
199 7848 : (m_bNoDataSetAsInt64 && m_nNoDataValueInt64 != 0) ||
200 7843 : (m_bNoDataSetAsUInt64 && m_nNoDataValueUInt64 != 0))
201 : {
202 278 : const GDALDataType eDataType = GetRasterBand(1)->GetRasterDataType();
203 278 : const int nDataTypeSize = GDALGetDataTypeSizeBytes(eDataType);
204 278 : if (nDataTypeSize &&
205 278 : nDataTypeSize * 8 == static_cast<int>(m_nBitsPerSample))
206 : {
207 267 : if (m_bNoDataSetAsInt64)
208 : {
209 6 : GDALCopyWords64(&m_nNoDataValueInt64, GDT_Int64, 0, pabyData,
210 : eDataType, nDataTypeSize,
211 6 : nBlockBytes / nDataTypeSize);
212 : }
213 261 : else if (m_bNoDataSetAsUInt64)
214 : {
215 5 : GDALCopyWords64(&m_nNoDataValueUInt64, GDT_UInt64, 0, pabyData,
216 : eDataType, nDataTypeSize,
217 5 : nBlockBytes / nDataTypeSize);
218 : }
219 : else
220 : {
221 256 : double dfNoData = m_dfNoDataValue;
222 256 : GDALCopyWords64(&dfNoData, GDT_Float64, 0, pabyData, eDataType,
223 256 : nDataTypeSize, nBlockBytes / nDataTypeSize);
224 267 : }
225 : }
226 11 : else if (nDataTypeSize)
227 : {
228 : // Handle non power-of-two depths.
229 : // Ideally make a packed buffer, but that is a bit tedious,
230 : // so use the normal I/O interfaces.
231 :
232 11 : CPLFree(pabyData);
233 :
234 11 : pabyData = static_cast<GByte *>(VSI_MALLOC3_VERBOSE(
235 : m_nBlockXSize, m_nBlockYSize, nDataTypeSize));
236 11 : if (pabyData == nullptr)
237 0 : return CE_Failure;
238 11 : if (m_bNoDataSetAsInt64)
239 : {
240 0 : GDALCopyWords64(&m_nNoDataValueInt64, GDT_Int64, 0, pabyData,
241 : eDataType, nDataTypeSize,
242 0 : static_cast<GPtrDiff_t>(m_nBlockXSize) *
243 0 : m_nBlockYSize);
244 : }
245 11 : else if (m_bNoDataSetAsUInt64)
246 : {
247 0 : GDALCopyWords64(&m_nNoDataValueUInt64, GDT_UInt64, 0, pabyData,
248 : eDataType, nDataTypeSize,
249 0 : static_cast<GPtrDiff_t>(m_nBlockXSize) *
250 0 : m_nBlockYSize);
251 : }
252 : else
253 : {
254 11 : GDALCopyWords64(&m_dfNoDataValue, GDT_Float64, 0, pabyData,
255 : eDataType, nDataTypeSize,
256 11 : static_cast<GPtrDiff_t>(m_nBlockXSize) *
257 11 : m_nBlockYSize);
258 : }
259 11 : CPLErr eErr = CE_None;
260 46 : for (int iBlock = 0; iBlock < nBlockCount; ++iBlock)
261 : {
262 35 : if (panByteCounts[iBlock] == 0)
263 : {
264 18 : if (m_nPlanarConfig == PLANARCONFIG_SEPARATE || nBands == 1)
265 : {
266 24 : if (GetRasterBand(1 + iBlock / m_nBlocksPerBand)
267 12 : ->WriteBlock((iBlock % m_nBlocksPerBand) %
268 12 : m_nBlocksPerRow,
269 12 : (iBlock % m_nBlocksPerBand) /
270 12 : m_nBlocksPerRow,
271 12 : pabyData) != CE_None)
272 : {
273 0 : eErr = CE_Failure;
274 : }
275 : }
276 : else
277 : {
278 : // In contig case, don't directly call WriteBlock(), as
279 : // it could cause useless decompression-recompression.
280 6 : const int nXOff =
281 6 : (iBlock % m_nBlocksPerRow) * m_nBlockXSize;
282 6 : const int nYOff =
283 6 : (iBlock / m_nBlocksPerRow) * m_nBlockYSize;
284 6 : const int nXSize =
285 6 : (nXOff + m_nBlockXSize <= nRasterXSize)
286 6 : ? m_nBlockXSize
287 2 : : nRasterXSize - nXOff;
288 6 : const int nYSize =
289 6 : (nYOff + m_nBlockYSize <= nRasterYSize)
290 6 : ? m_nBlockYSize
291 3 : : nRasterYSize - nYOff;
292 18 : for (int iBand = 1; iBand <= nBands; ++iBand)
293 : {
294 12 : if (GetRasterBand(iBand)->RasterIO(
295 : GF_Write, nXOff, nYOff, nXSize, nYSize,
296 : pabyData, nXSize, nYSize, eDataType, 0, 0,
297 12 : nullptr) != CE_None)
298 : {
299 0 : eErr = CE_Failure;
300 : }
301 : }
302 : }
303 : }
304 : }
305 11 : CPLFree(pabyData);
306 11 : return eErr;
307 267 : }
308 : }
309 :
310 : /* -------------------------------------------------------------------- */
311 : /* When we must fill with zeroes, try to create non-sparse file */
312 : /* w.r.t TIFF spec ... as a sparse file w.r.t filesystem, ie by */
313 : /* seeking to end of file instead of writing zero blocks. */
314 : /* -------------------------------------------------------------------- */
315 7838 : else if (m_nCompression == COMPRESSION_NONE && (m_nBitsPerSample % 8) == 0)
316 : {
317 6293 : CPLErr eErr = CE_None;
318 : // Only use libtiff to write the first sparse block to ensure that it
319 : // will serialize offset and count arrays back to disk.
320 6293 : int nCountBlocksToZero = 0;
321 2321560 : for (int iBlock = 0; iBlock < nBlockCount; ++iBlock)
322 : {
323 2315270 : if (panByteCounts[iBlock] == 0)
324 : {
325 2219800 : if (nCountBlocksToZero == 0)
326 : {
327 1117 : const bool bWriteEmptyTilesBak = m_bWriteEmptyTiles;
328 1117 : m_bWriteEmptyTiles = true;
329 1117 : const bool bOK = WriteEncodedTileOrStrip(iBlock, pabyData,
330 1117 : FALSE) == CE_None;
331 1117 : m_bWriteEmptyTiles = bWriteEmptyTilesBak;
332 1117 : if (!bOK)
333 : {
334 2 : eErr = CE_Failure;
335 2 : break;
336 : }
337 : }
338 2219800 : nCountBlocksToZero++;
339 : }
340 : }
341 6293 : CPLFree(pabyData);
342 :
343 6293 : --nCountBlocksToZero;
344 :
345 : // And then seek to end of file for other ones.
346 6293 : if (nCountBlocksToZero > 0)
347 : {
348 337 : toff_t *panByteOffsets = nullptr;
349 :
350 337 : if (TIFFIsTiled(m_hTIFF))
351 92 : TIFFGetField(m_hTIFF, TIFFTAG_TILEOFFSETS, &panByteOffsets);
352 : else
353 245 : TIFFGetField(m_hTIFF, TIFFTAG_STRIPOFFSETS, &panByteOffsets);
354 :
355 337 : if (panByteOffsets == nullptr)
356 : {
357 0 : ReportError(
358 : CE_Failure, CPLE_AppDefined,
359 : "FillEmptyTiles() failed because panByteOffsets == NULL");
360 0 : return CE_Failure;
361 : }
362 :
363 337 : VSILFILE *fpTIF = VSI_TIFFGetVSILFile(TIFFClientdata(m_hTIFF));
364 337 : VSIFSeekL(fpTIF, 0, SEEK_END);
365 337 : const vsi_l_offset nOffset = VSIFTellL(fpTIF);
366 :
367 337 : vsi_l_offset iBlockToZero = 0;
368 2227900 : for (int iBlock = 0; iBlock < nBlockCount; ++iBlock)
369 : {
370 2227560 : if (panByteCounts[iBlock] == 0)
371 : {
372 2218680 : panByteOffsets[iBlock] = static_cast<toff_t>(
373 2218680 : nOffset + iBlockToZero * nBlockBytes);
374 2218680 : panByteCounts[iBlock] = nBlockBytes;
375 2218680 : iBlockToZero++;
376 : }
377 : }
378 337 : CPLAssert(iBlockToZero ==
379 : static_cast<vsi_l_offset>(nCountBlocksToZero));
380 :
381 337 : if (VSIFTruncateL(fpTIF, nOffset + iBlockToZero * nBlockBytes) != 0)
382 : {
383 0 : eErr = CE_Failure;
384 0 : ReportError(CE_Failure, CPLE_FileIO,
385 : "Cannot initialize empty blocks");
386 : }
387 : }
388 :
389 6293 : return eErr;
390 : }
391 :
392 : /* -------------------------------------------------------------------- */
393 : /* Check all blocks, writing out data for uninitialized blocks. */
394 : /* -------------------------------------------------------------------- */
395 :
396 1812 : GByte *pabyRaw = nullptr;
397 1812 : vsi_l_offset nRawSize = 0;
398 1812 : CPLErr eErr = CE_None;
399 56289 : for (int iBlock = 0; iBlock < nBlockCount; ++iBlock)
400 : {
401 54484 : if (panByteCounts[iBlock] == 0)
402 : {
403 17502 : if (pabyRaw == nullptr)
404 : {
405 10159 : if (WriteEncodedTileOrStrip(iBlock, pabyData, FALSE) != CE_None)
406 : {
407 7 : eErr = CE_Failure;
408 7 : break;
409 : }
410 :
411 10152 : vsi_l_offset nOffset = 0;
412 10152 : if (!IsBlockAvailable(iBlock, &nOffset, &nRawSize, nullptr))
413 0 : break;
414 :
415 : // When using compression, get back the compressed block
416 : // so we can use the raw API to write it faster.
417 10152 : if (m_nCompression != COMPRESSION_NONE)
418 : {
419 : pabyRaw = static_cast<GByte *>(
420 478 : VSI_MALLOC_VERBOSE(static_cast<size_t>(nRawSize)));
421 478 : if (pabyRaw)
422 : {
423 : VSILFILE *fp =
424 478 : VSI_TIFFGetVSILFile(TIFFClientdata(m_hTIFF));
425 478 : const vsi_l_offset nCurOffset = VSIFTellL(fp);
426 478 : VSIFSeekL(fp, nOffset, SEEK_SET);
427 478 : VSIFReadL(pabyRaw, 1, static_cast<size_t>(nRawSize),
428 : fp);
429 478 : VSIFSeekL(fp, nCurOffset, SEEK_SET);
430 : }
431 : }
432 : }
433 : else
434 : {
435 7343 : WriteRawStripOrTile(iBlock, pabyRaw,
436 : static_cast<GPtrDiff_t>(nRawSize));
437 : }
438 : }
439 : }
440 :
441 1812 : CPLFree(pabyData);
442 1812 : VSIFree(pabyRaw);
443 1812 : return eErr;
444 : }
445 :
446 : /************************************************************************/
447 : /* HasOnlyNoData() */
448 : /************************************************************************/
449 :
450 42785 : bool GTiffDataset::HasOnlyNoData(const void *pBuffer, int nWidth, int nHeight,
451 : int nLineStride, int nComponents)
452 : {
453 42785 : if (m_nSampleFormat == SAMPLEFORMAT_COMPLEXINT ||
454 42785 : m_nSampleFormat == SAMPLEFORMAT_COMPLEXIEEEFP)
455 0 : return false;
456 42785 : if (m_bNoDataSetAsInt64 || m_bNoDataSetAsUInt64)
457 6 : return false; // FIXME: over pessimistic
458 85558 : return GDALBufferHasOnlyNoData(
459 42779 : pBuffer, m_bNoDataSet ? m_dfNoDataValue : 0.0, nWidth, nHeight,
460 42779 : nLineStride, nComponents, m_nBitsPerSample,
461 42779 : m_nSampleFormat == SAMPLEFORMAT_UINT ? GSF_UNSIGNED_INT
462 4824 : : m_nSampleFormat == SAMPLEFORMAT_INT ? GSF_SIGNED_INT
463 42779 : : GSF_FLOATING_POINT);
464 : }
465 :
466 : /************************************************************************/
467 : /* IsFirstPixelEqualToNoData() */
468 : /************************************************************************/
469 :
470 169271 : inline bool GTiffDataset::IsFirstPixelEqualToNoData(const void *pBuffer)
471 : {
472 169271 : const GDALDataType eDT = GetRasterBand(1)->GetRasterDataType();
473 169271 : const double dfEffectiveNoData = (m_bNoDataSet) ? m_dfNoDataValue : 0.0;
474 169271 : if (m_bNoDataSetAsInt64 || m_bNoDataSetAsUInt64)
475 10 : return true; // FIXME: over pessimistic
476 169261 : if (m_nBitsPerSample == 8 ||
477 58898 : (m_nBitsPerSample < 8 && dfEffectiveNoData == 0))
478 : {
479 113809 : if (eDT == GDT_Int8)
480 : {
481 278 : return GDALIsValueInRange<signed char>(dfEffectiveNoData) &&
482 139 : *(static_cast<const signed char *>(pBuffer)) ==
483 278 : static_cast<signed char>(dfEffectiveNoData);
484 : }
485 227309 : return GDALIsValueInRange<GByte>(dfEffectiveNoData) &&
486 113639 : *(static_cast<const GByte *>(pBuffer)) ==
487 227309 : static_cast<GByte>(dfEffectiveNoData);
488 : }
489 55452 : if (m_nBitsPerSample == 16 && eDT == GDT_UInt16)
490 : {
491 4686 : return GDALIsValueInRange<GUInt16>(dfEffectiveNoData) &&
492 2343 : *(static_cast<const GUInt16 *>(pBuffer)) ==
493 4686 : static_cast<GUInt16>(dfEffectiveNoData);
494 : }
495 53109 : if (m_nBitsPerSample == 16 && eDT == GDT_Int16)
496 : {
497 8476 : return GDALIsValueInRange<GInt16>(dfEffectiveNoData) &&
498 4238 : *(static_cast<const GInt16 *>(pBuffer)) ==
499 8476 : static_cast<GInt16>(dfEffectiveNoData);
500 : }
501 48871 : if (m_nBitsPerSample == 32 && eDT == GDT_UInt32)
502 : {
503 378 : return GDALIsValueInRange<GUInt32>(dfEffectiveNoData) &&
504 189 : *(static_cast<const GUInt32 *>(pBuffer)) ==
505 378 : static_cast<GUInt32>(dfEffectiveNoData);
506 : }
507 48682 : if (m_nBitsPerSample == 32 && eDT == GDT_Int32)
508 : {
509 506 : return GDALIsValueInRange<GInt32>(dfEffectiveNoData) &&
510 253 : *(static_cast<const GInt32 *>(pBuffer)) ==
511 506 : static_cast<GInt32>(dfEffectiveNoData);
512 : }
513 48429 : if (m_nBitsPerSample == 64 && eDT == GDT_UInt64)
514 : {
515 234 : return GDALIsValueInRange<std::uint64_t>(dfEffectiveNoData) &&
516 117 : *(static_cast<const std::uint64_t *>(pBuffer)) ==
517 234 : static_cast<std::uint64_t>(dfEffectiveNoData);
518 : }
519 48312 : if (m_nBitsPerSample == 64 && eDT == GDT_Int64)
520 : {
521 236 : return GDALIsValueInRange<std::int64_t>(dfEffectiveNoData) &&
522 118 : *(static_cast<const std::int64_t *>(pBuffer)) ==
523 236 : static_cast<std::int64_t>(dfEffectiveNoData);
524 : }
525 48194 : if (m_nBitsPerSample == 32 && eDT == GDT_Float32)
526 : {
527 41181 : if (std::isnan(m_dfNoDataValue))
528 3 : return CPL_TO_BOOL(
529 6 : std::isnan(*(static_cast<const float *>(pBuffer))));
530 82356 : return GDALIsValueInRange<float>(dfEffectiveNoData) &&
531 41178 : *(static_cast<const float *>(pBuffer)) ==
532 82356 : static_cast<float>(dfEffectiveNoData);
533 : }
534 7013 : if (m_nBitsPerSample == 64 && eDT == GDT_Float64)
535 : {
536 4351 : if (std::isnan(dfEffectiveNoData))
537 3 : return CPL_TO_BOOL(
538 6 : std::isnan(*(static_cast<const double *>(pBuffer))));
539 4348 : return *(static_cast<const double *>(pBuffer)) == dfEffectiveNoData;
540 : }
541 2662 : return false;
542 : }
543 :
544 : /************************************************************************/
545 : /* WriteDealWithLercAndNan() */
546 : /************************************************************************/
547 :
548 : template <typename T>
549 0 : void GTiffDataset::WriteDealWithLercAndNan(T *pBuffer, int nActualBlockWidth,
550 : int nActualBlockHeight,
551 : int nStrileHeight)
552 : {
553 : // This method does 2 things:
554 : // - warn the user if he tries to write NaN values with libtiff < 4.6.1
555 : // and multi-band PlanarConfig=Contig configuration
556 : // - and in right-most and bottom-most tiles, replace non accessible
557 : // pixel values by a safe one.
558 :
559 0 : const auto fPaddingValue =
560 : #if !defined(LIBTIFF_MULTIBAND_LERC_NAN_OK)
561 : m_nPlanarConfig == PLANARCONFIG_CONTIG && nBands > 1
562 : ? 0
563 : :
564 : #endif
565 : std::numeric_limits<T>::quiet_NaN();
566 :
567 0 : const int nBandsPerStrile =
568 0 : m_nPlanarConfig == PLANARCONFIG_CONTIG ? nBands : 1;
569 0 : for (int j = 0; j < nActualBlockHeight; ++j)
570 : {
571 : #if !defined(LIBTIFF_MULTIBAND_LERC_NAN_OK)
572 : static bool bHasWarned = false;
573 : if (m_nPlanarConfig == PLANARCONFIG_CONTIG && nBands > 1 && !bHasWarned)
574 : {
575 : for (int i = 0; i < nActualBlockWidth * nBandsPerStrile; ++i)
576 : {
577 : if (std::isnan(
578 : pBuffer[j * m_nBlockXSize * nBandsPerStrile + i]))
579 : {
580 : bHasWarned = true;
581 : CPLError(CE_Warning, CPLE_AppDefined,
582 : "libtiff < 4.6.1 does not handle properly NaN "
583 : "values for multi-band PlanarConfig=Contig "
584 : "configuration. As a workaround, you can set the "
585 : "INTERLEAVE=BAND creation option.");
586 : break;
587 : }
588 : }
589 : }
590 : #endif
591 0 : for (int i = nActualBlockWidth * nBandsPerStrile;
592 0 : i < m_nBlockXSize * nBandsPerStrile; ++i)
593 : {
594 0 : pBuffer[j * m_nBlockXSize * nBandsPerStrile + i] = fPaddingValue;
595 : }
596 : }
597 0 : for (int j = nActualBlockHeight; j < nStrileHeight; ++j)
598 : {
599 0 : for (int i = 0; i < m_nBlockXSize * nBandsPerStrile; ++i)
600 : {
601 0 : pBuffer[j * m_nBlockXSize * nBandsPerStrile + i] = fPaddingValue;
602 : }
603 : }
604 0 : }
605 :
606 : /************************************************************************/
607 : /* WriteEncodedTile() */
608 : /************************************************************************/
609 :
610 50276 : bool GTiffDataset::WriteEncodedTile(uint32_t tile, GByte *pabyData,
611 : int bPreserveDataBuffer)
612 : {
613 50276 : const int iColumn = (tile % m_nBlocksPerBand) % m_nBlocksPerRow;
614 50276 : const int iRow = (tile % m_nBlocksPerBand) / m_nBlocksPerRow;
615 :
616 100552 : const int nActualBlockWidth = (iColumn == m_nBlocksPerRow - 1)
617 50276 : ? nRasterXSize - iColumn * m_nBlockXSize
618 : : m_nBlockXSize;
619 100552 : const int nActualBlockHeight = (iRow == m_nBlocksPerColumn - 1)
620 50276 : ? nRasterYSize - iRow * m_nBlockYSize
621 : : m_nBlockYSize;
622 :
623 : /* -------------------------------------------------------------------- */
624 : /* Don't write empty blocks in some cases. */
625 : /* -------------------------------------------------------------------- */
626 50276 : if (!m_bWriteEmptyTiles && IsFirstPixelEqualToNoData(pabyData))
627 : {
628 1946 : if (!IsBlockAvailable(tile, nullptr, nullptr, nullptr))
629 : {
630 1946 : const int nComponents =
631 1946 : m_nPlanarConfig == PLANARCONFIG_CONTIG ? nBands : 1;
632 :
633 1946 : if (HasOnlyNoData(pabyData, nActualBlockWidth, nActualBlockHeight,
634 : m_nBlockXSize, nComponents))
635 : {
636 1171 : return true;
637 : }
638 : }
639 : }
640 :
641 : // Is this a partial right edge or bottom edge tile?
642 95224 : const bool bPartialTile = (nActualBlockWidth < m_nBlockXSize) ||
643 46119 : (nActualBlockHeight < m_nBlockYSize);
644 :
645 : const bool bIsLercFloatingPoint =
646 49171 : m_nCompression == COMPRESSION_LERC &&
647 66 : (GetRasterBand(1)->GetRasterDataType() == GDT_Float32 ||
648 64 : GetRasterBand(1)->GetRasterDataType() == GDT_Float64);
649 :
650 : // Do we need to spread edge values right or down for a partial
651 : // JPEG encoded tile? We do this to avoid edge artifacts.
652 : // We also need to be careful with LERC and NaN values
653 49105 : const bool bNeedTempBuffer =
654 53769 : bPartialTile &&
655 4664 : (m_nCompression == COMPRESSION_JPEG || bIsLercFloatingPoint);
656 :
657 : // If we need to fill out the tile, or if we want to prevent
658 : // TIFFWriteEncodedTile from altering the buffer as part of
659 : // byte swapping the data on write then we will need a temporary
660 : // working buffer. If not, we can just do a direct write.
661 49105 : const GPtrDiff_t cc = static_cast<GPtrDiff_t>(TIFFTileSize(m_hTIFF));
662 :
663 63374 : if (bPreserveDataBuffer &&
664 14269 : (TIFFIsByteSwapped(m_hTIFF) || bNeedTempBuffer || m_panMaskOffsetLsb))
665 : {
666 158 : if (m_pabyTempWriteBuffer == nullptr)
667 : {
668 35 : m_pabyTempWriteBuffer = CPLMalloc(cc);
669 : }
670 158 : memcpy(m_pabyTempWriteBuffer, pabyData, cc);
671 :
672 158 : pabyData = static_cast<GByte *>(m_pabyTempWriteBuffer);
673 : }
674 :
675 : // Perform tile fill if needed.
676 : // TODO: we should also handle the case of nBitsPerSample == 12
677 : // but this is more involved.
678 49105 : if (bPartialTile && m_nCompression == COMPRESSION_JPEG &&
679 134 : m_nBitsPerSample == 8)
680 : {
681 132 : const int nComponents =
682 132 : m_nPlanarConfig == PLANARCONFIG_CONTIG ? nBands : 1;
683 :
684 132 : CPLDebug("GTiff", "Filling out jpeg edge tile on write.");
685 :
686 132 : const int nRightPixelsToFill =
687 132 : iColumn == m_nBlocksPerRow - 1
688 132 : ? m_nBlockXSize * (iColumn + 1) - nRasterXSize
689 : : 0;
690 132 : const int nBottomPixelsToFill =
691 132 : iRow == m_nBlocksPerColumn - 1
692 132 : ? m_nBlockYSize * (iRow + 1) - nRasterYSize
693 : : 0;
694 :
695 : // Fill out to the right.
696 132 : const int iSrcX = m_nBlockXSize - nRightPixelsToFill - 1;
697 :
698 12461 : for (int iX = iSrcX + 1; iX < m_nBlockXSize; ++iX)
699 : {
700 3955880 : for (int iY = 0; iY < m_nBlockYSize; ++iY)
701 : {
702 3943550 : memcpy(pabyData +
703 3943550 : (static_cast<GPtrDiff_t>(m_nBlockXSize) * iY + iX) *
704 3943550 : nComponents,
705 3943550 : pabyData + (static_cast<GPtrDiff_t>(m_nBlockXSize) * iY +
706 3943550 : iSrcX) *
707 3943550 : nComponents,
708 : nComponents);
709 : }
710 : }
711 :
712 : // Now fill out the bottom.
713 132 : const int iSrcY = m_nBlockYSize - nBottomPixelsToFill - 1;
714 17682 : for (int iY = iSrcY + 1; iY < m_nBlockYSize; ++iY)
715 : {
716 17550 : memcpy(pabyData + static_cast<GPtrDiff_t>(m_nBlockXSize) *
717 17550 : nComponents * iY,
718 17550 : pabyData + static_cast<GPtrDiff_t>(m_nBlockXSize) *
719 17550 : nComponents * iSrcY,
720 17550 : static_cast<GPtrDiff_t>(m_nBlockXSize) * nComponents);
721 : }
722 : }
723 :
724 49105 : if (bIsLercFloatingPoint &&
725 : (bPartialTile
726 : #if !defined(LIBTIFF_MULTIBAND_LERC_NAN_OK)
727 : /* libtiff < 4.6.1 doesn't generate a LERC mask for multi-band contig configuration */
728 : || (m_nPlanarConfig == PLANARCONFIG_CONTIG && nBands > 1)
729 : #endif
730 : ))
731 : {
732 0 : if (GetRasterBand(1)->GetRasterDataType() == GDT_Float32)
733 0 : WriteDealWithLercAndNan(reinterpret_cast<float *>(pabyData),
734 : nActualBlockWidth, nActualBlockHeight,
735 : m_nBlockYSize);
736 : else
737 0 : WriteDealWithLercAndNan(reinterpret_cast<double *>(pabyData),
738 : nActualBlockWidth, nActualBlockHeight,
739 : m_nBlockYSize);
740 : }
741 :
742 49105 : if (m_panMaskOffsetLsb)
743 : {
744 0 : const int iBand = m_nPlanarConfig == PLANARCONFIG_SEPARATE
745 0 : ? static_cast<int>(tile) / m_nBlocksPerBand
746 : : -1;
747 0 : DiscardLsb(pabyData, cc, iBand);
748 : }
749 :
750 49105 : if (m_bStreamingOut)
751 : {
752 17 : if (tile != static_cast<uint32_t>(m_nLastWrittenBlockId + 1))
753 : {
754 1 : ReportError(CE_Failure, CPLE_NotSupported,
755 : "Attempt to write block %d whereas %d was expected",
756 1 : tile, m_nLastWrittenBlockId + 1);
757 1 : return false;
758 : }
759 16 : if (static_cast<GPtrDiff_t>(VSIFWriteL(pabyData, 1, cc, m_fpToWrite)) !=
760 : cc)
761 : {
762 0 : ReportError(CE_Failure, CPLE_FileIO,
763 : "Could not write " CPL_FRMT_GUIB " bytes",
764 : static_cast<GUIntBig>(cc));
765 0 : return false;
766 : }
767 16 : m_nLastWrittenBlockId = tile;
768 16 : return true;
769 : }
770 :
771 : /* -------------------------------------------------------------------- */
772 : /* Should we do compression in a worker thread ? */
773 : /* -------------------------------------------------------------------- */
774 49088 : if (SubmitCompressionJob(tile, pabyData, cc, m_nBlockYSize))
775 19833 : return true;
776 :
777 29255 : return TIFFWriteEncodedTile(m_hTIFF, tile, pabyData, cc) == cc;
778 : }
779 :
780 : /************************************************************************/
781 : /* WriteEncodedStrip() */
782 : /************************************************************************/
783 :
784 178299 : bool GTiffDataset::WriteEncodedStrip(uint32_t strip, GByte *pabyData,
785 : int bPreserveDataBuffer)
786 : {
787 178299 : GPtrDiff_t cc = static_cast<GPtrDiff_t>(TIFFStripSize(m_hTIFF));
788 178299 : const auto ccFull = cc;
789 :
790 : /* -------------------------------------------------------------------- */
791 : /* If this is the last strip in the image, and is partial, then */
792 : /* we need to trim the number of scanlines written to the */
793 : /* amount of valid data we have. (#2748) */
794 : /* -------------------------------------------------------------------- */
795 178299 : const int nStripWithinBand = strip % m_nBlocksPerBand;
796 178299 : int nStripHeight = m_nRowsPerStrip;
797 :
798 178299 : if (nStripWithinBand * nStripHeight > GetRasterYSize() - nStripHeight)
799 : {
800 386 : nStripHeight = GetRasterYSize() - nStripWithinBand * m_nRowsPerStrip;
801 386 : cc = (cc / m_nRowsPerStrip) * nStripHeight;
802 772 : CPLDebug("GTiff",
803 : "Adjusted bytes to write from " CPL_FRMT_GUIB
804 : " to " CPL_FRMT_GUIB ".",
805 386 : static_cast<GUIntBig>(TIFFStripSize(m_hTIFF)),
806 : static_cast<GUIntBig>(cc));
807 : }
808 :
809 : /* -------------------------------------------------------------------- */
810 : /* Don't write empty blocks in some cases. */
811 : /* -------------------------------------------------------------------- */
812 178299 : if (!m_bWriteEmptyTiles && IsFirstPixelEqualToNoData(pabyData))
813 : {
814 41013 : if (!IsBlockAvailable(strip, nullptr, nullptr, nullptr))
815 : {
816 40839 : const int nComponents =
817 40839 : m_nPlanarConfig == PLANARCONFIG_CONTIG ? nBands : 1;
818 :
819 40839 : if (HasOnlyNoData(pabyData, m_nBlockXSize, nStripHeight,
820 : m_nBlockXSize, nComponents))
821 : {
822 28308 : return true;
823 : }
824 : }
825 : }
826 :
827 : /* -------------------------------------------------------------------- */
828 : /* TIFFWriteEncodedStrip can alter the passed buffer if */
829 : /* byte-swapping is necessary so we use a temporary buffer */
830 : /* before calling it. */
831 : /* -------------------------------------------------------------------- */
832 239463 : if (bPreserveDataBuffer &&
833 89472 : (TIFFIsByteSwapped(m_hTIFF) || m_panMaskOffsetLsb))
834 : {
835 294 : if (m_pabyTempWriteBuffer == nullptr)
836 : {
837 126 : m_pabyTempWriteBuffer = CPLMalloc(ccFull);
838 : }
839 294 : memcpy(m_pabyTempWriteBuffer, pabyData, cc);
840 294 : pabyData = static_cast<GByte *>(m_pabyTempWriteBuffer);
841 : }
842 :
843 : #if !defined(LIBTIFF_MULTIBAND_LERC_NAN_OK)
844 : const bool bIsLercFloatingPoint =
845 : m_nCompression == COMPRESSION_LERC &&
846 : (GetRasterBand(1)->GetRasterDataType() == GDT_Float32 ||
847 : GetRasterBand(1)->GetRasterDataType() == GDT_Float64);
848 : if (bIsLercFloatingPoint &&
849 : /* libtiff < 4.6.1 doesn't generate a LERC mask for multi-band contig configuration */
850 : m_nPlanarConfig == PLANARCONFIG_CONTIG && nBands > 1)
851 : {
852 : if (GetRasterBand(1)->GetRasterDataType() == GDT_Float32)
853 : WriteDealWithLercAndNan(reinterpret_cast<float *>(pabyData),
854 : m_nBlockXSize, nStripHeight, nStripHeight);
855 : else
856 : WriteDealWithLercAndNan(reinterpret_cast<double *>(pabyData),
857 : m_nBlockXSize, nStripHeight, nStripHeight);
858 : }
859 : #endif
860 :
861 149991 : if (m_panMaskOffsetLsb)
862 : {
863 366 : int iBand = m_nPlanarConfig == PLANARCONFIG_SEPARATE
864 183 : ? static_cast<int>(strip) / m_nBlocksPerBand
865 : : -1;
866 183 : DiscardLsb(pabyData, cc, iBand);
867 : }
868 :
869 149991 : if (m_bStreamingOut)
870 : {
871 1408 : if (strip != static_cast<uint32_t>(m_nLastWrittenBlockId + 1))
872 : {
873 1 : ReportError(CE_Failure, CPLE_NotSupported,
874 : "Attempt to write block %d whereas %d was expected",
875 1 : strip, m_nLastWrittenBlockId + 1);
876 1 : return false;
877 : }
878 1407 : if (static_cast<GPtrDiff_t>(VSIFWriteL(pabyData, 1, cc, m_fpToWrite)) !=
879 : cc)
880 : {
881 0 : ReportError(CE_Failure, CPLE_FileIO,
882 : "Could not write " CPL_FRMT_GUIB " bytes",
883 : static_cast<GUIntBig>(cc));
884 0 : return false;
885 : }
886 1407 : m_nLastWrittenBlockId = strip;
887 1407 : return true;
888 : }
889 :
890 : /* -------------------------------------------------------------------- */
891 : /* Should we do compression in a worker thread ? */
892 : /* -------------------------------------------------------------------- */
893 148583 : if (SubmitCompressionJob(strip, pabyData, cc, nStripHeight))
894 6727 : return true;
895 :
896 141856 : return TIFFWriteEncodedStrip(m_hTIFF, strip, pabyData, cc) == cc;
897 : }
898 :
899 : /************************************************************************/
900 : /* InitCompressionThreads() */
901 : /************************************************************************/
902 :
903 31860 : void GTiffDataset::InitCompressionThreads(bool bUpdateMode,
904 : CSLConstList papszOptions)
905 : {
906 : // Raster == tile, then no need for threads
907 31860 : if (m_nBlockXSize == nRasterXSize && m_nBlockYSize == nRasterYSize)
908 23278 : return;
909 :
910 8582 : const char *pszNumThreads = "";
911 8582 : bool bOK = false;
912 8582 : const int nThreads = GDALGetNumThreads(
913 : papszOptions, "NUM_THREADS", GDAL_DEFAULT_MAX_THREAD_COUNT,
914 : /* bDefaultToAllCPUs=*/false, &pszNumThreads, &bOK);
915 8582 : if (nThreads > 1)
916 : {
917 106 : if ((bUpdateMode && m_nCompression != COMPRESSION_NONE) ||
918 24 : (nBands >= 1 && IsMultiThreadedReadCompatible()))
919 : {
920 77 : CPLDebug("GTiff",
921 : "Using up to %d threads for compression/decompression",
922 : nThreads);
923 :
924 77 : m_poThreadPool = GDALGetGlobalThreadPool(nThreads);
925 77 : if (bUpdateMode && m_poThreadPool)
926 58 : m_poCompressQueue = m_poThreadPool->CreateJobQueue();
927 :
928 77 : if (m_poCompressQueue != nullptr)
929 : {
930 : // Add a margin of an extra job w.r.t thread number
931 : // so as to optimize compression time (enables the main
932 : // thread to do boring I/O while all CPUs are working).
933 58 : m_asCompressionJobs.resize(nThreads + 1);
934 58 : memset(&m_asCompressionJobs[0], 0,
935 58 : m_asCompressionJobs.size() *
936 : sizeof(GTiffCompressionJob));
937 58 : for (int i = 0;
938 280 : i < static_cast<int>(m_asCompressionJobs.size()); ++i)
939 : {
940 444 : m_asCompressionJobs[i].pszTmpFilename =
941 222 : CPLStrdup(VSIMemGenerateHiddenFilename(
942 : CPLSPrintf("thread_job_%d.tif", i)));
943 222 : m_asCompressionJobs[i].nStripOrTile = -1;
944 : }
945 :
946 : // This is kind of a hack, but basically using
947 : // TIFFWriteRawStrip/Tile and then TIFFReadEncodedStrip/Tile
948 : // does not work on a newly created file, because
949 : // TIFF_MYBUFFER is not set in tif_flags
950 : // (if using TIFFWriteEncodedStrip/Tile first,
951 : // TIFFWriteBufferSetup() is automatically called).
952 : // This should likely rather fixed in libtiff itself.
953 58 : CPL_IGNORE_RET_VAL(TIFFWriteBufferSetup(m_hTIFF, nullptr, -1));
954 : }
955 : }
956 : }
957 8500 : else if (!bOK)
958 : {
959 3 : ReportError(CE_Warning, CPLE_AppDefined,
960 : "Invalid value for NUM_THREADS: %s", pszNumThreads);
961 : }
962 : }
963 :
964 : /************************************************************************/
965 : /* ThreadCompressionFunc() */
966 : /************************************************************************/
967 :
968 26572 : void GTiffDataset::ThreadCompressionFunc(void *pData)
969 : {
970 26572 : GTiffCompressionJob *psJob = static_cast<GTiffCompressionJob *>(pData);
971 26572 : GTiffDataset *poDS = psJob->poDS;
972 :
973 26572 : VSILFILE *fpTmp = VSIFOpenL(psJob->pszTmpFilename, "wb+");
974 26572 : TIFF *hTIFFTmp = VSI_TIFFOpen(
975 53144 : psJob->pszTmpFilename, psJob->bTIFFIsBigEndian ? "wb+" : "wl+", fpTmp);
976 26572 : CPLAssert(hTIFFTmp != nullptr);
977 26572 : TIFFSetField(hTIFFTmp, TIFFTAG_IMAGEWIDTH, poDS->m_nBlockXSize);
978 26572 : TIFFSetField(hTIFFTmp, TIFFTAG_IMAGELENGTH, psJob->nHeight);
979 26572 : TIFFSetField(hTIFFTmp, TIFFTAG_BITSPERSAMPLE, poDS->m_nBitsPerSample);
980 26572 : TIFFSetField(hTIFFTmp, TIFFTAG_COMPRESSION, poDS->m_nCompression);
981 26572 : TIFFSetField(hTIFFTmp, TIFFTAG_PHOTOMETRIC, poDS->m_nPhotometric);
982 26572 : TIFFSetField(hTIFFTmp, TIFFTAG_SAMPLEFORMAT, poDS->m_nSampleFormat);
983 26572 : TIFFSetField(hTIFFTmp, TIFFTAG_SAMPLESPERPIXEL, poDS->m_nSamplesPerPixel);
984 26572 : TIFFSetField(hTIFFTmp, TIFFTAG_ROWSPERSTRIP, poDS->m_nBlockYSize);
985 26572 : TIFFSetField(hTIFFTmp, TIFFTAG_PLANARCONFIG, poDS->m_nPlanarConfig);
986 26572 : if (psJob->nPredictor != PREDICTOR_NONE)
987 263 : TIFFSetField(hTIFFTmp, TIFFTAG_PREDICTOR, psJob->nPredictor);
988 26572 : if (poDS->m_nCompression == COMPRESSION_LERC)
989 : {
990 24 : TIFFSetField(hTIFFTmp, TIFFTAG_LERC_PARAMETERS, 2,
991 24 : poDS->m_anLercAddCompressionAndVersion);
992 : }
993 26572 : if (psJob->nExtraSampleCount)
994 : {
995 352 : TIFFSetField(hTIFFTmp, TIFFTAG_EXTRASAMPLES, psJob->nExtraSampleCount,
996 : psJob->pExtraSamples);
997 : }
998 :
999 26572 : poDS->RestoreVolatileParameters(hTIFFTmp);
1000 :
1001 53144 : bool bOK = TIFFWriteEncodedStrip(hTIFFTmp, 0, psJob->pabyBuffer,
1002 26572 : psJob->nBufferSize) == psJob->nBufferSize;
1003 :
1004 26572 : toff_t nOffset = 0;
1005 26572 : if (bOK)
1006 : {
1007 26572 : toff_t *panOffsets = nullptr;
1008 26572 : toff_t *panByteCounts = nullptr;
1009 26572 : TIFFGetField(hTIFFTmp, TIFFTAG_STRIPOFFSETS, &panOffsets);
1010 26572 : TIFFGetField(hTIFFTmp, TIFFTAG_STRIPBYTECOUNTS, &panByteCounts);
1011 :
1012 26572 : nOffset = panOffsets[0];
1013 26572 : psJob->nCompressedBufferSize =
1014 26572 : static_cast<GPtrDiff_t>(panByteCounts[0]);
1015 : }
1016 : else
1017 : {
1018 0 : CPLError(CE_Failure, CPLE_AppDefined,
1019 : "Error when compressing strip/tile %d", psJob->nStripOrTile);
1020 : }
1021 :
1022 26572 : XTIFFClose(hTIFFTmp);
1023 26572 : if (VSIFCloseL(fpTmp) != 0)
1024 : {
1025 0 : if (bOK)
1026 : {
1027 0 : bOK = false;
1028 0 : CPLError(CE_Failure, CPLE_AppDefined,
1029 : "Error when compressing strip/tile %d",
1030 : psJob->nStripOrTile);
1031 : }
1032 : }
1033 :
1034 26572 : if (bOK)
1035 : {
1036 26572 : vsi_l_offset nFileSize = 0;
1037 : GByte *pabyCompressedBuffer =
1038 26572 : VSIGetMemFileBuffer(psJob->pszTmpFilename, &nFileSize, FALSE);
1039 26572 : CPLAssert(static_cast<vsi_l_offset>(
1040 : nOffset + psJob->nCompressedBufferSize) <= nFileSize);
1041 26572 : psJob->pabyCompressedBuffer = pabyCompressedBuffer + nOffset;
1042 : }
1043 : else
1044 : {
1045 0 : psJob->pabyCompressedBuffer = nullptr;
1046 0 : psJob->nCompressedBufferSize = 0;
1047 : }
1048 :
1049 26572 : auto poMainDS = poDS->m_poBaseDS ? poDS->m_poBaseDS : poDS;
1050 26572 : if (poMainDS->m_poCompressQueue)
1051 : {
1052 1576 : std::lock_guard oLock(poMainDS->m_oCompressThreadPoolMutex);
1053 1576 : psJob->bReady = true;
1054 : }
1055 26572 : }
1056 :
1057 : /************************************************************************/
1058 : /* WriteRawStripOrTile() */
1059 : /************************************************************************/
1060 :
1061 33915 : void GTiffDataset::WriteRawStripOrTile(int nStripOrTile,
1062 : GByte *pabyCompressedBuffer,
1063 : GPtrDiff_t nCompressedBufferSize)
1064 : {
1065 : #ifdef DEBUG_VERBOSE
1066 : CPLDebug("GTIFF", "Writing raw strip/tile %d, size " CPL_FRMT_GUIB,
1067 : nStripOrTile, static_cast<GUIntBig>(nCompressedBufferSize));
1068 : #endif
1069 33915 : toff_t *panOffsets = nullptr;
1070 33915 : toff_t *panByteCounts = nullptr;
1071 33915 : bool bWriteAtEnd = true;
1072 33915 : bool bWriteLeader = m_bLeaderSizeAsUInt4;
1073 33915 : bool bWriteTrailer = m_bTrailerRepeatedLast4BytesRepeated;
1074 33915 : if (TIFFGetField(m_hTIFF,
1075 33915 : TIFFIsTiled(m_hTIFF) ? TIFFTAG_TILEOFFSETS
1076 : : TIFFTAG_STRIPOFFSETS,
1077 33915 : &panOffsets) &&
1078 33915 : panOffsets != nullptr && panOffsets[nStripOrTile] != 0)
1079 : {
1080 : // Forces TIFFAppendStrip() to consider if the location of the
1081 : // tile/strip can be reused or if the strile should be written at end of
1082 : // file.
1083 360 : TIFFSetWriteOffset(m_hTIFF, 0);
1084 :
1085 360 : if (m_bBlockOrderRowMajor)
1086 : {
1087 264 : if (TIFFGetField(m_hTIFF,
1088 264 : TIFFIsTiled(m_hTIFF) ? TIFFTAG_TILEBYTECOUNTS
1089 : : TIFFTAG_STRIPBYTECOUNTS,
1090 528 : &panByteCounts) &&
1091 264 : panByteCounts != nullptr)
1092 : {
1093 264 : if (static_cast<GUIntBig>(nCompressedBufferSize) >
1094 264 : panByteCounts[nStripOrTile])
1095 : {
1096 8 : GTiffDataset *poRootDS = m_poBaseDS ? m_poBaseDS : this;
1097 8 : if (!poRootDS->m_bKnownIncompatibleEdition &&
1098 8 : !poRootDS->m_bWriteKnownIncompatibleEdition)
1099 : {
1100 8 : ReportError(
1101 : CE_Warning, CPLE_AppDefined,
1102 : "A strile cannot be rewritten in place, which "
1103 : "invalidates the BLOCK_ORDER optimization.");
1104 8 : poRootDS->m_bKnownIncompatibleEdition = true;
1105 8 : poRootDS->m_bWriteKnownIncompatibleEdition = true;
1106 : }
1107 : }
1108 : // For mask interleaving, if the size is not exactly the same,
1109 : // completely give up (we could potentially move the mask in
1110 : // case the imagery is smaller)
1111 256 : else if (m_poMaskDS && m_bMaskInterleavedWithImagery &&
1112 0 : static_cast<GUIntBig>(nCompressedBufferSize) !=
1113 0 : panByteCounts[nStripOrTile])
1114 : {
1115 0 : GTiffDataset *poRootDS = m_poBaseDS ? m_poBaseDS : this;
1116 0 : if (!poRootDS->m_bKnownIncompatibleEdition &&
1117 0 : !poRootDS->m_bWriteKnownIncompatibleEdition)
1118 : {
1119 0 : ReportError(
1120 : CE_Warning, CPLE_AppDefined,
1121 : "A strile cannot be rewritten in place, which "
1122 : "invalidates the MASK_INTERLEAVED_WITH_IMAGERY "
1123 : "optimization.");
1124 0 : poRootDS->m_bKnownIncompatibleEdition = true;
1125 0 : poRootDS->m_bWriteKnownIncompatibleEdition = true;
1126 : }
1127 0 : bWriteLeader = false;
1128 0 : bWriteTrailer = false;
1129 0 : if (m_bLeaderSizeAsUInt4)
1130 : {
1131 : // If there was a valid leader, invalidat it
1132 0 : VSI_TIFFSeek(m_hTIFF, panOffsets[nStripOrTile] - 4,
1133 : SEEK_SET);
1134 : uint32_t nOldSize;
1135 0 : VSIFReadL(&nOldSize, 1, 4,
1136 : VSI_TIFFGetVSILFile(TIFFClientdata(m_hTIFF)));
1137 0 : CPL_LSBPTR32(&nOldSize);
1138 0 : if (nOldSize == panByteCounts[nStripOrTile])
1139 : {
1140 0 : uint32_t nInvalidatedSize = 0;
1141 0 : VSI_TIFFSeek(m_hTIFF, panOffsets[nStripOrTile] - 4,
1142 : SEEK_SET);
1143 0 : VSI_TIFFWrite(m_hTIFF, &nInvalidatedSize,
1144 : sizeof(nInvalidatedSize));
1145 : }
1146 : }
1147 : }
1148 : else
1149 : {
1150 256 : bWriteAtEnd = false;
1151 : }
1152 : }
1153 : }
1154 : }
1155 33915 : if (bWriteLeader &&
1156 25001 : static_cast<GUIntBig>(nCompressedBufferSize) <= 0xFFFFFFFFU)
1157 : {
1158 : // cppcheck-suppress knownConditionTrueFalse
1159 25001 : if (bWriteAtEnd)
1160 : {
1161 24745 : VSI_TIFFSeek(m_hTIFF, 0, SEEK_END);
1162 : }
1163 : else
1164 : {
1165 : // If we rewrite an existing strile in place with an existing
1166 : // leader, check that the leader is valid, before rewriting it. And
1167 : // if it is not valid, then do not write the trailer, as we could
1168 : // corrupt other data.
1169 256 : VSI_TIFFSeek(m_hTIFF, panOffsets[nStripOrTile] - 4, SEEK_SET);
1170 : uint32_t nOldSize;
1171 256 : VSIFReadL(&nOldSize, 1, 4,
1172 : VSI_TIFFGetVSILFile(TIFFClientdata(m_hTIFF)));
1173 256 : CPL_LSBPTR32(&nOldSize);
1174 256 : bWriteLeader =
1175 256 : panByteCounts && nOldSize == panByteCounts[nStripOrTile];
1176 256 : bWriteTrailer = bWriteLeader;
1177 256 : VSI_TIFFSeek(m_hTIFF, panOffsets[nStripOrTile] - 4, SEEK_SET);
1178 : }
1179 : // cppcheck-suppress knownConditionTrueFalse
1180 25001 : if (bWriteLeader)
1181 : {
1182 25001 : uint32_t nSize = static_cast<uint32_t>(nCompressedBufferSize);
1183 25001 : CPL_LSBPTR32(&nSize);
1184 25001 : if (!VSI_TIFFWrite(m_hTIFF, &nSize, sizeof(nSize)))
1185 0 : m_bWriteError = true;
1186 : }
1187 : }
1188 : tmsize_t written;
1189 33915 : if (TIFFIsTiled(m_hTIFF))
1190 26260 : written = TIFFWriteRawTile(m_hTIFF, nStripOrTile, pabyCompressedBuffer,
1191 : nCompressedBufferSize);
1192 : else
1193 7655 : written = TIFFWriteRawStrip(m_hTIFF, nStripOrTile, pabyCompressedBuffer,
1194 : nCompressedBufferSize);
1195 33915 : if (written != nCompressedBufferSize)
1196 12 : m_bWriteError = true;
1197 33915 : if (bWriteTrailer &&
1198 25001 : static_cast<GUIntBig>(nCompressedBufferSize) <= 0xFFFFFFFFU)
1199 : {
1200 25001 : GByte abyLastBytes[4] = {};
1201 25001 : if (nCompressedBufferSize >= 4)
1202 25001 : memcpy(abyLastBytes,
1203 25001 : pabyCompressedBuffer + nCompressedBufferSize - 4, 4);
1204 : else
1205 0 : memcpy(abyLastBytes, pabyCompressedBuffer, nCompressedBufferSize);
1206 25001 : if (!VSI_TIFFWrite(m_hTIFF, abyLastBytes, 4))
1207 0 : m_bWriteError = true;
1208 : }
1209 33915 : }
1210 :
1211 : /************************************************************************/
1212 : /* WaitCompletionForJobIdx() */
1213 : /************************************************************************/
1214 :
1215 1576 : void GTiffDataset::WaitCompletionForJobIdx(int i)
1216 : {
1217 1576 : auto poMainDS = m_poBaseDS ? m_poBaseDS : this;
1218 1576 : auto poQueue = poMainDS->m_poCompressQueue.get();
1219 1576 : auto &oQueue = poMainDS->m_asQueueJobIdx;
1220 1576 : auto &asJobs = poMainDS->m_asCompressionJobs;
1221 1576 : auto &mutex = poMainDS->m_oCompressThreadPoolMutex;
1222 :
1223 1576 : CPLAssert(i >= 0 && static_cast<size_t>(i) < asJobs.size());
1224 1576 : CPLAssert(asJobs[i].nStripOrTile >= 0);
1225 1576 : CPLAssert(!oQueue.empty());
1226 :
1227 1576 : bool bHasWarned = false;
1228 : while (true)
1229 : {
1230 : bool bReady;
1231 : {
1232 2221 : std::lock_guard oLock(mutex);
1233 2221 : bReady = asJobs[i].bReady;
1234 : }
1235 2221 : if (!bReady)
1236 : {
1237 645 : if (!bHasWarned)
1238 : {
1239 384 : CPLDebug("GTIFF",
1240 : "Waiting for worker job to finish handling block %d",
1241 384 : asJobs[i].nStripOrTile);
1242 384 : bHasWarned = true;
1243 : }
1244 645 : poQueue->GetPool()->WaitEvent();
1245 : }
1246 : else
1247 : {
1248 1576 : break;
1249 : }
1250 645 : }
1251 :
1252 1576 : if (asJobs[i].nCompressedBufferSize)
1253 : {
1254 3152 : asJobs[i].poDS->WriteRawStripOrTile(asJobs[i].nStripOrTile,
1255 1576 : asJobs[i].pabyCompressedBuffer,
1256 1576 : asJobs[i].nCompressedBufferSize);
1257 : }
1258 1576 : asJobs[i].pabyCompressedBuffer = nullptr;
1259 1576 : asJobs[i].nBufferSize = 0;
1260 : {
1261 : // Likely useless, but makes Coverity happy
1262 1576 : std::lock_guard oLock(mutex);
1263 1576 : asJobs[i].bReady = false;
1264 : }
1265 1576 : asJobs[i].nStripOrTile = -1;
1266 1576 : oQueue.pop();
1267 1576 : }
1268 :
1269 : /************************************************************************/
1270 : /* WaitCompletionForBlock() */
1271 : /************************************************************************/
1272 :
1273 2319940 : void GTiffDataset::WaitCompletionForBlock(int nBlockId)
1274 : {
1275 2319940 : auto poQueue = m_poBaseDS ? m_poBaseDS->m_poCompressQueue.get()
1276 2300720 : : m_poCompressQueue.get();
1277 : // cppcheck-suppress constVariableReference
1278 2319940 : auto &oQueue = m_poBaseDS ? m_poBaseDS->m_asQueueJobIdx : m_asQueueJobIdx;
1279 : // cppcheck-suppress constVariableReference
1280 2300720 : auto &asJobs =
1281 2319940 : m_poBaseDS ? m_poBaseDS->m_asCompressionJobs : m_asCompressionJobs;
1282 :
1283 2319940 : if (poQueue != nullptr && !oQueue.empty())
1284 : {
1285 1066 : for (int i = 0; i < static_cast<int>(asJobs.size()); ++i)
1286 : {
1287 888 : if (asJobs[i].poDS == this && asJobs[i].nStripOrTile == nBlockId)
1288 : {
1289 128 : while (!oQueue.empty() &&
1290 64 : !(asJobs[oQueue.front()].poDS == this &&
1291 64 : asJobs[oQueue.front()].nStripOrTile == nBlockId))
1292 : {
1293 0 : WaitCompletionForJobIdx(oQueue.front());
1294 : }
1295 64 : CPLAssert(!oQueue.empty() &&
1296 : asJobs[oQueue.front()].poDS == this &&
1297 : asJobs[oQueue.front()].nStripOrTile == nBlockId);
1298 64 : WaitCompletionForJobIdx(oQueue.front());
1299 : }
1300 : }
1301 : }
1302 2319940 : }
1303 :
1304 : /************************************************************************/
1305 : /* SubmitCompressionJob() */
1306 : /************************************************************************/
1307 :
1308 197671 : bool GTiffDataset::SubmitCompressionJob(int nStripOrTile, GByte *pabyData,
1309 : GPtrDiff_t cc, int nHeight)
1310 : {
1311 : /* -------------------------------------------------------------------- */
1312 : /* Should we do compression in a worker thread ? */
1313 : /* -------------------------------------------------------------------- */
1314 197671 : auto poQueue = m_poBaseDS ? m_poBaseDS->m_poCompressQueue.get()
1315 183687 : : m_poCompressQueue.get();
1316 :
1317 197671 : if (poQueue && m_nCompression == COMPRESSION_NONE)
1318 : {
1319 : // We don't do multi-threaded compression for uncompressed...
1320 : // but we must wait for other related compression tasks (e.g mask)
1321 : // to be completed
1322 0 : poQueue->WaitCompletion();
1323 :
1324 : // Flush remaining data
1325 : // cppcheck-suppress constVariableReference
1326 0 : auto &oQueue =
1327 0 : m_poBaseDS ? m_poBaseDS->m_asQueueJobIdx : m_asQueueJobIdx;
1328 0 : while (!oQueue.empty())
1329 : {
1330 0 : WaitCompletionForJobIdx(oQueue.front());
1331 : }
1332 : }
1333 :
1334 : const auto SetupJob =
1335 123013 : [this, pabyData, cc, nHeight, nStripOrTile](GTiffCompressionJob &sJob)
1336 : {
1337 26572 : sJob.poDS = this;
1338 26572 : sJob.bTIFFIsBigEndian = CPL_TO_BOOL(TIFFIsBigEndian(m_hTIFF));
1339 : GByte *pabyBuffer =
1340 26572 : static_cast<GByte *>(VSI_REALLOC_VERBOSE(sJob.pabyBuffer, cc));
1341 26572 : if (!pabyBuffer)
1342 0 : return false;
1343 26572 : sJob.pabyBuffer = pabyBuffer;
1344 26572 : memcpy(sJob.pabyBuffer, pabyData, cc);
1345 26572 : sJob.nBufferSize = cc;
1346 26572 : sJob.nHeight = nHeight;
1347 26572 : sJob.nStripOrTile = nStripOrTile;
1348 26572 : sJob.nPredictor = PREDICTOR_NONE;
1349 26572 : if (GTIFFSupportsPredictor(m_nCompression))
1350 : {
1351 16725 : TIFFGetField(m_hTIFF, TIFFTAG_PREDICTOR, &sJob.nPredictor);
1352 : }
1353 :
1354 26572 : sJob.pExtraSamples = nullptr;
1355 26572 : sJob.nExtraSampleCount = 0;
1356 26572 : TIFFGetField(m_hTIFF, TIFFTAG_EXTRASAMPLES, &sJob.nExtraSampleCount,
1357 : &sJob.pExtraSamples);
1358 26572 : return true;
1359 197671 : };
1360 :
1361 197671 : if (poQueue == nullptr || !(m_nCompression == COMPRESSION_ADOBE_DEFLATE ||
1362 806 : m_nCompression == COMPRESSION_LZW ||
1363 78 : m_nCompression == COMPRESSION_PACKBITS ||
1364 72 : m_nCompression == COMPRESSION_LZMA ||
1365 62 : m_nCompression == COMPRESSION_ZSTD ||
1366 52 : m_nCompression == COMPRESSION_LERC ||
1367 46 : m_nCompression == COMPRESSION_JXL ||
1368 46 : m_nCompression == COMPRESSION_JXL_DNG_1_7 ||
1369 28 : m_nCompression == COMPRESSION_WEBP ||
1370 18 : m_nCompression == COMPRESSION_JPEG))
1371 : {
1372 196095 : if (m_bBlockOrderRowMajor || m_bLeaderSizeAsUInt4 ||
1373 171099 : m_bTrailerRepeatedLast4BytesRepeated)
1374 : {
1375 : GTiffCompressionJob sJob;
1376 24996 : memset(&sJob, 0, sizeof(sJob));
1377 24996 : if (SetupJob(sJob))
1378 : {
1379 24996 : sJob.pszTmpFilename =
1380 24996 : CPLStrdup(VSIMemGenerateHiddenFilename("temp.tif"));
1381 :
1382 24996 : ThreadCompressionFunc(&sJob);
1383 :
1384 24996 : if (sJob.nCompressedBufferSize)
1385 : {
1386 24996 : sJob.poDS->WriteRawStripOrTile(sJob.nStripOrTile,
1387 : sJob.pabyCompressedBuffer,
1388 : sJob.nCompressedBufferSize);
1389 : }
1390 :
1391 24996 : CPLFree(sJob.pabyBuffer);
1392 24996 : VSIUnlink(sJob.pszTmpFilename);
1393 24996 : CPLFree(sJob.pszTmpFilename);
1394 24996 : return sJob.nCompressedBufferSize > 0 && !m_bWriteError;
1395 : }
1396 : }
1397 :
1398 171099 : return false;
1399 : }
1400 :
1401 1576 : auto poMainDS = m_poBaseDS ? m_poBaseDS : this;
1402 1576 : auto &oQueue = poMainDS->m_asQueueJobIdx;
1403 1576 : auto &asJobs = poMainDS->m_asCompressionJobs;
1404 :
1405 1576 : int nNextCompressionJobAvail = -1;
1406 :
1407 1576 : if (oQueue.size() == asJobs.size())
1408 : {
1409 1443 : CPLAssert(!oQueue.empty());
1410 1443 : nNextCompressionJobAvail = oQueue.front();
1411 1443 : WaitCompletionForJobIdx(nNextCompressionJobAvail);
1412 : }
1413 : else
1414 : {
1415 133 : const int nJobs = static_cast<int>(asJobs.size());
1416 324 : for (int i = 0; i < nJobs; ++i)
1417 : {
1418 324 : if (asJobs[i].nBufferSize == 0)
1419 : {
1420 133 : nNextCompressionJobAvail = i;
1421 133 : break;
1422 : }
1423 : }
1424 : }
1425 1576 : CPLAssert(nNextCompressionJobAvail >= 0);
1426 :
1427 1576 : GTiffCompressionJob *psJob = &asJobs[nNextCompressionJobAvail];
1428 1576 : bool bOK = SetupJob(*psJob);
1429 1576 : if (bOK)
1430 : {
1431 1576 : poQueue->SubmitJob(ThreadCompressionFunc, psJob);
1432 1576 : oQueue.push(nNextCompressionJobAvail);
1433 : }
1434 :
1435 1576 : return bOK;
1436 : }
1437 :
1438 : /************************************************************************/
1439 : /* DiscardLsb() */
1440 : /************************************************************************/
1441 :
1442 272 : template <class T> bool MustNotDiscardLsb(T value, bool bHasNoData, T nodata)
1443 : {
1444 272 : return bHasNoData && value == nodata;
1445 : }
1446 :
1447 : template <>
1448 44 : bool MustNotDiscardLsb<float>(float value, bool bHasNoData, float nodata)
1449 : {
1450 44 : return (bHasNoData && value == nodata) || !std::isfinite(value);
1451 : }
1452 :
1453 : template <>
1454 44 : bool MustNotDiscardLsb<double>(double value, bool bHasNoData, double nodata)
1455 : {
1456 44 : return (bHasNoData && value == nodata) || !std::isfinite(value);
1457 : }
1458 :
1459 : template <class T> T AdjustValue(T value, uint64_t nRoundUpBitTest);
1460 :
1461 10 : template <class T> T AdjustValueInt(T value, uint64_t nRoundUpBitTest)
1462 : {
1463 10 : if (value >=
1464 10 : static_cast<T>(std::numeric_limits<T>::max() - (nRoundUpBitTest << 1)))
1465 0 : return static_cast<T>(value - (nRoundUpBitTest << 1));
1466 10 : return static_cast<T>(value + (nRoundUpBitTest << 1));
1467 : }
1468 :
1469 0 : template <> int8_t AdjustValue<int8_t>(int8_t value, uint64_t nRoundUpBitTest)
1470 : {
1471 0 : return AdjustValueInt(value, nRoundUpBitTest);
1472 : }
1473 :
1474 : template <>
1475 2 : uint8_t AdjustValue<uint8_t>(uint8_t value, uint64_t nRoundUpBitTest)
1476 : {
1477 2 : return AdjustValueInt(value, nRoundUpBitTest);
1478 : }
1479 :
1480 : template <>
1481 2 : int16_t AdjustValue<int16_t>(int16_t value, uint64_t nRoundUpBitTest)
1482 : {
1483 2 : return AdjustValueInt(value, nRoundUpBitTest);
1484 : }
1485 :
1486 : template <>
1487 2 : uint16_t AdjustValue<uint16_t>(uint16_t value, uint64_t nRoundUpBitTest)
1488 : {
1489 2 : return AdjustValueInt(value, nRoundUpBitTest);
1490 : }
1491 :
1492 : template <>
1493 2 : int32_t AdjustValue<int32_t>(int32_t value, uint64_t nRoundUpBitTest)
1494 : {
1495 2 : return AdjustValueInt(value, nRoundUpBitTest);
1496 : }
1497 :
1498 : template <>
1499 2 : uint32_t AdjustValue<uint32_t>(uint32_t value, uint64_t nRoundUpBitTest)
1500 : {
1501 2 : return AdjustValueInt(value, nRoundUpBitTest);
1502 : }
1503 :
1504 : template <>
1505 0 : int64_t AdjustValue<int64_t>(int64_t value, uint64_t nRoundUpBitTest)
1506 : {
1507 0 : return AdjustValueInt(value, nRoundUpBitTest);
1508 : }
1509 :
1510 : template <>
1511 0 : uint64_t AdjustValue<uint64_t>(uint64_t value, uint64_t nRoundUpBitTest)
1512 : {
1513 0 : return AdjustValueInt(value, nRoundUpBitTest);
1514 : }
1515 :
1516 0 : template <> GFloat16 AdjustValue<GFloat16>(GFloat16 value, uint64_t)
1517 : {
1518 : using std::nextafter;
1519 0 : return nextafter(value, cpl::NumericLimits<GFloat16>::max());
1520 : }
1521 :
1522 0 : template <> float AdjustValue<float>(float value, uint64_t)
1523 : {
1524 0 : return std::nextafter(value, std::numeric_limits<float>::max());
1525 : }
1526 :
1527 0 : template <> double AdjustValue<double>(double value, uint64_t)
1528 : {
1529 0 : return std::nextafter(value, std::numeric_limits<double>::max());
1530 : }
1531 :
1532 : template <class Teffective, class T>
1533 : T RoundValueDiscardLsb(const void *ptr, uint64_t nMask,
1534 : uint64_t nRoundUpBitTest);
1535 :
1536 : template <class T>
1537 16 : T RoundValueDiscardLsbUnsigned(const void *ptr, uint64_t nMask,
1538 : uint64_t nRoundUpBitTest)
1539 : {
1540 32 : if ((*reinterpret_cast<const T *>(ptr) & nMask) >
1541 16 : static_cast<uint64_t>(std::numeric_limits<T>::max()) -
1542 16 : (nRoundUpBitTest << 1U))
1543 : {
1544 4 : return static_cast<T>(std::numeric_limits<T>::max() & nMask);
1545 : }
1546 12 : const uint64_t newval =
1547 12 : (*reinterpret_cast<const T *>(ptr) & nMask) + (nRoundUpBitTest << 1U);
1548 12 : return static_cast<T>(newval);
1549 : }
1550 :
1551 : template <class T>
1552 18 : T RoundValueDiscardLsbSigned(const void *ptr, uint64_t nMask,
1553 : uint64_t nRoundUpBitTest)
1554 : {
1555 18 : T oldval = *reinterpret_cast<const T *>(ptr);
1556 18 : if (oldval < 0)
1557 : {
1558 4 : return static_cast<T>(oldval & nMask);
1559 : }
1560 14 : const uint64_t newval =
1561 14 : (*reinterpret_cast<const T *>(ptr) & nMask) + (nRoundUpBitTest << 1U);
1562 14 : if (newval > static_cast<uint64_t>(std::numeric_limits<T>::max()))
1563 4 : return static_cast<T>(std::numeric_limits<T>::max() & nMask);
1564 10 : return static_cast<T>(newval);
1565 : }
1566 :
1567 : template <>
1568 11 : uint16_t RoundValueDiscardLsb<uint16_t, uint16_t>(const void *ptr,
1569 : uint64_t nMask,
1570 : uint64_t nRoundUpBitTest)
1571 : {
1572 11 : return RoundValueDiscardLsbUnsigned<uint16_t>(ptr, nMask, nRoundUpBitTest);
1573 : }
1574 :
1575 : template <>
1576 5 : uint32_t RoundValueDiscardLsb<uint32_t, uint32_t>(const void *ptr,
1577 : uint64_t nMask,
1578 : uint64_t nRoundUpBitTest)
1579 : {
1580 5 : return RoundValueDiscardLsbUnsigned<uint32_t>(ptr, nMask, nRoundUpBitTest);
1581 : }
1582 :
1583 : template <>
1584 0 : uint64_t RoundValueDiscardLsb<uint64_t, uint64_t>(const void *ptr,
1585 : uint64_t nMask,
1586 : uint64_t nRoundUpBitTest)
1587 : {
1588 0 : return RoundValueDiscardLsbUnsigned<uint64_t>(ptr, nMask, nRoundUpBitTest);
1589 : }
1590 :
1591 : template <>
1592 0 : int8_t RoundValueDiscardLsb<int8_t, int8_t>(const void *ptr, uint64_t nMask,
1593 : uint64_t nRoundUpBitTest)
1594 : {
1595 0 : return RoundValueDiscardLsbSigned<int8_t>(ptr, nMask, nRoundUpBitTest);
1596 : }
1597 :
1598 : template <>
1599 13 : int16_t RoundValueDiscardLsb<int16_t, int16_t>(const void *ptr, uint64_t nMask,
1600 : uint64_t nRoundUpBitTest)
1601 : {
1602 13 : return RoundValueDiscardLsbSigned<int16_t>(ptr, nMask, nRoundUpBitTest);
1603 : }
1604 :
1605 : template <>
1606 5 : int32_t RoundValueDiscardLsb<int32_t, int32_t>(const void *ptr, uint64_t nMask,
1607 : uint64_t nRoundUpBitTest)
1608 : {
1609 5 : return RoundValueDiscardLsbSigned<int32_t>(ptr, nMask, nRoundUpBitTest);
1610 : }
1611 :
1612 : template <>
1613 0 : int64_t RoundValueDiscardLsb<int64_t, int64_t>(const void *ptr, uint64_t nMask,
1614 : uint64_t nRoundUpBitTest)
1615 : {
1616 0 : return RoundValueDiscardLsbSigned<int64_t>(ptr, nMask, nRoundUpBitTest);
1617 : }
1618 :
1619 : template <>
1620 0 : uint16_t RoundValueDiscardLsb<GFloat16, uint16_t>(const void *ptr,
1621 : uint64_t nMask,
1622 : uint64_t nRoundUpBitTest)
1623 : {
1624 0 : return RoundValueDiscardLsbUnsigned<uint16_t>(ptr, nMask, nRoundUpBitTest);
1625 : }
1626 :
1627 : template <>
1628 0 : uint32_t RoundValueDiscardLsb<float, uint32_t>(const void *ptr, uint64_t nMask,
1629 : uint64_t nRoundUpBitTest)
1630 : {
1631 0 : return RoundValueDiscardLsbUnsigned<uint32_t>(ptr, nMask, nRoundUpBitTest);
1632 : }
1633 :
1634 : template <>
1635 0 : uint64_t RoundValueDiscardLsb<double, uint64_t>(const void *ptr, uint64_t nMask,
1636 : uint64_t nRoundUpBitTest)
1637 : {
1638 0 : return RoundValueDiscardLsbUnsigned<uint64_t>(ptr, nMask, nRoundUpBitTest);
1639 : }
1640 :
1641 : template <class Teffective, class T>
1642 145 : static void DiscardLsbT(GByte *pabyBuffer, size_t nBytes, int iBand, int nBands,
1643 : uint16_t nPlanarConfig,
1644 : const GTiffDataset::MaskOffset *panMaskOffsetLsb,
1645 : bool bHasNoData, Teffective nNoDataValue)
1646 : {
1647 : static_assert(sizeof(Teffective) == sizeof(T),
1648 : "sizeof(Teffective) == sizeof(T)");
1649 145 : if (nPlanarConfig == PLANARCONFIG_SEPARATE)
1650 : {
1651 98 : const auto nMask = panMaskOffsetLsb[iBand].nMask;
1652 98 : const auto nRoundUpBitTest = panMaskOffsetLsb[iBand].nRoundUpBitTest;
1653 196 : for (size_t i = 0; i < nBytes / sizeof(T); ++i)
1654 : {
1655 98 : if (MustNotDiscardLsb(reinterpret_cast<Teffective *>(pabyBuffer)[i],
1656 : bHasNoData, nNoDataValue))
1657 : {
1658 22 : continue;
1659 : }
1660 :
1661 76 : if (reinterpret_cast<T *>(pabyBuffer)[i] & nRoundUpBitTest)
1662 : {
1663 30 : reinterpret_cast<T *>(pabyBuffer)[i] =
1664 15 : RoundValueDiscardLsb<Teffective, T>(
1665 15 : &(reinterpret_cast<T *>(pabyBuffer)[i]), nMask,
1666 : nRoundUpBitTest);
1667 : }
1668 : else
1669 : {
1670 61 : reinterpret_cast<T *>(pabyBuffer)[i] = static_cast<T>(
1671 61 : reinterpret_cast<T *>(pabyBuffer)[i] & nMask);
1672 : }
1673 :
1674 : // Make sure that by discarding LSB we don't end up to a value
1675 : // that is no the nodata value
1676 76 : if (MustNotDiscardLsb(reinterpret_cast<Teffective *>(pabyBuffer)[i],
1677 : bHasNoData, nNoDataValue))
1678 : {
1679 8 : reinterpret_cast<Teffective *>(pabyBuffer)[i] =
1680 4 : AdjustValue(nNoDataValue, nRoundUpBitTest);
1681 : }
1682 : }
1683 : }
1684 : else
1685 : {
1686 94 : for (size_t i = 0; i < nBytes / sizeof(T); i += nBands)
1687 : {
1688 147 : for (int j = 0; j < nBands; ++j)
1689 : {
1690 100 : if (MustNotDiscardLsb(
1691 100 : reinterpret_cast<Teffective *>(pabyBuffer)[i + j],
1692 : bHasNoData, nNoDataValue))
1693 : {
1694 14 : continue;
1695 : }
1696 :
1697 86 : if (reinterpret_cast<T *>(pabyBuffer)[i + j] &
1698 86 : panMaskOffsetLsb[j].nRoundUpBitTest)
1699 : {
1700 38 : reinterpret_cast<T *>(pabyBuffer)[i + j] =
1701 19 : RoundValueDiscardLsb<Teffective, T>(
1702 19 : &(reinterpret_cast<T *>(pabyBuffer)[i + j]),
1703 19 : panMaskOffsetLsb[j].nMask,
1704 19 : panMaskOffsetLsb[j].nRoundUpBitTest);
1705 : }
1706 : else
1707 : {
1708 67 : reinterpret_cast<T *>(pabyBuffer)[i + j] = static_cast<T>(
1709 67 : (reinterpret_cast<T *>(pabyBuffer)[i + j] &
1710 67 : panMaskOffsetLsb[j].nMask));
1711 : }
1712 :
1713 : // Make sure that by discarding LSB we don't end up to a value
1714 : // that is no the nodata value
1715 86 : if (MustNotDiscardLsb(
1716 86 : reinterpret_cast<Teffective *>(pabyBuffer)[i + j],
1717 : bHasNoData, nNoDataValue))
1718 : {
1719 8 : reinterpret_cast<Teffective *>(pabyBuffer)[i + j] =
1720 4 : AdjustValue(nNoDataValue,
1721 4 : panMaskOffsetLsb[j].nRoundUpBitTest);
1722 : }
1723 : }
1724 : }
1725 : }
1726 145 : }
1727 :
1728 183 : static void DiscardLsb(GByte *pabyBuffer, GPtrDiff_t nBytes, int iBand,
1729 : int nBands, uint16_t nSampleFormat,
1730 : uint16_t nBitsPerSample, uint16_t nPlanarConfig,
1731 : const GTiffDataset::MaskOffset *panMaskOffsetLsb,
1732 : bool bHasNoData, double dfNoDataValue)
1733 : {
1734 183 : if (nBitsPerSample == 8 && nSampleFormat == SAMPLEFORMAT_UINT)
1735 : {
1736 38 : uint8_t nNoDataValue = 0;
1737 38 : if (bHasNoData && GDALIsValueExactAs<uint8_t>(dfNoDataValue))
1738 : {
1739 6 : nNoDataValue = static_cast<uint8_t>(dfNoDataValue);
1740 : }
1741 : else
1742 : {
1743 32 : bHasNoData = false;
1744 : }
1745 38 : if (nPlanarConfig == PLANARCONFIG_SEPARATE)
1746 : {
1747 25 : const auto nMask =
1748 25 : static_cast<unsigned>(panMaskOffsetLsb[iBand].nMask);
1749 25 : const auto nRoundUpBitTest =
1750 25 : static_cast<unsigned>(panMaskOffsetLsb[iBand].nRoundUpBitTest);
1751 50 : for (decltype(nBytes) i = 0; i < nBytes; ++i)
1752 : {
1753 25 : if (bHasNoData && pabyBuffer[i] == nNoDataValue)
1754 3 : continue;
1755 :
1756 : // Keep 255 in case it is alpha.
1757 22 : if (pabyBuffer[i] != 255)
1758 : {
1759 21 : if (pabyBuffer[i] & nRoundUpBitTest)
1760 5 : pabyBuffer[i] = static_cast<GByte>(
1761 5 : std::min(255U, (pabyBuffer[i] & nMask) +
1762 5 : (nRoundUpBitTest << 1U)));
1763 : else
1764 16 : pabyBuffer[i] =
1765 16 : static_cast<GByte>(pabyBuffer[i] & nMask);
1766 :
1767 : // Make sure that by discarding LSB we don't end up to a
1768 : // value that is no the nodata value
1769 21 : if (bHasNoData && pabyBuffer[i] == nNoDataValue)
1770 2 : pabyBuffer[i] =
1771 1 : AdjustValue(nNoDataValue, nRoundUpBitTest);
1772 : }
1773 : }
1774 : }
1775 : else
1776 : {
1777 26 : for (decltype(nBytes) i = 0; i < nBytes; i += nBands)
1778 : {
1779 42 : for (int j = 0; j < nBands; ++j)
1780 : {
1781 29 : if (bHasNoData && pabyBuffer[i + j] == nNoDataValue)
1782 2 : continue;
1783 :
1784 : // Keep 255 in case it is alpha.
1785 27 : if (pabyBuffer[i + j] != 255)
1786 : {
1787 25 : if (pabyBuffer[i + j] &
1788 25 : panMaskOffsetLsb[j].nRoundUpBitTest)
1789 : {
1790 6 : pabyBuffer[i + j] = static_cast<GByte>(std::min(
1791 12 : 255U,
1792 6 : (pabyBuffer[i + j] &
1793 : static_cast<unsigned>(
1794 6 : panMaskOffsetLsb[j].nMask)) +
1795 : (static_cast<unsigned>(
1796 6 : panMaskOffsetLsb[j].nRoundUpBitTest)
1797 6 : << 1U)));
1798 : }
1799 : else
1800 : {
1801 19 : pabyBuffer[i + j] = static_cast<GByte>(
1802 19 : pabyBuffer[i + j] & panMaskOffsetLsb[j].nMask);
1803 : }
1804 :
1805 : // Make sure that by discarding LSB we don't end up to a
1806 : // value that is no the nodata value
1807 25 : if (bHasNoData && pabyBuffer[i + j] == nNoDataValue)
1808 1 : pabyBuffer[i + j] = AdjustValue(
1809 : nNoDataValue,
1810 1 : panMaskOffsetLsb[j].nRoundUpBitTest);
1811 : }
1812 : }
1813 : }
1814 38 : }
1815 : }
1816 145 : else if (nBitsPerSample == 8 && nSampleFormat == SAMPLEFORMAT_INT)
1817 : {
1818 0 : int8_t nNoDataValue = 0;
1819 0 : if (bHasNoData && GDALIsValueExactAs<int8_t>(dfNoDataValue))
1820 : {
1821 0 : nNoDataValue = static_cast<int8_t>(dfNoDataValue);
1822 : }
1823 : else
1824 : {
1825 0 : bHasNoData = false;
1826 : }
1827 0 : DiscardLsbT<int8_t, int8_t>(pabyBuffer, nBytes, iBand, nBands,
1828 : nPlanarConfig, panMaskOffsetLsb, bHasNoData,
1829 0 : nNoDataValue);
1830 : }
1831 145 : else if (nBitsPerSample == 16 && nSampleFormat == SAMPLEFORMAT_INT)
1832 : {
1833 48 : int16_t nNoDataValue = 0;
1834 48 : if (bHasNoData && GDALIsValueExactAs<int16_t>(dfNoDataValue))
1835 : {
1836 6 : nNoDataValue = static_cast<int16_t>(dfNoDataValue);
1837 : }
1838 : else
1839 : {
1840 42 : bHasNoData = false;
1841 : }
1842 48 : DiscardLsbT<int16_t, int16_t>(pabyBuffer, nBytes, iBand, nBands,
1843 : nPlanarConfig, panMaskOffsetLsb,
1844 48 : bHasNoData, nNoDataValue);
1845 : }
1846 97 : else if (nBitsPerSample == 16 && nSampleFormat == SAMPLEFORMAT_UINT)
1847 : {
1848 33 : uint16_t nNoDataValue = 0;
1849 33 : if (bHasNoData && GDALIsValueExactAs<uint16_t>(dfNoDataValue))
1850 : {
1851 6 : nNoDataValue = static_cast<uint16_t>(dfNoDataValue);
1852 : }
1853 : else
1854 : {
1855 27 : bHasNoData = false;
1856 : }
1857 33 : DiscardLsbT<uint16_t, uint16_t>(pabyBuffer, nBytes, iBand, nBands,
1858 : nPlanarConfig, panMaskOffsetLsb,
1859 33 : bHasNoData, nNoDataValue);
1860 : }
1861 64 : else if (nBitsPerSample == 32 && nSampleFormat == SAMPLEFORMAT_INT)
1862 : {
1863 13 : int32_t nNoDataValue = 0;
1864 13 : if (bHasNoData && GDALIsValueExactAs<int32_t>(dfNoDataValue))
1865 : {
1866 6 : nNoDataValue = static_cast<int32_t>(dfNoDataValue);
1867 : }
1868 : else
1869 : {
1870 7 : bHasNoData = false;
1871 : }
1872 13 : DiscardLsbT<int32_t, int32_t>(pabyBuffer, nBytes, iBand, nBands,
1873 : nPlanarConfig, panMaskOffsetLsb,
1874 13 : bHasNoData, nNoDataValue);
1875 : }
1876 51 : else if (nBitsPerSample == 32 && nSampleFormat == SAMPLEFORMAT_UINT)
1877 : {
1878 13 : uint32_t nNoDataValue = 0;
1879 13 : if (bHasNoData && GDALIsValueExactAs<uint32_t>(dfNoDataValue))
1880 : {
1881 6 : nNoDataValue = static_cast<uint32_t>(dfNoDataValue);
1882 : }
1883 : else
1884 : {
1885 7 : bHasNoData = false;
1886 : }
1887 13 : DiscardLsbT<uint32_t, uint32_t>(pabyBuffer, nBytes, iBand, nBands,
1888 : nPlanarConfig, panMaskOffsetLsb,
1889 13 : bHasNoData, nNoDataValue);
1890 : }
1891 38 : else if (nBitsPerSample == 64 && nSampleFormat == SAMPLEFORMAT_INT)
1892 : {
1893 : // FIXME: we should not rely on dfNoDataValue when we support native
1894 : // data type for nodata
1895 0 : int64_t nNoDataValue = 0;
1896 0 : if (bHasNoData && GDALIsValueExactAs<int64_t>(dfNoDataValue))
1897 : {
1898 0 : nNoDataValue = static_cast<int64_t>(dfNoDataValue);
1899 : }
1900 : else
1901 : {
1902 0 : bHasNoData = false;
1903 : }
1904 0 : DiscardLsbT<int64_t, int64_t>(pabyBuffer, nBytes, iBand, nBands,
1905 : nPlanarConfig, panMaskOffsetLsb,
1906 0 : bHasNoData, nNoDataValue);
1907 : }
1908 38 : else if (nBitsPerSample == 64 && nSampleFormat == SAMPLEFORMAT_UINT)
1909 : {
1910 : // FIXME: we should not rely on dfNoDataValue when we support native
1911 : // data type for nodata
1912 0 : uint64_t nNoDataValue = 0;
1913 0 : if (bHasNoData && GDALIsValueExactAs<uint64_t>(dfNoDataValue))
1914 : {
1915 0 : nNoDataValue = static_cast<uint64_t>(dfNoDataValue);
1916 : }
1917 : else
1918 : {
1919 0 : bHasNoData = false;
1920 : }
1921 0 : DiscardLsbT<uint64_t, uint64_t>(pabyBuffer, nBytes, iBand, nBands,
1922 : nPlanarConfig, panMaskOffsetLsb,
1923 0 : bHasNoData, nNoDataValue);
1924 : }
1925 38 : else if (nBitsPerSample == 16 && nSampleFormat == SAMPLEFORMAT_IEEEFP)
1926 : {
1927 0 : const GFloat16 fNoDataValue = static_cast<GFloat16>(dfNoDataValue);
1928 0 : DiscardLsbT<GFloat16, uint16_t>(pabyBuffer, nBytes, iBand, nBands,
1929 : nPlanarConfig, panMaskOffsetLsb,
1930 0 : bHasNoData, fNoDataValue);
1931 : }
1932 38 : else if (nBitsPerSample == 32 && nSampleFormat == SAMPLEFORMAT_IEEEFP)
1933 : {
1934 19 : const float fNoDataValue = static_cast<float>(dfNoDataValue);
1935 19 : DiscardLsbT<float, uint32_t>(pabyBuffer, nBytes, iBand, nBands,
1936 : nPlanarConfig, panMaskOffsetLsb,
1937 19 : bHasNoData, fNoDataValue);
1938 : }
1939 19 : else if (nBitsPerSample == 64 && nSampleFormat == SAMPLEFORMAT_IEEEFP)
1940 : {
1941 19 : DiscardLsbT<double, uint64_t>(pabyBuffer, nBytes, iBand, nBands,
1942 : nPlanarConfig, panMaskOffsetLsb,
1943 : bHasNoData, dfNoDataValue);
1944 : }
1945 183 : }
1946 :
1947 183 : void GTiffDataset::DiscardLsb(GByte *pabyBuffer, GPtrDiff_t nBytes,
1948 : int iBand) const
1949 : {
1950 183 : ::DiscardLsb(pabyBuffer, nBytes, iBand, nBands, m_nSampleFormat,
1951 183 : m_nBitsPerSample, m_nPlanarConfig, m_panMaskOffsetLsb,
1952 183 : m_bNoDataSet, m_dfNoDataValue);
1953 183 : }
1954 :
1955 : /************************************************************************/
1956 : /* WriteEncodedTileOrStrip() */
1957 : /************************************************************************/
1958 :
1959 228575 : CPLErr GTiffDataset::WriteEncodedTileOrStrip(uint32_t tile_or_strip, void *data,
1960 : int bPreserveDataBuffer)
1961 : {
1962 228575 : CPLErr eErr = CE_None;
1963 :
1964 228575 : if (TIFFIsTiled(m_hTIFF))
1965 : {
1966 50276 : if (!(WriteEncodedTile(tile_or_strip, static_cast<GByte *>(data),
1967 : bPreserveDataBuffer)))
1968 : {
1969 14 : eErr = CE_Failure;
1970 : }
1971 : }
1972 : else
1973 : {
1974 178299 : if (!(WriteEncodedStrip(tile_or_strip, static_cast<GByte *>(data),
1975 : bPreserveDataBuffer)))
1976 : {
1977 8 : eErr = CE_Failure;
1978 : }
1979 : }
1980 :
1981 228575 : return eErr;
1982 : }
1983 :
1984 : /************************************************************************/
1985 : /* FlushBlockBuf() */
1986 : /************************************************************************/
1987 :
1988 9602 : CPLErr GTiffDataset::FlushBlockBuf()
1989 :
1990 : {
1991 9602 : if (m_nLoadedBlock < 0 || !m_bLoadedBlockDirty)
1992 0 : return CE_None;
1993 :
1994 9602 : m_bLoadedBlockDirty = false;
1995 :
1996 : const CPLErr eErr =
1997 9602 : WriteEncodedTileOrStrip(m_nLoadedBlock, m_pabyBlockBuf, true);
1998 9602 : if (eErr != CE_None)
1999 : {
2000 0 : ReportError(CE_Failure, CPLE_AppDefined,
2001 : "WriteEncodedTile/Strip() failed.");
2002 0 : m_bWriteError = true;
2003 : }
2004 :
2005 9602 : return eErr;
2006 : }
2007 :
2008 : /************************************************************************/
2009 : /* GTiffFillStreamableOffsetAndCount() */
2010 : /************************************************************************/
2011 :
2012 8 : static void GTiffFillStreamableOffsetAndCount(TIFF *hTIFF, int nSize)
2013 : {
2014 8 : uint32_t nXSize = 0;
2015 8 : uint32_t nYSize = 0;
2016 8 : TIFFGetField(hTIFF, TIFFTAG_IMAGEWIDTH, &nXSize);
2017 8 : TIFFGetField(hTIFF, TIFFTAG_IMAGELENGTH, &nYSize);
2018 8 : const bool bIsTiled = CPL_TO_BOOL(TIFFIsTiled(hTIFF));
2019 : const int nBlockCount =
2020 8 : bIsTiled ? TIFFNumberOfTiles(hTIFF) : TIFFNumberOfStrips(hTIFF);
2021 :
2022 8 : toff_t *panOffset = nullptr;
2023 8 : TIFFGetField(hTIFF, bIsTiled ? TIFFTAG_TILEOFFSETS : TIFFTAG_STRIPOFFSETS,
2024 : &panOffset);
2025 8 : toff_t *panSize = nullptr;
2026 8 : TIFFGetField(hTIFF,
2027 : bIsTiled ? TIFFTAG_TILEBYTECOUNTS : TIFFTAG_STRIPBYTECOUNTS,
2028 : &panSize);
2029 8 : toff_t nOffset = nSize;
2030 : // Trick to avoid clang static analyzer raising false positive about
2031 : // divide by zero later.
2032 8 : int nBlocksPerBand = 1;
2033 8 : uint32_t nRowsPerStrip = 0;
2034 8 : if (!bIsTiled)
2035 : {
2036 6 : TIFFGetField(hTIFF, TIFFTAG_ROWSPERSTRIP, &nRowsPerStrip);
2037 6 : if (nRowsPerStrip > static_cast<uint32_t>(nYSize))
2038 0 : nRowsPerStrip = nYSize;
2039 6 : nBlocksPerBand = DIV_ROUND_UP(nYSize, nRowsPerStrip);
2040 : }
2041 2947 : for (int i = 0; i < nBlockCount; ++i)
2042 : {
2043 : GPtrDiff_t cc = bIsTiled
2044 2939 : ? static_cast<GPtrDiff_t>(TIFFTileSize(hTIFF))
2045 2907 : : static_cast<GPtrDiff_t>(TIFFStripSize(hTIFF));
2046 2939 : if (!bIsTiled)
2047 : {
2048 : /* --------------------------------------------------------------------
2049 : */
2050 : /* If this is the last strip in the image, and is partial, then
2051 : */
2052 : /* we need to trim the number of scanlines written to the */
2053 : /* amount of valid data we have. (#2748) */
2054 : /* --------------------------------------------------------------------
2055 : */
2056 2907 : int nStripWithinBand = i % nBlocksPerBand;
2057 2907 : if (nStripWithinBand * nRowsPerStrip > nYSize - nRowsPerStrip)
2058 : {
2059 1 : cc = (cc / nRowsPerStrip) *
2060 1 : (nYSize - nStripWithinBand * nRowsPerStrip);
2061 : }
2062 : }
2063 2939 : panOffset[i] = nOffset;
2064 2939 : panSize[i] = cc;
2065 2939 : nOffset += cc;
2066 : }
2067 8 : }
2068 :
2069 : /************************************************************************/
2070 : /* Crystalize() */
2071 : /* */
2072 : /* Make sure that the directory information is written out for */
2073 : /* a new file, require before writing any imagery data. */
2074 : /************************************************************************/
2075 :
2076 2654080 : void GTiffDataset::Crystalize()
2077 :
2078 : {
2079 2654080 : if (m_bCrystalized)
2080 2648360 : return;
2081 :
2082 : // TODO: libtiff writes extended tags in the order they are specified
2083 : // and not in increasing order.
2084 5722 : WriteMetadata(this, m_hTIFF, true, m_eProfile, m_osFilename.c_str(),
2085 5722 : m_papszCreationOptions);
2086 5722 : WriteGeoTIFFInfo();
2087 5722 : if (m_bNoDataSet)
2088 338 : WriteNoDataValue(m_hTIFF, m_dfNoDataValue);
2089 5384 : else if (m_bNoDataSetAsInt64)
2090 4 : WriteNoDataValue(m_hTIFF, m_nNoDataValueInt64);
2091 5380 : else if (m_bNoDataSetAsUInt64)
2092 4 : WriteNoDataValue(m_hTIFF, m_nNoDataValueUInt64);
2093 :
2094 5722 : m_bMetadataChanged = false;
2095 5722 : m_bGeoTIFFInfoChanged = false;
2096 5722 : m_bNoDataChanged = false;
2097 5722 : m_bNeedsRewrite = false;
2098 :
2099 5722 : m_bCrystalized = true;
2100 :
2101 5722 : TIFFWriteCheck(m_hTIFF, TIFFIsTiled(m_hTIFF), "GTiffDataset::Crystalize");
2102 :
2103 5722 : TIFFWriteDirectory(m_hTIFF);
2104 5722 : if (m_bStreamingOut)
2105 : {
2106 : // We need to write twice the directory to be sure that custom
2107 : // TIFF tags are correctly sorted and that padding bytes have been
2108 : // added.
2109 3 : TIFFSetDirectory(m_hTIFF, 0);
2110 3 : TIFFWriteDirectory(m_hTIFF);
2111 :
2112 3 : if (VSIFSeekL(m_fpL, 0, SEEK_END) != 0)
2113 : {
2114 0 : ReportError(CE_Failure, CPLE_FileIO, "Could not seek");
2115 : }
2116 3 : const int nSize = static_cast<int>(VSIFTellL(m_fpL));
2117 :
2118 3 : TIFFSetDirectory(m_hTIFF, 0);
2119 3 : GTiffFillStreamableOffsetAndCount(m_hTIFF, nSize);
2120 3 : TIFFWriteDirectory(m_hTIFF);
2121 :
2122 3 : vsi_l_offset nDataLength = 0;
2123 : void *pabyBuffer =
2124 3 : VSIGetMemFileBuffer(m_pszTmpFilename, &nDataLength, FALSE);
2125 3 : if (static_cast<int>(VSIFWriteL(
2126 3 : pabyBuffer, 1, static_cast<int>(nDataLength), m_fpToWrite)) !=
2127 : static_cast<int>(nDataLength))
2128 : {
2129 0 : ReportError(CE_Failure, CPLE_FileIO, "Could not write %d bytes",
2130 : static_cast<int>(nDataLength));
2131 : }
2132 : // In case of single strip file, there's a libtiff check that would
2133 : // issue a warning since the file hasn't the required size.
2134 3 : CPLPushErrorHandler(CPLQuietErrorHandler);
2135 3 : TIFFSetDirectory(m_hTIFF, 0);
2136 3 : CPLPopErrorHandler();
2137 : }
2138 : else
2139 : {
2140 5719 : const tdir_t nNumberOfDirs = TIFFNumberOfDirectories(m_hTIFF);
2141 5719 : if (nNumberOfDirs > 0)
2142 : {
2143 5719 : TIFFSetDirectory(m_hTIFF, static_cast<tdir_t>(nNumberOfDirs - 1));
2144 : }
2145 : }
2146 :
2147 5722 : RestoreVolatileParameters(m_hTIFF);
2148 :
2149 5722 : m_nDirOffset = TIFFCurrentDirOffset(m_hTIFF);
2150 : }
2151 :
2152 : /************************************************************************/
2153 : /* FlushCache() */
2154 : /* */
2155 : /* We override this so we can also flush out local tiff strip */
2156 : /* cache if need be. */
2157 : /************************************************************************/
2158 :
2159 4543 : CPLErr GTiffDataset::FlushCache(bool bAtClosing)
2160 :
2161 : {
2162 4543 : return FlushCacheInternal(bAtClosing, true);
2163 : }
2164 :
2165 46338 : CPLErr GTiffDataset::FlushCacheInternal(bool bAtClosing, bool bFlushDirectory)
2166 : {
2167 46338 : if (m_bIsFinalized)
2168 2 : return CE_None;
2169 :
2170 46336 : CPLErr eErr = GDALPamDataset::FlushCache(bAtClosing);
2171 :
2172 46336 : if (m_bLoadedBlockDirty && m_nLoadedBlock != -1)
2173 : {
2174 262 : if (FlushBlockBuf() != CE_None)
2175 0 : eErr = CE_Failure;
2176 : }
2177 :
2178 46336 : CPLFree(m_pabyBlockBuf);
2179 46336 : m_pabyBlockBuf = nullptr;
2180 46336 : m_nLoadedBlock = -1;
2181 46336 : m_bLoadedBlockDirty = false;
2182 :
2183 : // Finish compression
2184 46336 : auto poQueue = m_poBaseDS ? m_poBaseDS->m_poCompressQueue.get()
2185 44014 : : m_poCompressQueue.get();
2186 46336 : if (poQueue)
2187 : {
2188 161 : poQueue->WaitCompletion();
2189 :
2190 : // Flush remaining data
2191 : // cppcheck-suppress constVariableReference
2192 :
2193 161 : auto &oQueue =
2194 161 : m_poBaseDS ? m_poBaseDS->m_asQueueJobIdx : m_asQueueJobIdx;
2195 230 : while (!oQueue.empty())
2196 : {
2197 69 : WaitCompletionForJobIdx(oQueue.front());
2198 : }
2199 : }
2200 :
2201 46336 : if (bFlushDirectory && GetAccess() == GA_Update)
2202 : {
2203 13861 : if (FlushDirectory() != CE_None)
2204 12 : eErr = CE_Failure;
2205 : }
2206 46336 : return eErr;
2207 : }
2208 :
2209 : /************************************************************************/
2210 : /* FlushDirectory() */
2211 : /************************************************************************/
2212 :
2213 21758 : CPLErr GTiffDataset::FlushDirectory()
2214 :
2215 : {
2216 21758 : CPLErr eErr = CE_None;
2217 :
2218 686 : const auto ReloadAllOtherDirectories = [this]()
2219 : {
2220 338 : const auto poBaseDS = m_poBaseDS ? m_poBaseDS : this;
2221 341 : for (auto &poOvrDS : poBaseDS->m_apoOverviewDS)
2222 : {
2223 3 : if (poOvrDS->m_bCrystalized && poOvrDS.get() != this)
2224 : {
2225 3 : poOvrDS->ReloadDirectory(true);
2226 : }
2227 :
2228 3 : if (poOvrDS->m_poMaskDS && poOvrDS->m_poMaskDS.get() != this &&
2229 0 : poOvrDS->m_poMaskDS->m_bCrystalized)
2230 : {
2231 0 : poOvrDS->m_poMaskDS->ReloadDirectory(true);
2232 : }
2233 : }
2234 338 : if (poBaseDS->m_poMaskDS && poBaseDS->m_poMaskDS.get() != this &&
2235 0 : poBaseDS->m_poMaskDS->m_bCrystalized)
2236 : {
2237 0 : poBaseDS->m_poMaskDS->ReloadDirectory(true);
2238 : }
2239 338 : if (poBaseDS->m_bCrystalized && poBaseDS != this)
2240 : {
2241 7 : poBaseDS->ReloadDirectory(true);
2242 : }
2243 338 : };
2244 :
2245 21758 : if (eAccess == GA_Update)
2246 : {
2247 15539 : if (m_bMetadataChanged)
2248 : {
2249 201 : m_bNeedsRewrite =
2250 201 : WriteMetadata(this, m_hTIFF, true, m_eProfile,
2251 201 : m_osFilename.c_str(), m_papszCreationOptions);
2252 201 : m_bMetadataChanged = false;
2253 :
2254 201 : if (m_bForceUnsetRPC)
2255 : {
2256 5 : double *padfRPCTag = nullptr;
2257 : uint16_t nCount;
2258 5 : if (TIFFGetField(m_hTIFF, TIFFTAG_RPCCOEFFICIENT, &nCount,
2259 5 : &padfRPCTag))
2260 : {
2261 3 : std::vector<double> zeroes(92);
2262 3 : TIFFSetField(m_hTIFF, TIFFTAG_RPCCOEFFICIENT, 92,
2263 : zeroes.data());
2264 3 : TIFFUnsetField(m_hTIFF, TIFFTAG_RPCCOEFFICIENT);
2265 3 : m_bNeedsRewrite = true;
2266 : }
2267 :
2268 5 : if (m_poBaseDS == nullptr)
2269 : {
2270 5 : GDALWriteRPCTXTFile(m_osFilename.c_str(), nullptr);
2271 5 : GDALWriteRPBFile(m_osFilename.c_str(), nullptr);
2272 : }
2273 : }
2274 : }
2275 :
2276 15539 : if (m_bGeoTIFFInfoChanged)
2277 : {
2278 145 : WriteGeoTIFFInfo();
2279 145 : m_bGeoTIFFInfoChanged = false;
2280 : }
2281 :
2282 15539 : if (m_bNoDataChanged)
2283 : {
2284 53 : if (m_bNoDataSet)
2285 : {
2286 37 : WriteNoDataValue(m_hTIFF, m_dfNoDataValue);
2287 : }
2288 16 : else if (m_bNoDataSetAsInt64)
2289 : {
2290 0 : WriteNoDataValue(m_hTIFF, m_nNoDataValueInt64);
2291 : }
2292 16 : else if (m_bNoDataSetAsUInt64)
2293 : {
2294 0 : WriteNoDataValue(m_hTIFF, m_nNoDataValueUInt64);
2295 : }
2296 : else
2297 : {
2298 16 : UnsetNoDataValue(m_hTIFF);
2299 : }
2300 53 : m_bNeedsRewrite = true;
2301 53 : m_bNoDataChanged = false;
2302 : }
2303 :
2304 15539 : if (m_bNeedsRewrite)
2305 : {
2306 363 : if (!m_bCrystalized)
2307 : {
2308 28 : Crystalize();
2309 : }
2310 : else
2311 : {
2312 335 : const TIFFSizeProc pfnSizeProc = TIFFGetSizeProc(m_hTIFF);
2313 :
2314 335 : m_nDirOffset = pfnSizeProc(TIFFClientdata(m_hTIFF));
2315 335 : if ((m_nDirOffset % 2) == 1)
2316 71 : ++m_nDirOffset;
2317 :
2318 335 : if (TIFFRewriteDirectory(m_hTIFF) == 0)
2319 0 : eErr = CE_Failure;
2320 :
2321 335 : TIFFSetSubDirectory(m_hTIFF, m_nDirOffset);
2322 :
2323 335 : ReloadAllOtherDirectories();
2324 :
2325 335 : if (m_bLayoutIFDSBeforeData && m_bBlockOrderRowMajor &&
2326 2 : m_bLeaderSizeAsUInt4 &&
2327 2 : m_bTrailerRepeatedLast4BytesRepeated &&
2328 2 : !m_bKnownIncompatibleEdition &&
2329 2 : !m_bWriteKnownIncompatibleEdition)
2330 : {
2331 2 : ReportError(CE_Warning, CPLE_AppDefined,
2332 : "The IFD has been rewritten at the end of "
2333 : "the file, which breaks COG layout.");
2334 2 : m_bKnownIncompatibleEdition = true;
2335 2 : m_bWriteKnownIncompatibleEdition = true;
2336 : }
2337 : }
2338 :
2339 363 : m_bNeedsRewrite = false;
2340 : }
2341 : }
2342 :
2343 : // There are some circumstances in which we can reach this point
2344 : // without having made this our directory (SetDirectory()) in which
2345 : // case we should not risk a flush.
2346 37297 : if (GetAccess() == GA_Update &&
2347 15539 : TIFFCurrentDirOffset(m_hTIFF) == m_nDirOffset)
2348 : {
2349 15539 : const TIFFSizeProc pfnSizeProc = TIFFGetSizeProc(m_hTIFF);
2350 :
2351 15539 : toff_t nNewDirOffset = pfnSizeProc(TIFFClientdata(m_hTIFF));
2352 15539 : if ((nNewDirOffset % 2) == 1)
2353 3413 : ++nNewDirOffset;
2354 :
2355 15539 : if (TIFFFlush(m_hTIFF) == 0)
2356 12 : eErr = CE_Failure;
2357 :
2358 15539 : if (m_nDirOffset != TIFFCurrentDirOffset(m_hTIFF))
2359 : {
2360 3 : m_nDirOffset = nNewDirOffset;
2361 3 : ReloadAllOtherDirectories();
2362 3 : CPLDebug("GTiff",
2363 : "directory moved during flush in FlushDirectory()");
2364 : }
2365 : }
2366 :
2367 21758 : SetDirectory();
2368 21758 : return eErr;
2369 : }
2370 :
2371 : /************************************************************************/
2372 : /* CleanOverviews() */
2373 : /************************************************************************/
2374 :
2375 5 : CPLErr GTiffDataset::CleanOverviews()
2376 :
2377 : {
2378 5 : CPLAssert(!m_poBaseDS);
2379 :
2380 5 : ScanDirectories();
2381 :
2382 5 : FlushDirectory();
2383 :
2384 : /* -------------------------------------------------------------------- */
2385 : /* Cleanup overviews objects, and get offsets to all overview */
2386 : /* directories. */
2387 : /* -------------------------------------------------------------------- */
2388 10 : std::vector<toff_t> anOvDirOffsets;
2389 :
2390 10 : for (auto &poOvrDS : m_apoOverviewDS)
2391 : {
2392 5 : anOvDirOffsets.push_back(poOvrDS->m_nDirOffset);
2393 5 : if (poOvrDS->m_poMaskDS)
2394 1 : anOvDirOffsets.push_back(poOvrDS->m_poMaskDS->m_nDirOffset);
2395 : }
2396 5 : m_apoOverviewDS.clear();
2397 :
2398 : /* -------------------------------------------------------------------- */
2399 : /* Loop through all the directories, translating the offsets */
2400 : /* into indexes we can use with TIFFUnlinkDirectory(). */
2401 : /* -------------------------------------------------------------------- */
2402 10 : std::vector<uint16_t> anOvDirIndexes;
2403 5 : int iThisOffset = 1;
2404 :
2405 5 : TIFFSetDirectory(m_hTIFF, 0);
2406 :
2407 : while (true)
2408 : {
2409 28 : for (toff_t nOffset : anOvDirOffsets)
2410 : {
2411 16 : if (nOffset == TIFFCurrentDirOffset(m_hTIFF))
2412 : {
2413 6 : anOvDirIndexes.push_back(static_cast<uint16_t>(iThisOffset));
2414 : }
2415 : }
2416 :
2417 12 : if (TIFFLastDirectory(m_hTIFF))
2418 5 : break;
2419 :
2420 7 : TIFFReadDirectory(m_hTIFF);
2421 7 : ++iThisOffset;
2422 7 : }
2423 :
2424 : /* -------------------------------------------------------------------- */
2425 : /* Actually unlink the target directories. Note that we do */
2426 : /* this from last to first so as to avoid renumbering any of */
2427 : /* the earlier directories we need to remove. */
2428 : /* -------------------------------------------------------------------- */
2429 11 : while (!anOvDirIndexes.empty())
2430 : {
2431 6 : TIFFUnlinkDirectory(m_hTIFF, anOvDirIndexes.back());
2432 6 : anOvDirIndexes.pop_back();
2433 : }
2434 :
2435 5 : if (m_poMaskDS)
2436 : {
2437 1 : m_poMaskDS->m_apoOverviewDS.clear();
2438 : }
2439 :
2440 5 : if (!SetDirectory())
2441 0 : return CE_Failure;
2442 :
2443 5 : return CE_None;
2444 : }
2445 :
2446 : /************************************************************************/
2447 : /* RegisterNewOverviewDataset() */
2448 : /************************************************************************/
2449 :
2450 510 : CPLErr GTiffDataset::RegisterNewOverviewDataset(toff_t nOverviewOffset,
2451 : int l_nJpegQuality,
2452 : CSLConstList papszOptions)
2453 : {
2454 : const auto GetOptionValue =
2455 5610 : [papszOptions](const char *pszOptionKey, const char *pszConfigOptionKey,
2456 11219 : const char **ppszKeyUsed = nullptr)
2457 : {
2458 5610 : const char *pszVal = CSLFetchNameValue(papszOptions, pszOptionKey);
2459 5610 : if (pszVal)
2460 : {
2461 1 : if (ppszKeyUsed)
2462 1 : *ppszKeyUsed = pszOptionKey;
2463 1 : return pszVal;
2464 : }
2465 5609 : pszVal = CSLFetchNameValue(papszOptions, pszConfigOptionKey);
2466 5609 : if (pszVal)
2467 : {
2468 0 : if (ppszKeyUsed)
2469 0 : *ppszKeyUsed = pszConfigOptionKey;
2470 0 : return pszVal;
2471 : }
2472 5609 : if (pszConfigOptionKey)
2473 : {
2474 5609 : pszVal = CPLGetConfigOption(pszConfigOptionKey, nullptr);
2475 5609 : if (pszVal && ppszKeyUsed)
2476 13 : *ppszKeyUsed = pszConfigOptionKey;
2477 : }
2478 5609 : return pszVal;
2479 510 : };
2480 :
2481 510 : int nZLevel = m_nZLevel;
2482 510 : if (const char *opt = GetOptionValue("ZLEVEL", "ZLEVEL_OVERVIEW"))
2483 : {
2484 4 : nZLevel = atoi(opt);
2485 : }
2486 :
2487 510 : int nZSTDLevel = m_nZSTDLevel;
2488 510 : if (const char *opt = GetOptionValue("ZSTD_LEVEL", "ZSTD_LEVEL_OVERVIEW"))
2489 : {
2490 4 : nZSTDLevel = atoi(opt);
2491 : }
2492 :
2493 510 : bool bWebpLossless = m_bWebPLossless;
2494 : const char *pszWebPLosslessOverview =
2495 510 : GetOptionValue("WEBP_LOSSLESS", "WEBP_LOSSLESS_OVERVIEW");
2496 510 : if (pszWebPLosslessOverview)
2497 : {
2498 2 : bWebpLossless = CPLTestBool(pszWebPLosslessOverview);
2499 : }
2500 :
2501 510 : int nWebpLevel = m_nWebPLevel;
2502 510 : const char *pszKeyWebpLevel = "";
2503 510 : if (const char *opt = GetOptionValue("WEBP_LEVEL", "WEBP_LEVEL_OVERVIEW",
2504 : &pszKeyWebpLevel))
2505 : {
2506 14 : if (pszWebPLosslessOverview == nullptr && m_bWebPLossless)
2507 : {
2508 1 : CPLDebug("GTiff",
2509 : "%s specified, but not WEBP_LOSSLESS_OVERVIEW. "
2510 : "Assuming WEBP_LOSSLESS_OVERVIEW=NO",
2511 : pszKeyWebpLevel);
2512 1 : bWebpLossless = false;
2513 : }
2514 13 : else if (bWebpLossless)
2515 : {
2516 0 : CPLError(CE_Warning, CPLE_AppDefined,
2517 : "%s is specified, but WEBP_LOSSLESS_OVERVIEW=YES. "
2518 : "%s will be ignored.",
2519 : pszKeyWebpLevel, pszKeyWebpLevel);
2520 : }
2521 14 : nWebpLevel = atoi(opt);
2522 : }
2523 :
2524 510 : double dfMaxZError = m_dfMaxZErrorOverview;
2525 510 : if (const char *opt = GetOptionValue("MAX_Z_ERROR", "MAX_Z_ERROR_OVERVIEW"))
2526 : {
2527 20 : dfMaxZError = CPLAtof(opt);
2528 : }
2529 :
2530 510 : signed char nJpegTablesMode = m_nJpegTablesMode;
2531 510 : if (const char *opt =
2532 510 : GetOptionValue("JPEG_TABLESMODE", "JPEG_TABLESMODE_OVERVIEW"))
2533 : {
2534 0 : nJpegTablesMode = static_cast<signed char>(atoi(opt));
2535 : }
2536 :
2537 : #ifdef HAVE_JXL
2538 510 : bool bJXLLossless = m_bJXLLossless;
2539 510 : if (const char *opt =
2540 510 : GetOptionValue("JXL_LOSSLESS", "JXL_LOSSLESS_OVERVIEW"))
2541 : {
2542 0 : bJXLLossless = CPLTestBool(opt);
2543 : }
2544 :
2545 510 : float fJXLDistance = m_fJXLDistance;
2546 510 : if (const char *opt =
2547 510 : GetOptionValue("JXL_DISTANCE", "JXL_DISTANCE_OVERVIEW"))
2548 : {
2549 0 : fJXLDistance = static_cast<float>(CPLAtof(opt));
2550 : }
2551 :
2552 510 : float fJXLAlphaDistance = m_fJXLAlphaDistance;
2553 510 : if (const char *opt =
2554 510 : GetOptionValue("JXL_ALPHA_DISTANCE", "JXL_ALPHA_DISTANCE_OVERVIEW"))
2555 : {
2556 0 : fJXLAlphaDistance = static_cast<float>(CPLAtof(opt));
2557 : }
2558 :
2559 510 : int nJXLEffort = m_nJXLEffort;
2560 510 : if (const char *opt = GetOptionValue("JXL_EFFORT", "JXL_EFFORT_OVERVIEW"))
2561 : {
2562 0 : nJXLEffort = atoi(opt);
2563 : }
2564 : #endif
2565 :
2566 1020 : auto poODS = std::make_shared<GTiffDataset>();
2567 510 : poODS->ShareLockWithParentDataset(this);
2568 510 : poODS->eAccess = GA_Update;
2569 510 : poODS->m_osFilename = m_osFilename;
2570 510 : const char *pszSparseOK = GetOptionValue("SPARSE_OK", "SPARSE_OK_OVERVIEW");
2571 510 : if (pszSparseOK && CPLTestBool(pszSparseOK))
2572 : {
2573 1 : poODS->m_bWriteEmptyTiles = false;
2574 1 : poODS->m_bFillEmptyTilesAtClosing = false;
2575 : }
2576 : else
2577 : {
2578 509 : poODS->m_bWriteEmptyTiles = m_bWriteEmptyTiles;
2579 509 : poODS->m_bFillEmptyTilesAtClosing = m_bFillEmptyTilesAtClosing;
2580 : }
2581 510 : poODS->m_nJpegQuality = static_cast<signed char>(l_nJpegQuality);
2582 510 : poODS->m_nWebPLevel = static_cast<signed char>(nWebpLevel);
2583 510 : poODS->m_nZLevel = static_cast<signed char>(nZLevel);
2584 510 : poODS->m_nLZMAPreset = m_nLZMAPreset;
2585 510 : poODS->m_nZSTDLevel = static_cast<signed char>(nZSTDLevel);
2586 510 : poODS->m_bWebPLossless = bWebpLossless;
2587 510 : poODS->m_nJpegTablesMode = nJpegTablesMode;
2588 510 : poODS->m_dfMaxZError = dfMaxZError;
2589 510 : poODS->m_dfMaxZErrorOverview = dfMaxZError;
2590 1020 : memcpy(poODS->m_anLercAddCompressionAndVersion,
2591 510 : m_anLercAddCompressionAndVersion,
2592 : sizeof(m_anLercAddCompressionAndVersion));
2593 : #ifdef HAVE_JXL
2594 510 : poODS->m_bJXLLossless = bJXLLossless;
2595 510 : poODS->m_fJXLDistance = fJXLDistance;
2596 510 : poODS->m_fJXLAlphaDistance = fJXLAlphaDistance;
2597 510 : poODS->m_nJXLEffort = nJXLEffort;
2598 : #endif
2599 :
2600 510 : if (poODS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF), nOverviewOffset,
2601 510 : GA_Update) != CE_None)
2602 : {
2603 0 : return CE_Failure;
2604 : }
2605 :
2606 : // Assign color interpretation from main dataset
2607 510 : const int l_nBands = GetRasterCount();
2608 1524 : for (int i = 1; i <= l_nBands; i++)
2609 : {
2610 1014 : auto poBand = dynamic_cast<GTiffRasterBand *>(poODS->GetRasterBand(i));
2611 1014 : if (poBand)
2612 1014 : poBand->m_eBandInterp = GetRasterBand(i)->GetColorInterpretation();
2613 : }
2614 :
2615 : // Do that now that m_nCompression is set
2616 510 : poODS->RestoreVolatileParameters(poODS->m_hTIFF);
2617 :
2618 510 : poODS->m_poBaseDS = this;
2619 510 : poODS->m_bIsOverview = true;
2620 :
2621 510 : m_apoOverviewDS.push_back(std::move(poODS));
2622 510 : return CE_None;
2623 : }
2624 :
2625 : /************************************************************************/
2626 : /* CreateTIFFColorTable() */
2627 : /************************************************************************/
2628 :
2629 12 : static void CreateTIFFColorTable(
2630 : GDALColorTable *poColorTable, int nBits, int nColorTableMultiplier,
2631 : std::vector<unsigned short> &anTRed, std::vector<unsigned short> &anTGreen,
2632 : std::vector<unsigned short> &anTBlue, unsigned short *&panRed,
2633 : unsigned short *&panGreen, unsigned short *&panBlue)
2634 : {
2635 : int nColors;
2636 :
2637 12 : if (nBits == 8)
2638 12 : nColors = 256;
2639 0 : else if (nBits < 8)
2640 0 : nColors = 1 << nBits;
2641 : else
2642 0 : nColors = 65536;
2643 :
2644 12 : anTRed.resize(nColors, 0);
2645 12 : anTGreen.resize(nColors, 0);
2646 12 : anTBlue.resize(nColors, 0);
2647 :
2648 3084 : for (int iColor = 0; iColor < nColors; ++iColor)
2649 : {
2650 3072 : if (iColor < poColorTable->GetColorEntryCount())
2651 : {
2652 : GDALColorEntry sRGB;
2653 :
2654 3072 : poColorTable->GetColorEntryAsRGB(iColor, &sRGB);
2655 :
2656 3072 : anTRed[iColor] = GTiffDataset::ClampCTEntry(iColor, 1, sRGB.c1,
2657 : nColorTableMultiplier);
2658 3072 : anTGreen[iColor] = GTiffDataset::ClampCTEntry(
2659 3072 : iColor, 2, sRGB.c2, nColorTableMultiplier);
2660 3072 : anTBlue[iColor] = GTiffDataset::ClampCTEntry(iColor, 3, sRGB.c3,
2661 : nColorTableMultiplier);
2662 : }
2663 : else
2664 : {
2665 0 : anTRed[iColor] = 0;
2666 0 : anTGreen[iColor] = 0;
2667 0 : anTBlue[iColor] = 0;
2668 : }
2669 : }
2670 :
2671 12 : panRed = &(anTRed[0]);
2672 12 : panGreen = &(anTGreen[0]);
2673 12 : panBlue = &(anTBlue[0]);
2674 12 : }
2675 :
2676 : /************************************************************************/
2677 : /* GetOverviewParameters() */
2678 : /************************************************************************/
2679 :
2680 327 : bool GTiffDataset::GetOverviewParameters(
2681 : int &nCompression, uint16_t &nPlanarConfig, uint16_t &nPredictor,
2682 : uint16_t &nPhotometric, int &nOvrJpegQuality, std::string &osNoData,
2683 : uint16_t *&panExtraSampleValues, uint16_t &nExtraSamples,
2684 : CSLConstList papszOptions) const
2685 : {
2686 : const auto GetOptionValue =
2687 1083 : [papszOptions](const char *pszOptionKey, const char *pszConfigOptionKey,
2688 2158 : const char **ppszKeyUsed = nullptr)
2689 : {
2690 1083 : const char *pszVal = CSLFetchNameValue(papszOptions, pszOptionKey);
2691 1083 : if (pszVal)
2692 : {
2693 8 : if (ppszKeyUsed)
2694 8 : *ppszKeyUsed = pszOptionKey;
2695 8 : return pszVal;
2696 : }
2697 1075 : pszVal = CSLFetchNameValue(papszOptions, pszConfigOptionKey);
2698 1075 : if (pszVal)
2699 : {
2700 0 : if (ppszKeyUsed)
2701 0 : *ppszKeyUsed = pszConfigOptionKey;
2702 0 : return pszVal;
2703 : }
2704 1075 : pszVal = CPLGetConfigOption(pszConfigOptionKey, nullptr);
2705 1075 : if (pszVal && ppszKeyUsed)
2706 58 : *ppszKeyUsed = pszConfigOptionKey;
2707 1075 : return pszVal;
2708 327 : };
2709 :
2710 : /* -------------------------------------------------------------------- */
2711 : /* Determine compression method. */
2712 : /* -------------------------------------------------------------------- */
2713 327 : nCompression = m_nCompression;
2714 327 : const char *pszOptionKey = "";
2715 : const char *pszCompressValue =
2716 327 : GetOptionValue("COMPRESS", "COMPRESS_OVERVIEW", &pszOptionKey);
2717 327 : if (pszCompressValue != nullptr)
2718 : {
2719 56 : nCompression =
2720 56 : GTIFFGetCompressionMethod(pszCompressValue, pszOptionKey);
2721 56 : if (nCompression < 0)
2722 : {
2723 0 : nCompression = m_nCompression;
2724 : }
2725 : }
2726 :
2727 : /* -------------------------------------------------------------------- */
2728 : /* Determine planar configuration. */
2729 : /* -------------------------------------------------------------------- */
2730 327 : nPlanarConfig = m_nPlanarConfig;
2731 327 : if (nCompression == COMPRESSION_WEBP)
2732 : {
2733 11 : nPlanarConfig = PLANARCONFIG_CONTIG;
2734 : }
2735 : const char *pszInterleave =
2736 327 : GetOptionValue("INTERLEAVE", "INTERLEAVE_OVERVIEW", &pszOptionKey);
2737 327 : if (pszInterleave != nullptr && pszInterleave[0] != '\0')
2738 : {
2739 2 : if (EQUAL(pszInterleave, "PIXEL"))
2740 1 : nPlanarConfig = PLANARCONFIG_CONTIG;
2741 1 : else if (EQUAL(pszInterleave, "BAND"))
2742 1 : nPlanarConfig = PLANARCONFIG_SEPARATE;
2743 : else
2744 : {
2745 0 : CPLError(CE_Warning, CPLE_AppDefined,
2746 : "%s=%s unsupported, "
2747 : "value must be PIXEL or BAND. ignoring",
2748 : pszOptionKey, pszInterleave);
2749 : }
2750 : }
2751 :
2752 : /* -------------------------------------------------------------------- */
2753 : /* Determine predictor tag */
2754 : /* -------------------------------------------------------------------- */
2755 327 : nPredictor = PREDICTOR_NONE;
2756 327 : if (GTIFFSupportsPredictor(nCompression))
2757 : {
2758 : const char *pszPredictor =
2759 75 : GetOptionValue("PREDICTOR", "PREDICTOR_OVERVIEW");
2760 75 : if (pszPredictor != nullptr)
2761 : {
2762 1 : nPredictor = static_cast<uint16_t>(atoi(pszPredictor));
2763 : }
2764 74 : else if (GTIFFSupportsPredictor(m_nCompression))
2765 73 : TIFFGetField(m_hTIFF, TIFFTAG_PREDICTOR, &nPredictor);
2766 : }
2767 :
2768 : /* -------------------------------------------------------------------- */
2769 : /* Determine photometric tag */
2770 : /* -------------------------------------------------------------------- */
2771 327 : if (m_nPhotometric == PHOTOMETRIC_YCBCR && nCompression != COMPRESSION_JPEG)
2772 1 : nPhotometric = PHOTOMETRIC_RGB;
2773 : else
2774 326 : nPhotometric = m_nPhotometric;
2775 : const char *pszPhotometric =
2776 327 : GetOptionValue("PHOTOMETRIC", "PHOTOMETRIC_OVERVIEW", &pszOptionKey);
2777 327 : if (!GTIFFUpdatePhotometric(pszPhotometric, pszOptionKey, nCompression,
2778 327 : pszInterleave, nBands, nPhotometric,
2779 : nPlanarConfig))
2780 : {
2781 0 : return false;
2782 : }
2783 :
2784 : /* -------------------------------------------------------------------- */
2785 : /* Determine JPEG quality */
2786 : /* -------------------------------------------------------------------- */
2787 327 : nOvrJpegQuality = m_nJpegQuality;
2788 327 : if (nCompression == COMPRESSION_JPEG)
2789 : {
2790 : const char *pszJPEGQuality =
2791 27 : GetOptionValue("JPEG_QUALITY", "JPEG_QUALITY_OVERVIEW");
2792 27 : if (pszJPEGQuality != nullptr)
2793 : {
2794 9 : nOvrJpegQuality = atoi(pszJPEGQuality);
2795 : }
2796 : }
2797 :
2798 : /* -------------------------------------------------------------------- */
2799 : /* Set nodata. */
2800 : /* -------------------------------------------------------------------- */
2801 327 : if (m_bNoDataSet)
2802 : {
2803 17 : osNoData = GTiffFormatGDALNoDataTagValue(m_dfNoDataValue);
2804 : }
2805 :
2806 : /* -------------------------------------------------------------------- */
2807 : /* Fetch extra sample tag */
2808 : /* -------------------------------------------------------------------- */
2809 327 : panExtraSampleValues = nullptr;
2810 327 : nExtraSamples = 0;
2811 327 : if (TIFFGetField(m_hTIFF, TIFFTAG_EXTRASAMPLES, &nExtraSamples,
2812 327 : &panExtraSampleValues))
2813 : {
2814 : uint16_t *panExtraSampleValuesNew = static_cast<uint16_t *>(
2815 40 : CPLMalloc(nExtraSamples * sizeof(uint16_t)));
2816 40 : memcpy(panExtraSampleValuesNew, panExtraSampleValues,
2817 40 : nExtraSamples * sizeof(uint16_t));
2818 40 : panExtraSampleValues = panExtraSampleValuesNew;
2819 : }
2820 : else
2821 : {
2822 287 : panExtraSampleValues = nullptr;
2823 287 : nExtraSamples = 0;
2824 : }
2825 :
2826 327 : return true;
2827 : }
2828 :
2829 : /************************************************************************/
2830 : /* CreateOverviewsFromSrcOverviews() */
2831 : /************************************************************************/
2832 :
2833 : // If poOvrDS is not null, it is used and poSrcDS is ignored.
2834 :
2835 69 : CPLErr GTiffDataset::CreateOverviewsFromSrcOverviews(GDALDataset *poSrcDS,
2836 : GDALDataset *poOvrDS,
2837 : int nOverviews)
2838 : {
2839 69 : CPLAssert(poSrcDS->GetRasterCount() != 0);
2840 69 : CPLAssert(m_apoOverviewDS.empty());
2841 :
2842 69 : ScanDirectories();
2843 :
2844 69 : FlushDirectory();
2845 :
2846 69 : int nOvBitsPerSample = m_nBitsPerSample;
2847 :
2848 : /* -------------------------------------------------------------------- */
2849 : /* Do we need some metadata for the overviews? */
2850 : /* -------------------------------------------------------------------- */
2851 138 : CPLString osMetadata;
2852 :
2853 69 : GTIFFBuildOverviewMetadata("NONE", this, false, osMetadata);
2854 :
2855 : int nCompression;
2856 : uint16_t nPlanarConfig;
2857 : uint16_t nPredictor;
2858 : uint16_t nPhotometric;
2859 : int nOvrJpegQuality;
2860 138 : std::string osNoData;
2861 69 : uint16_t *panExtraSampleValues = nullptr;
2862 69 : uint16_t nExtraSamples = 0;
2863 69 : if (!GetOverviewParameters(nCompression, nPlanarConfig, nPredictor,
2864 : nPhotometric, nOvrJpegQuality, osNoData,
2865 : panExtraSampleValues, nExtraSamples,
2866 : /*papszOptions=*/nullptr))
2867 : {
2868 0 : return CE_Failure;
2869 : }
2870 :
2871 : /* -------------------------------------------------------------------- */
2872 : /* Do we have a palette? If so, create a TIFF compatible version. */
2873 : /* -------------------------------------------------------------------- */
2874 138 : std::vector<unsigned short> anTRed;
2875 138 : std::vector<unsigned short> anTGreen;
2876 69 : std::vector<unsigned short> anTBlue;
2877 69 : unsigned short *panRed = nullptr;
2878 69 : unsigned short *panGreen = nullptr;
2879 69 : unsigned short *panBlue = nullptr;
2880 :
2881 69 : if (nPhotometric == PHOTOMETRIC_PALETTE && m_poColorTable != nullptr)
2882 : {
2883 0 : if (m_nColorTableMultiplier == 0)
2884 0 : m_nColorTableMultiplier = DEFAULT_COLOR_TABLE_MULTIPLIER_257;
2885 :
2886 0 : CreateTIFFColorTable(m_poColorTable.get(), nOvBitsPerSample,
2887 : m_nColorTableMultiplier, anTRed, anTGreen, anTBlue,
2888 : panRed, panGreen, panBlue);
2889 : }
2890 :
2891 69 : int nOvrBlockXSize = 0;
2892 69 : int nOvrBlockYSize = 0;
2893 69 : GTIFFGetOverviewBlockSize(GDALRasterBand::ToHandle(GetRasterBand(1)),
2894 : &nOvrBlockXSize, &nOvrBlockYSize, nullptr,
2895 : nullptr);
2896 :
2897 69 : CPLErr eErr = CE_None;
2898 :
2899 195 : for (int i = 0; i < nOverviews && eErr == CE_None; ++i)
2900 : {
2901 : GDALRasterBand *poOvrBand =
2902 163 : poOvrDS ? ((i == 0) ? poOvrDS->GetRasterBand(1)
2903 37 : : poOvrDS->GetRasterBand(1)->GetOverview(i - 1))
2904 55 : : poSrcDS->GetRasterBand(1)->GetOverview(i);
2905 :
2906 126 : int nOXSize = poOvrBand->GetXSize();
2907 126 : int nOYSize = poOvrBand->GetYSize();
2908 :
2909 252 : toff_t nOverviewOffset = GTIFFWriteDirectory(
2910 : m_hTIFF, FILETYPE_REDUCEDIMAGE, nOXSize, nOYSize, nOvBitsPerSample,
2911 126 : nPlanarConfig, m_nSamplesPerPixel, nOvrBlockXSize, nOvrBlockYSize,
2912 126 : TRUE, nCompression, nPhotometric, m_nSampleFormat, nPredictor,
2913 : panRed, panGreen, panBlue, nExtraSamples, panExtraSampleValues,
2914 : osMetadata,
2915 126 : nOvrJpegQuality >= 0 ? CPLSPrintf("%d", nOvrJpegQuality) : nullptr,
2916 126 : CPLSPrintf("%d", m_nJpegTablesMode),
2917 2 : osNoData.empty() ? nullptr : osNoData.c_str(),
2918 126 : m_anLercAddCompressionAndVersion, m_bWriteCOGLayout);
2919 :
2920 126 : if (nOverviewOffset == 0)
2921 0 : eErr = CE_Failure;
2922 : else
2923 126 : eErr = RegisterNewOverviewDataset(nOverviewOffset, nOvrJpegQuality,
2924 : nullptr);
2925 : }
2926 :
2927 : // For directory reloading, so that the chaining to the next directory is
2928 : // reloaded, as well as compression parameters.
2929 69 : ReloadDirectory();
2930 :
2931 69 : CPLFree(panExtraSampleValues);
2932 69 : panExtraSampleValues = nullptr;
2933 :
2934 69 : return eErr;
2935 : }
2936 :
2937 : /************************************************************************/
2938 : /* CreateInternalMaskOverviews() */
2939 : /************************************************************************/
2940 :
2941 273 : CPLErr GTiffDataset::CreateInternalMaskOverviews(int nOvrBlockXSize,
2942 : int nOvrBlockYSize)
2943 : {
2944 273 : ScanDirectories();
2945 :
2946 : /* -------------------------------------------------------------------- */
2947 : /* Create overviews for the mask. */
2948 : /* -------------------------------------------------------------------- */
2949 273 : CPLErr eErr = CE_None;
2950 :
2951 273 : if (m_poMaskDS != nullptr && m_poMaskDS->GetRasterCount() == 1)
2952 : {
2953 : int nMaskOvrCompression;
2954 43 : if (strstr(GDALGetMetadataItem(GDALGetDriverByName("GTiff"),
2955 : GDAL_DMD_CREATIONOPTIONLIST, nullptr),
2956 43 : "<Value>DEFLATE</Value>") != nullptr)
2957 43 : nMaskOvrCompression = COMPRESSION_ADOBE_DEFLATE;
2958 : else
2959 0 : nMaskOvrCompression = COMPRESSION_PACKBITS;
2960 :
2961 115 : for (auto &poOvrDS : m_apoOverviewDS)
2962 : {
2963 72 : if (poOvrDS->m_poMaskDS == nullptr)
2964 : {
2965 60 : const toff_t nOverviewOffset = GTIFFWriteDirectory(
2966 : m_hTIFF, FILETYPE_REDUCEDIMAGE | FILETYPE_MASK,
2967 60 : poOvrDS->nRasterXSize, poOvrDS->nRasterYSize, 1,
2968 : PLANARCONFIG_CONTIG, 1, nOvrBlockXSize, nOvrBlockYSize,
2969 : TRUE, nMaskOvrCompression, PHOTOMETRIC_MASK,
2970 : SAMPLEFORMAT_UINT, PREDICTOR_NONE, nullptr, nullptr,
2971 : nullptr, 0, nullptr, "", nullptr, nullptr, nullptr, nullptr,
2972 60 : m_bWriteCOGLayout);
2973 :
2974 60 : if (nOverviewOffset == 0)
2975 : {
2976 0 : eErr = CE_Failure;
2977 0 : continue;
2978 : }
2979 :
2980 120 : auto poMaskODS = std::make_shared<GTiffDataset>();
2981 60 : poMaskODS->eAccess = GA_Update;
2982 60 : poMaskODS->ShareLockWithParentDataset(this);
2983 60 : poMaskODS->m_osFilename = m_osFilename;
2984 60 : if (poMaskODS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF),
2985 : nOverviewOffset,
2986 60 : GA_Update) != CE_None)
2987 : {
2988 0 : eErr = CE_Failure;
2989 : }
2990 : else
2991 : {
2992 120 : poMaskODS->m_bPromoteTo8Bits =
2993 60 : CPLTestBool(CPLGetConfigOption(
2994 : "GDAL_TIFF_INTERNAL_MASK_TO_8BIT", "YES"));
2995 60 : poMaskODS->m_poBaseDS = this;
2996 60 : poMaskODS->m_poImageryDS = poOvrDS.get();
2997 60 : poOvrDS->m_poMaskDS = poMaskODS;
2998 60 : m_poMaskDS->m_apoOverviewDS.push_back(std::move(poMaskODS));
2999 : }
3000 : }
3001 : }
3002 : }
3003 :
3004 273 : ReloadDirectory();
3005 :
3006 273 : return eErr;
3007 : }
3008 :
3009 : /************************************************************************/
3010 : /* AddOverviews() */
3011 : /************************************************************************/
3012 :
3013 : CPLErr
3014 13 : GTiffDataset::AddOverviews(const std::vector<GDALDataset *> &apoSrcOvrDSIn,
3015 : GDALProgressFunc pfnProgress, void *pProgressData,
3016 : CSLConstList papszOptions)
3017 : {
3018 : /* -------------------------------------------------------------------- */
3019 : /* If we don't have read access, then create the overviews */
3020 : /* externally. */
3021 : /* -------------------------------------------------------------------- */
3022 13 : if (GetAccess() != GA_Update)
3023 : {
3024 4 : CPLDebug("GTiff", "File open for read-only accessing, "
3025 : "creating overviews externally.");
3026 :
3027 4 : CPLErr eErr = GDALDataset::AddOverviews(apoSrcOvrDSIn, pfnProgress,
3028 : pProgressData, papszOptions);
3029 4 : if (eErr == CE_None && m_poMaskDS)
3030 : {
3031 0 : ReportError(
3032 : CE_Warning, CPLE_NotSupported,
3033 : "Building external overviews whereas there is an internal "
3034 : "mask is not fully supported. "
3035 : "The overviews of the non-mask bands will be created, "
3036 : "but not the overviews of the mask band.");
3037 : }
3038 4 : return eErr;
3039 : }
3040 :
3041 18 : std::vector<GDALDataset *> apoSrcOvrDS = apoSrcOvrDSIn;
3042 : // Sort overviews by descending size
3043 9 : std::sort(apoSrcOvrDS.begin(), apoSrcOvrDS.end(),
3044 0 : [](const GDALDataset *poDS1, const GDALDataset *poDS2)
3045 0 : { return poDS1->GetRasterXSize() > poDS2->GetRasterXSize(); });
3046 :
3047 9 : if (!GDALDefaultOverviews::CheckSrcOverviewsConsistencyWithBase(
3048 : this, apoSrcOvrDS))
3049 5 : return CE_Failure;
3050 :
3051 4 : ScanDirectories();
3052 :
3053 : // Make implicit JPEG overviews invisible, but do not destroy
3054 : // them in case they are already used (not sure that the client
3055 : // has the right to do that). Behavior maybe undefined in GDAL API.
3056 4 : std::swap(m_apoJPEGOverviewDSOld, m_apoJPEGOverviewDS);
3057 4 : m_apoJPEGOverviewDS.clear();
3058 :
3059 4 : FlushDirectory();
3060 :
3061 : /* -------------------------------------------------------------------- */
3062 : /* If we are averaging bit data to grayscale we need to create */
3063 : /* 8bit overviews. */
3064 : /* -------------------------------------------------------------------- */
3065 4 : int nOvBitsPerSample = m_nBitsPerSample;
3066 :
3067 : /* -------------------------------------------------------------------- */
3068 : /* Do we need some metadata for the overviews? */
3069 : /* -------------------------------------------------------------------- */
3070 8 : CPLString osMetadata;
3071 :
3072 4 : const bool bIsForMaskBand = nBands == 1 && GetRasterBand(1)->IsMaskBand();
3073 4 : GTIFFBuildOverviewMetadata(/* resampling = */ "", this, bIsForMaskBand,
3074 : osMetadata);
3075 :
3076 : int nCompression;
3077 : uint16_t nPlanarConfig;
3078 : uint16_t nPredictor;
3079 : uint16_t nPhotometric;
3080 : int nOvrJpegQuality;
3081 8 : std::string osNoData;
3082 4 : uint16_t *panExtraSampleValues = nullptr;
3083 4 : uint16_t nExtraSamples = 0;
3084 4 : if (!GetOverviewParameters(nCompression, nPlanarConfig, nPredictor,
3085 : nPhotometric, nOvrJpegQuality, osNoData,
3086 : panExtraSampleValues, nExtraSamples,
3087 : papszOptions))
3088 : {
3089 0 : return CE_Failure;
3090 : }
3091 :
3092 : /* -------------------------------------------------------------------- */
3093 : /* Do we have a palette? If so, create a TIFF compatible version. */
3094 : /* -------------------------------------------------------------------- */
3095 8 : std::vector<unsigned short> anTRed;
3096 8 : std::vector<unsigned short> anTGreen;
3097 4 : std::vector<unsigned short> anTBlue;
3098 4 : unsigned short *panRed = nullptr;
3099 4 : unsigned short *panGreen = nullptr;
3100 4 : unsigned short *panBlue = nullptr;
3101 :
3102 4 : if (nPhotometric == PHOTOMETRIC_PALETTE && m_poColorTable != nullptr)
3103 : {
3104 0 : if (m_nColorTableMultiplier == 0)
3105 0 : m_nColorTableMultiplier = DEFAULT_COLOR_TABLE_MULTIPLIER_257;
3106 :
3107 0 : CreateTIFFColorTable(m_poColorTable.get(), nOvBitsPerSample,
3108 : m_nColorTableMultiplier, anTRed, anTGreen, anTBlue,
3109 : panRed, panGreen, panBlue);
3110 : }
3111 :
3112 : /* -------------------------------------------------------------------- */
3113 : /* Establish which of the overview levels we already have, and */
3114 : /* which are new. We assume that band 1 of the file is */
3115 : /* representative. */
3116 : /* -------------------------------------------------------------------- */
3117 4 : int nOvrBlockXSize = 0;
3118 4 : int nOvrBlockYSize = 0;
3119 4 : GTIFFGetOverviewBlockSize(GDALRasterBand::ToHandle(GetRasterBand(1)),
3120 : &nOvrBlockXSize, &nOvrBlockYSize, papszOptions,
3121 : "BLOCKSIZE");
3122 :
3123 4 : CPLErr eErr = CE_None;
3124 8 : for (const auto *poSrcOvrDS : apoSrcOvrDS)
3125 : {
3126 4 : bool bFound = false;
3127 4 : for (auto &poOvrDS : m_apoOverviewDS)
3128 : {
3129 4 : if (poOvrDS->GetRasterXSize() == poSrcOvrDS->GetRasterXSize() &&
3130 2 : poOvrDS->GetRasterYSize() == poSrcOvrDS->GetRasterYSize())
3131 : {
3132 2 : bFound = true;
3133 2 : break;
3134 : }
3135 : }
3136 4 : if (!bFound && eErr == CE_None)
3137 : {
3138 2 : if (m_bLayoutIFDSBeforeData && !m_bKnownIncompatibleEdition &&
3139 0 : !m_bWriteKnownIncompatibleEdition)
3140 : {
3141 0 : ReportError(CE_Warning, CPLE_AppDefined,
3142 : "Adding new overviews invalidates the "
3143 : "LAYOUT=IFDS_BEFORE_DATA property");
3144 0 : m_bKnownIncompatibleEdition = true;
3145 0 : m_bWriteKnownIncompatibleEdition = true;
3146 : }
3147 :
3148 6 : const toff_t nOverviewOffset = GTIFFWriteDirectory(
3149 : m_hTIFF, FILETYPE_REDUCEDIMAGE, poSrcOvrDS->GetRasterXSize(),
3150 : poSrcOvrDS->GetRasterYSize(), nOvBitsPerSample, nPlanarConfig,
3151 2 : m_nSamplesPerPixel, nOvrBlockXSize, nOvrBlockYSize, TRUE,
3152 2 : nCompression, nPhotometric, m_nSampleFormat, nPredictor, panRed,
3153 : panGreen, panBlue, nExtraSamples, panExtraSampleValues,
3154 : osMetadata,
3155 2 : nOvrJpegQuality >= 0 ? CPLSPrintf("%d", nOvrJpegQuality)
3156 : : nullptr,
3157 2 : CPLSPrintf("%d", m_nJpegTablesMode),
3158 0 : osNoData.empty() ? nullptr : osNoData.c_str(),
3159 2 : m_anLercAddCompressionAndVersion, false);
3160 :
3161 2 : if (nOverviewOffset == 0)
3162 0 : eErr = CE_Failure;
3163 : else
3164 2 : eErr = RegisterNewOverviewDataset(
3165 : nOverviewOffset, nOvrJpegQuality, papszOptions);
3166 : }
3167 : }
3168 :
3169 4 : CPLFree(panExtraSampleValues);
3170 4 : panExtraSampleValues = nullptr;
3171 :
3172 4 : ReloadDirectory();
3173 :
3174 4 : if (!pfnProgress)
3175 2 : pfnProgress = GDALDummyProgress;
3176 :
3177 : // almost 0, but not 0 to please Coverity Scan
3178 4 : double dfTotalPixels = std::numeric_limits<double>::min();
3179 8 : for (const auto *poSrcOvrDS : apoSrcOvrDS)
3180 : {
3181 4 : dfTotalPixels += static_cast<double>(poSrcOvrDS->GetRasterXSize()) *
3182 4 : poSrcOvrDS->GetRasterYSize();
3183 : }
3184 :
3185 : // Copy source datasets into target overview datasets
3186 4 : double dfCurPixels = 0;
3187 8 : for (auto *poSrcOvrDS : apoSrcOvrDS)
3188 : {
3189 4 : GDALDataset *poDstOvrDS = nullptr;
3190 4 : for (auto &poOvrDS : m_apoOverviewDS)
3191 : {
3192 8 : if (poOvrDS->GetRasterXSize() == poSrcOvrDS->GetRasterXSize() &&
3193 4 : poOvrDS->GetRasterYSize() == poSrcOvrDS->GetRasterYSize())
3194 : {
3195 4 : poDstOvrDS = poOvrDS.get();
3196 4 : break;
3197 : }
3198 : }
3199 4 : if (eErr == CE_None && poDstOvrDS)
3200 : {
3201 : const double dfThisPixels =
3202 4 : static_cast<double>(poSrcOvrDS->GetRasterXSize()) *
3203 4 : poSrcOvrDS->GetRasterYSize();
3204 8 : void *pScaledProgressData = GDALCreateScaledProgress(
3205 : dfCurPixels / dfTotalPixels,
3206 4 : (dfCurPixels + dfThisPixels) / dfTotalPixels, pfnProgress,
3207 : pProgressData);
3208 4 : dfCurPixels += dfThisPixels;
3209 4 : eErr = GDALDatasetCopyWholeRaster(GDALDataset::ToHandle(poSrcOvrDS),
3210 : GDALDataset::ToHandle(poDstOvrDS),
3211 : nullptr, GDALScaledProgress,
3212 : pScaledProgressData);
3213 4 : GDALDestroyScaledProgress(pScaledProgressData);
3214 : }
3215 : }
3216 :
3217 4 : return eErr;
3218 : }
3219 :
3220 : /************************************************************************/
3221 : /* IBuildOverviews() */
3222 : /************************************************************************/
3223 :
3224 408 : CPLErr GTiffDataset::IBuildOverviews(const char *pszResampling, int nOverviews,
3225 : const int *panOverviewList, int nBandsIn,
3226 : const int *panBandList,
3227 : GDALProgressFunc pfnProgress,
3228 : void *pProgressData,
3229 : CSLConstList papszOptions)
3230 :
3231 : {
3232 408 : ScanDirectories();
3233 :
3234 : // Make implicit JPEG overviews invisible, but do not destroy
3235 : // them in case they are already used (not sure that the client
3236 : // has the right to do that. Behavior maybe undefined in GDAL API.
3237 408 : std::swap(m_apoJPEGOverviewDSOld, m_apoJPEGOverviewDS);
3238 408 : m_apoJPEGOverviewDS.clear();
3239 :
3240 : /* -------------------------------------------------------------------- */
3241 : /* If RRD or external OVR overviews requested, then invoke */
3242 : /* generic handling. */
3243 : /* -------------------------------------------------------------------- */
3244 408 : bool bUseGenericHandling = false;
3245 408 : bool bUseRRD = false;
3246 816 : CPLStringList aosOptions(papszOptions);
3247 :
3248 408 : const char *pszLocation = CSLFetchNameValue(papszOptions, "LOCATION");
3249 408 : if (pszLocation && EQUAL(pszLocation, "EXTERNAL"))
3250 : {
3251 1 : bUseGenericHandling = true;
3252 : }
3253 407 : else if (pszLocation && EQUAL(pszLocation, "INTERNAL"))
3254 : {
3255 0 : if (GetAccess() != GA_Update)
3256 : {
3257 0 : CPLError(CE_Failure, CPLE_AppDefined,
3258 : "Cannot create internal overviews on file opened in "
3259 : "read-only mode");
3260 0 : return CE_Failure;
3261 : }
3262 : }
3263 407 : else if (pszLocation && EQUAL(pszLocation, "RRD"))
3264 : {
3265 3 : bUseGenericHandling = true;
3266 3 : bUseRRD = true;
3267 3 : aosOptions.SetNameValue("USE_RRD", "YES");
3268 : }
3269 : // Legacy
3270 404 : else if ((bUseRRD = CPLTestBool(
3271 : CSLFetchNameValueDef(papszOptions, "USE_RRD",
3272 808 : CPLGetConfigOption("USE_RRD", "NO")))) ||
3273 404 : CPLTestBool(CSLFetchNameValueDef(
3274 : papszOptions, "TIFF_USE_OVR",
3275 : CPLGetConfigOption("TIFF_USE_OVR", "NO"))))
3276 : {
3277 0 : bUseGenericHandling = true;
3278 : }
3279 :
3280 : /* -------------------------------------------------------------------- */
3281 : /* If we don't have read access, then create the overviews */
3282 : /* externally. */
3283 : /* -------------------------------------------------------------------- */
3284 408 : if (GetAccess() != GA_Update)
3285 : {
3286 143 : CPLDebug("GTiff", "File open for read-only accessing, "
3287 : "creating overviews externally.");
3288 :
3289 143 : bUseGenericHandling = true;
3290 : }
3291 :
3292 408 : if (bUseGenericHandling)
3293 : {
3294 146 : if (!m_apoOverviewDS.empty())
3295 : {
3296 0 : ReportError(CE_Failure, CPLE_NotSupported,
3297 : "Cannot add external overviews when there are already "
3298 : "internal overviews");
3299 0 : return CE_Failure;
3300 : }
3301 :
3302 146 : if (!m_bWriteEmptyTiles && !bUseRRD)
3303 : {
3304 1 : aosOptions.SetNameValue("SPARSE_OK", "YES");
3305 : }
3306 :
3307 146 : CPLErr eErr = GDALDataset::IBuildOverviews(
3308 : pszResampling, nOverviews, panOverviewList, nBandsIn, panBandList,
3309 146 : pfnProgress, pProgressData, aosOptions);
3310 146 : if (eErr == CE_None && m_poMaskDS)
3311 : {
3312 1 : ReportError(
3313 : CE_Warning, CPLE_NotSupported,
3314 : "Building external overviews whereas there is an internal "
3315 : "mask is not fully supported. "
3316 : "The overviews of the non-mask bands will be created, "
3317 : "but not the overviews of the mask band.");
3318 : }
3319 146 : return eErr;
3320 : }
3321 :
3322 : /* -------------------------------------------------------------------- */
3323 : /* Our TIFF overview support currently only works safely if all */
3324 : /* bands are handled at the same time. */
3325 : /* -------------------------------------------------------------------- */
3326 262 : if (nBandsIn != GetRasterCount())
3327 : {
3328 0 : ReportError(CE_Failure, CPLE_NotSupported,
3329 : "Generation of overviews in TIFF currently only "
3330 : "supported when operating on all bands. "
3331 : "Operation failed.");
3332 0 : return CE_Failure;
3333 : }
3334 :
3335 : /* -------------------------------------------------------------------- */
3336 : /* If zero overviews were requested, we need to clear all */
3337 : /* existing overviews. */
3338 : /* -------------------------------------------------------------------- */
3339 262 : if (nOverviews == 0)
3340 : {
3341 8 : if (m_apoOverviewDS.empty())
3342 3 : return GDALDataset::IBuildOverviews(
3343 : pszResampling, nOverviews, panOverviewList, nBandsIn,
3344 3 : panBandList, pfnProgress, pProgressData, papszOptions);
3345 :
3346 5 : return CleanOverviews();
3347 : }
3348 :
3349 254 : CPLErr eErr = CE_None;
3350 :
3351 : /* -------------------------------------------------------------------- */
3352 : /* Initialize progress counter. */
3353 : /* -------------------------------------------------------------------- */
3354 254 : if (!pfnProgress(0.0, nullptr, pProgressData))
3355 : {
3356 0 : ReportError(CE_Failure, CPLE_UserInterrupt, "User terminated");
3357 0 : return CE_Failure;
3358 : }
3359 :
3360 254 : FlushDirectory();
3361 :
3362 : /* -------------------------------------------------------------------- */
3363 : /* If we are averaging bit data to grayscale we need to create */
3364 : /* 8bit overviews. */
3365 : /* -------------------------------------------------------------------- */
3366 254 : int nOvBitsPerSample = m_nBitsPerSample;
3367 :
3368 254 : if (STARTS_WITH_CI(pszResampling, "AVERAGE_BIT2"))
3369 2 : nOvBitsPerSample = 8;
3370 :
3371 : /* -------------------------------------------------------------------- */
3372 : /* Do we need some metadata for the overviews? */
3373 : /* -------------------------------------------------------------------- */
3374 508 : CPLString osMetadata;
3375 :
3376 254 : const bool bIsForMaskBand = nBands == 1 && GetRasterBand(1)->IsMaskBand();
3377 254 : GTIFFBuildOverviewMetadata(pszResampling, this, bIsForMaskBand, osMetadata);
3378 :
3379 : int nCompression;
3380 : uint16_t nPlanarConfig;
3381 : uint16_t nPredictor;
3382 : uint16_t nPhotometric;
3383 : int nOvrJpegQuality;
3384 508 : std::string osNoData;
3385 254 : uint16_t *panExtraSampleValues = nullptr;
3386 254 : uint16_t nExtraSamples = 0;
3387 254 : if (!GetOverviewParameters(nCompression, nPlanarConfig, nPredictor,
3388 : nPhotometric, nOvrJpegQuality, osNoData,
3389 : panExtraSampleValues, nExtraSamples,
3390 : papszOptions))
3391 : {
3392 0 : return CE_Failure;
3393 : }
3394 :
3395 : /* -------------------------------------------------------------------- */
3396 : /* Do we have a palette? If so, create a TIFF compatible version. */
3397 : /* -------------------------------------------------------------------- */
3398 508 : std::vector<unsigned short> anTRed;
3399 508 : std::vector<unsigned short> anTGreen;
3400 508 : std::vector<unsigned short> anTBlue;
3401 254 : unsigned short *panRed = nullptr;
3402 254 : unsigned short *panGreen = nullptr;
3403 254 : unsigned short *panBlue = nullptr;
3404 :
3405 254 : if (nPhotometric == PHOTOMETRIC_PALETTE && m_poColorTable != nullptr)
3406 : {
3407 12 : if (m_nColorTableMultiplier == 0)
3408 0 : m_nColorTableMultiplier = DEFAULT_COLOR_TABLE_MULTIPLIER_257;
3409 :
3410 12 : CreateTIFFColorTable(m_poColorTable.get(), nOvBitsPerSample,
3411 : m_nColorTableMultiplier, anTRed, anTGreen, anTBlue,
3412 : panRed, panGreen, panBlue);
3413 : }
3414 :
3415 : /* -------------------------------------------------------------------- */
3416 : /* Establish which of the overview levels we already have, and */
3417 : /* which are new. We assume that band 1 of the file is */
3418 : /* representative. */
3419 : /* -------------------------------------------------------------------- */
3420 254 : int nOvrBlockXSize = 0;
3421 254 : int nOvrBlockYSize = 0;
3422 254 : GTIFFGetOverviewBlockSize(GDALRasterBand::ToHandle(GetRasterBand(1)),
3423 : &nOvrBlockXSize, &nOvrBlockYSize, papszOptions,
3424 : "BLOCKSIZE");
3425 508 : std::vector<bool> abRequireNewOverview(nOverviews, true);
3426 692 : for (int i = 0; i < nOverviews && eErr == CE_None; ++i)
3427 : {
3428 771 : for (auto &poODS : m_apoOverviewDS)
3429 : {
3430 : const int nOvFactor =
3431 778 : GDALComputeOvFactor(poODS->GetRasterXSize(), GetRasterXSize(),
3432 389 : poODS->GetRasterYSize(), GetRasterYSize());
3433 :
3434 : // If we already have a 1x1 overview and this new one would result
3435 : // in it too, then don't create it.
3436 449 : if (poODS->GetRasterXSize() == 1 && poODS->GetRasterYSize() == 1 &&
3437 449 : DIV_ROUND_UP(GetRasterXSize(), panOverviewList[i]) == 1 &&
3438 21 : DIV_ROUND_UP(GetRasterYSize(), panOverviewList[i]) == 1)
3439 : {
3440 21 : abRequireNewOverview[i] = false;
3441 21 : break;
3442 : }
3443 :
3444 701 : if (nOvFactor == panOverviewList[i] ||
3445 333 : nOvFactor == GDALOvLevelAdjust2(panOverviewList[i],
3446 : GetRasterXSize(),
3447 : GetRasterYSize()))
3448 : {
3449 35 : abRequireNewOverview[i] = false;
3450 35 : break;
3451 : }
3452 : }
3453 :
3454 438 : if (abRequireNewOverview[i])
3455 : {
3456 382 : if (m_bLayoutIFDSBeforeData && !m_bKnownIncompatibleEdition &&
3457 2 : !m_bWriteKnownIncompatibleEdition)
3458 : {
3459 2 : ReportError(CE_Warning, CPLE_AppDefined,
3460 : "Adding new overviews invalidates the "
3461 : "LAYOUT=IFDS_BEFORE_DATA property");
3462 2 : m_bKnownIncompatibleEdition = true;
3463 2 : m_bWriteKnownIncompatibleEdition = true;
3464 : }
3465 :
3466 : const int nOXSize =
3467 382 : DIV_ROUND_UP(GetRasterXSize(), panOverviewList[i]);
3468 : const int nOYSize =
3469 382 : DIV_ROUND_UP(GetRasterYSize(), panOverviewList[i]);
3470 :
3471 764 : const toff_t nOverviewOffset = GTIFFWriteDirectory(
3472 : m_hTIFF, FILETYPE_REDUCEDIMAGE, nOXSize, nOYSize,
3473 382 : nOvBitsPerSample, nPlanarConfig, m_nSamplesPerPixel,
3474 : nOvrBlockXSize, nOvrBlockYSize, TRUE, nCompression,
3475 382 : nPhotometric, m_nSampleFormat, nPredictor, panRed, panGreen,
3476 : panBlue, nExtraSamples, panExtraSampleValues, osMetadata,
3477 382 : nOvrJpegQuality >= 0 ? CPLSPrintf("%d", nOvrJpegQuality)
3478 : : nullptr,
3479 382 : CPLSPrintf("%d", m_nJpegTablesMode),
3480 25 : osNoData.empty() ? nullptr : osNoData.c_str(),
3481 382 : m_anLercAddCompressionAndVersion, false);
3482 :
3483 382 : if (nOverviewOffset == 0)
3484 0 : eErr = CE_Failure;
3485 : else
3486 382 : eErr = RegisterNewOverviewDataset(
3487 : nOverviewOffset, nOvrJpegQuality, papszOptions);
3488 : }
3489 : }
3490 :
3491 254 : CPLFree(panExtraSampleValues);
3492 254 : panExtraSampleValues = nullptr;
3493 :
3494 254 : ReloadDirectory();
3495 :
3496 : /* -------------------------------------------------------------------- */
3497 : /* Create overviews for the mask. */
3498 : /* -------------------------------------------------------------------- */
3499 254 : if (eErr != CE_None)
3500 0 : return eErr;
3501 :
3502 254 : eErr = CreateInternalMaskOverviews(nOvrBlockXSize, nOvrBlockYSize);
3503 :
3504 : /* -------------------------------------------------------------------- */
3505 : /* Refresh overviews for the mask */
3506 : /* -------------------------------------------------------------------- */
3507 : const bool bHasInternalMask =
3508 254 : m_poMaskDS != nullptr && m_poMaskDS->GetRasterCount() == 1;
3509 : const bool bHasExternalMask =
3510 254 : !bHasInternalMask && oOvManager.HaveMaskFile();
3511 254 : const bool bHasMask = bHasInternalMask || bHasExternalMask;
3512 :
3513 254 : if (bHasInternalMask)
3514 : {
3515 48 : std::vector<GDALRasterBandH> ahOverviewBands;
3516 64 : for (auto &poOvrDS : m_apoOverviewDS)
3517 : {
3518 40 : if (poOvrDS->m_poMaskDS != nullptr)
3519 : {
3520 40 : ahOverviewBands.push_back(GDALRasterBand::ToHandle(
3521 40 : poOvrDS->m_poMaskDS->GetRasterBand(1)));
3522 : }
3523 : }
3524 :
3525 48 : void *pScaledProgressData = GDALCreateScaledProgress(
3526 24 : 0, 1.0 / (nBands + 1), pfnProgress, pProgressData);
3527 24 : eErr = GDALRegenerateOverviewsEx(
3528 24 : m_poMaskDS->GetRasterBand(1),
3529 24 : static_cast<int>(ahOverviewBands.size()), ahOverviewBands.data(),
3530 : pszResampling, GDALScaledProgress, pScaledProgressData,
3531 : papszOptions);
3532 24 : GDALDestroyScaledProgress(pScaledProgressData);
3533 : }
3534 230 : else if (bHasExternalMask)
3535 : {
3536 4 : void *pScaledProgressData = GDALCreateScaledProgress(
3537 2 : 0, 1.0 / (nBands + 1), pfnProgress, pProgressData);
3538 2 : eErr = oOvManager.BuildOverviewsMask(
3539 : pszResampling, nOverviews, panOverviewList, GDALScaledProgress,
3540 : pScaledProgressData, papszOptions);
3541 2 : GDALDestroyScaledProgress(pScaledProgressData);
3542 : }
3543 :
3544 : // If we have an alpha band, we want it to be generated before downsampling
3545 : // other bands
3546 254 : bool bHasAlphaBand = false;
3547 66255 : for (int iBand = 0; iBand < nBands; iBand++)
3548 : {
3549 66001 : if (papoBands[iBand]->GetColorInterpretation() == GCI_AlphaBand)
3550 18 : bHasAlphaBand = true;
3551 : }
3552 :
3553 : /* -------------------------------------------------------------------- */
3554 : /* Refresh old overviews that were listed. */
3555 : /* -------------------------------------------------------------------- */
3556 254 : const auto poColorTable = GetRasterBand(panBandList[0])->GetColorTable();
3557 21 : if ((m_nPlanarConfig == PLANARCONFIG_CONTIG || bHasAlphaBand) &&
3558 235 : GDALDataTypeIsComplex(
3559 235 : GetRasterBand(panBandList[0])->GetRasterDataType()) == FALSE &&
3560 12 : (poColorTable == nullptr || STARTS_WITH_CI(pszResampling, "NEAR") ||
3561 509 : poColorTable->IsIdentity()) &&
3562 227 : (STARTS_WITH_CI(pszResampling, "NEAR") ||
3563 118 : EQUAL(pszResampling, "AVERAGE") || EQUAL(pszResampling, "RMS") ||
3564 48 : EQUAL(pszResampling, "GAUSS") || EQUAL(pszResampling, "CUBIC") ||
3565 30 : EQUAL(pszResampling, "CUBICSPLINE") ||
3566 29 : EQUAL(pszResampling, "LANCZOS") || EQUAL(pszResampling, "BILINEAR") ||
3567 25 : EQUAL(pszResampling, "MODE")))
3568 : {
3569 : // In the case of pixel interleaved compressed overviews, we want to
3570 : // generate the overviews for all the bands block by block, and not
3571 : // band after band, in order to write the block once and not loose
3572 : // space in the TIFF file. We also use that logic for uncompressed
3573 : // overviews, since GDALRegenerateOverviewsMultiBand() will be able to
3574 : // trigger cascading overview regeneration even in the presence
3575 : // of an alpha band.
3576 :
3577 205 : int nNewOverviews = 0;
3578 :
3579 : GDALRasterBand ***papapoOverviewBands = static_cast<GDALRasterBand ***>(
3580 205 : CPLCalloc(sizeof(void *), nBandsIn));
3581 : GDALRasterBand **papoBandList =
3582 205 : static_cast<GDALRasterBand **>(CPLCalloc(sizeof(void *), nBandsIn));
3583 66109 : for (int iBand = 0; iBand < nBandsIn; ++iBand)
3584 : {
3585 65904 : GDALRasterBand *poBand = GetRasterBand(panBandList[iBand]);
3586 :
3587 65904 : papoBandList[iBand] = poBand;
3588 131808 : papapoOverviewBands[iBand] = static_cast<GDALRasterBand **>(
3589 65904 : CPLCalloc(sizeof(void *), poBand->GetOverviewCount()));
3590 :
3591 65904 : int iCurOverview = 0;
3592 : std::vector<bool> abAlreadyUsedOverviewBand(
3593 65904 : poBand->GetOverviewCount(), false);
3594 :
3595 132094 : for (int i = 0; i < nOverviews; ++i)
3596 : {
3597 66650 : for (int j = 0; j < poBand->GetOverviewCount(); ++j)
3598 : {
3599 66635 : if (abAlreadyUsedOverviewBand[j])
3600 459 : continue;
3601 :
3602 : int nOvFactor;
3603 66176 : GDALRasterBand *poOverview = poBand->GetOverview(j);
3604 :
3605 66176 : nOvFactor = GDALComputeOvFactor(
3606 : poOverview->GetXSize(), poBand->GetXSize(),
3607 : poOverview->GetYSize(), poBand->GetYSize());
3608 :
3609 66176 : GDALCopyNoDataValue(poOverview, poBand);
3610 :
3611 66177 : if (nOvFactor == panOverviewList[i] ||
3612 1 : nOvFactor == GDALOvLevelAdjust2(panOverviewList[i],
3613 : poBand->GetXSize(),
3614 : poBand->GetYSize()))
3615 : {
3616 66175 : if (iBand == 0)
3617 : {
3618 : const auto osNewResampling =
3619 664 : GDALGetNormalizedOvrResampling(pszResampling);
3620 : const char *pszExistingResampling =
3621 332 : poOverview->GetMetadataItem("RESAMPLING");
3622 664 : if (pszExistingResampling &&
3623 332 : pszExistingResampling != osNewResampling)
3624 : {
3625 2 : poOverview->SetMetadataItem(
3626 2 : "RESAMPLING", osNewResampling.c_str());
3627 : }
3628 : }
3629 :
3630 66175 : abAlreadyUsedOverviewBand[j] = true;
3631 66175 : CPLAssert(iCurOverview < poBand->GetOverviewCount());
3632 66175 : papapoOverviewBands[iBand][iCurOverview] = poOverview;
3633 66175 : ++iCurOverview;
3634 66175 : break;
3635 : }
3636 : }
3637 : }
3638 :
3639 65904 : if (nNewOverviews == 0)
3640 : {
3641 205 : nNewOverviews = iCurOverview;
3642 : }
3643 65699 : else if (nNewOverviews != iCurOverview)
3644 : {
3645 0 : CPLAssert(false);
3646 : return CE_Failure;
3647 : }
3648 : }
3649 :
3650 : void *pScaledProgressData =
3651 205 : bHasMask ? GDALCreateScaledProgress(1.0 / (nBands + 1), 1.0,
3652 : pfnProgress, pProgressData)
3653 179 : : GDALCreateScaledProgress(0.0, 1.0, pfnProgress,
3654 205 : pProgressData);
3655 205 : GDALRegenerateOverviewsMultiBand(nBandsIn, papoBandList, nNewOverviews,
3656 : papapoOverviewBands, pszResampling,
3657 : GDALScaledProgress,
3658 : pScaledProgressData, papszOptions);
3659 205 : GDALDestroyScaledProgress(pScaledProgressData);
3660 :
3661 66109 : for (int iBand = 0; iBand < nBandsIn; ++iBand)
3662 : {
3663 65904 : CPLFree(papapoOverviewBands[iBand]);
3664 : }
3665 205 : CPLFree(papapoOverviewBands);
3666 205 : CPLFree(papoBandList);
3667 : }
3668 : else
3669 : {
3670 : GDALRasterBand **papoOverviewBands = static_cast<GDALRasterBand **>(
3671 49 : CPLCalloc(sizeof(void *), nOverviews));
3672 :
3673 49 : const int iBandOffset = bHasMask ? 1 : 0;
3674 :
3675 146 : for (int iBand = 0; iBand < nBandsIn && eErr == CE_None; ++iBand)
3676 : {
3677 97 : GDALRasterBand *poBand = GetRasterBand(panBandList[iBand]);
3678 97 : if (poBand == nullptr)
3679 : {
3680 0 : eErr = CE_Failure;
3681 0 : break;
3682 : }
3683 :
3684 : std::vector<bool> abAlreadyUsedOverviewBand(
3685 194 : poBand->GetOverviewCount(), false);
3686 :
3687 97 : int nNewOverviews = 0;
3688 290 : for (int i = 0; i < nOverviews; ++i)
3689 : {
3690 451 : for (int j = 0; j < poBand->GetOverviewCount(); ++j)
3691 : {
3692 433 : if (abAlreadyUsedOverviewBand[j])
3693 257 : continue;
3694 :
3695 176 : GDALRasterBand *poOverview = poBand->GetOverview(j);
3696 :
3697 176 : GDALCopyNoDataValue(poOverview, poBand);
3698 :
3699 176 : const int nOvFactor = GDALComputeOvFactor(
3700 : poOverview->GetXSize(), poBand->GetXSize(),
3701 : poOverview->GetYSize(), poBand->GetYSize());
3702 :
3703 177 : if (nOvFactor == panOverviewList[i] ||
3704 1 : nOvFactor == GDALOvLevelAdjust2(panOverviewList[i],
3705 : poBand->GetXSize(),
3706 : poBand->GetYSize()))
3707 : {
3708 175 : if (iBand == 0)
3709 : {
3710 : const auto osNewResampling =
3711 170 : GDALGetNormalizedOvrResampling(pszResampling);
3712 : const char *pszExistingResampling =
3713 85 : poOverview->GetMetadataItem("RESAMPLING");
3714 137 : if (pszExistingResampling &&
3715 52 : pszExistingResampling != osNewResampling)
3716 : {
3717 1 : poOverview->SetMetadataItem(
3718 1 : "RESAMPLING", osNewResampling.c_str());
3719 : }
3720 : }
3721 :
3722 175 : abAlreadyUsedOverviewBand[j] = true;
3723 175 : CPLAssert(nNewOverviews < poBand->GetOverviewCount());
3724 175 : papoOverviewBands[nNewOverviews++] = poOverview;
3725 175 : break;
3726 : }
3727 : }
3728 : }
3729 :
3730 194 : void *pScaledProgressData = GDALCreateScaledProgress(
3731 97 : (iBand + iBandOffset) /
3732 97 : static_cast<double>(nBandsIn + iBandOffset),
3733 97 : (iBand + iBandOffset + 1) /
3734 97 : static_cast<double>(nBandsIn + iBandOffset),
3735 : pfnProgress, pProgressData);
3736 :
3737 97 : eErr = GDALRegenerateOverviewsEx(
3738 : poBand, nNewOverviews,
3739 : reinterpret_cast<GDALRasterBandH *>(papoOverviewBands),
3740 : pszResampling, GDALScaledProgress, pScaledProgressData,
3741 : papszOptions);
3742 :
3743 97 : GDALDestroyScaledProgress(pScaledProgressData);
3744 : }
3745 :
3746 : /* --------------------------------------------------------------------
3747 : */
3748 : /* Cleanup */
3749 : /* --------------------------------------------------------------------
3750 : */
3751 49 : CPLFree(papoOverviewBands);
3752 : }
3753 :
3754 254 : pfnProgress(1.0, nullptr, pProgressData);
3755 :
3756 254 : return eErr;
3757 : }
3758 :
3759 : /************************************************************************/
3760 : /* GTiffWriteDummyGeokeyDirectory() */
3761 : /************************************************************************/
3762 :
3763 1506 : static void GTiffWriteDummyGeokeyDirectory(TIFF *hTIFF)
3764 : {
3765 : // If we have existing geokeys, try to wipe them
3766 : // by writing a dummy geokey directory. (#2546)
3767 1506 : uint16_t *panVI = nullptr;
3768 1506 : uint16_t nKeyCount = 0;
3769 :
3770 1506 : if (TIFFGetField(hTIFF, TIFFTAG_GEOKEYDIRECTORY, &nKeyCount, &panVI))
3771 : {
3772 25 : GUInt16 anGKVersionInfo[4] = {1, 1, 0, 0};
3773 25 : double adfDummyDoubleParams[1] = {0.0};
3774 25 : TIFFSetField(hTIFF, TIFFTAG_GEOKEYDIRECTORY, 4, anGKVersionInfo);
3775 25 : TIFFSetField(hTIFF, TIFFTAG_GEODOUBLEPARAMS, 1, adfDummyDoubleParams);
3776 25 : TIFFSetField(hTIFF, TIFFTAG_GEOASCIIPARAMS, "");
3777 : }
3778 1506 : }
3779 :
3780 : /************************************************************************/
3781 : /* IsSRSCompatibleOfGeoTIFF() */
3782 : /************************************************************************/
3783 :
3784 3164 : static bool IsSRSCompatibleOfGeoTIFF(const OGRSpatialReference *poSRS,
3785 : GTIFFKeysFlavorEnum eGeoTIFFKeysFlavor)
3786 : {
3787 3164 : char *pszWKT = nullptr;
3788 3164 : if ((poSRS->IsGeographic() || poSRS->IsProjected()) && !poSRS->IsCompound())
3789 : {
3790 3146 : const char *pszAuthName = poSRS->GetAuthorityName(nullptr);
3791 3146 : const char *pszAuthCode = poSRS->GetAuthorityCode(nullptr);
3792 3146 : if (pszAuthName && pszAuthCode && EQUAL(pszAuthName, "EPSG"))
3793 2576 : return true;
3794 : }
3795 : OGRErr eErr;
3796 : {
3797 1176 : CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
3798 1176 : if (poSRS->IsDerivedGeographic() ||
3799 588 : (poSRS->IsProjected() && !poSRS->IsCompound() &&
3800 70 : poSRS->GetAxesCount() == 3))
3801 : {
3802 0 : eErr = OGRERR_FAILURE;
3803 : }
3804 : else
3805 : {
3806 : // Geographic3D CRS can't be exported to WKT1, but are
3807 : // valid GeoTIFF 1.1
3808 588 : const char *const apszOptions[] = {
3809 588 : poSRS->IsGeographic() ? nullptr : "FORMAT=WKT1", nullptr};
3810 588 : eErr = poSRS->exportToWkt(&pszWKT, apszOptions);
3811 588 : if (eErr == OGRERR_FAILURE && poSRS->IsProjected() &&
3812 : eGeoTIFFKeysFlavor == GEOTIFF_KEYS_ESRI_PE)
3813 : {
3814 0 : CPLFree(pszWKT);
3815 0 : const char *const apszOptionsESRIWKT[] = {"FORMAT=WKT1_ESRI",
3816 : nullptr};
3817 0 : eErr = poSRS->exportToWkt(&pszWKT, apszOptionsESRIWKT);
3818 : }
3819 : }
3820 : }
3821 588 : const bool bCompatibleOfGeoTIFF =
3822 1175 : (eErr == OGRERR_NONE && pszWKT != nullptr &&
3823 587 : strstr(pszWKT, "custom_proj4") == nullptr);
3824 588 : CPLFree(pszWKT);
3825 588 : return bCompatibleOfGeoTIFF;
3826 : }
3827 :
3828 : /************************************************************************/
3829 : /* WriteGeoTIFFInfo() */
3830 : /************************************************************************/
3831 :
3832 5867 : void GTiffDataset::WriteGeoTIFFInfo()
3833 :
3834 : {
3835 5867 : bool bPixelIsPoint = false;
3836 5867 : bool bPointGeoIgnore = false;
3837 :
3838 : const char *pszAreaOrPoint =
3839 5867 : GTiffDataset::GetMetadataItem(GDALMD_AREA_OR_POINT);
3840 5867 : if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_POINT))
3841 : {
3842 19 : bPixelIsPoint = true;
3843 : bPointGeoIgnore =
3844 19 : CPLTestBool(CPLGetConfigOption("GTIFF_POINT_GEO_IGNORE", "FALSE"));
3845 : }
3846 :
3847 5867 : if (m_bForceUnsetGTOrGCPs)
3848 : {
3849 11 : m_bNeedsRewrite = true;
3850 11 : m_bForceUnsetGTOrGCPs = false;
3851 :
3852 11 : TIFFUnsetField(m_hTIFF, TIFFTAG_GEOPIXELSCALE);
3853 11 : TIFFUnsetField(m_hTIFF, TIFFTAG_GEOTIEPOINTS);
3854 11 : TIFFUnsetField(m_hTIFF, TIFFTAG_GEOTRANSMATRIX);
3855 : }
3856 :
3857 5867 : if (m_bForceUnsetProjection)
3858 : {
3859 8 : m_bNeedsRewrite = true;
3860 8 : m_bForceUnsetProjection = false;
3861 :
3862 8 : TIFFUnsetField(m_hTIFF, TIFFTAG_GEOKEYDIRECTORY);
3863 8 : TIFFUnsetField(m_hTIFF, TIFFTAG_GEODOUBLEPARAMS);
3864 8 : TIFFUnsetField(m_hTIFF, TIFFTAG_GEOASCIIPARAMS);
3865 : }
3866 :
3867 : /* -------------------------------------------------------------------- */
3868 : /* Write geotransform if valid. */
3869 : /* -------------------------------------------------------------------- */
3870 5867 : if (m_bGeoTransformValid)
3871 : {
3872 1812 : m_bNeedsRewrite = true;
3873 :
3874 : /* --------------------------------------------------------------------
3875 : */
3876 : /* Clear old tags to ensure we don't end up with conflicting */
3877 : /* information. (#2625) */
3878 : /* --------------------------------------------------------------------
3879 : */
3880 1812 : TIFFUnsetField(m_hTIFF, TIFFTAG_GEOPIXELSCALE);
3881 1812 : TIFFUnsetField(m_hTIFF, TIFFTAG_GEOTIEPOINTS);
3882 1812 : TIFFUnsetField(m_hTIFF, TIFFTAG_GEOTRANSMATRIX);
3883 :
3884 : /* --------------------------------------------------------------------
3885 : */
3886 : /* Write the transform. If we have a normal north-up image we */
3887 : /* use the tiepoint plus pixelscale otherwise we use a matrix. */
3888 : /* --------------------------------------------------------------------
3889 : */
3890 1812 : if (m_gt.xrot == 0.0 && m_gt.yrot == 0.0 && m_gt.yscale < 0.0)
3891 : {
3892 1720 : double dfOffset = 0.0;
3893 1720 : if (m_eProfile != GTiffProfile::BASELINE)
3894 : {
3895 : // In the case the SRS has a vertical component and we have
3896 : // a single band, encode its scale/offset in the GeoTIFF tags
3897 1714 : int bHasScale = FALSE;
3898 1714 : double dfScale = GetRasterBand(1)->GetScale(&bHasScale);
3899 1714 : int bHasOffset = FALSE;
3900 1714 : dfOffset = GetRasterBand(1)->GetOffset(&bHasOffset);
3901 : const bool bApplyScaleOffset =
3902 1714 : m_oSRS.IsVertical() && GetRasterCount() == 1;
3903 1714 : if (bApplyScaleOffset && !bHasScale)
3904 0 : dfScale = 1.0;
3905 1714 : if (!bApplyScaleOffset || !bHasOffset)
3906 1711 : dfOffset = 0.0;
3907 1714 : const double adfPixelScale[3] = {m_gt.xscale, fabs(m_gt.yscale),
3908 1714 : bApplyScaleOffset ? dfScale
3909 1714 : : 0.0};
3910 1714 : TIFFSetField(m_hTIFF, TIFFTAG_GEOPIXELSCALE, 3, adfPixelScale);
3911 : }
3912 :
3913 1720 : double adfTiePoints[6] = {0.0, 0.0, 0.0,
3914 1720 : m_gt.xorig, m_gt.yorig, dfOffset};
3915 :
3916 1720 : if (bPixelIsPoint && !bPointGeoIgnore)
3917 : {
3918 15 : adfTiePoints[3] += m_gt.xscale * 0.5 + m_gt.xrot * 0.5;
3919 15 : adfTiePoints[4] += m_gt.yrot * 0.5 + m_gt.yscale * 0.5;
3920 : }
3921 :
3922 1720 : if (m_eProfile != GTiffProfile::BASELINE)
3923 1720 : TIFFSetField(m_hTIFF, TIFFTAG_GEOTIEPOINTS, 6, adfTiePoints);
3924 : }
3925 : else
3926 : {
3927 92 : double adfMatrix[16] = {};
3928 :
3929 92 : adfMatrix[0] = m_gt.xscale;
3930 92 : adfMatrix[1] = m_gt.xrot;
3931 92 : adfMatrix[3] = m_gt.xorig;
3932 92 : adfMatrix[4] = m_gt.yrot;
3933 92 : adfMatrix[5] = m_gt.yscale;
3934 92 : adfMatrix[7] = m_gt.yorig;
3935 92 : adfMatrix[15] = 1.0;
3936 :
3937 92 : if (bPixelIsPoint && !bPointGeoIgnore)
3938 : {
3939 0 : adfMatrix[3] += m_gt.xscale * 0.5 + m_gt.xrot * 0.5;
3940 0 : adfMatrix[7] += m_gt.yrot * 0.5 + m_gt.yscale * 0.5;
3941 : }
3942 :
3943 92 : if (m_eProfile != GTiffProfile::BASELINE)
3944 92 : TIFFSetField(m_hTIFF, TIFFTAG_GEOTRANSMATRIX, 16, adfMatrix);
3945 : }
3946 :
3947 1812 : if (m_poBaseDS == nullptr)
3948 : {
3949 : // Do we need a world file?
3950 1812 : if (CPLFetchBool(m_papszCreationOptions, "TFW", false))
3951 7 : GDALWriteWorldFile(m_osFilename.c_str(), "tfw", m_gt.data());
3952 1805 : else if (CPLFetchBool(m_papszCreationOptions, "WORLDFILE", false))
3953 2 : GDALWriteWorldFile(m_osFilename.c_str(), "wld", m_gt.data());
3954 : }
3955 : }
3956 4069 : else if (GetGCPCount() > 0 && GetGCPCount() <= knMAX_GCP_COUNT &&
3957 14 : m_eProfile != GTiffProfile::BASELINE)
3958 : {
3959 14 : m_bNeedsRewrite = true;
3960 :
3961 : double *padfTiePoints = static_cast<double *>(
3962 14 : CPLMalloc(6 * sizeof(double) * GetGCPCount()));
3963 :
3964 74 : for (size_t iGCP = 0; iGCP < m_aoGCPs.size(); ++iGCP)
3965 : {
3966 :
3967 60 : padfTiePoints[iGCP * 6 + 0] = m_aoGCPs[iGCP].Pixel();
3968 60 : padfTiePoints[iGCP * 6 + 1] = m_aoGCPs[iGCP].Line();
3969 60 : padfTiePoints[iGCP * 6 + 2] = 0;
3970 60 : padfTiePoints[iGCP * 6 + 3] = m_aoGCPs[iGCP].X();
3971 60 : padfTiePoints[iGCP * 6 + 4] = m_aoGCPs[iGCP].Y();
3972 60 : padfTiePoints[iGCP * 6 + 5] = m_aoGCPs[iGCP].Z();
3973 :
3974 60 : if (bPixelIsPoint && !bPointGeoIgnore)
3975 : {
3976 0 : padfTiePoints[iGCP * 6 + 0] += 0.5;
3977 0 : padfTiePoints[iGCP * 6 + 1] += 0.5;
3978 : }
3979 : }
3980 :
3981 14 : TIFFSetField(m_hTIFF, TIFFTAG_GEOTIEPOINTS, 6 * GetGCPCount(),
3982 : padfTiePoints);
3983 14 : CPLFree(padfTiePoints);
3984 : }
3985 :
3986 : /* -------------------------------------------------------------------- */
3987 : /* Write out projection definition. */
3988 : /* -------------------------------------------------------------------- */
3989 5867 : const bool bHasProjection = !m_oSRS.IsEmpty();
3990 5867 : if ((bHasProjection || bPixelIsPoint) &&
3991 1510 : m_eProfile != GTiffProfile::BASELINE)
3992 : {
3993 1506 : m_bNeedsRewrite = true;
3994 :
3995 : // If we have existing geokeys, try to wipe them
3996 : // by writing a dummy geokey directory. (#2546)
3997 1506 : GTiffWriteDummyGeokeyDirectory(m_hTIFF);
3998 :
3999 1506 : GTIF *psGTIF = GTiffDataset::GTIFNew(m_hTIFF);
4000 :
4001 : // Set according to coordinate system.
4002 1506 : if (bHasProjection)
4003 : {
4004 1505 : if (IsSRSCompatibleOfGeoTIFF(&m_oSRS, m_eGeoTIFFKeysFlavor))
4005 : {
4006 1503 : GTIFSetFromOGISDefnEx(psGTIF,
4007 : OGRSpatialReference::ToHandle(&m_oSRS),
4008 : m_eGeoTIFFKeysFlavor, m_eGeoTIFFVersion);
4009 : }
4010 : else
4011 : {
4012 2 : GDALPamDataset::SetSpatialRef(&m_oSRS);
4013 : }
4014 : }
4015 :
4016 1506 : if (bPixelIsPoint)
4017 : {
4018 19 : GTIFKeySet(psGTIF, GTRasterTypeGeoKey, TYPE_SHORT, 1,
4019 : RasterPixelIsPoint);
4020 : }
4021 :
4022 1506 : GTIFWriteKeys(psGTIF);
4023 1506 : GTIFFree(psGTIF);
4024 : }
4025 5867 : }
4026 :
4027 : /************************************************************************/
4028 : /* AppendMetadataItem() */
4029 : /************************************************************************/
4030 :
4031 3891 : static void AppendMetadataItem(CPLXMLNode **ppsRoot, CPLXMLNode **ppsTail,
4032 : const char *pszKey, const char *pszValue,
4033 : CPLXMLNode *psValueNode, int nBand,
4034 : const char *pszRole, const char *pszDomain)
4035 :
4036 : {
4037 3891 : CPLAssert(pszValue || psValueNode);
4038 3891 : CPLAssert(!(pszValue && psValueNode));
4039 :
4040 : /* -------------------------------------------------------------------- */
4041 : /* Create the Item element, and subcomponents. */
4042 : /* -------------------------------------------------------------------- */
4043 3891 : CPLXMLNode *psItem = CPLCreateXMLNode(nullptr, CXT_Element, "Item");
4044 3891 : CPLAddXMLAttributeAndValue(psItem, "name", pszKey);
4045 :
4046 3891 : if (nBand > 0)
4047 : {
4048 1165 : char szBandId[32] = {};
4049 1165 : snprintf(szBandId, sizeof(szBandId), "%d", nBand - 1);
4050 1165 : CPLAddXMLAttributeAndValue(psItem, "sample", szBandId);
4051 : }
4052 :
4053 3891 : if (pszRole != nullptr)
4054 383 : CPLAddXMLAttributeAndValue(psItem, "role", pszRole);
4055 :
4056 3891 : if (pszDomain != nullptr && strlen(pszDomain) > 0)
4057 1010 : CPLAddXMLAttributeAndValue(psItem, "domain", pszDomain);
4058 :
4059 3891 : if (pszValue)
4060 : {
4061 : // Note: this escaping should not normally be done, as the serialization
4062 : // of the tree to XML also does it, so we end up width double XML escaping,
4063 : // but keep it for backward compatibility.
4064 3870 : char *pszEscapedItemValue = CPLEscapeString(pszValue, -1, CPLES_XML);
4065 3870 : CPLCreateXMLNode(psItem, CXT_Text, pszEscapedItemValue);
4066 3870 : CPLFree(pszEscapedItemValue);
4067 : }
4068 : else
4069 : {
4070 21 : CPLAddXMLChild(psItem, psValueNode);
4071 : }
4072 :
4073 : /* -------------------------------------------------------------------- */
4074 : /* Create root, if missing. */
4075 : /* -------------------------------------------------------------------- */
4076 3891 : if (*ppsRoot == nullptr)
4077 762 : *ppsRoot = CPLCreateXMLNode(nullptr, CXT_Element, "GDALMetadata");
4078 :
4079 : /* -------------------------------------------------------------------- */
4080 : /* Append item to tail. We keep track of the tail to avoid */
4081 : /* O(nsquared) time as the list gets longer. */
4082 : /* -------------------------------------------------------------------- */
4083 3891 : if (*ppsTail == nullptr)
4084 762 : CPLAddXMLChild(*ppsRoot, psItem);
4085 : else
4086 3129 : CPLAddXMLSibling(*ppsTail, psItem);
4087 :
4088 3891 : *ppsTail = psItem;
4089 3891 : }
4090 :
4091 : /************************************************************************/
4092 : /* AppendMetadataItem() */
4093 : /************************************************************************/
4094 :
4095 3870 : static void AppendMetadataItem(CPLXMLNode **ppsRoot, CPLXMLNode **ppsTail,
4096 : const char *pszKey, const char *pszValue,
4097 : int nBand, const char *pszRole,
4098 : const char *pszDomain)
4099 :
4100 : {
4101 3870 : AppendMetadataItem(ppsRoot, ppsTail, pszKey, pszValue, nullptr, nBand,
4102 : pszRole, pszDomain);
4103 3870 : }
4104 :
4105 : /************************************************************************/
4106 : /* WriteMDMetadata() */
4107 : /************************************************************************/
4108 :
4109 311043 : static void WriteMDMetadata(GDALMultiDomainMetadata *poMDMD, TIFF *hTIFF,
4110 : CPLXMLNode **ppsRoot, CPLXMLNode **ppsTail,
4111 : int nBand, GTiffProfile eProfile)
4112 :
4113 : {
4114 :
4115 : /* ==================================================================== */
4116 : /* Process each domain. */
4117 : /* ==================================================================== */
4118 311043 : CSLConstList papszDomainList = poMDMD->GetDomainList();
4119 319520 : for (int iDomain = 0; papszDomainList && papszDomainList[iDomain];
4120 : ++iDomain)
4121 : {
4122 8477 : CSLConstList papszMD = poMDMD->GetMetadata(papszDomainList[iDomain]);
4123 8477 : bool bIsXMLOrJSON = false;
4124 :
4125 8477 : if (EQUAL(papszDomainList[iDomain], "IMAGE_STRUCTURE") ||
4126 2474 : EQUAL(papszDomainList[iDomain], "DERIVED_SUBDATASETS"))
4127 6006 : continue; // Ignored.
4128 2471 : if (EQUAL(papszDomainList[iDomain], "COLOR_PROFILE"))
4129 3 : continue; // Handled elsewhere.
4130 2468 : if (EQUAL(papszDomainList[iDomain], MD_DOMAIN_RPC))
4131 7 : continue; // Handled elsewhere.
4132 2462 : if (EQUAL(papszDomainList[iDomain], "xml:ESRI") &&
4133 1 : CPLTestBool(CPLGetConfigOption("ESRI_XML_PAM", "NO")))
4134 1 : continue; // Handled elsewhere.
4135 2460 : if (EQUAL(papszDomainList[iDomain], "xml:XMP"))
4136 2 : continue; // Handled in SetMetadata.
4137 :
4138 2458 : if (STARTS_WITH_CI(papszDomainList[iDomain], "xml:") ||
4139 2456 : STARTS_WITH_CI(papszDomainList[iDomain], "json:"))
4140 : {
4141 12 : bIsXMLOrJSON = true;
4142 : }
4143 :
4144 : /* --------------------------------------------------------------------
4145 : */
4146 : /* Process each item in this domain. */
4147 : /* --------------------------------------------------------------------
4148 : */
4149 7543 : for (int iItem = 0; papszMD && papszMD[iItem]; ++iItem)
4150 : {
4151 5085 : const char *pszItemValue = nullptr;
4152 5085 : char *pszItemName = nullptr;
4153 :
4154 5085 : if (bIsXMLOrJSON)
4155 : {
4156 11 : pszItemName = CPLStrdup("doc");
4157 11 : pszItemValue = papszMD[iItem];
4158 : }
4159 : else
4160 : {
4161 5074 : pszItemValue = CPLParseNameValue(papszMD[iItem], &pszItemName);
4162 5074 : if (pszItemName == nullptr)
4163 : {
4164 49 : CPLDebug("GTiff", "Invalid metadata item : %s",
4165 49 : papszMD[iItem]);
4166 49 : continue;
4167 : }
4168 : }
4169 :
4170 : /* --------------------------------------------------------------------
4171 : */
4172 : /* Convert into XML item or handle as a special TIFF tag. */
4173 : /* --------------------------------------------------------------------
4174 : */
4175 5036 : if (strlen(papszDomainList[iDomain]) == 0 && nBand == 0 &&
4176 3681 : (STARTS_WITH_CI(pszItemName, "TIFFTAG_") ||
4177 3620 : (EQUAL(pszItemName, "GEO_METADATA") &&
4178 3619 : eProfile == GTiffProfile::GDALGEOTIFF) ||
4179 3619 : (EQUAL(pszItemName, "TIFF_RSID") &&
4180 : eProfile == GTiffProfile::GDALGEOTIFF)))
4181 : {
4182 63 : if (EQUAL(pszItemName, "TIFFTAG_RESOLUTIONUNIT"))
4183 : {
4184 : // ResolutionUnit can't be 0, which is the default if
4185 : // atoi() fails. Set to 1=Unknown.
4186 9 : int v = atoi(pszItemValue);
4187 9 : if (!v)
4188 1 : v = RESUNIT_NONE;
4189 9 : TIFFSetField(hTIFF, TIFFTAG_RESOLUTIONUNIT, v);
4190 : }
4191 : else
4192 : {
4193 54 : bool bFoundTag = false;
4194 54 : size_t iTag = 0; // Used after for.
4195 54 : const auto *pasTIFFTags = GTiffDataset::GetTIFFTags();
4196 286 : for (; pasTIFFTags[iTag].pszTagName; ++iTag)
4197 : {
4198 286 : if (EQUAL(pszItemName, pasTIFFTags[iTag].pszTagName))
4199 : {
4200 54 : bFoundTag = true;
4201 54 : break;
4202 : }
4203 : }
4204 :
4205 54 : if (bFoundTag &&
4206 54 : pasTIFFTags[iTag].eType == GTIFFTAGTYPE_STRING)
4207 33 : TIFFSetField(hTIFF, pasTIFFTags[iTag].nTagVal,
4208 : pszItemValue);
4209 21 : else if (bFoundTag &&
4210 21 : pasTIFFTags[iTag].eType == GTIFFTAGTYPE_FLOAT)
4211 16 : TIFFSetField(hTIFF, pasTIFFTags[iTag].nTagVal,
4212 : CPLAtof(pszItemValue));
4213 5 : else if (bFoundTag &&
4214 5 : pasTIFFTags[iTag].eType == GTIFFTAGTYPE_SHORT)
4215 4 : TIFFSetField(hTIFF, pasTIFFTags[iTag].nTagVal,
4216 : atoi(pszItemValue));
4217 1 : else if (bFoundTag && pasTIFFTags[iTag].eType ==
4218 : GTIFFTAGTYPE_BYTE_STRING)
4219 : {
4220 1 : uint32_t nLen =
4221 1 : static_cast<uint32_t>(strlen(pszItemValue));
4222 1 : if (nLen)
4223 : {
4224 1 : TIFFSetField(hTIFF, pasTIFFTags[iTag].nTagVal, nLen,
4225 : pszItemValue);
4226 1 : }
4227 : }
4228 : else
4229 0 : CPLError(CE_Warning, CPLE_NotSupported,
4230 : "%s metadata item is unhandled and "
4231 : "will not be written",
4232 : pszItemName);
4233 63 : }
4234 : }
4235 4973 : else if (nBand == 0 && EQUAL(pszItemName, GDALMD_AREA_OR_POINT))
4236 : {
4237 : /* Do nothing, handled elsewhere. */;
4238 : }
4239 : else
4240 : {
4241 3077 : AppendMetadataItem(ppsRoot, ppsTail, pszItemName, pszItemValue,
4242 3077 : nBand, nullptr, papszDomainList[iDomain]);
4243 : }
4244 :
4245 5036 : CPLFree(pszItemName);
4246 : }
4247 :
4248 : /* --------------------------------------------------------------------
4249 : */
4250 : /* Remove TIFFTAG_xxxxxx that are already set but no longer in */
4251 : /* the metadata list (#5619) */
4252 : /* --------------------------------------------------------------------
4253 : */
4254 2458 : if (strlen(papszDomainList[iDomain]) == 0 && nBand == 0)
4255 : {
4256 2172 : const auto *pasTIFFTags = GTiffDataset::GetTIFFTags();
4257 32580 : for (size_t iTag = 0; pasTIFFTags[iTag].pszTagName; ++iTag)
4258 : {
4259 30408 : uint32_t nCount = 0;
4260 30408 : char *pszText = nullptr;
4261 30408 : int16_t nVal = 0;
4262 30408 : float fVal = 0.0f;
4263 : const char *pszVal =
4264 30408 : CSLFetchNameValue(papszMD, pasTIFFTags[iTag].pszTagName);
4265 60753 : if (pszVal == nullptr &&
4266 30345 : ((pasTIFFTags[iTag].eType == GTIFFTAGTYPE_STRING &&
4267 17343 : TIFFGetField(hTIFF, pasTIFFTags[iTag].nTagVal,
4268 30337 : &pszText)) ||
4269 30337 : (pasTIFFTags[iTag].eType == GTIFFTAGTYPE_SHORT &&
4270 6503 : TIFFGetField(hTIFF, pasTIFFTags[iTag].nTagVal, &nVal)) ||
4271 30334 : (pasTIFFTags[iTag].eType == GTIFFTAGTYPE_FLOAT &&
4272 4328 : TIFFGetField(hTIFF, pasTIFFTags[iTag].nTagVal, &fVal)) ||
4273 30333 : (pasTIFFTags[iTag].eType == GTIFFTAGTYPE_BYTE_STRING &&
4274 2171 : TIFFGetField(hTIFF, pasTIFFTags[iTag].nTagVal, &nCount,
4275 : &pszText))))
4276 : {
4277 13 : TIFFUnsetField(hTIFF, pasTIFFTags[iTag].nTagVal);
4278 : }
4279 : }
4280 : }
4281 : }
4282 311043 : }
4283 :
4284 : /************************************************************************/
4285 : /* WriteRPC() */
4286 : /************************************************************************/
4287 :
4288 10154 : void GTiffDataset::WriteRPC(GDALDataset *poSrcDS, TIFF *l_hTIFF,
4289 : int bSrcIsGeoTIFF, GTiffProfile eProfile,
4290 : const char *pszTIFFFilename,
4291 : CSLConstList papszCreationOptions,
4292 : bool bWriteOnlyInPAMIfNeeded)
4293 : {
4294 : /* -------------------------------------------------------------------- */
4295 : /* Handle RPC data written to TIFF RPCCoefficient tag, RPB file, */
4296 : /* RPCTEXT file or PAM. */
4297 : /* -------------------------------------------------------------------- */
4298 10154 : CSLConstList papszRPCMD = poSrcDS->GetMetadata(MD_DOMAIN_RPC);
4299 10154 : if (papszRPCMD != nullptr)
4300 : {
4301 32 : bool bRPCSerializedOtherWay = false;
4302 :
4303 32 : if (eProfile == GTiffProfile::GDALGEOTIFF)
4304 : {
4305 20 : if (!bWriteOnlyInPAMIfNeeded)
4306 11 : GTiffDatasetWriteRPCTag(l_hTIFF, papszRPCMD);
4307 20 : bRPCSerializedOtherWay = true;
4308 : }
4309 :
4310 : // Write RPB file if explicitly asked, or if a non GDAL specific
4311 : // profile is selected and RPCTXT is not asked.
4312 : bool bRPBExplicitlyAsked =
4313 32 : CPLFetchBool(papszCreationOptions, "RPB", false);
4314 : bool bRPBExplicitlyDenied =
4315 32 : !CPLFetchBool(papszCreationOptions, "RPB", true);
4316 44 : if ((eProfile != GTiffProfile::GDALGEOTIFF &&
4317 12 : !CPLFetchBool(papszCreationOptions, "RPCTXT", false) &&
4318 44 : !bRPBExplicitlyDenied) ||
4319 : bRPBExplicitlyAsked)
4320 : {
4321 8 : if (!bWriteOnlyInPAMIfNeeded)
4322 4 : GDALWriteRPBFile(pszTIFFFilename, papszRPCMD);
4323 8 : bRPCSerializedOtherWay = true;
4324 : }
4325 :
4326 32 : if (CPLFetchBool(papszCreationOptions, "RPCTXT", false))
4327 : {
4328 2 : if (!bWriteOnlyInPAMIfNeeded)
4329 1 : GDALWriteRPCTXTFile(pszTIFFFilename, papszRPCMD);
4330 2 : bRPCSerializedOtherWay = true;
4331 : }
4332 :
4333 32 : if (!bRPCSerializedOtherWay && bWriteOnlyInPAMIfNeeded && bSrcIsGeoTIFF)
4334 1 : cpl::down_cast<GTiffDataset *>(poSrcDS)
4335 1 : ->GDALPamDataset::SetMetadata(papszRPCMD, MD_DOMAIN_RPC);
4336 : }
4337 10154 : }
4338 :
4339 : /************************************************************************/
4340 : /* WriteMetadata() */
4341 : /************************************************************************/
4342 :
4343 8055 : bool GTiffDataset::WriteMetadata(GDALDataset *poSrcDS, TIFF *l_hTIFF,
4344 : bool bSrcIsGeoTIFF, GTiffProfile eProfile,
4345 : const char *pszTIFFFilename,
4346 : CSLConstList papszCreationOptions,
4347 : bool bExcludeRPBandIMGFileWriting)
4348 :
4349 : {
4350 : /* -------------------------------------------------------------------- */
4351 : /* Convert all the remaining metadata into a simple XML */
4352 : /* format. */
4353 : /* -------------------------------------------------------------------- */
4354 8055 : CPLXMLNode *psRoot = nullptr;
4355 8055 : CPLXMLNode *psTail = nullptr;
4356 :
4357 : const char *pszCopySrcMDD =
4358 8055 : CSLFetchNameValueDef(papszCreationOptions, "COPY_SRC_MDD", "AUTO");
4359 : char **papszSrcMDD =
4360 8055 : CSLFetchNameValueMultiple(papszCreationOptions, "SRC_MDD");
4361 :
4362 : GTiffDataset *poSrcDSGTiff =
4363 8055 : bSrcIsGeoTIFF ? cpl::down_cast<GTiffDataset *>(poSrcDS) : nullptr;
4364 :
4365 8055 : if (poSrcDSGTiff)
4366 : {
4367 5929 : WriteMDMetadata(&poSrcDSGTiff->m_oGTiffMDMD, l_hTIFF, &psRoot, &psTail,
4368 : 0, eProfile);
4369 : }
4370 : else
4371 : {
4372 2126 : if (EQUAL(pszCopySrcMDD, "AUTO") || CPLTestBool(pszCopySrcMDD) ||
4373 : papszSrcMDD)
4374 : {
4375 4246 : GDALMultiDomainMetadata l_oMDMD;
4376 : {
4377 2123 : CSLConstList papszMD = poSrcDS->GetMetadata();
4378 2127 : if (CSLCount(papszMD) > 0 &&
4379 4 : (!papszSrcMDD || CSLFindString(papszSrcMDD, "") >= 0 ||
4380 2 : CSLFindString(papszSrcMDD, "_DEFAULT_") >= 0))
4381 : {
4382 1606 : l_oMDMD.SetMetadata(papszMD);
4383 : }
4384 : }
4385 :
4386 2123 : if (EQUAL(pszCopySrcMDD, "AUTO") && !papszSrcMDD)
4387 : {
4388 : // Propagate ISIS3 or VICAR metadata
4389 6342 : for (const char *pszMDD : {"json:ISIS3", "json:VICAR"})
4390 : {
4391 4228 : CSLConstList papszMD = poSrcDS->GetMetadata(pszMDD);
4392 4228 : if (papszMD)
4393 : {
4394 5 : l_oMDMD.SetMetadata(papszMD, pszMDD);
4395 : }
4396 : }
4397 : }
4398 :
4399 2123 : if ((!EQUAL(pszCopySrcMDD, "AUTO") && CPLTestBool(pszCopySrcMDD)) ||
4400 : papszSrcMDD)
4401 : {
4402 9 : char **papszDomainList = poSrcDS->GetMetadataDomainList();
4403 39 : for (CSLConstList papszIter = papszDomainList;
4404 39 : papszIter && *papszIter; ++papszIter)
4405 : {
4406 30 : const char *pszDomain = *papszIter;
4407 46 : if (pszDomain[0] != 0 &&
4408 16 : (!papszSrcMDD ||
4409 16 : CSLFindString(papszSrcMDD, pszDomain) >= 0))
4410 : {
4411 12 : l_oMDMD.SetMetadata(poSrcDS->GetMetadata(pszDomain),
4412 : pszDomain);
4413 : }
4414 : }
4415 9 : CSLDestroy(papszDomainList);
4416 : }
4417 :
4418 2123 : WriteMDMetadata(&l_oMDMD, l_hTIFF, &psRoot, &psTail, 0, eProfile);
4419 : }
4420 : }
4421 :
4422 8055 : if (!bExcludeRPBandIMGFileWriting &&
4423 5923 : (!poSrcDSGTiff || poSrcDSGTiff->m_poBaseDS == nullptr))
4424 : {
4425 8044 : WriteRPC(poSrcDS, l_hTIFF, bSrcIsGeoTIFF, eProfile, pszTIFFFilename,
4426 : papszCreationOptions);
4427 :
4428 : /* ------------------------------------------------------------------ */
4429 : /* Handle metadata data written to an IMD file. */
4430 : /* ------------------------------------------------------------------ */
4431 8044 : CSLConstList papszIMDMD = poSrcDS->GetMetadata(MD_DOMAIN_IMD);
4432 8044 : if (papszIMDMD != nullptr)
4433 : {
4434 20 : GDALWriteIMDFile(pszTIFFFilename, papszIMDMD);
4435 : }
4436 : }
4437 :
4438 8055 : uint16_t nPhotometric = 0;
4439 8055 : if (!TIFFGetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, &(nPhotometric)))
4440 1 : nPhotometric = PHOTOMETRIC_MINISBLACK;
4441 :
4442 8055 : const bool bStandardColorInterp = GTIFFIsStandardColorInterpretation(
4443 : GDALDataset::ToHandle(poSrcDS), nPhotometric, papszCreationOptions);
4444 :
4445 : /* -------------------------------------------------------------------- */
4446 : /* We also need to address band specific metadata, and special */
4447 : /* "role" metadata. */
4448 : /* -------------------------------------------------------------------- */
4449 316006 : for (int nBand = 1; nBand <= poSrcDS->GetRasterCount(); ++nBand)
4450 : {
4451 307951 : GDALRasterBand *poBand = poSrcDS->GetRasterBand(nBand);
4452 :
4453 307951 : if (bSrcIsGeoTIFF)
4454 : {
4455 : GTiffRasterBand *poSrcBandGTiff =
4456 302900 : cpl::down_cast<GTiffRasterBand *>(poBand);
4457 302900 : assert(poSrcBandGTiff);
4458 302900 : WriteMDMetadata(&poSrcBandGTiff->m_oGTiffMDMD, l_hTIFF, &psRoot,
4459 : &psTail, nBand, eProfile);
4460 : }
4461 : else
4462 : {
4463 10102 : GDALMultiDomainMetadata l_oMDMD;
4464 5051 : bool bOMDMDSet = false;
4465 :
4466 5051 : if (EQUAL(pszCopySrcMDD, "AUTO") && !papszSrcMDD)
4467 : {
4468 15117 : for (const char *pszDomain : {"", "IMAGERY"})
4469 : {
4470 10078 : if (CSLConstList papszMD = poBand->GetMetadata(pszDomain))
4471 : {
4472 89 : if (papszMD[0])
4473 : {
4474 89 : bOMDMDSet = true;
4475 89 : l_oMDMD.SetMetadata(papszMD, pszDomain);
4476 : }
4477 : }
4478 5039 : }
4479 : }
4480 12 : else if (CPLTestBool(pszCopySrcMDD) || papszSrcMDD)
4481 : {
4482 9 : char **papszDomainList = poBand->GetMetadataDomainList();
4483 3 : for (const char *pszDomain :
4484 15 : cpl::Iterate(CSLConstList(papszDomainList)))
4485 : {
4486 9 : if (pszDomain[0] != 0 &&
4487 5 : !EQUAL(pszDomain, "IMAGE_STRUCTURE") &&
4488 2 : (!papszSrcMDD ||
4489 2 : CSLFindString(papszSrcMDD, pszDomain) >= 0))
4490 : {
4491 2 : bOMDMDSet = true;
4492 2 : l_oMDMD.SetMetadata(poBand->GetMetadata(pszDomain),
4493 : pszDomain);
4494 : }
4495 : }
4496 9 : CSLDestroy(papszDomainList);
4497 : }
4498 :
4499 5051 : if (bOMDMDSet)
4500 : {
4501 91 : WriteMDMetadata(&l_oMDMD, l_hTIFF, &psRoot, &psTail, nBand,
4502 : eProfile);
4503 : }
4504 : }
4505 :
4506 307951 : const double dfOffset = poBand->GetOffset();
4507 307951 : const double dfScale = poBand->GetScale();
4508 307951 : bool bGeoTIFFScaleOffsetInZ = false;
4509 307951 : GDALGeoTransform gt;
4510 : // Check if we have already encoded scale/offset in the GeoTIFF tags
4511 314050 : if (poSrcDS->GetGeoTransform(gt) == CE_None && gt.xrot == 0.0 &&
4512 6083 : gt.yrot == 0.0 && gt.yscale < 0.0 && poSrcDS->GetSpatialRef() &&
4513 314057 : poSrcDS->GetSpatialRef()->IsVertical() &&
4514 7 : poSrcDS->GetRasterCount() == 1)
4515 : {
4516 7 : bGeoTIFFScaleOffsetInZ = true;
4517 : }
4518 :
4519 307951 : if ((dfOffset != 0.0 || dfScale != 1.0) && !bGeoTIFFScaleOffsetInZ)
4520 : {
4521 25 : char szValue[128] = {};
4522 :
4523 25 : CPLsnprintf(szValue, sizeof(szValue), "%.17g", dfOffset);
4524 25 : AppendMetadataItem(&psRoot, &psTail, "OFFSET", szValue, nBand,
4525 : "offset", "");
4526 25 : CPLsnprintf(szValue, sizeof(szValue), "%.17g", dfScale);
4527 25 : AppendMetadataItem(&psRoot, &psTail, "SCALE", szValue, nBand,
4528 : "scale", "");
4529 : }
4530 :
4531 307951 : const char *pszUnitType = poBand->GetUnitType();
4532 307951 : if (pszUnitType != nullptr && pszUnitType[0] != '\0')
4533 : {
4534 40 : bool bWriteUnit = true;
4535 40 : auto poSRS = poSrcDS->GetSpatialRef();
4536 40 : if (poSRS && poSRS->IsCompound())
4537 : {
4538 2 : const char *pszVertUnit = nullptr;
4539 2 : poSRS->GetTargetLinearUnits("COMPD_CS|VERT_CS", &pszVertUnit);
4540 2 : if (pszVertUnit && EQUAL(pszVertUnit, pszUnitType))
4541 : {
4542 2 : bWriteUnit = false;
4543 : }
4544 : }
4545 40 : if (bWriteUnit)
4546 : {
4547 38 : AppendMetadataItem(&psRoot, &psTail, "UNITTYPE", pszUnitType,
4548 : nBand, "unittype", "");
4549 : }
4550 : }
4551 :
4552 307951 : if (strlen(poBand->GetDescription()) > 0)
4553 : {
4554 24 : AppendMetadataItem(&psRoot, &psTail, "DESCRIPTION",
4555 24 : poBand->GetDescription(), nBand, "description",
4556 : "");
4557 : }
4558 :
4559 308168 : if (!bStandardColorInterp &&
4560 217 : !(nBand <= 3 && EQUAL(CSLFetchNameValueDef(papszCreationOptions,
4561 : "PHOTOMETRIC", ""),
4562 : "RGB")))
4563 : {
4564 250 : AppendMetadataItem(&psRoot, &psTail, "COLORINTERP",
4565 : GDALGetColorInterpretationName(
4566 250 : poBand->GetColorInterpretation()),
4567 : nBand, "colorinterp", "");
4568 : }
4569 : }
4570 :
4571 8055 : CSLDestroy(papszSrcMDD);
4572 :
4573 : const char *pszTilingSchemeName =
4574 8055 : CSLFetchNameValue(papszCreationOptions, "@TILING_SCHEME_NAME");
4575 8055 : if (pszTilingSchemeName)
4576 : {
4577 23 : AppendMetadataItem(&psRoot, &psTail, "NAME", pszTilingSchemeName, 0,
4578 : nullptr, "TILING_SCHEME");
4579 :
4580 23 : const char *pszZoomLevel = CSLFetchNameValue(
4581 : papszCreationOptions, "@TILING_SCHEME_ZOOM_LEVEL");
4582 23 : if (pszZoomLevel)
4583 : {
4584 23 : AppendMetadataItem(&psRoot, &psTail, "ZOOM_LEVEL", pszZoomLevel, 0,
4585 : nullptr, "TILING_SCHEME");
4586 : }
4587 :
4588 23 : const char *pszAlignedLevels = CSLFetchNameValue(
4589 : papszCreationOptions, "@TILING_SCHEME_ALIGNED_LEVELS");
4590 23 : if (pszAlignedLevels)
4591 : {
4592 4 : AppendMetadataItem(&psRoot, &psTail, "ALIGNED_LEVELS",
4593 : pszAlignedLevels, 0, nullptr, "TILING_SCHEME");
4594 : }
4595 : }
4596 :
4597 8055 : if (const char *pszOverviewResampling =
4598 8055 : CSLFetchNameValue(papszCreationOptions, "@OVERVIEW_RESAMPLING"))
4599 : {
4600 39 : AppendMetadataItem(&psRoot, &psTail, "OVERVIEW_RESAMPLING",
4601 : pszOverviewResampling, 0, nullptr,
4602 : "IMAGE_STRUCTURE");
4603 : }
4604 :
4605 : /* -------------------------------------------------------------------- */
4606 : /* Write information about some codecs. */
4607 : /* -------------------------------------------------------------------- */
4608 8055 : if (CPLTestBool(
4609 : CPLGetConfigOption("GTIFF_WRITE_IMAGE_STRUCTURE_METADATA", "YES")))
4610 : {
4611 : const char *pszTileInterleave =
4612 8050 : CSLFetchNameValue(papszCreationOptions, "@TILE_INTERLEAVE");
4613 8050 : if (pszTileInterleave && CPLTestBool(pszTileInterleave))
4614 : {
4615 7 : AppendMetadataItem(&psRoot, &psTail, "INTERLEAVE", "TILE", 0,
4616 : nullptr, "IMAGE_STRUCTURE");
4617 : }
4618 :
4619 : const char *pszCompress =
4620 8050 : CSLFetchNameValue(papszCreationOptions, "COMPRESS");
4621 8050 : if (pszCompress && EQUAL(pszCompress, "WEBP"))
4622 : {
4623 31 : if (GTiffGetWebPLossless(papszCreationOptions))
4624 : {
4625 6 : AppendMetadataItem(&psRoot, &psTail,
4626 : "COMPRESSION_REVERSIBILITY", "LOSSLESS", 0,
4627 : nullptr, "IMAGE_STRUCTURE");
4628 : }
4629 : else
4630 : {
4631 25 : AppendMetadataItem(
4632 : &psRoot, &psTail, "WEBP_LEVEL",
4633 25 : CPLSPrintf("%d", GTiffGetWebPLevel(papszCreationOptions)),
4634 : 0, nullptr, "IMAGE_STRUCTURE");
4635 : }
4636 : }
4637 8019 : else if (pszCompress && STARTS_WITH_CI(pszCompress, "LERC"))
4638 : {
4639 : const double dfMaxZError =
4640 97 : GTiffGetLERCMaxZError(papszCreationOptions);
4641 : const double dfMaxZErrorOverview =
4642 97 : GTiffGetLERCMaxZErrorOverview(papszCreationOptions);
4643 97 : if (dfMaxZError == 0.0 && dfMaxZErrorOverview == 0.0)
4644 : {
4645 83 : AppendMetadataItem(&psRoot, &psTail,
4646 : "COMPRESSION_REVERSIBILITY", "LOSSLESS", 0,
4647 : nullptr, "IMAGE_STRUCTURE");
4648 : }
4649 : else
4650 : {
4651 14 : AppendMetadataItem(&psRoot, &psTail, "MAX_Z_ERROR",
4652 : CSLFetchNameValueDef(papszCreationOptions,
4653 : "MAX_Z_ERROR", ""),
4654 : 0, nullptr, "IMAGE_STRUCTURE");
4655 14 : if (dfMaxZError != dfMaxZErrorOverview)
4656 : {
4657 3 : AppendMetadataItem(
4658 : &psRoot, &psTail, "MAX_Z_ERROR_OVERVIEW",
4659 : CSLFetchNameValueDef(papszCreationOptions,
4660 : "MAX_Z_ERROR_OVERVIEW", ""),
4661 : 0, nullptr, "IMAGE_STRUCTURE");
4662 : }
4663 97 : }
4664 : }
4665 : #if HAVE_JXL
4666 7922 : else if (pszCompress && EQUAL(pszCompress, "JXL"))
4667 : {
4668 101 : float fDistance = 0.0f;
4669 101 : if (GTiffGetJXLLossless(papszCreationOptions))
4670 : {
4671 82 : AppendMetadataItem(&psRoot, &psTail,
4672 : "COMPRESSION_REVERSIBILITY", "LOSSLESS", 0,
4673 : nullptr, "IMAGE_STRUCTURE");
4674 : }
4675 : else
4676 : {
4677 19 : fDistance = GTiffGetJXLDistance(papszCreationOptions);
4678 19 : AppendMetadataItem(
4679 : &psRoot, &psTail, "JXL_DISTANCE",
4680 : CPLSPrintf("%f", static_cast<double>(fDistance)), 0,
4681 : nullptr, "IMAGE_STRUCTURE");
4682 : }
4683 : const float fAlphaDistance =
4684 101 : GTiffGetJXLAlphaDistance(papszCreationOptions);
4685 101 : if (fAlphaDistance >= 0.0f && fAlphaDistance != fDistance)
4686 : {
4687 2 : AppendMetadataItem(
4688 : &psRoot, &psTail, "JXL_ALPHA_DISTANCE",
4689 : CPLSPrintf("%f", static_cast<double>(fAlphaDistance)), 0,
4690 : nullptr, "IMAGE_STRUCTURE");
4691 : }
4692 101 : AppendMetadataItem(
4693 : &psRoot, &psTail, "JXL_EFFORT",
4694 : CPLSPrintf("%d", GTiffGetJXLEffort(papszCreationOptions)), 0,
4695 : nullptr, "IMAGE_STRUCTURE");
4696 : }
4697 : #endif
4698 : }
4699 :
4700 8055 : if (!CPLTestBool(CPLGetConfigOption("GTIFF_WRITE_RAT_TO_PAM", "NO")))
4701 : {
4702 316000 : for (int nBand = 1; nBand <= poSrcDS->GetRasterCount(); ++nBand)
4703 : {
4704 307948 : GDALRasterAttributeTable *poRAT = nullptr;
4705 307948 : if (poSrcDSGTiff)
4706 : {
4707 302898 : auto poBand = cpl::down_cast<GTiffRasterBand *>(
4708 : poSrcDSGTiff->GetRasterBand(nBand));
4709 : // Scenario of https://github.com/OSGeo/gdal/issues/13930
4710 : // Do not try to fetch the RAT from auxiliary files if creating
4711 : // a new GeoTIFF file
4712 302898 : if (poBand->m_bRATSet)
4713 105 : poRAT = poBand->GetDefaultRAT();
4714 : }
4715 : else
4716 : {
4717 5050 : poRAT = poSrcDS->GetRasterBand(nBand)->GetDefaultRAT();
4718 : }
4719 307948 : if (poRAT)
4720 : {
4721 22 : auto psSerializedRAT = poRAT->Serialize();
4722 22 : if (psSerializedRAT)
4723 : {
4724 21 : AppendMetadataItem(
4725 : &psRoot, &psTail, DEFAULT_RASTER_ATTRIBUTE_TABLE,
4726 : nullptr, psSerializedRAT, nBand, RAT_ROLE, nullptr);
4727 : }
4728 : }
4729 : }
4730 : }
4731 :
4732 : /* -------------------------------------------------------------------- */
4733 : /* Write out the generic XML metadata if there is any. */
4734 : /* -------------------------------------------------------------------- */
4735 8055 : if (psRoot != nullptr)
4736 : {
4737 762 : bool bRet = true;
4738 :
4739 762 : if (eProfile == GTiffProfile::GDALGEOTIFF)
4740 : {
4741 745 : char *pszXML_MD = CPLSerializeXMLTree(psRoot);
4742 745 : TIFFSetField(l_hTIFF, TIFFTAG_GDAL_METADATA, pszXML_MD);
4743 745 : CPLFree(pszXML_MD);
4744 : }
4745 : else
4746 : {
4747 17 : if (bSrcIsGeoTIFF)
4748 11 : cpl::down_cast<GTiffDataset *>(poSrcDS)->PushMetadataToPam();
4749 : else
4750 6 : bRet = false;
4751 : }
4752 :
4753 762 : CPLDestroyXMLNode(psRoot);
4754 :
4755 762 : return bRet;
4756 : }
4757 :
4758 : // If we have no more metadata but it existed before,
4759 : // remove the GDAL_METADATA tag.
4760 7293 : if (eProfile == GTiffProfile::GDALGEOTIFF)
4761 : {
4762 7269 : char *pszText = nullptr;
4763 7269 : if (TIFFGetField(l_hTIFF, TIFFTAG_GDAL_METADATA, &pszText))
4764 : {
4765 7 : TIFFUnsetField(l_hTIFF, TIFFTAG_GDAL_METADATA);
4766 : }
4767 : }
4768 :
4769 7293 : return true;
4770 : }
4771 :
4772 : /************************************************************************/
4773 : /* PushMetadataToPam() */
4774 : /* */
4775 : /* When producing a strict profile TIFF or if our aggregate */
4776 : /* metadata is too big for a single tiff tag we may end up */
4777 : /* needing to write it via the PAM mechanisms. This method */
4778 : /* copies all the appropriate metadata into the PAM level */
4779 : /* metadata object but with special care to avoid copying */
4780 : /* metadata handled in other ways in TIFF format. */
4781 : /************************************************************************/
4782 :
4783 17 : void GTiffDataset::PushMetadataToPam()
4784 :
4785 : {
4786 17 : if (GetPamFlags() & GPF_DISABLED)
4787 0 : return;
4788 :
4789 17 : const bool bStandardColorInterp = GTIFFIsStandardColorInterpretation(
4790 17 : GDALDataset::ToHandle(this), m_nPhotometric, m_papszCreationOptions);
4791 :
4792 55 : for (int nBand = 0; nBand <= GetRasterCount(); ++nBand)
4793 : {
4794 38 : GDALMultiDomainMetadata *poSrcMDMD = nullptr;
4795 38 : GTiffRasterBand *poBand = nullptr;
4796 :
4797 38 : if (nBand == 0)
4798 : {
4799 17 : poSrcMDMD = &(this->m_oGTiffMDMD);
4800 : }
4801 : else
4802 : {
4803 21 : poBand = cpl::down_cast<GTiffRasterBand *>(GetRasterBand(nBand));
4804 21 : poSrcMDMD = &(poBand->m_oGTiffMDMD);
4805 : }
4806 :
4807 : /* --------------------------------------------------------------------
4808 : */
4809 : /* Loop over the available domains. */
4810 : /* --------------------------------------------------------------------
4811 : */
4812 38 : CSLConstList papszDomainList = poSrcMDMD->GetDomainList();
4813 74 : for (int iDomain = 0; papszDomainList && papszDomainList[iDomain];
4814 : ++iDomain)
4815 : {
4816 36 : char **papszMD = poSrcMDMD->GetMetadata(papszDomainList[iDomain]);
4817 :
4818 36 : if (EQUAL(papszDomainList[iDomain], MD_DOMAIN_RPC) ||
4819 36 : EQUAL(papszDomainList[iDomain], MD_DOMAIN_IMD) ||
4820 36 : EQUAL(papszDomainList[iDomain], "_temporary_") ||
4821 36 : EQUAL(papszDomainList[iDomain], "IMAGE_STRUCTURE") ||
4822 19 : EQUAL(papszDomainList[iDomain], "COLOR_PROFILE"))
4823 17 : continue;
4824 :
4825 19 : papszMD = CSLDuplicate(papszMD);
4826 :
4827 69 : for (int i = CSLCount(papszMD) - 1; i >= 0; --i)
4828 : {
4829 50 : if (STARTS_WITH_CI(papszMD[i], "TIFFTAG_") ||
4830 50 : EQUALN(papszMD[i], GDALMD_AREA_OR_POINT,
4831 : strlen(GDALMD_AREA_OR_POINT)))
4832 4 : papszMD = CSLRemoveStrings(papszMD, i, 1, nullptr);
4833 : }
4834 :
4835 19 : if (nBand == 0)
4836 10 : GDALPamDataset::SetMetadata(papszMD, papszDomainList[iDomain]);
4837 : else
4838 9 : poBand->GDALPamRasterBand::SetMetadata(
4839 9 : papszMD, papszDomainList[iDomain]);
4840 :
4841 19 : CSLDestroy(papszMD);
4842 : }
4843 :
4844 : /* --------------------------------------------------------------------
4845 : */
4846 : /* Handle some "special domain" stuff. */
4847 : /* --------------------------------------------------------------------
4848 : */
4849 38 : if (poBand != nullptr)
4850 : {
4851 21 : poBand->GDALPamRasterBand::SetOffset(poBand->GetOffset());
4852 21 : poBand->GDALPamRasterBand::SetScale(poBand->GetScale());
4853 21 : poBand->GDALPamRasterBand::SetUnitType(poBand->GetUnitType());
4854 21 : poBand->GDALPamRasterBand::SetDescription(poBand->GetDescription());
4855 21 : if (!bStandardColorInterp)
4856 : {
4857 3 : poBand->GDALPamRasterBand::SetColorInterpretation(
4858 3 : poBand->GetColorInterpretation());
4859 : }
4860 : }
4861 : }
4862 17 : MarkPamDirty();
4863 : }
4864 :
4865 : /************************************************************************/
4866 : /* WriteNoDataValue() */
4867 : /************************************************************************/
4868 :
4869 520 : void GTiffDataset::WriteNoDataValue(TIFF *hTIFF, double dfNoData)
4870 :
4871 : {
4872 1040 : CPLString osVal(GTiffFormatGDALNoDataTagValue(dfNoData));
4873 520 : TIFFSetField(hTIFF, TIFFTAG_GDAL_NODATA, osVal.c_str());
4874 520 : }
4875 :
4876 5 : void GTiffDataset::WriteNoDataValue(TIFF *hTIFF, int64_t nNoData)
4877 :
4878 : {
4879 5 : TIFFSetField(hTIFF, TIFFTAG_GDAL_NODATA,
4880 : CPLSPrintf(CPL_FRMT_GIB, static_cast<GIntBig>(nNoData)));
4881 5 : }
4882 :
4883 5 : void GTiffDataset::WriteNoDataValue(TIFF *hTIFF, uint64_t nNoData)
4884 :
4885 : {
4886 5 : TIFFSetField(hTIFF, TIFFTAG_GDAL_NODATA,
4887 : CPLSPrintf(CPL_FRMT_GUIB, static_cast<GUIntBig>(nNoData)));
4888 5 : }
4889 :
4890 : /************************************************************************/
4891 : /* UnsetNoDataValue() */
4892 : /************************************************************************/
4893 :
4894 16 : void GTiffDataset::UnsetNoDataValue(TIFF *l_hTIFF)
4895 :
4896 : {
4897 16 : TIFFUnsetField(l_hTIFF, TIFFTAG_GDAL_NODATA);
4898 16 : }
4899 :
4900 : /************************************************************************/
4901 : /* SaveICCProfile() */
4902 : /* */
4903 : /* Save ICC Profile or colorimetric data into file */
4904 : /* pDS: */
4905 : /* Dataset that contains the metadata with the ICC or colorimetric */
4906 : /* data. If this argument is specified, all other arguments are */
4907 : /* ignored. Set them to NULL or 0. */
4908 : /* hTIFF: */
4909 : /* Pointer to TIFF handle. Only needed if pDS is NULL or */
4910 : /* pDS->m_hTIFF is NULL. */
4911 : /* papszParamList: */
4912 : /* Options containing the ICC profile or colorimetric metadata. */
4913 : /* Ignored if pDS is not NULL. */
4914 : /* nBitsPerSample: */
4915 : /* Bits per sample. Ignored if pDS is not NULL. */
4916 : /************************************************************************/
4917 :
4918 9800 : void GTiffDataset::SaveICCProfile(GTiffDataset *pDS, TIFF *l_hTIFF,
4919 : CSLConstList papszParamList,
4920 : uint32_t l_nBitsPerSample)
4921 : {
4922 9800 : if ((pDS != nullptr) && (pDS->eAccess != GA_Update))
4923 0 : return;
4924 :
4925 9800 : if (l_hTIFF == nullptr)
4926 : {
4927 2 : if (pDS == nullptr)
4928 0 : return;
4929 :
4930 2 : l_hTIFF = pDS->m_hTIFF;
4931 2 : if (l_hTIFF == nullptr)
4932 0 : return;
4933 : }
4934 :
4935 9800 : if ((papszParamList == nullptr) && (pDS == nullptr))
4936 4859 : return;
4937 :
4938 : const char *pszICCProfile =
4939 : (pDS != nullptr)
4940 4941 : ? pDS->GetMetadataItem("SOURCE_ICC_PROFILE", "COLOR_PROFILE")
4941 4939 : : CSLFetchNameValue(papszParamList, "SOURCE_ICC_PROFILE");
4942 4941 : if (pszICCProfile != nullptr)
4943 : {
4944 8 : char *pEmbedBuffer = CPLStrdup(pszICCProfile);
4945 : int32_t nEmbedLen =
4946 8 : CPLBase64DecodeInPlace(reinterpret_cast<GByte *>(pEmbedBuffer));
4947 :
4948 8 : TIFFSetField(l_hTIFF, TIFFTAG_ICCPROFILE, nEmbedLen, pEmbedBuffer);
4949 :
4950 8 : CPLFree(pEmbedBuffer);
4951 : }
4952 : else
4953 : {
4954 : // Output colorimetric data.
4955 4933 : float pCHR[6] = {}; // Primaries.
4956 4933 : uint16_t pTXR[6] = {}; // Transfer range.
4957 4933 : const char *pszCHRNames[] = {"SOURCE_PRIMARIES_RED",
4958 : "SOURCE_PRIMARIES_GREEN",
4959 : "SOURCE_PRIMARIES_BLUE"};
4960 4933 : const char *pszTXRNames[] = {"TIFFTAG_TRANSFERRANGE_BLACK",
4961 : "TIFFTAG_TRANSFERRANGE_WHITE"};
4962 :
4963 : // Output chromacities.
4964 4933 : bool bOutputCHR = true;
4965 4948 : for (int i = 0; i < 3 && bOutputCHR; ++i)
4966 : {
4967 : const char *pszColorProfile =
4968 : (pDS != nullptr)
4969 4943 : ? pDS->GetMetadataItem(pszCHRNames[i], "COLOR_PROFILE")
4970 4940 : : CSLFetchNameValue(papszParamList, pszCHRNames[i]);
4971 4943 : if (pszColorProfile == nullptr)
4972 : {
4973 4928 : bOutputCHR = false;
4974 4928 : break;
4975 : }
4976 :
4977 : const CPLStringList aosTokens(CSLTokenizeString2(
4978 : pszColorProfile, ",",
4979 : CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES |
4980 15 : CSLT_STRIPENDSPACES));
4981 :
4982 15 : if (aosTokens.size() != 3)
4983 : {
4984 0 : bOutputCHR = false;
4985 0 : break;
4986 : }
4987 :
4988 60 : for (int j = 0; j < 3; ++j)
4989 : {
4990 45 : float v = static_cast<float>(CPLAtof(aosTokens[j]));
4991 :
4992 45 : if (j == 2)
4993 : {
4994 : // Last term of xyY color must be 1.0.
4995 15 : if (v != 1.0f)
4996 : {
4997 0 : bOutputCHR = false;
4998 0 : break;
4999 : }
5000 : }
5001 : else
5002 : {
5003 30 : pCHR[i * 2 + j] = v;
5004 : }
5005 : }
5006 : }
5007 :
5008 4933 : if (bOutputCHR)
5009 : {
5010 5 : TIFFSetField(l_hTIFF, TIFFTAG_PRIMARYCHROMATICITIES, pCHR);
5011 : }
5012 :
5013 : // Output whitepoint.
5014 : const char *pszSourceWhitePoint =
5015 : (pDS != nullptr)
5016 4933 : ? pDS->GetMetadataItem("SOURCE_WHITEPOINT", "COLOR_PROFILE")
5017 4932 : : CSLFetchNameValue(papszParamList, "SOURCE_WHITEPOINT");
5018 4933 : if (pszSourceWhitePoint != nullptr)
5019 : {
5020 : const CPLStringList aosTokens(CSLTokenizeString2(
5021 : pszSourceWhitePoint, ",",
5022 : CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES |
5023 10 : CSLT_STRIPENDSPACES));
5024 :
5025 5 : bool bOutputWhitepoint = true;
5026 5 : float pWP[2] = {0.0f, 0.0f}; // Whitepoint
5027 5 : if (aosTokens.size() != 3)
5028 : {
5029 0 : bOutputWhitepoint = false;
5030 : }
5031 : else
5032 : {
5033 20 : for (int j = 0; j < 3; ++j)
5034 : {
5035 15 : const float v = static_cast<float>(CPLAtof(aosTokens[j]));
5036 :
5037 15 : if (j == 2)
5038 : {
5039 : // Last term of xyY color must be 1.0.
5040 5 : if (v != 1.0f)
5041 : {
5042 0 : bOutputWhitepoint = false;
5043 0 : break;
5044 : }
5045 : }
5046 : else
5047 : {
5048 10 : pWP[j] = v;
5049 : }
5050 : }
5051 : }
5052 :
5053 5 : if (bOutputWhitepoint)
5054 : {
5055 5 : TIFFSetField(l_hTIFF, TIFFTAG_WHITEPOINT, pWP);
5056 : }
5057 : }
5058 :
5059 : // Set transfer function metadata.
5060 : char const *pszTFRed =
5061 : (pDS != nullptr)
5062 4933 : ? pDS->GetMetadataItem("TIFFTAG_TRANSFERFUNCTION_RED",
5063 : "COLOR_PROFILE")
5064 4932 : : CSLFetchNameValue(papszParamList,
5065 4933 : "TIFFTAG_TRANSFERFUNCTION_RED");
5066 :
5067 : char const *pszTFGreen =
5068 : (pDS != nullptr)
5069 4933 : ? pDS->GetMetadataItem("TIFFTAG_TRANSFERFUNCTION_GREEN",
5070 : "COLOR_PROFILE")
5071 4932 : : CSLFetchNameValue(papszParamList,
5072 4933 : "TIFFTAG_TRANSFERFUNCTION_GREEN");
5073 :
5074 : char const *pszTFBlue =
5075 : (pDS != nullptr)
5076 4933 : ? pDS->GetMetadataItem("TIFFTAG_TRANSFERFUNCTION_BLUE",
5077 : "COLOR_PROFILE")
5078 4932 : : CSLFetchNameValue(papszParamList,
5079 4933 : "TIFFTAG_TRANSFERFUNCTION_BLUE");
5080 :
5081 4933 : if ((pszTFRed != nullptr) && (pszTFGreen != nullptr) &&
5082 : (pszTFBlue != nullptr))
5083 : {
5084 : // Get length of table.
5085 4 : const int nTransferFunctionLength =
5086 4 : 1 << ((pDS != nullptr) ? pDS->m_nBitsPerSample
5087 : : l_nBitsPerSample);
5088 :
5089 : const CPLStringList aosTokensRed(CSLTokenizeString2(
5090 : pszTFRed, ",",
5091 : CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES |
5092 8 : CSLT_STRIPENDSPACES));
5093 : const CPLStringList aosTokensGreen(CSLTokenizeString2(
5094 : pszTFGreen, ",",
5095 : CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES |
5096 8 : CSLT_STRIPENDSPACES));
5097 : const CPLStringList aosTokensBlue(CSLTokenizeString2(
5098 : pszTFBlue, ",",
5099 : CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES |
5100 8 : CSLT_STRIPENDSPACES));
5101 :
5102 4 : if ((aosTokensRed.size() == nTransferFunctionLength) &&
5103 8 : (aosTokensGreen.size() == nTransferFunctionLength) &&
5104 4 : (aosTokensBlue.size() == nTransferFunctionLength))
5105 : {
5106 : std::vector<uint16_t> anTransferFuncRed(
5107 8 : nTransferFunctionLength);
5108 : std::vector<uint16_t> anTransferFuncGreen(
5109 8 : nTransferFunctionLength);
5110 : std::vector<uint16_t> anTransferFuncBlue(
5111 8 : nTransferFunctionLength);
5112 :
5113 : // Convert our table in string format into int16_t format.
5114 1028 : for (int i = 0; i < nTransferFunctionLength; ++i)
5115 : {
5116 2048 : anTransferFuncRed[i] =
5117 1024 : static_cast<uint16_t>(atoi(aosTokensRed[i]));
5118 2048 : anTransferFuncGreen[i] =
5119 1024 : static_cast<uint16_t>(atoi(aosTokensGreen[i]));
5120 1024 : anTransferFuncBlue[i] =
5121 1024 : static_cast<uint16_t>(atoi(aosTokensBlue[i]));
5122 : }
5123 :
5124 4 : TIFFSetField(
5125 : l_hTIFF, TIFFTAG_TRANSFERFUNCTION, anTransferFuncRed.data(),
5126 : anTransferFuncGreen.data(), anTransferFuncBlue.data());
5127 : }
5128 : }
5129 :
5130 : // Output transfer range.
5131 4933 : bool bOutputTransferRange = true;
5132 4933 : for (int i = 0; (i < 2) && bOutputTransferRange; ++i)
5133 : {
5134 : const char *pszTXRVal =
5135 : (pDS != nullptr)
5136 4933 : ? pDS->GetMetadataItem(pszTXRNames[i], "COLOR_PROFILE")
5137 4932 : : CSLFetchNameValue(papszParamList, pszTXRNames[i]);
5138 4933 : if (pszTXRVal == nullptr)
5139 : {
5140 4933 : bOutputTransferRange = false;
5141 4933 : break;
5142 : }
5143 :
5144 : const CPLStringList aosTokens(CSLTokenizeString2(
5145 : pszTXRVal, ",",
5146 : CSLT_ALLOWEMPTYTOKENS | CSLT_STRIPLEADSPACES |
5147 0 : CSLT_STRIPENDSPACES));
5148 :
5149 0 : if (aosTokens.size() != 3)
5150 : {
5151 0 : bOutputTransferRange = false;
5152 0 : break;
5153 : }
5154 :
5155 0 : for (int j = 0; j < 3; ++j)
5156 : {
5157 0 : pTXR[i + j * 2] = static_cast<uint16_t>(atoi(aosTokens[j]));
5158 : }
5159 : }
5160 :
5161 4933 : if (bOutputTransferRange)
5162 : {
5163 0 : const int TIFFTAG_TRANSFERRANGE = 0x0156;
5164 0 : TIFFSetField(l_hTIFF, TIFFTAG_TRANSFERRANGE, pTXR);
5165 : }
5166 : }
5167 : }
5168 :
5169 17695 : static signed char GTiffGetLZMAPreset(CSLConstList papszOptions)
5170 : {
5171 17695 : int nLZMAPreset = -1;
5172 17695 : const char *pszValue = CSLFetchNameValue(papszOptions, "LZMA_PRESET");
5173 17695 : if (pszValue != nullptr)
5174 : {
5175 20 : nLZMAPreset = atoi(pszValue);
5176 20 : if (!(nLZMAPreset >= 0 && nLZMAPreset <= 9))
5177 : {
5178 0 : CPLError(CE_Warning, CPLE_IllegalArg,
5179 : "LZMA_PRESET=%s value not recognised, ignoring.",
5180 : pszValue);
5181 0 : nLZMAPreset = -1;
5182 : }
5183 : }
5184 17695 : return static_cast<signed char>(nLZMAPreset);
5185 : }
5186 :
5187 17695 : static signed char GTiffGetZSTDPreset(CSLConstList papszOptions)
5188 : {
5189 17695 : int nZSTDLevel = -1;
5190 17695 : const char *pszValue = CSLFetchNameValue(papszOptions, "ZSTD_LEVEL");
5191 17695 : if (pszValue != nullptr)
5192 : {
5193 24 : nZSTDLevel = atoi(pszValue);
5194 24 : if (!(nZSTDLevel >= 1 && nZSTDLevel <= 22))
5195 : {
5196 0 : CPLError(CE_Warning, CPLE_IllegalArg,
5197 : "ZSTD_LEVEL=%s value not recognised, ignoring.", pszValue);
5198 0 : nZSTDLevel = -1;
5199 : }
5200 : }
5201 17695 : return static_cast<signed char>(nZSTDLevel);
5202 : }
5203 :
5204 17695 : static signed char GTiffGetZLevel(CSLConstList papszOptions)
5205 : {
5206 17695 : int nZLevel = -1;
5207 17695 : const char *pszValue = CSLFetchNameValue(papszOptions, "ZLEVEL");
5208 17695 : if (pszValue != nullptr)
5209 : {
5210 44 : nZLevel = atoi(pszValue);
5211 : #ifdef TIFFTAG_DEFLATE_SUBCODEC
5212 44 : constexpr int nMaxLevel = 12;
5213 : #ifndef LIBDEFLATE_SUPPORT
5214 : if (nZLevel > 9 && nZLevel <= nMaxLevel)
5215 : {
5216 : CPLDebug("GTiff",
5217 : "ZLEVEL=%d not supported in a non-libdeflate enabled "
5218 : "libtiff build. Capping to 9",
5219 : nZLevel);
5220 : nZLevel = 9;
5221 : }
5222 : #endif
5223 : #else
5224 : constexpr int nMaxLevel = 9;
5225 : #endif
5226 44 : if (nZLevel < 1 || nZLevel > nMaxLevel)
5227 : {
5228 0 : CPLError(CE_Warning, CPLE_IllegalArg,
5229 : "ZLEVEL=%s value not recognised, ignoring.", pszValue);
5230 0 : nZLevel = -1;
5231 : }
5232 : }
5233 17695 : return static_cast<signed char>(nZLevel);
5234 : }
5235 :
5236 17695 : static signed char GTiffGetJpegQuality(CSLConstList papszOptions)
5237 : {
5238 17695 : int nJpegQuality = -1;
5239 17695 : const char *pszValue = CSLFetchNameValue(papszOptions, "JPEG_QUALITY");
5240 17695 : if (pszValue != nullptr)
5241 : {
5242 1939 : nJpegQuality = atoi(pszValue);
5243 1939 : if (nJpegQuality < 1 || nJpegQuality > 100)
5244 : {
5245 0 : CPLError(CE_Warning, CPLE_IllegalArg,
5246 : "JPEG_QUALITY=%s value not recognised, ignoring.",
5247 : pszValue);
5248 0 : nJpegQuality = -1;
5249 : }
5250 : }
5251 17695 : return static_cast<signed char>(nJpegQuality);
5252 : }
5253 :
5254 17695 : static signed char GTiffGetJpegTablesMode(CSLConstList papszOptions)
5255 : {
5256 17695 : return static_cast<signed char>(atoi(
5257 : CSLFetchNameValueDef(papszOptions, "JPEGTABLESMODE",
5258 17695 : CPLSPrintf("%d", knGTIFFJpegTablesModeDefault))));
5259 : }
5260 :
5261 : /************************************************************************/
5262 : /* GetDiscardLsbOption() */
5263 : /************************************************************************/
5264 :
5265 7836 : static GTiffDataset::MaskOffset *GetDiscardLsbOption(TIFF *hTIFF,
5266 : CSLConstList papszOptions)
5267 : {
5268 7836 : const char *pszBits = CSLFetchNameValue(papszOptions, "DISCARD_LSB");
5269 7836 : if (pszBits == nullptr)
5270 7714 : return nullptr;
5271 :
5272 122 : uint16_t nPhotometric = 0;
5273 122 : TIFFGetFieldDefaulted(hTIFF, TIFFTAG_PHOTOMETRIC, &nPhotometric);
5274 :
5275 122 : uint16_t nBitsPerSample = 0;
5276 122 : if (!TIFFGetField(hTIFF, TIFFTAG_BITSPERSAMPLE, &nBitsPerSample))
5277 0 : nBitsPerSample = 1;
5278 :
5279 122 : uint16_t nSamplesPerPixel = 0;
5280 122 : if (!TIFFGetField(hTIFF, TIFFTAG_SAMPLESPERPIXEL, &nSamplesPerPixel))
5281 0 : nSamplesPerPixel = 1;
5282 :
5283 122 : uint16_t nSampleFormat = 0;
5284 122 : if (!TIFFGetField(hTIFF, TIFFTAG_SAMPLEFORMAT, &nSampleFormat))
5285 0 : nSampleFormat = SAMPLEFORMAT_UINT;
5286 :
5287 122 : if (nPhotometric == PHOTOMETRIC_PALETTE)
5288 : {
5289 1 : CPLError(CE_Warning, CPLE_AppDefined,
5290 : "DISCARD_LSB ignored on a paletted image");
5291 1 : return nullptr;
5292 : }
5293 121 : if (!(nBitsPerSample == 8 || nBitsPerSample == 16 || nBitsPerSample == 32 ||
5294 13 : nBitsPerSample == 64))
5295 : {
5296 1 : CPLError(CE_Warning, CPLE_AppDefined,
5297 : "DISCARD_LSB ignored on non 8, 16, 32 or 64 bits images");
5298 1 : return nullptr;
5299 : }
5300 :
5301 240 : const CPLStringList aosTokens(CSLTokenizeString2(pszBits, ",", 0));
5302 120 : const int nTokens = aosTokens.size();
5303 120 : GTiffDataset::MaskOffset *panMaskOffsetLsb = nullptr;
5304 120 : if (nTokens == 1 || nTokens == nSamplesPerPixel)
5305 : {
5306 : panMaskOffsetLsb = static_cast<GTiffDataset::MaskOffset *>(
5307 119 : CPLCalloc(nSamplesPerPixel, sizeof(GTiffDataset::MaskOffset)));
5308 374 : for (int i = 0; i < nSamplesPerPixel; ++i)
5309 : {
5310 255 : const int nBits = atoi(aosTokens[nTokens == 1 ? 0 : i]);
5311 510 : const int nMaxBits = (nSampleFormat == SAMPLEFORMAT_IEEEFP)
5312 510 : ? ((nBitsPerSample == 16) ? 11 - 1
5313 78 : : (nBitsPerSample == 32) ? 23 - 1
5314 26 : : (nBitsPerSample == 64) ? 53 - 1
5315 : : 0)
5316 203 : : nSampleFormat == SAMPLEFORMAT_INT
5317 203 : ? nBitsPerSample - 2
5318 119 : : nBitsPerSample - 1;
5319 :
5320 255 : if (nBits < 0 || nBits > nMaxBits)
5321 : {
5322 0 : CPLError(
5323 : CE_Warning, CPLE_AppDefined,
5324 : "DISCARD_LSB ignored: values should be in [0,%d] range",
5325 : nMaxBits);
5326 0 : VSIFree(panMaskOffsetLsb);
5327 0 : return nullptr;
5328 : }
5329 255 : panMaskOffsetLsb[i].nMask =
5330 255 : ~((static_cast<uint64_t>(1) << nBits) - 1);
5331 255 : if (nBits > 1)
5332 : {
5333 249 : panMaskOffsetLsb[i].nRoundUpBitTest = static_cast<uint64_t>(1)
5334 249 : << (nBits - 1);
5335 : }
5336 119 : }
5337 : }
5338 : else
5339 : {
5340 1 : CPLError(CE_Warning, CPLE_AppDefined,
5341 : "DISCARD_LSB ignored: wrong number of components");
5342 : }
5343 120 : return panMaskOffsetLsb;
5344 : }
5345 :
5346 7836 : void GTiffDataset::GetDiscardLsbOption(CSLConstList papszOptions)
5347 : {
5348 7836 : m_panMaskOffsetLsb = ::GetDiscardLsbOption(m_hTIFF, papszOptions);
5349 7836 : }
5350 :
5351 : /************************************************************************/
5352 : /* GetProfile() */
5353 : /************************************************************************/
5354 :
5355 17746 : static GTiffProfile GetProfile(const char *pszProfile)
5356 : {
5357 17746 : GTiffProfile eProfile = GTiffProfile::GDALGEOTIFF;
5358 17746 : if (pszProfile != nullptr)
5359 : {
5360 70 : if (EQUAL(pszProfile, szPROFILE_BASELINE))
5361 50 : eProfile = GTiffProfile::BASELINE;
5362 20 : else if (EQUAL(pszProfile, szPROFILE_GeoTIFF))
5363 18 : eProfile = GTiffProfile::GEOTIFF;
5364 2 : else if (!EQUAL(pszProfile, szPROFILE_GDALGeoTIFF))
5365 : {
5366 0 : CPLError(CE_Warning, CPLE_NotSupported,
5367 : "Unsupported value for PROFILE: %s", pszProfile);
5368 : }
5369 : }
5370 17746 : return eProfile;
5371 : }
5372 :
5373 : /************************************************************************/
5374 : /* GTiffCreate() */
5375 : /* */
5376 : /* Shared functionality between GTiffDataset::Create() and */
5377 : /* GTiffCreateCopy() for creating TIFF file based on a set of */
5378 : /* options and a configuration. */
5379 : /************************************************************************/
5380 :
5381 9879 : TIFF *GTiffDataset::CreateLL(const char *pszFilename, int nXSize, int nYSize,
5382 : int l_nBands, GDALDataType eType,
5383 : double dfExtraSpaceForOverviews,
5384 : int nColorTableMultiplier,
5385 : CSLConstList papszParamList, VSILFILE **pfpL,
5386 : CPLString &l_osTmpFilename, bool bCreateCopy,
5387 : bool &bTileInterleavingOut)
5388 :
5389 : {
5390 9879 : bTileInterleavingOut = false;
5391 :
5392 9879 : GTiffOneTimeInit();
5393 :
5394 : /* -------------------------------------------------------------------- */
5395 : /* Blow on a few errors. */
5396 : /* -------------------------------------------------------------------- */
5397 9879 : if (nXSize < 1 || nYSize < 1 || l_nBands < 1)
5398 : {
5399 2 : ReportError(
5400 : pszFilename, CE_Failure, CPLE_AppDefined,
5401 : "Attempt to create %dx%dx%d TIFF file, but width, height and bands "
5402 : "must be positive.",
5403 : nXSize, nYSize, l_nBands);
5404 :
5405 2 : return nullptr;
5406 : }
5407 :
5408 9877 : if (l_nBands > 65535)
5409 : {
5410 1 : ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
5411 : "Attempt to create %dx%dx%d TIFF file, but bands "
5412 : "must be lesser or equal to 65535.",
5413 : nXSize, nYSize, l_nBands);
5414 :
5415 1 : return nullptr;
5416 : }
5417 :
5418 : /* -------------------------------------------------------------------- */
5419 : /* Setup values based on options. */
5420 : /* -------------------------------------------------------------------- */
5421 : const GTiffProfile eProfile =
5422 9876 : GetProfile(CSLFetchNameValue(papszParamList, "PROFILE"));
5423 :
5424 9876 : const bool bTiled = CPLFetchBool(papszParamList, "TILED", false);
5425 :
5426 9876 : int l_nBlockXSize = 0;
5427 9876 : if (const char *pszValue = CSLFetchNameValue(papszParamList, "BLOCKXSIZE"))
5428 : {
5429 461 : l_nBlockXSize = atoi(pszValue);
5430 461 : if (l_nBlockXSize < 0)
5431 : {
5432 0 : ReportError(pszFilename, CE_Failure, CPLE_IllegalArg,
5433 : "Invalid value for BLOCKXSIZE");
5434 0 : return nullptr;
5435 : }
5436 461 : if (!bTiled)
5437 : {
5438 10 : ReportError(pszFilename, CE_Warning, CPLE_IllegalArg,
5439 : "BLOCKXSIZE can only be used with TILED=YES");
5440 : }
5441 451 : else if (l_nBlockXSize % 16 != 0)
5442 : {
5443 1 : ReportError(pszFilename, CE_Failure, CPLE_IllegalArg,
5444 : "BLOCKXSIZE must be a multiple of 16");
5445 1 : return nullptr;
5446 : }
5447 : }
5448 :
5449 9875 : int l_nBlockYSize = 0;
5450 9875 : if (const char *pszValue = CSLFetchNameValue(papszParamList, "BLOCKYSIZE"))
5451 : {
5452 2572 : l_nBlockYSize = atoi(pszValue);
5453 2572 : if (l_nBlockYSize < 0)
5454 : {
5455 0 : ReportError(pszFilename, CE_Failure, CPLE_IllegalArg,
5456 : "Invalid value for BLOCKYSIZE");
5457 0 : return nullptr;
5458 : }
5459 2572 : if (bTiled && (l_nBlockYSize % 16 != 0))
5460 : {
5461 2 : ReportError(pszFilename, CE_Failure, CPLE_IllegalArg,
5462 : "BLOCKYSIZE must be a multiple of 16");
5463 2 : return nullptr;
5464 : }
5465 : }
5466 :
5467 9873 : if (bTiled)
5468 : {
5469 800 : if (l_nBlockXSize == 0)
5470 351 : l_nBlockXSize = 256;
5471 :
5472 800 : if (l_nBlockYSize == 0)
5473 351 : l_nBlockYSize = 256;
5474 : }
5475 :
5476 9873 : int nPlanar = 0;
5477 :
5478 : // Hidden @TILE_INTERLEAVE=YES parameter used by the COG driver
5479 9873 : if (bCreateCopy && CPLTestBool(CSLFetchNameValueDef(
5480 : papszParamList, "@TILE_INTERLEAVE", "NO")))
5481 : {
5482 7 : bTileInterleavingOut = true;
5483 7 : nPlanar = PLANARCONFIG_SEPARATE;
5484 : }
5485 : else
5486 : {
5487 9866 : if (const char *pszValue =
5488 9866 : CSLFetchNameValue(papszParamList, "INTERLEAVE"))
5489 : {
5490 1579 : if (EQUAL(pszValue, "PIXEL"))
5491 407 : nPlanar = PLANARCONFIG_CONTIG;
5492 1172 : else if (EQUAL(pszValue, "BAND"))
5493 : {
5494 1171 : nPlanar = PLANARCONFIG_SEPARATE;
5495 : }
5496 1 : else if (EQUAL(pszValue, "BAND"))
5497 : {
5498 0 : nPlanar = PLANARCONFIG_SEPARATE;
5499 : }
5500 : else
5501 : {
5502 1 : ReportError(
5503 : pszFilename, CE_Failure, CPLE_IllegalArg,
5504 : "INTERLEAVE=%s unsupported, value must be PIXEL or BAND.",
5505 : pszValue);
5506 1 : return nullptr;
5507 : }
5508 : }
5509 : else
5510 : {
5511 8287 : nPlanar = PLANARCONFIG_CONTIG;
5512 : }
5513 : }
5514 :
5515 9872 : int l_nCompression = COMPRESSION_NONE;
5516 9872 : if (const char *pszValue = CSLFetchNameValue(papszParamList, "COMPRESS"))
5517 : {
5518 3342 : l_nCompression = GTIFFGetCompressionMethod(pszValue, "COMPRESS");
5519 3342 : if (l_nCompression < 0)
5520 0 : return nullptr;
5521 : }
5522 :
5523 9872 : constexpr int JPEG_MAX_DIMENSION = 65500; // Defined in jpeglib.h
5524 9872 : constexpr int WEBP_MAX_DIMENSION = 16383;
5525 :
5526 : const struct
5527 : {
5528 : int nCodecID;
5529 : const char *pszCodecName;
5530 : int nMaxDim;
5531 9872 : } asLimitations[] = {
5532 : {COMPRESSION_JPEG, "JPEG", JPEG_MAX_DIMENSION},
5533 : {COMPRESSION_WEBP, "WEBP", WEBP_MAX_DIMENSION},
5534 : };
5535 :
5536 29604 : for (const auto &sLimitation : asLimitations)
5537 : {
5538 19740 : if (l_nCompression == sLimitation.nCodecID && !bTiled &&
5539 2074 : nXSize > sLimitation.nMaxDim)
5540 : {
5541 2 : ReportError(
5542 : pszFilename, CE_Failure, CPLE_IllegalArg,
5543 : "COMPRESS=%s is only compatible of un-tiled images whose "
5544 : "width is lesser or equal to %d pixels. "
5545 : "To overcome this limitation, set the TILED=YES creation "
5546 : "option.",
5547 2 : sLimitation.pszCodecName, sLimitation.nMaxDim);
5548 2 : return nullptr;
5549 : }
5550 19738 : else if (l_nCompression == sLimitation.nCodecID && bTiled &&
5551 52 : l_nBlockXSize > sLimitation.nMaxDim)
5552 : {
5553 2 : ReportError(pszFilename, CE_Failure, CPLE_IllegalArg,
5554 : "COMPRESS=%s is only compatible of tiled images whose "
5555 : "BLOCKXSIZE is lesser or equal to %d pixels.",
5556 2 : sLimitation.pszCodecName, sLimitation.nMaxDim);
5557 2 : return nullptr;
5558 : }
5559 19736 : else if (l_nCompression == sLimitation.nCodecID &&
5560 2122 : l_nBlockYSize > sLimitation.nMaxDim)
5561 : {
5562 4 : ReportError(pszFilename, CE_Failure, CPLE_IllegalArg,
5563 : "COMPRESS=%s is only compatible of images whose "
5564 : "BLOCKYSIZE is lesser or equal to %d pixels. "
5565 : "To overcome this limitation, set the TILED=YES "
5566 : "creation option",
5567 4 : sLimitation.pszCodecName, sLimitation.nMaxDim);
5568 4 : return nullptr;
5569 : }
5570 : }
5571 :
5572 : /* -------------------------------------------------------------------- */
5573 : /* How many bits per sample? We have a special case if NBITS */
5574 : /* specified for GDT_UInt8, GDT_UInt16, GDT_UInt32. */
5575 : /* -------------------------------------------------------------------- */
5576 9864 : int l_nBitsPerSample = GDALGetDataTypeSizeBits(eType);
5577 9864 : if (CSLFetchNameValue(papszParamList, "NBITS") != nullptr)
5578 : {
5579 1747 : int nMinBits = 0;
5580 1747 : int nMaxBits = 0;
5581 1747 : l_nBitsPerSample = atoi(CSLFetchNameValue(papszParamList, "NBITS"));
5582 1747 : if (eType == GDT_UInt8)
5583 : {
5584 527 : nMinBits = 1;
5585 527 : nMaxBits = 8;
5586 : }
5587 1220 : else if (eType == GDT_UInt16)
5588 : {
5589 1202 : nMinBits = 9;
5590 1202 : nMaxBits = 16;
5591 : }
5592 18 : else if (eType == GDT_UInt32)
5593 : {
5594 14 : nMinBits = 17;
5595 14 : nMaxBits = 32;
5596 : }
5597 4 : else if (eType == GDT_Float32)
5598 : {
5599 4 : if (l_nBitsPerSample != 16 && l_nBitsPerSample != 32)
5600 : {
5601 1 : ReportError(pszFilename, CE_Warning, CPLE_NotSupported,
5602 : "Only NBITS=16 is supported for data type Float32");
5603 1 : l_nBitsPerSample = GDALGetDataTypeSizeBits(eType);
5604 : }
5605 : }
5606 : else
5607 : {
5608 0 : ReportError(pszFilename, CE_Warning, CPLE_NotSupported,
5609 : "NBITS is not supported for data type %s",
5610 : GDALGetDataTypeName(eType));
5611 0 : l_nBitsPerSample = GDALGetDataTypeSizeBits(eType);
5612 : }
5613 :
5614 1747 : if (nMinBits != 0)
5615 : {
5616 1743 : if (l_nBitsPerSample < nMinBits)
5617 : {
5618 2 : ReportError(
5619 : pszFilename, CE_Warning, CPLE_AppDefined,
5620 : "NBITS=%d is invalid for data type %s. Using NBITS=%d",
5621 : l_nBitsPerSample, GDALGetDataTypeName(eType), nMinBits);
5622 2 : l_nBitsPerSample = nMinBits;
5623 : }
5624 1741 : else if (l_nBitsPerSample > nMaxBits)
5625 : {
5626 3 : ReportError(
5627 : pszFilename, CE_Warning, CPLE_AppDefined,
5628 : "NBITS=%d is invalid for data type %s. Using NBITS=%d",
5629 : l_nBitsPerSample, GDALGetDataTypeName(eType), nMaxBits);
5630 3 : l_nBitsPerSample = nMaxBits;
5631 : }
5632 : }
5633 : }
5634 :
5635 : #ifdef HAVE_JXL
5636 9864 : if ((l_nCompression == COMPRESSION_JXL ||
5637 106 : l_nCompression == COMPRESSION_JXL_DNG_1_7) &&
5638 105 : eType != GDT_Float16 && eType != GDT_Float32)
5639 : {
5640 : // Reflects tif_jxl's GetJXLDataType()
5641 85 : if (eType != GDT_UInt8 && eType != GDT_UInt16)
5642 : {
5643 1 : ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
5644 : "Data type %s not supported for JXL compression. Only "
5645 : "Byte, UInt16, Float16, Float32 are supported",
5646 : GDALGetDataTypeName(eType));
5647 2 : return nullptr;
5648 : }
5649 :
5650 : const struct
5651 : {
5652 : GDALDataType eDT;
5653 : int nBitsPerSample;
5654 84 : } asSupportedDTBitsPerSample[] = {
5655 : {GDT_UInt8, 8},
5656 : {GDT_UInt16, 16},
5657 : };
5658 :
5659 250 : for (const auto &sSupportedDTBitsPerSample : asSupportedDTBitsPerSample)
5660 : {
5661 167 : if (eType == sSupportedDTBitsPerSample.eDT &&
5662 84 : l_nBitsPerSample != sSupportedDTBitsPerSample.nBitsPerSample)
5663 : {
5664 1 : ReportError(
5665 : pszFilename, CE_Failure, CPLE_NotSupported,
5666 : "Bits per sample=%d not supported for JXL compression. "
5667 : "Only %d is supported for %s data type.",
5668 1 : l_nBitsPerSample, sSupportedDTBitsPerSample.nBitsPerSample,
5669 : GDALGetDataTypeName(eType));
5670 1 : return nullptr;
5671 : }
5672 : }
5673 : }
5674 : #endif
5675 :
5676 9862 : int nPredictor = PREDICTOR_NONE;
5677 9862 : const char *pszPredictor = CSLFetchNameValue(papszParamList, "PREDICTOR");
5678 9862 : if (pszPredictor)
5679 : {
5680 31 : nPredictor = atoi(pszPredictor);
5681 : }
5682 :
5683 9862 : if (nPredictor != PREDICTOR_NONE &&
5684 18 : l_nCompression != COMPRESSION_ADOBE_DEFLATE &&
5685 2 : l_nCompression != COMPRESSION_LZW &&
5686 2 : l_nCompression != COMPRESSION_LZMA &&
5687 : l_nCompression != COMPRESSION_ZSTD)
5688 : {
5689 1 : ReportError(pszFilename, CE_Warning, CPLE_NotSupported,
5690 : "PREDICTOR option is ignored for COMPRESS=%s. "
5691 : "Only valid for DEFLATE, LZW, LZMA or ZSTD",
5692 : CSLFetchNameValueDef(papszParamList, "COMPRESS", "NONE"));
5693 : }
5694 :
5695 : // Do early checks as libtiff will only error out when starting to write.
5696 9891 : else if (nPredictor != PREDICTOR_NONE &&
5697 30 : CPLTestBool(
5698 : CPLGetConfigOption("GDAL_GTIFF_PREDICTOR_CHECKS", "YES")))
5699 : {
5700 : #if (TIFFLIB_VERSION > 20210416) || defined(INTERNAL_LIBTIFF)
5701 : #define HAVE_PREDICTOR_2_FOR_64BIT
5702 : #endif
5703 30 : if (nPredictor == 2)
5704 : {
5705 24 : if (l_nBitsPerSample != 8 && l_nBitsPerSample != 16 &&
5706 : l_nBitsPerSample != 32
5707 : #ifdef HAVE_PREDICTOR_2_FOR_64BIT
5708 2 : && l_nBitsPerSample != 64
5709 : #endif
5710 : )
5711 : {
5712 : #if !defined(HAVE_PREDICTOR_2_FOR_64BIT)
5713 : if (l_nBitsPerSample == 64)
5714 : {
5715 : ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
5716 : "PREDICTOR=2 is supported on 64 bit samples "
5717 : "starting with libtiff > 4.3.0.");
5718 : }
5719 : else
5720 : #endif
5721 : {
5722 2 : const int nBITSHint = (l_nBitsPerSample < 8) ? 8
5723 1 : : (l_nBitsPerSample < 16) ? 16
5724 0 : : (l_nBitsPerSample < 32) ? 32
5725 : : 64;
5726 1 : ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
5727 : #ifdef HAVE_PREDICTOR_2_FOR_64BIT
5728 : "PREDICTOR=2 is only supported with 8/16/32/64 "
5729 : "bit samples. You can specify the NBITS=%d "
5730 : "creation option to promote to the closest "
5731 : "supported bits per sample value.",
5732 : #else
5733 : "PREDICTOR=2 is only supported with 8/16/32 "
5734 : "bit samples. You can specify the NBITS=%d "
5735 : "creation option to promote to the closest "
5736 : "supported bits per sample value.",
5737 : #endif
5738 : nBITSHint);
5739 : }
5740 1 : return nullptr;
5741 : }
5742 : }
5743 6 : else if (nPredictor == 3)
5744 : {
5745 5 : if (eType != GDT_Float16 && eType != GDT_Float32 &&
5746 : eType != GDT_Float64)
5747 : {
5748 1 : ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
5749 : "PREDICTOR=3 is only supported with Float16, "
5750 : "Float32 or Float64.");
5751 1 : return nullptr;
5752 : }
5753 : }
5754 : else
5755 : {
5756 1 : ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
5757 : "PREDICTOR=%s is not supported.", pszPredictor);
5758 1 : return nullptr;
5759 : }
5760 : }
5761 :
5762 9859 : const int l_nZLevel = GTiffGetZLevel(papszParamList);
5763 9859 : const int l_nLZMAPreset = GTiffGetLZMAPreset(papszParamList);
5764 9859 : const int l_nZSTDLevel = GTiffGetZSTDPreset(papszParamList);
5765 9859 : const int l_nWebPLevel = GTiffGetWebPLevel(papszParamList);
5766 9859 : const bool l_bWebPLossless = GTiffGetWebPLossless(papszParamList);
5767 9859 : const int l_nJpegQuality = GTiffGetJpegQuality(papszParamList);
5768 9859 : const int l_nJpegTablesMode = GTiffGetJpegTablesMode(papszParamList);
5769 9859 : const double l_dfMaxZError = GTiffGetLERCMaxZError(papszParamList);
5770 : #if HAVE_JXL
5771 9859 : bool bJXLLosslessSpecified = false;
5772 : const bool l_bJXLLossless =
5773 9859 : GTiffGetJXLLossless(papszParamList, &bJXLLosslessSpecified);
5774 9859 : const uint32_t l_nJXLEffort = GTiffGetJXLEffort(papszParamList);
5775 9859 : bool bJXLDistanceSpecified = false;
5776 : const float l_fJXLDistance =
5777 9859 : GTiffGetJXLDistance(papszParamList, &bJXLDistanceSpecified);
5778 9859 : if (bJXLDistanceSpecified && l_bJXLLossless)
5779 : {
5780 1 : ReportError(pszFilename, CE_Warning, CPLE_AppDefined,
5781 : "JXL_DISTANCE creation option is ignored, given %s "
5782 : "JXL_LOSSLESS=YES",
5783 : bJXLLosslessSpecified ? "(explicit)" : "(implicit)");
5784 : }
5785 9859 : bool bJXLAlphaDistanceSpecified = false;
5786 : const float l_fJXLAlphaDistance =
5787 9859 : GTiffGetJXLAlphaDistance(papszParamList, &bJXLAlphaDistanceSpecified);
5788 9859 : if (bJXLAlphaDistanceSpecified && l_bJXLLossless)
5789 : {
5790 1 : ReportError(pszFilename, CE_Warning, CPLE_AppDefined,
5791 : "JXL_ALPHA_DISTANCE creation option is ignored, given %s "
5792 : "JXL_LOSSLESS=YES",
5793 : bJXLLosslessSpecified ? "(explicit)" : "(implicit)");
5794 : }
5795 : #endif
5796 : /* -------------------------------------------------------------------- */
5797 : /* Streaming related code */
5798 : /* -------------------------------------------------------------------- */
5799 19718 : const CPLString osOriFilename(pszFilename);
5800 19718 : bool bStreaming = strcmp(pszFilename, "/vsistdout/") == 0 ||
5801 9859 : CPLFetchBool(papszParamList, "STREAMABLE_OUTPUT", false);
5802 : #ifdef S_ISFIFO
5803 9859 : if (!bStreaming)
5804 : {
5805 : VSIStatBufL sStat;
5806 9847 : if (VSIStatExL(pszFilename, &sStat,
5807 10726 : VSI_STAT_EXISTS_FLAG | VSI_STAT_NATURE_FLAG) == 0 &&
5808 879 : S_ISFIFO(sStat.st_mode))
5809 : {
5810 0 : bStreaming = true;
5811 : }
5812 : }
5813 : #endif
5814 9859 : if (bStreaming && !EQUAL("NONE", CSLFetchNameValueDef(papszParamList,
5815 : "COMPRESS", "NONE")))
5816 : {
5817 1 : ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
5818 : "Streaming only supported to uncompressed TIFF");
5819 1 : return nullptr;
5820 : }
5821 9858 : if (bStreaming && CPLFetchBool(papszParamList, "SPARSE_OK", false))
5822 : {
5823 1 : ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
5824 : "Streaming not supported with SPARSE_OK");
5825 1 : return nullptr;
5826 : }
5827 : const bool bCopySrcOverviews =
5828 9857 : CPLFetchBool(papszParamList, "COPY_SRC_OVERVIEWS", false);
5829 9857 : if (bStreaming && bCopySrcOverviews)
5830 : {
5831 1 : ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
5832 : "Streaming not supported with COPY_SRC_OVERVIEWS");
5833 1 : return nullptr;
5834 : }
5835 9856 : if (bStreaming)
5836 : {
5837 9 : l_osTmpFilename = VSIMemGenerateHiddenFilename("vsistdout.tif");
5838 9 : pszFilename = l_osTmpFilename.c_str();
5839 : }
5840 :
5841 : /* -------------------------------------------------------------------- */
5842 : /* Compute the uncompressed size. */
5843 : /* -------------------------------------------------------------------- */
5844 9856 : const unsigned nTileXCount =
5845 9856 : bTiled ? DIV_ROUND_UP(nXSize, l_nBlockXSize) : 0;
5846 9856 : const unsigned nTileYCount =
5847 9856 : bTiled ? DIV_ROUND_UP(nYSize, l_nBlockYSize) : 0;
5848 : const double dfUncompressedImageSize =
5849 9856 : (bTiled ? (static_cast<double>(nTileXCount) * nTileYCount *
5850 796 : l_nBlockXSize * l_nBlockYSize)
5851 9060 : : (nXSize * static_cast<double>(nYSize))) *
5852 9856 : l_nBands * GDALGetDataTypeSizeBytes(eType) +
5853 9856 : dfExtraSpaceForOverviews;
5854 :
5855 : /* -------------------------------------------------------------------- */
5856 : /* Should the file be created as a bigtiff file? */
5857 : /* -------------------------------------------------------------------- */
5858 9856 : const char *pszBIGTIFF = CSLFetchNameValue(papszParamList, "BIGTIFF");
5859 :
5860 9856 : if (pszBIGTIFF == nullptr)
5861 9415 : pszBIGTIFF = "IF_NEEDED";
5862 :
5863 9856 : bool bCreateBigTIFF = false;
5864 9856 : if (EQUAL(pszBIGTIFF, "IF_NEEDED"))
5865 : {
5866 9416 : if (l_nCompression == COMPRESSION_NONE &&
5867 : dfUncompressedImageSize > 4200000000.0)
5868 17 : bCreateBigTIFF = true;
5869 : }
5870 440 : else if (EQUAL(pszBIGTIFF, "IF_SAFER"))
5871 : {
5872 419 : if (dfUncompressedImageSize > 2000000000.0)
5873 1 : bCreateBigTIFF = true;
5874 : }
5875 : else
5876 : {
5877 21 : bCreateBigTIFF = CPLTestBool(pszBIGTIFF);
5878 21 : if (!bCreateBigTIFF && l_nCompression == COMPRESSION_NONE &&
5879 : dfUncompressedImageSize > 4200000000.0)
5880 : {
5881 2 : ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
5882 : "The TIFF file will be larger than 4GB, so BigTIFF is "
5883 : "necessary. Creation failed.");
5884 2 : return nullptr;
5885 : }
5886 : }
5887 :
5888 9854 : if (bCreateBigTIFF)
5889 35 : CPLDebug("GTiff", "File being created as a BigTIFF.");
5890 :
5891 : /* -------------------------------------------------------------------- */
5892 : /* Sanity check. */
5893 : /* -------------------------------------------------------------------- */
5894 9854 : if (bTiled)
5895 : {
5896 : // libtiff implementation limitation
5897 796 : if (nTileXCount > 0x80000000U / (bCreateBigTIFF ? 8 : 4) / nTileYCount)
5898 : {
5899 3 : ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
5900 : "File too large regarding tile size. This would result "
5901 : "in a file with tile arrays larger than 2GB");
5902 3 : return nullptr;
5903 : }
5904 : }
5905 :
5906 : /* -------------------------------------------------------------------- */
5907 : /* Check free space (only for big, non sparse) */
5908 : /* -------------------------------------------------------------------- */
5909 9851 : const double dfLikelyFloorOfFinalSize =
5910 : l_nCompression == COMPRESSION_NONE
5911 9851 : ? dfUncompressedImageSize
5912 : :
5913 : /* For compressed, we target 1% as the most optimistic reduction factor! */
5914 : 0.01 * dfUncompressedImageSize;
5915 9873 : if (dfLikelyFloorOfFinalSize >= 1e9 &&
5916 22 : !CPLFetchBool(papszParamList, "SPARSE_OK", false) &&
5917 5 : osOriFilename != "/vsistdout/" &&
5918 9878 : osOriFilename != "/vsistdout_redirect/" &&
5919 5 : CPLTestBool(CPLGetConfigOption("CHECK_DISK_FREE_SPACE", "TRUE")))
5920 : {
5921 : const GIntBig nFreeDiskSpace =
5922 4 : VSIGetDiskFreeSpace(CPLGetDirnameSafe(pszFilename).c_str());
5923 4 : if (nFreeDiskSpace >= 0 && nFreeDiskSpace < dfLikelyFloorOfFinalSize)
5924 : {
5925 6 : ReportError(
5926 : pszFilename, CE_Failure, CPLE_FileIO,
5927 : "Free disk space available is %s, "
5928 : "whereas %s are %s necessary. "
5929 : "You can disable this check by defining the "
5930 : "CHECK_DISK_FREE_SPACE configuration option to FALSE.",
5931 4 : CPLFormatReadableFileSize(static_cast<uint64_t>(nFreeDiskSpace))
5932 : .c_str(),
5933 4 : CPLFormatReadableFileSize(dfLikelyFloorOfFinalSize).c_str(),
5934 : l_nCompression == COMPRESSION_NONE
5935 : ? "at least"
5936 : : "likely at least (probably more)");
5937 2 : return nullptr;
5938 : }
5939 : }
5940 :
5941 : /* -------------------------------------------------------------------- */
5942 : /* Check if the user wishes a particular endianness */
5943 : /* -------------------------------------------------------------------- */
5944 :
5945 9849 : int eEndianness = ENDIANNESS_NATIVE;
5946 9849 : const char *pszEndianness = CSLFetchNameValue(papszParamList, "ENDIANNESS");
5947 9849 : if (pszEndianness == nullptr)
5948 9786 : pszEndianness = CPLGetConfigOption("GDAL_TIFF_ENDIANNESS", nullptr);
5949 9849 : if (pszEndianness != nullptr)
5950 : {
5951 123 : if (EQUAL(pszEndianness, "LITTLE"))
5952 : {
5953 36 : eEndianness = ENDIANNESS_LITTLE;
5954 : }
5955 87 : else if (EQUAL(pszEndianness, "BIG"))
5956 : {
5957 1 : eEndianness = ENDIANNESS_BIG;
5958 : }
5959 86 : else if (EQUAL(pszEndianness, "INVERTED"))
5960 : {
5961 : #ifdef CPL_LSB
5962 82 : eEndianness = ENDIANNESS_BIG;
5963 : #else
5964 : eEndianness = ENDIANNESS_LITTLE;
5965 : #endif
5966 : }
5967 4 : else if (!EQUAL(pszEndianness, "NATIVE"))
5968 : {
5969 1 : ReportError(pszFilename, CE_Warning, CPLE_NotSupported,
5970 : "ENDIANNESS=%s not supported. Defaulting to NATIVE",
5971 : pszEndianness);
5972 : }
5973 : }
5974 :
5975 : /* -------------------------------------------------------------------- */
5976 : /* Try opening the dataset. */
5977 : /* -------------------------------------------------------------------- */
5978 :
5979 : const bool bAppend =
5980 9849 : CPLFetchBool(papszParamList, "APPEND_SUBDATASET", false);
5981 :
5982 9849 : char szOpeningFlag[5] = {};
5983 9849 : strcpy(szOpeningFlag, bAppend ? "r+" : "w+");
5984 9849 : if (bCreateBigTIFF)
5985 32 : strcat(szOpeningFlag, "8");
5986 9849 : if (eEndianness == ENDIANNESS_BIG)
5987 83 : strcat(szOpeningFlag, "b");
5988 9766 : else if (eEndianness == ENDIANNESS_LITTLE)
5989 36 : strcat(szOpeningFlag, "l");
5990 :
5991 9849 : VSIErrorReset();
5992 9849 : const bool bOnlyVisibleAtCloseTime = CPLTestBool(CSLFetchNameValueDef(
5993 : papszParamList, "@CREATE_ONLY_VISIBLE_AT_CLOSE_TIME", "NO"));
5994 9849 : const bool bSuppressASAP = CPLTestBool(
5995 : CSLFetchNameValueDef(papszParamList, "@SUPPRESS_ASAP", "NO"));
5996 : auto l_fpL =
5997 9849 : (bOnlyVisibleAtCloseTime || bSuppressASAP) && !bAppend
5998 9917 : ? VSIFileManager::GetHandler(pszFilename)
5999 136 : ->CreateOnlyVisibleAtCloseTime(pszFilename, true, nullptr)
6000 68 : .release()
6001 19630 : : VSIFilesystemHandler::OpenStatic(pszFilename,
6002 : bAppend ? "r+b" : "w+b", true)
6003 9849 : .release();
6004 9849 : if (l_fpL == nullptr)
6005 : {
6006 21 : VSIToCPLErrorWithMsg(CE_Failure, CPLE_OpenFailed,
6007 42 : std::string("Attempt to create new tiff file `")
6008 21 : .append(pszFilename)
6009 21 : .append("' failed")
6010 : .c_str());
6011 21 : return nullptr;
6012 : }
6013 :
6014 9828 : if (bSuppressASAP)
6015 : {
6016 38 : l_fpL->CancelCreation();
6017 : }
6018 :
6019 9828 : TIFF *l_hTIFF = VSI_TIFFOpen(pszFilename, szOpeningFlag, l_fpL);
6020 9828 : if (l_hTIFF == nullptr)
6021 : {
6022 2 : if (CPLGetLastErrorNo() == 0)
6023 0 : CPLError(CE_Failure, CPLE_OpenFailed,
6024 : "Attempt to create new tiff file `%s' "
6025 : "failed in XTIFFOpen().",
6026 : pszFilename);
6027 2 : l_fpL->CancelCreation();
6028 2 : CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
6029 2 : return nullptr;
6030 : }
6031 :
6032 9826 : if (bAppend)
6033 : {
6034 : #if !(defined(INTERNAL_LIBTIFF) || TIFFLIB_VERSION > 20240911)
6035 : // This is a bit of a hack to cause (*tif->tif_cleanup)(tif); to be
6036 : // called. See https://trac.osgeo.org/gdal/ticket/2055
6037 : // Fixed in libtiff > 4.7.0
6038 : TIFFSetField(l_hTIFF, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
6039 : TIFFFreeDirectory(l_hTIFF);
6040 : #endif
6041 6 : TIFFCreateDirectory(l_hTIFF);
6042 : }
6043 :
6044 : /* -------------------------------------------------------------------- */
6045 : /* Do we have a custom pixel type (just used for signed byte now). */
6046 : /* -------------------------------------------------------------------- */
6047 9826 : const char *pszPixelType = CSLFetchNameValue(papszParamList, "PIXELTYPE");
6048 9826 : if (pszPixelType == nullptr)
6049 9818 : pszPixelType = "";
6050 9826 : if (eType == GDT_UInt8 && EQUAL(pszPixelType, "SIGNEDBYTE"))
6051 : {
6052 8 : CPLError(CE_Warning, CPLE_AppDefined,
6053 : "Using PIXELTYPE=SIGNEDBYTE with Byte data type is deprecated "
6054 : "(but still works). "
6055 : "Using Int8 data type instead is now recommended.");
6056 : }
6057 :
6058 : /* -------------------------------------------------------------------- */
6059 : /* Setup some standard flags. */
6060 : /* -------------------------------------------------------------------- */
6061 9826 : TIFFSetField(l_hTIFF, TIFFTAG_IMAGEWIDTH, nXSize);
6062 9826 : TIFFSetField(l_hTIFF, TIFFTAG_IMAGELENGTH, nYSize);
6063 9826 : TIFFSetField(l_hTIFF, TIFFTAG_BITSPERSAMPLE, l_nBitsPerSample);
6064 :
6065 9826 : uint16_t l_nSampleFormat = 0;
6066 9826 : if ((eType == GDT_UInt8 && EQUAL(pszPixelType, "SIGNEDBYTE")) ||
6067 9677 : eType == GDT_Int8 || eType == GDT_Int16 || eType == GDT_Int32 ||
6068 : eType == GDT_Int64)
6069 808 : l_nSampleFormat = SAMPLEFORMAT_INT;
6070 9018 : else if (eType == GDT_CInt16 || eType == GDT_CInt32)
6071 363 : l_nSampleFormat = SAMPLEFORMAT_COMPLEXINT;
6072 8655 : else if (eType == GDT_Float16 || eType == GDT_Float32 ||
6073 : eType == GDT_Float64)
6074 1155 : l_nSampleFormat = SAMPLEFORMAT_IEEEFP;
6075 7500 : else if (eType == GDT_CFloat16 || eType == GDT_CFloat32 ||
6076 : eType == GDT_CFloat64)
6077 471 : l_nSampleFormat = SAMPLEFORMAT_COMPLEXIEEEFP;
6078 : else
6079 7029 : l_nSampleFormat = SAMPLEFORMAT_UINT;
6080 :
6081 9826 : TIFFSetField(l_hTIFF, TIFFTAG_SAMPLEFORMAT, l_nSampleFormat);
6082 9826 : TIFFSetField(l_hTIFF, TIFFTAG_SAMPLESPERPIXEL, l_nBands);
6083 9826 : TIFFSetField(l_hTIFF, TIFFTAG_PLANARCONFIG, nPlanar);
6084 :
6085 : /* -------------------------------------------------------------------- */
6086 : /* Setup Photometric Interpretation. Take this value from the user */
6087 : /* passed option or guess correct value otherwise. */
6088 : /* -------------------------------------------------------------------- */
6089 9826 : int nSamplesAccountedFor = 1;
6090 9826 : bool bForceColorTable = false;
6091 :
6092 9826 : if (const char *pszValue = CSLFetchNameValue(papszParamList, "PHOTOMETRIC"))
6093 : {
6094 1911 : if (EQUAL(pszValue, "MINISBLACK"))
6095 14 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
6096 1897 : else if (EQUAL(pszValue, "MINISWHITE"))
6097 : {
6098 2 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISWHITE);
6099 : }
6100 1895 : else if (EQUAL(pszValue, "PALETTE"))
6101 : {
6102 5 : if (eType == GDT_UInt8 || eType == GDT_UInt16)
6103 : {
6104 4 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
6105 4 : nSamplesAccountedFor = 1;
6106 4 : bForceColorTable = true;
6107 : }
6108 : else
6109 : {
6110 1 : ReportError(
6111 : pszFilename, CE_Warning, CPLE_AppDefined,
6112 : "PHOTOMETRIC=PALETTE only compatible with Byte or UInt16");
6113 : }
6114 : }
6115 1890 : else if (EQUAL(pszValue, "RGB"))
6116 : {
6117 1150 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
6118 1150 : nSamplesAccountedFor = 3;
6119 : }
6120 740 : else if (EQUAL(pszValue, "CMYK"))
6121 : {
6122 10 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_SEPARATED);
6123 10 : nSamplesAccountedFor = 4;
6124 : }
6125 730 : else if (EQUAL(pszValue, "YCBCR"))
6126 : {
6127 : // Because of subsampling, setting YCBCR without JPEG compression
6128 : // leads to a crash currently. Would need to make
6129 : // GTiffRasterBand::IWriteBlock() aware of subsampling so that it
6130 : // doesn't overrun buffer size returned by libtiff.
6131 729 : if (l_nCompression != COMPRESSION_JPEG)
6132 : {
6133 1 : ReportError(
6134 : pszFilename, CE_Failure, CPLE_NotSupported,
6135 : "Currently, PHOTOMETRIC=YCBCR requires COMPRESS=JPEG");
6136 1 : XTIFFClose(l_hTIFF);
6137 1 : l_fpL->CancelCreation();
6138 1 : CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
6139 1 : return nullptr;
6140 : }
6141 :
6142 728 : if (nPlanar == PLANARCONFIG_SEPARATE)
6143 : {
6144 1 : ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
6145 : "PHOTOMETRIC=YCBCR requires INTERLEAVE=PIXEL");
6146 1 : XTIFFClose(l_hTIFF);
6147 1 : l_fpL->CancelCreation();
6148 1 : CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
6149 1 : return nullptr;
6150 : }
6151 :
6152 : // YCBCR strictly requires 3 bands. Not less, not more Issue an
6153 : // explicit error message as libtiff one is a bit cryptic:
6154 : // TIFFVStripSize64:Invalid td_samplesperpixel value.
6155 727 : if (l_nBands != 3)
6156 : {
6157 1 : ReportError(
6158 : pszFilename, CE_Failure, CPLE_NotSupported,
6159 : "PHOTOMETRIC=YCBCR not supported on a %d-band raster: "
6160 : "only compatible of a 3-band (RGB) raster",
6161 : l_nBands);
6162 1 : XTIFFClose(l_hTIFF);
6163 1 : l_fpL->CancelCreation();
6164 1 : CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
6165 1 : return nullptr;
6166 : }
6167 :
6168 726 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
6169 726 : nSamplesAccountedFor = 3;
6170 :
6171 : // Explicitly register the subsampling so that JPEGFixupTags
6172 : // is a no-op (helps for cloud optimized geotiffs)
6173 726 : TIFFSetField(l_hTIFF, TIFFTAG_YCBCRSUBSAMPLING, 2, 2);
6174 : }
6175 1 : else if (EQUAL(pszValue, "CIELAB"))
6176 : {
6177 0 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_CIELAB);
6178 0 : nSamplesAccountedFor = 3;
6179 : }
6180 1 : else if (EQUAL(pszValue, "ICCLAB"))
6181 : {
6182 0 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_ICCLAB);
6183 0 : nSamplesAccountedFor = 3;
6184 : }
6185 1 : else if (EQUAL(pszValue, "ITULAB"))
6186 : {
6187 0 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_ITULAB);
6188 0 : nSamplesAccountedFor = 3;
6189 : }
6190 : else
6191 : {
6192 1 : ReportError(pszFilename, CE_Warning, CPLE_IllegalArg,
6193 : "PHOTOMETRIC=%s value not recognised, ignoring. "
6194 : "Set the Photometric Interpretation as MINISBLACK.",
6195 : pszValue);
6196 1 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
6197 : }
6198 :
6199 1908 : if (l_nBands < nSamplesAccountedFor)
6200 : {
6201 1 : ReportError(pszFilename, CE_Warning, CPLE_IllegalArg,
6202 : "PHOTOMETRIC=%s value does not correspond to number "
6203 : "of bands (%d), ignoring. "
6204 : "Set the Photometric Interpretation as MINISBLACK.",
6205 : pszValue, l_nBands);
6206 1 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
6207 : }
6208 : }
6209 : else
6210 : {
6211 : // If image contains 3 or 4 bands and datatype is Byte then we will
6212 : // assume it is RGB. In all other cases assume it is MINISBLACK.
6213 7915 : if (l_nBands == 3 && eType == GDT_UInt8)
6214 : {
6215 318 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
6216 318 : nSamplesAccountedFor = 3;
6217 : }
6218 7597 : else if (l_nBands == 4 && eType == GDT_UInt8)
6219 : {
6220 : uint16_t v[1] = {
6221 718 : GTiffGetAlphaValue(CSLFetchNameValue(papszParamList, "ALPHA"),
6222 718 : DEFAULT_ALPHA_TYPE)};
6223 :
6224 718 : TIFFSetField(l_hTIFF, TIFFTAG_EXTRASAMPLES, 1, v);
6225 718 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
6226 718 : nSamplesAccountedFor = 4;
6227 : }
6228 : else
6229 : {
6230 6879 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
6231 6879 : nSamplesAccountedFor = 1;
6232 : }
6233 : }
6234 :
6235 : /* -------------------------------------------------------------------- */
6236 : /* If there are extra samples, we need to mark them with an */
6237 : /* appropriate extrasamples definition here. */
6238 : /* -------------------------------------------------------------------- */
6239 9823 : if (l_nBands > nSamplesAccountedFor)
6240 : {
6241 1383 : const int nExtraSamples = l_nBands - nSamplesAccountedFor;
6242 :
6243 : uint16_t *v = static_cast<uint16_t *>(
6244 1383 : CPLMalloc(sizeof(uint16_t) * nExtraSamples));
6245 :
6246 1383 : v[0] = GTiffGetAlphaValue(CSLFetchNameValue(papszParamList, "ALPHA"),
6247 : EXTRASAMPLE_UNSPECIFIED);
6248 :
6249 297694 : for (int i = 1; i < nExtraSamples; ++i)
6250 296311 : v[i] = EXTRASAMPLE_UNSPECIFIED;
6251 :
6252 1383 : TIFFSetField(l_hTIFF, TIFFTAG_EXTRASAMPLES, nExtraSamples, v);
6253 :
6254 1383 : CPLFree(v);
6255 : }
6256 :
6257 : // Set the ICC color profile.
6258 9823 : if (eProfile != GTiffProfile::BASELINE)
6259 : {
6260 9798 : SaveICCProfile(nullptr, l_hTIFF, papszParamList, l_nBitsPerSample);
6261 : }
6262 :
6263 : // Set the compression method before asking the default strip size
6264 : // This is useful when translating to a JPEG-In-TIFF file where
6265 : // the default strip size is 8 or 16 depending on the photometric value.
6266 9823 : TIFFSetField(l_hTIFF, TIFFTAG_COMPRESSION, l_nCompression);
6267 :
6268 9823 : if (l_nCompression == COMPRESSION_LERC)
6269 : {
6270 : const char *pszCompress =
6271 97 : CSLFetchNameValueDef(papszParamList, "COMPRESS", "");
6272 97 : if (EQUAL(pszCompress, "LERC_DEFLATE"))
6273 : {
6274 16 : TIFFSetField(l_hTIFF, TIFFTAG_LERC_ADD_COMPRESSION,
6275 : LERC_ADD_COMPRESSION_DEFLATE);
6276 : }
6277 81 : else if (EQUAL(pszCompress, "LERC_ZSTD"))
6278 : {
6279 14 : if (TIFFSetField(l_hTIFF, TIFFTAG_LERC_ADD_COMPRESSION,
6280 14 : LERC_ADD_COMPRESSION_ZSTD) != 1)
6281 : {
6282 0 : XTIFFClose(l_hTIFF);
6283 0 : l_fpL->CancelCreation();
6284 0 : CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
6285 0 : return nullptr;
6286 : }
6287 : }
6288 : }
6289 : // TODO later: take into account LERC version
6290 :
6291 : /* -------------------------------------------------------------------- */
6292 : /* Setup tiling/stripping flags. */
6293 : /* -------------------------------------------------------------------- */
6294 9823 : if (bTiled)
6295 : {
6296 1572 : if (!TIFFSetField(l_hTIFF, TIFFTAG_TILEWIDTH, l_nBlockXSize) ||
6297 786 : !TIFFSetField(l_hTIFF, TIFFTAG_TILELENGTH, l_nBlockYSize))
6298 : {
6299 0 : XTIFFClose(l_hTIFF);
6300 0 : l_fpL->CancelCreation();
6301 0 : CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
6302 0 : return nullptr;
6303 : }
6304 : }
6305 : else
6306 : {
6307 9037 : const uint32_t l_nRowsPerStrip = std::min(
6308 : nYSize, l_nBlockYSize == 0
6309 9037 : ? static_cast<int>(TIFFDefaultStripSize(l_hTIFF, 0))
6310 9037 : : l_nBlockYSize);
6311 :
6312 9037 : TIFFSetField(l_hTIFF, TIFFTAG_ROWSPERSTRIP, l_nRowsPerStrip);
6313 : }
6314 :
6315 : /* -------------------------------------------------------------------- */
6316 : /* Set compression related tags. */
6317 : /* -------------------------------------------------------------------- */
6318 9823 : if (GTIFFSupportsPredictor(l_nCompression))
6319 961 : TIFFSetField(l_hTIFF, TIFFTAG_PREDICTOR, nPredictor);
6320 9823 : if (l_nCompression == COMPRESSION_ADOBE_DEFLATE ||
6321 : l_nCompression == COMPRESSION_LERC)
6322 : {
6323 280 : GTiffSetDeflateSubCodec(l_hTIFF);
6324 :
6325 280 : if (l_nZLevel != -1)
6326 22 : TIFFSetField(l_hTIFF, TIFFTAG_ZIPQUALITY, l_nZLevel);
6327 : }
6328 9823 : if (l_nCompression == COMPRESSION_JPEG && l_nJpegQuality != -1)
6329 1905 : TIFFSetField(l_hTIFF, TIFFTAG_JPEGQUALITY, l_nJpegQuality);
6330 9823 : if (l_nCompression == COMPRESSION_LZMA && l_nLZMAPreset != -1)
6331 10 : TIFFSetField(l_hTIFF, TIFFTAG_LZMAPRESET, l_nLZMAPreset);
6332 9823 : if ((l_nCompression == COMPRESSION_ZSTD ||
6333 190 : l_nCompression == COMPRESSION_LERC) &&
6334 : l_nZSTDLevel != -1)
6335 12 : TIFFSetField(l_hTIFF, TIFFTAG_ZSTD_LEVEL, l_nZSTDLevel);
6336 9823 : if (l_nCompression == COMPRESSION_LERC)
6337 : {
6338 97 : TIFFSetField(l_hTIFF, TIFFTAG_LERC_MAXZERROR, l_dfMaxZError);
6339 : }
6340 : #if HAVE_JXL
6341 9823 : if (l_nCompression == COMPRESSION_JXL ||
6342 : l_nCompression == COMPRESSION_JXL_DNG_1_7)
6343 : {
6344 104 : TIFFSetField(l_hTIFF, TIFFTAG_JXL_LOSSYNESS,
6345 : l_bJXLLossless ? JXL_LOSSLESS : JXL_LOSSY);
6346 104 : TIFFSetField(l_hTIFF, TIFFTAG_JXL_EFFORT, l_nJXLEffort);
6347 104 : TIFFSetField(l_hTIFF, TIFFTAG_JXL_DISTANCE,
6348 : static_cast<double>(l_fJXLDistance));
6349 104 : TIFFSetField(l_hTIFF, TIFFTAG_JXL_ALPHA_DISTANCE,
6350 : static_cast<double>(l_fJXLAlphaDistance));
6351 : }
6352 : #endif
6353 9823 : if (l_nCompression == COMPRESSION_WEBP)
6354 33 : TIFFSetField(l_hTIFF, TIFFTAG_WEBP_LEVEL, l_nWebPLevel);
6355 9823 : if (l_nCompression == COMPRESSION_WEBP && l_bWebPLossless)
6356 7 : TIFFSetField(l_hTIFF, TIFFTAG_WEBP_LOSSLESS, 1);
6357 :
6358 9823 : if (l_nCompression == COMPRESSION_JPEG)
6359 2083 : TIFFSetField(l_hTIFF, TIFFTAG_JPEGTABLESMODE, l_nJpegTablesMode);
6360 :
6361 : /* -------------------------------------------------------------------- */
6362 : /* If we forced production of a file with photometric=palette, */
6363 : /* we need to push out a default color table. */
6364 : /* -------------------------------------------------------------------- */
6365 9823 : if (bForceColorTable)
6366 : {
6367 4 : const int nColors = eType == GDT_UInt8 ? 256 : 65536;
6368 :
6369 : unsigned short *panTRed = static_cast<unsigned short *>(
6370 4 : CPLMalloc(sizeof(unsigned short) * nColors));
6371 : unsigned short *panTGreen = static_cast<unsigned short *>(
6372 4 : CPLMalloc(sizeof(unsigned short) * nColors));
6373 : unsigned short *panTBlue = static_cast<unsigned short *>(
6374 4 : CPLMalloc(sizeof(unsigned short) * nColors));
6375 :
6376 1028 : for (int iColor = 0; iColor < nColors; ++iColor)
6377 : {
6378 1024 : if (eType == GDT_UInt8)
6379 : {
6380 1024 : panTRed[iColor] = GTiffDataset::ClampCTEntry(
6381 : iColor, 1, iColor, nColorTableMultiplier);
6382 1024 : panTGreen[iColor] = GTiffDataset::ClampCTEntry(
6383 : iColor, 2, iColor, nColorTableMultiplier);
6384 1024 : panTBlue[iColor] = GTiffDataset::ClampCTEntry(
6385 : iColor, 3, iColor, nColorTableMultiplier);
6386 : }
6387 : else
6388 : {
6389 0 : panTRed[iColor] = static_cast<unsigned short>(iColor);
6390 0 : panTGreen[iColor] = static_cast<unsigned short>(iColor);
6391 0 : panTBlue[iColor] = static_cast<unsigned short>(iColor);
6392 : }
6393 : }
6394 :
6395 4 : TIFFSetField(l_hTIFF, TIFFTAG_COLORMAP, panTRed, panTGreen, panTBlue);
6396 :
6397 4 : CPLFree(panTRed);
6398 4 : CPLFree(panTGreen);
6399 4 : CPLFree(panTBlue);
6400 : }
6401 :
6402 : // This trick
6403 : // creates a temporary in-memory file and fetches its JPEG tables so that
6404 : // we can directly set them, before tif_jpeg.c compute them at the first
6405 : // strip/tile writing, which is too late, since we have already crystalized
6406 : // the directory. This way we avoid a directory rewriting.
6407 11906 : if (l_nCompression == COMPRESSION_JPEG &&
6408 2083 : CPLTestBool(
6409 : CSLFetchNameValueDef(papszParamList, "WRITE_JPEGTABLE_TAG", "YES")))
6410 : {
6411 1014 : GTiffWriteJPEGTables(
6412 : l_hTIFF, CSLFetchNameValue(papszParamList, "PHOTOMETRIC"),
6413 : CSLFetchNameValue(papszParamList, "JPEG_QUALITY"),
6414 : CSLFetchNameValue(papszParamList, "JPEGTABLESMODE"));
6415 : }
6416 :
6417 9823 : *pfpL = l_fpL;
6418 :
6419 9823 : return l_hTIFF;
6420 : }
6421 :
6422 : /************************************************************************/
6423 : /* GuessJPEGQuality() */
6424 : /* */
6425 : /* Guess JPEG quality from JPEGTABLES tag. */
6426 : /************************************************************************/
6427 :
6428 3850 : static const GByte *GTIFFFindNextTable(const GByte *paby, GByte byMarker,
6429 : int nLen, int *pnLenTable)
6430 : {
6431 7967 : for (int i = 0; i + 1 < nLen;)
6432 : {
6433 7967 : if (paby[i] != 0xFF)
6434 0 : return nullptr;
6435 7967 : ++i;
6436 7967 : if (paby[i] == 0xD8)
6437 : {
6438 3117 : ++i;
6439 3117 : continue;
6440 : }
6441 4850 : if (i + 2 >= nLen)
6442 833 : return nullptr;
6443 4017 : int nMarkerLen = paby[i + 1] * 256 + paby[i + 2];
6444 4017 : if (i + 1 + nMarkerLen >= nLen)
6445 0 : return nullptr;
6446 4017 : if (paby[i] == byMarker)
6447 : {
6448 3017 : if (pnLenTable)
6449 2473 : *pnLenTable = nMarkerLen;
6450 3017 : return paby + i + 1;
6451 : }
6452 1000 : i += 1 + nMarkerLen;
6453 : }
6454 0 : return nullptr;
6455 : }
6456 :
6457 : constexpr GByte MARKER_HUFFMAN_TABLE = 0xC4;
6458 : constexpr GByte MARKER_QUANT_TABLE = 0xDB;
6459 :
6460 : // We assume that if there are several quantization tables, they are
6461 : // in the same order. Which is a reasonable assumption for updating
6462 : // a file generated by ourselves.
6463 904 : static bool GTIFFQuantizationTablesEqual(const GByte *paby1, int nLen1,
6464 : const GByte *paby2, int nLen2)
6465 : {
6466 904 : bool bFound = false;
6467 : while (true)
6468 : {
6469 945 : int nLenTable1 = 0;
6470 945 : int nLenTable2 = 0;
6471 : const GByte *paby1New =
6472 945 : GTIFFFindNextTable(paby1, MARKER_QUANT_TABLE, nLen1, &nLenTable1);
6473 : const GByte *paby2New =
6474 945 : GTIFFFindNextTable(paby2, MARKER_QUANT_TABLE, nLen2, &nLenTable2);
6475 945 : if (paby1New == nullptr && paby2New == nullptr)
6476 904 : return bFound;
6477 911 : if (paby1New == nullptr || paby2New == nullptr)
6478 0 : return false;
6479 911 : if (nLenTable1 != nLenTable2)
6480 207 : return false;
6481 704 : if (memcmp(paby1New, paby2New, nLenTable1) != 0)
6482 663 : return false;
6483 41 : paby1New += nLenTable1;
6484 41 : paby2New += nLenTable2;
6485 41 : nLen1 -= static_cast<int>(paby1New - paby1);
6486 41 : nLen2 -= static_cast<int>(paby2New - paby2);
6487 41 : paby1 = paby1New;
6488 41 : paby2 = paby2New;
6489 41 : bFound = true;
6490 41 : }
6491 : }
6492 :
6493 : // Guess the JPEG quality by comparing against the MD5Sum of precomputed
6494 : // quantization tables
6495 409 : static int GuessJPEGQualityFromMD5(const uint8_t md5JPEGQuantTable[][16],
6496 : const GByte *const pabyJPEGTable,
6497 : int nJPEGTableSize)
6498 : {
6499 409 : int nRemainingLen = nJPEGTableSize;
6500 409 : const GByte *pabyCur = pabyJPEGTable;
6501 :
6502 : struct CPLMD5Context context;
6503 409 : CPLMD5Init(&context);
6504 :
6505 : while (true)
6506 : {
6507 1060 : int nLenTable = 0;
6508 1060 : const GByte *pabyNew = GTIFFFindNextTable(pabyCur, MARKER_QUANT_TABLE,
6509 : nRemainingLen, &nLenTable);
6510 1060 : if (pabyNew == nullptr)
6511 409 : break;
6512 651 : CPLMD5Update(&context, pabyNew, nLenTable);
6513 651 : pabyNew += nLenTable;
6514 651 : nRemainingLen -= static_cast<int>(pabyNew - pabyCur);
6515 651 : pabyCur = pabyNew;
6516 651 : }
6517 :
6518 : GByte digest[16];
6519 409 : CPLMD5Final(digest, &context);
6520 :
6521 28846 : for (int i = 0; i < 100; i++)
6522 : {
6523 28843 : if (memcmp(md5JPEGQuantTable[i], digest, 16) == 0)
6524 : {
6525 406 : return i + 1;
6526 : }
6527 : }
6528 3 : return -1;
6529 : }
6530 :
6531 464 : int GTiffDataset::GuessJPEGQuality(bool &bOutHasQuantizationTable,
6532 : bool &bOutHasHuffmanTable)
6533 : {
6534 464 : CPLAssert(m_nCompression == COMPRESSION_JPEG);
6535 464 : uint32_t nJPEGTableSize = 0;
6536 464 : void *pJPEGTable = nullptr;
6537 464 : if (!TIFFGetField(m_hTIFF, TIFFTAG_JPEGTABLES, &nJPEGTableSize,
6538 : &pJPEGTable))
6539 : {
6540 14 : bOutHasQuantizationTable = false;
6541 14 : bOutHasHuffmanTable = false;
6542 14 : return -1;
6543 : }
6544 :
6545 450 : bOutHasQuantizationTable =
6546 450 : GTIFFFindNextTable(static_cast<const GByte *>(pJPEGTable),
6547 : MARKER_QUANT_TABLE, nJPEGTableSize,
6548 450 : nullptr) != nullptr;
6549 450 : bOutHasHuffmanTable =
6550 450 : GTIFFFindNextTable(static_cast<const GByte *>(pJPEGTable),
6551 : MARKER_HUFFMAN_TABLE, nJPEGTableSize,
6552 450 : nullptr) != nullptr;
6553 450 : if (!bOutHasQuantizationTable)
6554 7 : return -1;
6555 :
6556 443 : if ((nBands == 1 && m_nBitsPerSample == 8) ||
6557 382 : (nBands == 3 && m_nBitsPerSample == 8 &&
6558 336 : m_nPhotometric == PHOTOMETRIC_RGB) ||
6559 288 : (nBands == 4 && m_nBitsPerSample == 8 &&
6560 27 : m_nPhotometric == PHOTOMETRIC_SEPARATED))
6561 : {
6562 167 : return GuessJPEGQualityFromMD5(md5JPEGQuantTable_generic_8bit,
6563 : static_cast<const GByte *>(pJPEGTable),
6564 167 : static_cast<int>(nJPEGTableSize));
6565 : }
6566 :
6567 276 : if (nBands == 3 && m_nBitsPerSample == 8 &&
6568 242 : m_nPhotometric == PHOTOMETRIC_YCBCR)
6569 : {
6570 : int nRet =
6571 242 : GuessJPEGQualityFromMD5(md5JPEGQuantTable_3_YCBCR_8bit,
6572 : static_cast<const GByte *>(pJPEGTable),
6573 : static_cast<int>(nJPEGTableSize));
6574 242 : if (nRet < 0)
6575 : {
6576 : // libjpeg 9e has modified the YCbCr quantization tables.
6577 : nRet =
6578 0 : GuessJPEGQualityFromMD5(md5JPEGQuantTable_3_YCBCR_8bit_jpeg9e,
6579 : static_cast<const GByte *>(pJPEGTable),
6580 : static_cast<int>(nJPEGTableSize));
6581 : }
6582 242 : return nRet;
6583 : }
6584 :
6585 34 : char **papszLocalParameters = nullptr;
6586 : papszLocalParameters =
6587 34 : CSLSetNameValue(papszLocalParameters, "COMPRESS", "JPEG");
6588 34 : if (m_nPhotometric == PHOTOMETRIC_YCBCR)
6589 : papszLocalParameters =
6590 7 : CSLSetNameValue(papszLocalParameters, "PHOTOMETRIC", "YCBCR");
6591 27 : else if (m_nPhotometric == PHOTOMETRIC_SEPARATED)
6592 : papszLocalParameters =
6593 0 : CSLSetNameValue(papszLocalParameters, "PHOTOMETRIC", "CMYK");
6594 : papszLocalParameters =
6595 34 : CSLSetNameValue(papszLocalParameters, "BLOCKYSIZE", "16");
6596 34 : if (m_nBitsPerSample == 12)
6597 : papszLocalParameters =
6598 16 : CSLSetNameValue(papszLocalParameters, "NBITS", "12");
6599 :
6600 : const CPLString osTmpFilenameIn(
6601 34 : VSIMemGenerateHiddenFilename("gtiffdataset_guess_jpeg_quality_tmp"));
6602 :
6603 34 : int nRet = -1;
6604 938 : for (int nQuality = 0; nQuality <= 100 && nRet < 0; ++nQuality)
6605 : {
6606 904 : VSILFILE *fpTmp = nullptr;
6607 904 : if (nQuality == 0)
6608 : papszLocalParameters =
6609 34 : CSLSetNameValue(papszLocalParameters, "JPEG_QUALITY", "75");
6610 : else
6611 : papszLocalParameters =
6612 870 : CSLSetNameValue(papszLocalParameters, "JPEG_QUALITY",
6613 : CPLSPrintf("%d", nQuality));
6614 :
6615 904 : CPLPushErrorHandler(CPLQuietErrorHandler);
6616 904 : CPLString osTmp;
6617 : bool bTileInterleaving;
6618 1808 : TIFF *hTIFFTmp = CreateLL(
6619 904 : osTmpFilenameIn, 16, 16, (nBands <= 4) ? nBands : 1,
6620 : GetRasterBand(1)->GetRasterDataType(), 0.0, 0, papszLocalParameters,
6621 : &fpTmp, osTmp, /* bCreateCopy=*/false, bTileInterleaving);
6622 904 : CPLPopErrorHandler();
6623 904 : if (!hTIFFTmp)
6624 : {
6625 0 : break;
6626 : }
6627 :
6628 904 : TIFFWriteCheck(hTIFFTmp, FALSE, "CreateLL");
6629 904 : TIFFWriteDirectory(hTIFFTmp);
6630 904 : TIFFSetDirectory(hTIFFTmp, 0);
6631 : // Now reset jpegcolormode.
6632 1196 : if (m_nPhotometric == PHOTOMETRIC_YCBCR &&
6633 292 : CPLTestBool(CPLGetConfigOption("CONVERT_YCBCR_TO_RGB", "YES")))
6634 : {
6635 292 : TIFFSetField(hTIFFTmp, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
6636 : }
6637 :
6638 904 : GByte abyZeroData[(16 * 16 * 4 * 3) / 2] = {};
6639 904 : const int nBlockSize =
6640 904 : (16 * 16 * ((nBands <= 4) ? nBands : 1) * m_nBitsPerSample) / 8;
6641 904 : TIFFWriteEncodedStrip(hTIFFTmp, 0, abyZeroData, nBlockSize);
6642 :
6643 904 : uint32_t nJPEGTableSizeTry = 0;
6644 904 : void *pJPEGTableTry = nullptr;
6645 904 : if (TIFFGetField(hTIFFTmp, TIFFTAG_JPEGTABLES, &nJPEGTableSizeTry,
6646 904 : &pJPEGTableTry))
6647 : {
6648 904 : if (GTIFFQuantizationTablesEqual(
6649 : static_cast<GByte *>(pJPEGTable), nJPEGTableSize,
6650 : static_cast<GByte *>(pJPEGTableTry), nJPEGTableSizeTry))
6651 : {
6652 34 : nRet = (nQuality == 0) ? 75 : nQuality;
6653 : }
6654 : }
6655 :
6656 904 : XTIFFClose(hTIFFTmp);
6657 904 : CPL_IGNORE_RET_VAL(VSIFCloseL(fpTmp));
6658 : }
6659 :
6660 34 : CSLDestroy(papszLocalParameters);
6661 34 : VSIUnlink(osTmpFilenameIn);
6662 :
6663 34 : return nRet;
6664 : }
6665 :
6666 : /************************************************************************/
6667 : /* SetJPEGQualityAndTablesModeFromFile() */
6668 : /************************************************************************/
6669 :
6670 161 : void GTiffDataset::SetJPEGQualityAndTablesModeFromFile(
6671 : int nQuality, bool bHasQuantizationTable, bool bHasHuffmanTable)
6672 : {
6673 161 : if (nQuality > 0)
6674 : {
6675 154 : CPLDebug("GTiff", "Guessed JPEG quality to be %d", nQuality);
6676 154 : m_nJpegQuality = static_cast<signed char>(nQuality);
6677 154 : TIFFSetField(m_hTIFF, TIFFTAG_JPEGQUALITY, nQuality);
6678 :
6679 : // This means we will use the quantization tables from the
6680 : // JpegTables tag.
6681 154 : m_nJpegTablesMode = JPEGTABLESMODE_QUANT;
6682 : }
6683 : else
6684 : {
6685 7 : uint32_t nJPEGTableSize = 0;
6686 7 : void *pJPEGTable = nullptr;
6687 7 : if (!TIFFGetField(m_hTIFF, TIFFTAG_JPEGTABLES, &nJPEGTableSize,
6688 : &pJPEGTable))
6689 : {
6690 4 : toff_t *panByteCounts = nullptr;
6691 8 : const int nBlockCount = m_nPlanarConfig == PLANARCONFIG_SEPARATE
6692 4 : ? m_nBlocksPerBand * nBands
6693 : : m_nBlocksPerBand;
6694 4 : if (TIFFIsTiled(m_hTIFF))
6695 1 : TIFFGetField(m_hTIFF, TIFFTAG_TILEBYTECOUNTS, &panByteCounts);
6696 : else
6697 3 : TIFFGetField(m_hTIFF, TIFFTAG_STRIPBYTECOUNTS, &panByteCounts);
6698 :
6699 4 : bool bFoundNonEmptyBlock = false;
6700 4 : if (panByteCounts != nullptr)
6701 : {
6702 56 : for (int iBlock = 0; iBlock < nBlockCount; ++iBlock)
6703 : {
6704 53 : if (panByteCounts[iBlock] != 0)
6705 : {
6706 1 : bFoundNonEmptyBlock = true;
6707 1 : break;
6708 : }
6709 : }
6710 : }
6711 4 : if (bFoundNonEmptyBlock)
6712 : {
6713 1 : CPLDebug("GTiff", "Could not guess JPEG quality. "
6714 : "JPEG tables are missing, so going in "
6715 : "TIFFTAG_JPEGTABLESMODE = 0/2 mode");
6716 : // Write quantization tables in each strile.
6717 1 : m_nJpegTablesMode = 0;
6718 : }
6719 : }
6720 : else
6721 : {
6722 3 : if (bHasQuantizationTable)
6723 : {
6724 : // FIXME in libtiff: this is likely going to cause issues
6725 : // since libtiff will reuse in each strile the number of
6726 : // the global quantization table, which is invalid.
6727 1 : CPLDebug("GTiff",
6728 : "Could not guess JPEG quality although JPEG "
6729 : "quantization tables are present, so going in "
6730 : "TIFFTAG_JPEGTABLESMODE = 0/2 mode");
6731 : }
6732 : else
6733 : {
6734 2 : CPLDebug("GTiff",
6735 : "Could not guess JPEG quality since JPEG "
6736 : "quantization tables are not present, so going in "
6737 : "TIFFTAG_JPEGTABLESMODE = 0/2 mode");
6738 : }
6739 :
6740 : // Write quantization tables in each strile.
6741 3 : m_nJpegTablesMode = 0;
6742 : }
6743 : }
6744 161 : if (bHasHuffmanTable)
6745 : {
6746 : // If there are Huffman tables in header use them, otherwise
6747 : // if we use optimized tables, libtiff will currently reuse
6748 : // the number of the Huffman tables of the header for the
6749 : // optimized version of each strile, which is illegal.
6750 23 : m_nJpegTablesMode |= JPEGTABLESMODE_HUFF;
6751 : }
6752 161 : if (m_nJpegTablesMode >= 0)
6753 159 : TIFFSetField(m_hTIFF, TIFFTAG_JPEGTABLESMODE, m_nJpegTablesMode);
6754 161 : }
6755 :
6756 : /************************************************************************/
6757 : /* Create() */
6758 : /* */
6759 : /* Create a new GeoTIFF or TIFF file. */
6760 : /************************************************************************/
6761 :
6762 5761 : GDALDataset *GTiffDataset::Create(const char *pszFilename, int nXSize,
6763 : int nYSize, int l_nBands, GDALDataType eType,
6764 : CSLConstList papszParamList)
6765 :
6766 : {
6767 5761 : VSILFILE *l_fpL = nullptr;
6768 11522 : CPLString l_osTmpFilename;
6769 :
6770 : const int nColorTableMultiplier = std::max(
6771 11522 : 1,
6772 11522 : std::min(257,
6773 5761 : atoi(CSLFetchNameValueDef(
6774 : papszParamList, "COLOR_TABLE_MULTIPLIER",
6775 5761 : CPLSPrintf("%d", DEFAULT_COLOR_TABLE_MULTIPLIER_257)))));
6776 :
6777 : /* -------------------------------------------------------------------- */
6778 : /* Create the underlying TIFF file. */
6779 : /* -------------------------------------------------------------------- */
6780 : bool bTileInterleaving;
6781 : TIFF *l_hTIFF =
6782 5761 : CreateLL(pszFilename, nXSize, nYSize, l_nBands, eType, 0,
6783 : nColorTableMultiplier, papszParamList, &l_fpL, l_osTmpFilename,
6784 : /* bCreateCopy=*/false, bTileInterleaving);
6785 5761 : const bool bStreaming = !l_osTmpFilename.empty();
6786 :
6787 5761 : if (l_hTIFF == nullptr)
6788 38 : return nullptr;
6789 :
6790 : /* -------------------------------------------------------------------- */
6791 : /* Create the new GTiffDataset object. */
6792 : /* -------------------------------------------------------------------- */
6793 11446 : auto poDS = std::make_unique<GTiffDataset>();
6794 5723 : poDS->m_hTIFF = l_hTIFF;
6795 5723 : poDS->m_fpL = l_fpL;
6796 5723 : const bool bSuppressASAP = CPLTestBool(
6797 : CSLFetchNameValueDef(papszParamList, "@SUPPRESS_ASAP", "NO"));
6798 5723 : if (bSuppressASAP)
6799 34 : poDS->MarkSuppressOnClose();
6800 5723 : if (bStreaming)
6801 : {
6802 4 : poDS->m_bStreamingOut = true;
6803 4 : poDS->m_pszTmpFilename = CPLStrdup(l_osTmpFilename);
6804 4 : poDS->m_fpToWrite = VSIFOpenL(pszFilename, "wb");
6805 4 : if (poDS->m_fpToWrite == nullptr)
6806 : {
6807 1 : VSIUnlink(l_osTmpFilename);
6808 1 : return nullptr;
6809 : }
6810 : }
6811 5722 : poDS->nRasterXSize = nXSize;
6812 5722 : poDS->nRasterYSize = nYSize;
6813 5722 : poDS->eAccess = GA_Update;
6814 :
6815 : // This will avoid GTiffDataset::GetSiblingFiles() to trigger a directory
6816 : // listing, which is potentially costly and only makes sense when opening
6817 : // new files, not creating new ones. Helps for scenario like
6818 : // https://github.com/OSGeo/gdal/issues/13930
6819 5722 : poDS->m_bHasGotSiblingFiles = true;
6820 :
6821 5722 : poDS->m_nColorTableMultiplier = nColorTableMultiplier;
6822 :
6823 5722 : poDS->m_bCrystalized = false;
6824 5722 : poDS->m_nSamplesPerPixel = static_cast<uint16_t>(l_nBands);
6825 5722 : poDS->m_osFilename = pszFilename;
6826 :
6827 : // Don't try to load external metadata files (#6597).
6828 5722 : poDS->m_bIMDRPCMetadataLoaded = true;
6829 :
6830 : // Avoid premature crystalization that will cause directory re-writing if
6831 : // GetProjectionRef() or GetGeoTransform() are called on the newly created
6832 : // GeoTIFF.
6833 5722 : poDS->m_bLookedForProjection = true;
6834 :
6835 5722 : TIFFGetField(l_hTIFF, TIFFTAG_SAMPLEFORMAT, &(poDS->m_nSampleFormat));
6836 5722 : TIFFGetField(l_hTIFF, TIFFTAG_PLANARCONFIG, &(poDS->m_nPlanarConfig));
6837 : // Weird that we need this, but otherwise we get a Valgrind warning on
6838 : // tiff_write_124.
6839 5722 : if (!TIFFGetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, &(poDS->m_nPhotometric)))
6840 1 : poDS->m_nPhotometric = PHOTOMETRIC_MINISBLACK;
6841 5722 : TIFFGetField(l_hTIFF, TIFFTAG_BITSPERSAMPLE, &(poDS->m_nBitsPerSample));
6842 5722 : TIFFGetField(l_hTIFF, TIFFTAG_COMPRESSION, &(poDS->m_nCompression));
6843 :
6844 5722 : if (TIFFIsTiled(l_hTIFF))
6845 : {
6846 395 : TIFFGetField(l_hTIFF, TIFFTAG_TILEWIDTH, &(poDS->m_nBlockXSize));
6847 395 : TIFFGetField(l_hTIFF, TIFFTAG_TILELENGTH, &(poDS->m_nBlockYSize));
6848 : }
6849 : else
6850 : {
6851 5327 : if (!TIFFGetField(l_hTIFF, TIFFTAG_ROWSPERSTRIP,
6852 5327 : &(poDS->m_nRowsPerStrip)))
6853 0 : poDS->m_nRowsPerStrip = 1; // Dummy value.
6854 :
6855 5327 : poDS->m_nBlockXSize = nXSize;
6856 10654 : poDS->m_nBlockYSize =
6857 5327 : std::min(static_cast<int>(poDS->m_nRowsPerStrip), nYSize);
6858 : }
6859 :
6860 5722 : if (!poDS->ComputeBlocksPerColRowAndBand(l_nBands))
6861 : {
6862 0 : poDS->m_fpL->CancelCreation();
6863 0 : return nullptr;
6864 : }
6865 :
6866 5722 : poDS->m_eProfile = GetProfile(CSLFetchNameValue(papszParamList, "PROFILE"));
6867 :
6868 : /* -------------------------------------------------------------------- */
6869 : /* YCbCr JPEG compressed images should be translated on the fly */
6870 : /* to RGB by libtiff/libjpeg unless specifically requested */
6871 : /* otherwise. */
6872 : /* -------------------------------------------------------------------- */
6873 5722 : if (poDS->m_nCompression == COMPRESSION_JPEG &&
6874 5743 : poDS->m_nPhotometric == PHOTOMETRIC_YCBCR &&
6875 21 : CPLTestBool(CPLGetConfigOption("CONVERT_YCBCR_TO_RGB", "YES")))
6876 : {
6877 21 : int nColorMode = 0;
6878 :
6879 21 : poDS->SetMetadataItem("SOURCE_COLOR_SPACE", "YCbCr", "IMAGE_STRUCTURE");
6880 42 : if (!TIFFGetField(l_hTIFF, TIFFTAG_JPEGCOLORMODE, &nColorMode) ||
6881 21 : nColorMode != JPEGCOLORMODE_RGB)
6882 21 : TIFFSetField(l_hTIFF, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
6883 : }
6884 :
6885 5722 : if (poDS->m_nCompression == COMPRESSION_LERC)
6886 : {
6887 26 : uint32_t nLercParamCount = 0;
6888 26 : uint32_t *panLercParams = nullptr;
6889 26 : if (TIFFGetField(l_hTIFF, TIFFTAG_LERC_PARAMETERS, &nLercParamCount,
6890 52 : &panLercParams) &&
6891 26 : nLercParamCount == 2)
6892 : {
6893 26 : memcpy(poDS->m_anLercAddCompressionAndVersion, panLercParams,
6894 : sizeof(poDS->m_anLercAddCompressionAndVersion));
6895 : }
6896 : }
6897 :
6898 : /* -------------------------------------------------------------------- */
6899 : /* Read palette back as a color table if it has one. */
6900 : /* -------------------------------------------------------------------- */
6901 5722 : unsigned short *panRed = nullptr;
6902 5722 : unsigned short *panGreen = nullptr;
6903 5722 : unsigned short *panBlue = nullptr;
6904 :
6905 5726 : if (poDS->m_nPhotometric == PHOTOMETRIC_PALETTE &&
6906 4 : TIFFGetField(l_hTIFF, TIFFTAG_COLORMAP, &panRed, &panGreen, &panBlue))
6907 : {
6908 :
6909 4 : poDS->m_poColorTable = std::make_unique<GDALColorTable>();
6910 :
6911 4 : const int nColorCount = 1 << poDS->m_nBitsPerSample;
6912 :
6913 1028 : for (int iColor = nColorCount - 1; iColor >= 0; iColor--)
6914 : {
6915 1024 : const GDALColorEntry oEntry = {
6916 1024 : static_cast<short>(panRed[iColor] / nColorTableMultiplier),
6917 1024 : static_cast<short>(panGreen[iColor] / nColorTableMultiplier),
6918 1024 : static_cast<short>(panBlue[iColor] / nColorTableMultiplier),
6919 1024 : static_cast<short>(255)};
6920 :
6921 1024 : poDS->m_poColorTable->SetColorEntry(iColor, &oEntry);
6922 : }
6923 : }
6924 :
6925 : /* -------------------------------------------------------------------- */
6926 : /* Do we want to ensure all blocks get written out on close to */
6927 : /* avoid sparse files? */
6928 : /* -------------------------------------------------------------------- */
6929 5722 : if (!CPLFetchBool(papszParamList, "SPARSE_OK", false))
6930 5612 : poDS->m_bFillEmptyTilesAtClosing = true;
6931 :
6932 5722 : poDS->m_bWriteEmptyTiles =
6933 6540 : bStreaming || (poDS->m_nCompression != COMPRESSION_NONE &&
6934 818 : poDS->m_bFillEmptyTilesAtClosing);
6935 : // Only required for people writing non-compressed striped files in the
6936 : // right order and wanting all tstrips to be written in the same order
6937 : // so that the end result can be memory mapped without knowledge of each
6938 : // strip offset.
6939 5722 : if (CPLTestBool(CSLFetchNameValueDef(
6940 11444 : papszParamList, "WRITE_EMPTY_TILES_SYNCHRONOUSLY", "FALSE")) ||
6941 5722 : CPLTestBool(CSLFetchNameValueDef(
6942 : papszParamList, "@WRITE_EMPTY_TILES_SYNCHRONOUSLY", "FALSE")))
6943 : {
6944 26 : poDS->m_bWriteEmptyTiles = true;
6945 : }
6946 :
6947 : /* -------------------------------------------------------------------- */
6948 : /* Preserve creation options for consulting later (for instance */
6949 : /* to decide if a TFW file should be written). */
6950 : /* -------------------------------------------------------------------- */
6951 5722 : poDS->m_papszCreationOptions = CSLDuplicate(papszParamList);
6952 :
6953 5722 : poDS->m_nZLevel = GTiffGetZLevel(papszParamList);
6954 5722 : poDS->m_nLZMAPreset = GTiffGetLZMAPreset(papszParamList);
6955 5722 : poDS->m_nZSTDLevel = GTiffGetZSTDPreset(papszParamList);
6956 5722 : poDS->m_nWebPLevel = GTiffGetWebPLevel(papszParamList);
6957 5722 : poDS->m_bWebPLossless = GTiffGetWebPLossless(papszParamList);
6958 5724 : if (poDS->m_nWebPLevel != 100 && poDS->m_bWebPLossless &&
6959 2 : CSLFetchNameValue(papszParamList, "WEBP_LEVEL"))
6960 : {
6961 0 : CPLError(CE_Warning, CPLE_AppDefined,
6962 : "WEBP_LEVEL is specified, but WEBP_LOSSLESS=YES. "
6963 : "WEBP_LEVEL will be ignored.");
6964 : }
6965 5722 : poDS->m_nJpegQuality = GTiffGetJpegQuality(papszParamList);
6966 5722 : poDS->m_nJpegTablesMode = GTiffGetJpegTablesMode(papszParamList);
6967 5722 : poDS->m_dfMaxZError = GTiffGetLERCMaxZError(papszParamList);
6968 5722 : poDS->m_dfMaxZErrorOverview = GTiffGetLERCMaxZErrorOverview(papszParamList);
6969 : #if HAVE_JXL
6970 5722 : poDS->m_bJXLLossless = GTiffGetJXLLossless(papszParamList);
6971 5722 : poDS->m_nJXLEffort = GTiffGetJXLEffort(papszParamList);
6972 5722 : poDS->m_fJXLDistance = GTiffGetJXLDistance(papszParamList);
6973 5722 : poDS->m_fJXLAlphaDistance = GTiffGetJXLAlphaDistance(papszParamList);
6974 : #endif
6975 5722 : poDS->InitCreationOrOpenOptions(true, papszParamList);
6976 :
6977 : /* -------------------------------------------------------------------- */
6978 : /* Create band information objects. */
6979 : /* -------------------------------------------------------------------- */
6980 308286 : for (int iBand = 0; iBand < l_nBands; ++iBand)
6981 : {
6982 371771 : if (poDS->m_nBitsPerSample == 8 || poDS->m_nBitsPerSample == 16 ||
6983 372012 : poDS->m_nBitsPerSample == 32 || poDS->m_nBitsPerSample == 64 ||
6984 241 : poDS->m_nBitsPerSample == 128)
6985 : {
6986 604998 : poDS->SetBand(iBand + 1, std::make_unique<GTiffRasterBand>(
6987 604998 : poDS.get(), iBand + 1));
6988 : }
6989 : else
6990 : {
6991 130 : poDS->SetBand(iBand + 1, std::make_unique<GTiffOddBitsBand>(
6992 65 : poDS.get(), iBand + 1));
6993 130 : poDS->GetRasterBand(iBand + 1)->SetMetadataItem(
6994 130 : "NBITS", CPLString().Printf("%d", poDS->m_nBitsPerSample),
6995 65 : "IMAGE_STRUCTURE");
6996 : }
6997 : }
6998 :
6999 5722 : poDS->GetDiscardLsbOption(papszParamList);
7000 :
7001 5722 : if (poDS->m_nPlanarConfig == PLANARCONFIG_CONTIG && l_nBands != 1)
7002 835 : poDS->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
7003 : else
7004 4887 : poDS->SetMetadataItem("INTERLEAVE", "BAND", "IMAGE_STRUCTURE");
7005 :
7006 5722 : poDS->oOvManager.Initialize(poDS.get(), pszFilename);
7007 :
7008 5722 : return poDS.release();
7009 : }
7010 :
7011 : /************************************************************************/
7012 : /* CopyImageryAndMask() */
7013 : /************************************************************************/
7014 :
7015 345 : CPLErr GTiffDataset::CopyImageryAndMask(GTiffDataset *poDstDS,
7016 : GDALDataset *poSrcDS,
7017 : GDALRasterBand *poSrcMaskBand,
7018 : GDALProgressFunc pfnProgress,
7019 : void *pProgressData)
7020 : {
7021 345 : CPLErr eErr = CE_None;
7022 :
7023 345 : const auto eType = poDstDS->GetRasterBand(1)->GetRasterDataType();
7024 345 : const int nDataTypeSize = GDALGetDataTypeSizeBytes(eType);
7025 345 : const int l_nBands = poDstDS->GetRasterCount();
7026 : GByte *pBlockBuffer = static_cast<GByte *>(
7027 345 : VSI_MALLOC3_VERBOSE(poDstDS->m_nBlockXSize, poDstDS->m_nBlockYSize,
7028 : cpl::fits_on<int>(l_nBands * nDataTypeSize)));
7029 345 : if (pBlockBuffer == nullptr)
7030 : {
7031 0 : eErr = CE_Failure;
7032 : }
7033 345 : const int nYSize = poDstDS->nRasterYSize;
7034 345 : const int nXSize = poDstDS->nRasterXSize;
7035 : const bool bIsOddBand =
7036 345 : dynamic_cast<GTiffOddBitsBand *>(poDstDS->GetRasterBand(1)) != nullptr;
7037 :
7038 345 : if (poDstDS->m_poMaskDS)
7039 : {
7040 59 : CPLAssert(poDstDS->m_poMaskDS->m_nBlockXSize == poDstDS->m_nBlockXSize);
7041 59 : CPLAssert(poDstDS->m_poMaskDS->m_nBlockYSize == poDstDS->m_nBlockYSize);
7042 : }
7043 :
7044 345 : if (poDstDS->m_nPlanarConfig == PLANARCONFIG_SEPARATE &&
7045 58 : !poDstDS->m_bTileInterleave)
7046 : {
7047 45 : int iBlock = 0;
7048 45 : const int nBlocks = poDstDS->m_nBlocksPerBand *
7049 45 : (l_nBands + (poDstDS->m_poMaskDS ? 1 : 0));
7050 195 : for (int i = 0; eErr == CE_None && i < l_nBands; i++)
7051 : {
7052 345 : for (int iY = 0; iY < nYSize && eErr == CE_None;
7053 195 : iY = ((nYSize - iY < poDstDS->m_nBlockYSize)
7054 195 : ? nYSize
7055 59 : : iY + poDstDS->m_nBlockYSize))
7056 : {
7057 : const int nReqYSize =
7058 195 : std::min(nYSize - iY, poDstDS->m_nBlockYSize);
7059 495 : for (int iX = 0; iX < nXSize && eErr == CE_None;
7060 300 : iX = ((nXSize - iX < poDstDS->m_nBlockXSize)
7061 300 : ? nXSize
7062 155 : : iX + poDstDS->m_nBlockXSize))
7063 : {
7064 : const int nReqXSize =
7065 300 : std::min(nXSize - iX, poDstDS->m_nBlockXSize);
7066 300 : if (nReqXSize < poDstDS->m_nBlockXSize ||
7067 155 : nReqYSize < poDstDS->m_nBlockYSize)
7068 : {
7069 190 : memset(pBlockBuffer, 0,
7070 190 : static_cast<size_t>(poDstDS->m_nBlockXSize) *
7071 190 : poDstDS->m_nBlockYSize * nDataTypeSize);
7072 : }
7073 300 : eErr = poSrcDS->GetRasterBand(i + 1)->RasterIO(
7074 : GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
7075 : nReqXSize, nReqYSize, eType, nDataTypeSize,
7076 300 : static_cast<GSpacing>(nDataTypeSize) *
7077 300 : poDstDS->m_nBlockXSize,
7078 : nullptr);
7079 300 : if (eErr == CE_None)
7080 : {
7081 300 : eErr = poDstDS->WriteEncodedTileOrStrip(
7082 : iBlock, pBlockBuffer, false);
7083 : }
7084 :
7085 300 : iBlock++;
7086 600 : if (pfnProgress &&
7087 300 : !pfnProgress(static_cast<double>(iBlock) / nBlocks,
7088 : nullptr, pProgressData))
7089 : {
7090 0 : eErr = CE_Failure;
7091 : }
7092 :
7093 300 : if (poDstDS->m_bWriteError)
7094 0 : eErr = CE_Failure;
7095 : }
7096 : }
7097 : }
7098 45 : if (poDstDS->m_poMaskDS && eErr == CE_None)
7099 : {
7100 6 : int iBlockMask = 0;
7101 17 : for (int iY = 0, nYBlock = 0; iY < nYSize && eErr == CE_None;
7102 11 : iY = ((nYSize - iY < poDstDS->m_nBlockYSize)
7103 11 : ? nYSize
7104 5 : : iY + poDstDS->m_nBlockYSize),
7105 : nYBlock++)
7106 : {
7107 : const int nReqYSize =
7108 11 : std::min(nYSize - iY, poDstDS->m_nBlockYSize);
7109 49 : for (int iX = 0, nXBlock = 0; iX < nXSize && eErr == CE_None;
7110 38 : iX = ((nXSize - iX < poDstDS->m_nBlockXSize)
7111 38 : ? nXSize
7112 30 : : iX + poDstDS->m_nBlockXSize),
7113 : nXBlock++)
7114 : {
7115 : const int nReqXSize =
7116 38 : std::min(nXSize - iX, poDstDS->m_nBlockXSize);
7117 38 : if (nReqXSize < poDstDS->m_nBlockXSize ||
7118 30 : nReqYSize < poDstDS->m_nBlockYSize)
7119 : {
7120 16 : memset(pBlockBuffer, 0,
7121 16 : static_cast<size_t>(poDstDS->m_nBlockXSize) *
7122 16 : poDstDS->m_nBlockYSize);
7123 : }
7124 76 : eErr = poSrcMaskBand->RasterIO(
7125 : GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
7126 : nReqXSize, nReqYSize, GDT_UInt8, 1,
7127 38 : poDstDS->m_nBlockXSize, nullptr);
7128 38 : if (eErr == CE_None)
7129 : {
7130 : // Avoid any attempt to load from disk
7131 38 : poDstDS->m_poMaskDS->m_nLoadedBlock = iBlockMask;
7132 : eErr =
7133 38 : poDstDS->m_poMaskDS->GetRasterBand(1)->WriteBlock(
7134 : nXBlock, nYBlock, pBlockBuffer);
7135 38 : if (eErr == CE_None)
7136 38 : eErr = poDstDS->m_poMaskDS->FlushBlockBuf();
7137 : }
7138 :
7139 38 : iBlockMask++;
7140 76 : if (pfnProgress &&
7141 38 : !pfnProgress(static_cast<double>(iBlock + iBlockMask) /
7142 : nBlocks,
7143 : nullptr, pProgressData))
7144 : {
7145 0 : eErr = CE_Failure;
7146 : }
7147 :
7148 38 : if (poDstDS->m_poMaskDS->m_bWriteError)
7149 0 : eErr = CE_Failure;
7150 : }
7151 : }
7152 45 : }
7153 : }
7154 : else
7155 : {
7156 300 : int iBlock = 0;
7157 300 : const int nBlocks = poDstDS->m_nBlocksPerBand;
7158 7094 : for (int iY = 0, nYBlock = 0; iY < nYSize && eErr == CE_None;
7159 6794 : iY = ((nYSize - iY < poDstDS->m_nBlockYSize)
7160 6794 : ? nYSize
7161 6569 : : iY + poDstDS->m_nBlockYSize),
7162 : nYBlock++)
7163 : {
7164 6794 : const int nReqYSize = std::min(nYSize - iY, poDstDS->m_nBlockYSize);
7165 26511 : for (int iX = 0, nXBlock = 0; iX < nXSize && eErr == CE_None;
7166 19717 : iX = ((nXSize - iX < poDstDS->m_nBlockXSize)
7167 19717 : ? nXSize
7168 19420 : : iX + poDstDS->m_nBlockXSize),
7169 : nXBlock++)
7170 : {
7171 : const int nReqXSize =
7172 19717 : std::min(nXSize - iX, poDstDS->m_nBlockXSize);
7173 19717 : if (nReqXSize < poDstDS->m_nBlockXSize ||
7174 19420 : nReqYSize < poDstDS->m_nBlockYSize)
7175 : {
7176 466 : memset(pBlockBuffer, 0,
7177 466 : static_cast<size_t>(poDstDS->m_nBlockXSize) *
7178 466 : poDstDS->m_nBlockYSize * l_nBands *
7179 466 : nDataTypeSize);
7180 : }
7181 :
7182 19717 : if (poDstDS->m_bTileInterleave)
7183 : {
7184 114 : eErr = poSrcDS->RasterIO(
7185 : GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
7186 : nReqXSize, nReqYSize, eType, l_nBands, nullptr,
7187 : nDataTypeSize,
7188 57 : static_cast<GSpacing>(nDataTypeSize) *
7189 57 : poDstDS->m_nBlockXSize,
7190 57 : static_cast<GSpacing>(nDataTypeSize) *
7191 57 : poDstDS->m_nBlockXSize * poDstDS->m_nBlockYSize,
7192 : nullptr);
7193 57 : if (eErr == CE_None)
7194 : {
7195 228 : for (int i = 0; eErr == CE_None && i < l_nBands; i++)
7196 : {
7197 171 : eErr = poDstDS->WriteEncodedTileOrStrip(
7198 171 : iBlock + i * poDstDS->m_nBlocksPerBand,
7199 171 : pBlockBuffer + static_cast<size_t>(i) *
7200 171 : poDstDS->m_nBlockXSize *
7201 171 : poDstDS->m_nBlockYSize *
7202 171 : nDataTypeSize,
7203 : false);
7204 : }
7205 : }
7206 : }
7207 19660 : else if (!bIsOddBand)
7208 : {
7209 39198 : eErr = poSrcDS->RasterIO(
7210 : GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
7211 : nReqXSize, nReqYSize, eType, l_nBands, nullptr,
7212 19599 : static_cast<GSpacing>(nDataTypeSize) * l_nBands,
7213 19599 : static_cast<GSpacing>(nDataTypeSize) * l_nBands *
7214 19599 : poDstDS->m_nBlockXSize,
7215 : nDataTypeSize, nullptr);
7216 19599 : if (eErr == CE_None)
7217 : {
7218 19598 : eErr = poDstDS->WriteEncodedTileOrStrip(
7219 : iBlock, pBlockBuffer, false);
7220 : }
7221 : }
7222 : else
7223 : {
7224 : // In the odd bit case, this is a bit messy to ensure
7225 : // the strile gets written synchronously.
7226 : // We load the content of the n-1 bands in the cache,
7227 : // and for the last band we invoke WriteBlock() directly
7228 : // We also force FlushBlockBuf()
7229 122 : std::vector<GDALRasterBlock *> apoLockedBlocks;
7230 91 : for (int i = 0; eErr == CE_None && i < l_nBands - 1; i++)
7231 : {
7232 : auto poBlock =
7233 30 : poDstDS->GetRasterBand(i + 1)->GetLockedBlockRef(
7234 30 : nXBlock, nYBlock, TRUE);
7235 30 : if (poBlock)
7236 : {
7237 60 : eErr = poSrcDS->GetRasterBand(i + 1)->RasterIO(
7238 : GF_Read, iX, iY, nReqXSize, nReqYSize,
7239 : poBlock->GetDataRef(), nReqXSize, nReqYSize,
7240 : eType, nDataTypeSize,
7241 30 : static_cast<GSpacing>(nDataTypeSize) *
7242 30 : poDstDS->m_nBlockXSize,
7243 : nullptr);
7244 30 : poBlock->MarkDirty();
7245 30 : apoLockedBlocks.emplace_back(poBlock);
7246 : }
7247 : else
7248 : {
7249 0 : eErr = CE_Failure;
7250 : }
7251 : }
7252 61 : if (eErr == CE_None)
7253 : {
7254 122 : eErr = poSrcDS->GetRasterBand(l_nBands)->RasterIO(
7255 : GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
7256 : nReqXSize, nReqYSize, eType, nDataTypeSize,
7257 61 : static_cast<GSpacing>(nDataTypeSize) *
7258 61 : poDstDS->m_nBlockXSize,
7259 : nullptr);
7260 : }
7261 61 : if (eErr == CE_None)
7262 : {
7263 : // Avoid any attempt to load from disk
7264 61 : poDstDS->m_nLoadedBlock = iBlock;
7265 61 : eErr = poDstDS->GetRasterBand(l_nBands)->WriteBlock(
7266 : nXBlock, nYBlock, pBlockBuffer);
7267 61 : if (eErr == CE_None)
7268 61 : eErr = poDstDS->FlushBlockBuf();
7269 : }
7270 91 : for (auto poBlock : apoLockedBlocks)
7271 : {
7272 30 : poBlock->MarkClean();
7273 30 : poBlock->DropLock();
7274 : }
7275 : }
7276 :
7277 19717 : if (eErr == CE_None && poDstDS->m_poMaskDS)
7278 : {
7279 4664 : if (nReqXSize < poDstDS->m_nBlockXSize ||
7280 4621 : nReqYSize < poDstDS->m_nBlockYSize)
7281 : {
7282 81 : memset(pBlockBuffer, 0,
7283 81 : static_cast<size_t>(poDstDS->m_nBlockXSize) *
7284 81 : poDstDS->m_nBlockYSize);
7285 : }
7286 9328 : eErr = poSrcMaskBand->RasterIO(
7287 : GF_Read, iX, iY, nReqXSize, nReqYSize, pBlockBuffer,
7288 : nReqXSize, nReqYSize, GDT_UInt8, 1,
7289 4664 : poDstDS->m_nBlockXSize, nullptr);
7290 4664 : if (eErr == CE_None)
7291 : {
7292 : // Avoid any attempt to load from disk
7293 4664 : poDstDS->m_poMaskDS->m_nLoadedBlock = iBlock;
7294 : eErr =
7295 4664 : poDstDS->m_poMaskDS->GetRasterBand(1)->WriteBlock(
7296 : nXBlock, nYBlock, pBlockBuffer);
7297 4664 : if (eErr == CE_None)
7298 4664 : eErr = poDstDS->m_poMaskDS->FlushBlockBuf();
7299 : }
7300 : }
7301 19717 : if (poDstDS->m_bWriteError)
7302 6 : eErr = CE_Failure;
7303 :
7304 19717 : iBlock++;
7305 39434 : if (pfnProgress &&
7306 19717 : !pfnProgress(static_cast<double>(iBlock) / nBlocks, nullptr,
7307 : pProgressData))
7308 : {
7309 0 : eErr = CE_Failure;
7310 : }
7311 : }
7312 : }
7313 : }
7314 :
7315 345 : poDstDS->FlushCache(false); // mostly to wait for thread completion
7316 345 : VSIFree(pBlockBuffer);
7317 :
7318 345 : return eErr;
7319 : }
7320 :
7321 : /************************************************************************/
7322 : /* CreateCopy() */
7323 : /************************************************************************/
7324 :
7325 2150 : GDALDataset *GTiffDataset::CreateCopy(const char *pszFilename,
7326 : GDALDataset *poSrcDS, int bStrict,
7327 : CSLConstList papszOptions,
7328 : GDALProgressFunc pfnProgress,
7329 : void *pProgressData)
7330 :
7331 : {
7332 2150 : if (poSrcDS->GetRasterCount() == 0)
7333 : {
7334 2 : ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
7335 : "Unable to export GeoTIFF files with zero bands.");
7336 2 : return nullptr;
7337 : }
7338 :
7339 2148 : GDALRasterBand *const poPBand = poSrcDS->GetRasterBand(1);
7340 2148 : GDALDataType eType = poPBand->GetRasterDataType();
7341 :
7342 : /* -------------------------------------------------------------------- */
7343 : /* Check, whether all bands in input dataset has the same type. */
7344 : /* -------------------------------------------------------------------- */
7345 2148 : const int l_nBands = poSrcDS->GetRasterCount();
7346 5077 : for (int iBand = 2; iBand <= l_nBands; ++iBand)
7347 : {
7348 2929 : if (eType != poSrcDS->GetRasterBand(iBand)->GetRasterDataType())
7349 : {
7350 0 : if (bStrict)
7351 : {
7352 0 : ReportError(
7353 : pszFilename, CE_Failure, CPLE_AppDefined,
7354 : "Unable to export GeoTIFF file with different datatypes "
7355 : "per different bands. All bands should have the same "
7356 : "types in TIFF.");
7357 0 : return nullptr;
7358 : }
7359 : else
7360 : {
7361 0 : ReportError(
7362 : pszFilename, CE_Warning, CPLE_AppDefined,
7363 : "Unable to export GeoTIFF file with different datatypes "
7364 : "per different bands. All bands should have the same "
7365 : "types in TIFF.");
7366 : }
7367 : }
7368 : }
7369 :
7370 : /* -------------------------------------------------------------------- */
7371 : /* Capture the profile. */
7372 : /* -------------------------------------------------------------------- */
7373 : const GTiffProfile eProfile =
7374 2148 : GetProfile(CSLFetchNameValue(papszOptions, "PROFILE"));
7375 :
7376 2148 : const bool bGeoTIFF = eProfile != GTiffProfile::BASELINE;
7377 :
7378 : /* -------------------------------------------------------------------- */
7379 : /* Special handling for NBITS. Copy from band metadata if found. */
7380 : /* -------------------------------------------------------------------- */
7381 2148 : char **papszCreateOptions = CSLDuplicate(papszOptions);
7382 :
7383 2148 : if (poPBand->GetMetadataItem("NBITS", "IMAGE_STRUCTURE") != nullptr &&
7384 2165 : atoi(poPBand->GetMetadataItem("NBITS", "IMAGE_STRUCTURE")) > 0 &&
7385 17 : CSLFetchNameValue(papszCreateOptions, "NBITS") == nullptr)
7386 : {
7387 3 : papszCreateOptions = CSLSetNameValue(
7388 : papszCreateOptions, "NBITS",
7389 3 : poPBand->GetMetadataItem("NBITS", "IMAGE_STRUCTURE"));
7390 : }
7391 :
7392 2148 : if (CSLFetchNameValue(papszOptions, "PIXELTYPE") == nullptr &&
7393 : eType == GDT_UInt8)
7394 : {
7395 1778 : poPBand->EnablePixelTypeSignedByteWarning(false);
7396 : const char *pszPixelType =
7397 1778 : poPBand->GetMetadataItem("PIXELTYPE", "IMAGE_STRUCTURE");
7398 1778 : poPBand->EnablePixelTypeSignedByteWarning(true);
7399 1778 : if (pszPixelType)
7400 : {
7401 1 : papszCreateOptions =
7402 1 : CSLSetNameValue(papszCreateOptions, "PIXELTYPE", pszPixelType);
7403 : }
7404 : }
7405 :
7406 : /* -------------------------------------------------------------------- */
7407 : /* Color profile. Copy from band metadata if found. */
7408 : /* -------------------------------------------------------------------- */
7409 2148 : if (bGeoTIFF)
7410 : {
7411 2131 : const char *pszOptionsMD[] = {"SOURCE_ICC_PROFILE",
7412 : "SOURCE_PRIMARIES_RED",
7413 : "SOURCE_PRIMARIES_GREEN",
7414 : "SOURCE_PRIMARIES_BLUE",
7415 : "SOURCE_WHITEPOINT",
7416 : "TIFFTAG_TRANSFERFUNCTION_RED",
7417 : "TIFFTAG_TRANSFERFUNCTION_GREEN",
7418 : "TIFFTAG_TRANSFERFUNCTION_BLUE",
7419 : "TIFFTAG_TRANSFERRANGE_BLACK",
7420 : "TIFFTAG_TRANSFERRANGE_WHITE",
7421 : nullptr};
7422 :
7423 : // Copy all the tags. Options will override tags in the source.
7424 2131 : int i = 0;
7425 23421 : while (pszOptionsMD[i] != nullptr)
7426 : {
7427 : char const *pszMD =
7428 21292 : CSLFetchNameValue(papszOptions, pszOptionsMD[i]);
7429 21292 : if (pszMD == nullptr)
7430 : pszMD =
7431 21284 : poSrcDS->GetMetadataItem(pszOptionsMD[i], "COLOR_PROFILE");
7432 :
7433 21292 : if ((pszMD != nullptr) && !EQUAL(pszMD, ""))
7434 : {
7435 16 : papszCreateOptions =
7436 16 : CSLSetNameValue(papszCreateOptions, pszOptionsMD[i], pszMD);
7437 :
7438 : // If an ICC profile exists, other tags are not needed.
7439 16 : if (EQUAL(pszOptionsMD[i], "SOURCE_ICC_PROFILE"))
7440 2 : break;
7441 : }
7442 :
7443 21290 : ++i;
7444 : }
7445 : }
7446 :
7447 2148 : double dfExtraSpaceForOverviews = 0;
7448 : const bool bCopySrcOverviews =
7449 2148 : CPLFetchBool(papszCreateOptions, "COPY_SRC_OVERVIEWS", false);
7450 2148 : std::unique_ptr<GDALDataset> poOvrDS;
7451 2148 : int nSrcOverviews = 0;
7452 2148 : if (bCopySrcOverviews)
7453 : {
7454 : const char *pszOvrDS =
7455 229 : CSLFetchNameValue(papszCreateOptions, "@OVERVIEW_DATASET");
7456 229 : if (pszOvrDS)
7457 : {
7458 : // Empty string is used by COG driver to indicate that we want
7459 : // to ignore source overviews.
7460 37 : if (!EQUAL(pszOvrDS, ""))
7461 : {
7462 35 : poOvrDS.reset(GDALDataset::Open(pszOvrDS));
7463 35 : if (!poOvrDS)
7464 : {
7465 0 : CSLDestroy(papszCreateOptions);
7466 0 : return nullptr;
7467 : }
7468 35 : if (poOvrDS->GetRasterCount() != l_nBands)
7469 : {
7470 0 : CSLDestroy(papszCreateOptions);
7471 0 : return nullptr;
7472 : }
7473 35 : nSrcOverviews =
7474 35 : poOvrDS->GetRasterBand(1)->GetOverviewCount() + 1;
7475 : }
7476 : }
7477 : else
7478 : {
7479 192 : nSrcOverviews = poSrcDS->GetRasterBand(1)->GetOverviewCount();
7480 : }
7481 :
7482 : // Limit number of overviews if specified
7483 : const char *pszOverviewCount =
7484 229 : CSLFetchNameValue(papszCreateOptions, "@OVERVIEW_COUNT");
7485 229 : if (pszOverviewCount)
7486 8 : nSrcOverviews =
7487 8 : std::max(0, std::min(nSrcOverviews, atoi(pszOverviewCount)));
7488 :
7489 229 : if (nSrcOverviews)
7490 : {
7491 204 : for (int j = 1; j <= l_nBands; ++j)
7492 : {
7493 : const int nOtherBandOverviewCount =
7494 134 : poOvrDS ? poOvrDS->GetRasterBand(j)->GetOverviewCount() + 1
7495 198 : : poSrcDS->GetRasterBand(j)->GetOverviewCount();
7496 134 : if (nOtherBandOverviewCount < nSrcOverviews)
7497 : {
7498 1 : ReportError(
7499 : pszFilename, CE_Failure, CPLE_NotSupported,
7500 : "COPY_SRC_OVERVIEWS cannot be used when the bands have "
7501 : "not the same number of overview levels.");
7502 1 : CSLDestroy(papszCreateOptions);
7503 1 : return nullptr;
7504 : }
7505 388 : for (int i = 0; i < nSrcOverviews; ++i)
7506 : {
7507 : GDALRasterBand *poOvrBand =
7508 : poOvrDS
7509 353 : ? (i == 0 ? poOvrDS->GetRasterBand(j)
7510 192 : : poOvrDS->GetRasterBand(j)->GetOverview(
7511 96 : i - 1))
7512 348 : : poSrcDS->GetRasterBand(j)->GetOverview(i);
7513 257 : if (poOvrBand == nullptr)
7514 : {
7515 1 : ReportError(
7516 : pszFilename, CE_Failure, CPLE_NotSupported,
7517 : "COPY_SRC_OVERVIEWS cannot be used when one "
7518 : "overview band is NULL.");
7519 1 : CSLDestroy(papszCreateOptions);
7520 1 : return nullptr;
7521 : }
7522 : GDALRasterBand *poOvrFirstBand =
7523 : poOvrDS
7524 352 : ? (i == 0 ? poOvrDS->GetRasterBand(1)
7525 192 : : poOvrDS->GetRasterBand(1)->GetOverview(
7526 96 : i - 1))
7527 346 : : poSrcDS->GetRasterBand(1)->GetOverview(i);
7528 511 : if (poOvrBand->GetXSize() != poOvrFirstBand->GetXSize() ||
7529 255 : poOvrBand->GetYSize() != poOvrFirstBand->GetYSize())
7530 : {
7531 1 : ReportError(
7532 : pszFilename, CE_Failure, CPLE_NotSupported,
7533 : "COPY_SRC_OVERVIEWS cannot be used when the "
7534 : "overview bands have not the same dimensions "
7535 : "among bands.");
7536 1 : CSLDestroy(papszCreateOptions);
7537 1 : return nullptr;
7538 : }
7539 : }
7540 : }
7541 :
7542 198 : for (int i = 0; i < nSrcOverviews; ++i)
7543 : {
7544 : GDALRasterBand *poOvrFirstBand =
7545 : poOvrDS
7546 201 : ? (i == 0
7547 73 : ? poOvrDS->GetRasterBand(1)
7548 38 : : poOvrDS->GetRasterBand(1)->GetOverview(i - 1))
7549 183 : : poSrcDS->GetRasterBand(1)->GetOverview(i);
7550 128 : dfExtraSpaceForOverviews +=
7551 128 : static_cast<double>(poOvrFirstBand->GetXSize()) *
7552 128 : poOvrFirstBand->GetYSize();
7553 : }
7554 70 : dfExtraSpaceForOverviews *=
7555 70 : l_nBands * GDALGetDataTypeSizeBytes(eType);
7556 : }
7557 : else
7558 : {
7559 156 : CPLDebug("GTiff", "No source overviews to copy");
7560 : }
7561 : }
7562 :
7563 : /* -------------------------------------------------------------------- */
7564 : /* Should we use optimized way of copying from an input JPEG */
7565 : /* dataset? */
7566 : /* -------------------------------------------------------------------- */
7567 :
7568 : // TODO(schwehr): Refactor bDirectCopyFromJPEG to be a const.
7569 : #if defined(HAVE_LIBJPEG) || defined(JPEG_DIRECT_COPY)
7570 2145 : bool bDirectCopyFromJPEG = false;
7571 : #endif
7572 :
7573 : // Note: JPEG_DIRECT_COPY is not defined by default, because it is mainly
7574 : // useful for debugging purposes.
7575 : #ifdef JPEG_DIRECT_COPY
7576 : if (CPLFetchBool(papszCreateOptions, "JPEG_DIRECT_COPY", false) &&
7577 : GTIFF_CanDirectCopyFromJPEG(poSrcDS, papszCreateOptions))
7578 : {
7579 : CPLDebug("GTiff", "Using special direct copy mode from a JPEG dataset");
7580 :
7581 : bDirectCopyFromJPEG = true;
7582 : }
7583 : #endif
7584 :
7585 : #ifdef HAVE_LIBJPEG
7586 2145 : bool bCopyFromJPEG = false;
7587 :
7588 : // When CreateCopy'ing() from a JPEG dataset, and asking for COMPRESS=JPEG,
7589 : // use DCT coefficients (unless other options are incompatible, like
7590 : // strip/tile dimensions, specifying JPEG_QUALITY option, incompatible
7591 : // PHOTOMETRIC with the source colorspace, etc.) to avoid the lossy steps
7592 : // involved by decompression/recompression.
7593 4290 : if (!bDirectCopyFromJPEG &&
7594 2145 : GTIFF_CanCopyFromJPEG(poSrcDS, papszCreateOptions))
7595 : {
7596 12 : CPLDebug("GTiff", "Using special copy mode from a JPEG dataset");
7597 :
7598 12 : bCopyFromJPEG = true;
7599 : }
7600 : #endif
7601 :
7602 : /* -------------------------------------------------------------------- */
7603 : /* If the source is RGB, then set the PHOTOMETRIC=RGB value */
7604 : /* -------------------------------------------------------------------- */
7605 :
7606 : const bool bForcePhotometric =
7607 2145 : CSLFetchNameValue(papszOptions, "PHOTOMETRIC") != nullptr;
7608 :
7609 1229 : if (l_nBands >= 3 && !bForcePhotometric &&
7610 : #ifdef HAVE_LIBJPEG
7611 1191 : !bCopyFromJPEG &&
7612 : #endif
7613 1185 : poSrcDS->GetRasterBand(1)->GetColorInterpretation() == GCI_RedBand &&
7614 4447 : poSrcDS->GetRasterBand(2)->GetColorInterpretation() == GCI_GreenBand &&
7615 1073 : poSrcDS->GetRasterBand(3)->GetColorInterpretation() == GCI_BlueBand)
7616 : {
7617 1067 : papszCreateOptions =
7618 1067 : CSLSetNameValue(papszCreateOptions, "PHOTOMETRIC", "RGB");
7619 : }
7620 :
7621 : /* -------------------------------------------------------------------- */
7622 : /* Create the file. */
7623 : /* -------------------------------------------------------------------- */
7624 2145 : VSILFILE *l_fpL = nullptr;
7625 4290 : CPLString l_osTmpFilename;
7626 :
7627 2145 : const int nXSize = poSrcDS->GetRasterXSize();
7628 2145 : const int nYSize = poSrcDS->GetRasterYSize();
7629 :
7630 : const int nColorTableMultiplier = std::max(
7631 4290 : 1,
7632 4290 : std::min(257,
7633 2145 : atoi(CSLFetchNameValueDef(
7634 : papszOptions, "COLOR_TABLE_MULTIPLIER",
7635 2145 : CPLSPrintf("%d", DEFAULT_COLOR_TABLE_MULTIPLIER_257)))));
7636 :
7637 2145 : bool bTileInterleaving = false;
7638 2145 : TIFF *l_hTIFF = CreateLL(pszFilename, nXSize, nYSize, l_nBands, eType,
7639 : dfExtraSpaceForOverviews, nColorTableMultiplier,
7640 : papszCreateOptions, &l_fpL, l_osTmpFilename,
7641 : /* bCreateCopy = */ true, bTileInterleaving);
7642 2145 : const bool bStreaming = !l_osTmpFilename.empty();
7643 :
7644 2145 : CSLDestroy(papszCreateOptions);
7645 2145 : papszCreateOptions = nullptr;
7646 :
7647 2145 : if (l_hTIFF == nullptr)
7648 : {
7649 18 : if (bStreaming)
7650 0 : VSIUnlink(l_osTmpFilename);
7651 18 : return nullptr;
7652 : }
7653 :
7654 2127 : uint16_t l_nPlanarConfig = 0;
7655 2127 : TIFFGetField(l_hTIFF, TIFFTAG_PLANARCONFIG, &l_nPlanarConfig);
7656 :
7657 2127 : uint16_t l_nCompression = 0;
7658 :
7659 2127 : if (!TIFFGetField(l_hTIFF, TIFFTAG_COMPRESSION, &(l_nCompression)))
7660 0 : l_nCompression = COMPRESSION_NONE;
7661 :
7662 : /* -------------------------------------------------------------------- */
7663 : /* Set the alpha channel if we find one. */
7664 : /* -------------------------------------------------------------------- */
7665 2127 : uint16_t *extraSamples = nullptr;
7666 2127 : uint16_t nExtraSamples = 0;
7667 2127 : if (TIFFGetField(l_hTIFF, TIFFTAG_EXTRASAMPLES, &nExtraSamples,
7668 2392 : &extraSamples) &&
7669 265 : nExtraSamples > 0)
7670 : {
7671 : // We need to allocate a new array as (current) libtiff
7672 : // versions will not like that we reuse the array we got from
7673 : // TIFFGetField().
7674 : uint16_t *pasNewExtraSamples = static_cast<uint16_t *>(
7675 265 : CPLMalloc(nExtraSamples * sizeof(uint16_t)));
7676 265 : memcpy(pasNewExtraSamples, extraSamples,
7677 265 : nExtraSamples * sizeof(uint16_t));
7678 265 : const char *pszAlpha = CPLGetConfigOption(
7679 : "GTIFF_ALPHA", CSLFetchNameValue(papszOptions, "ALPHA"));
7680 : const uint16_t nAlpha =
7681 265 : GTiffGetAlphaValue(pszAlpha, DEFAULT_ALPHA_TYPE);
7682 265 : const int nBaseSamples = l_nBands - nExtraSamples;
7683 895 : for (int iExtraBand = nBaseSamples + 1; iExtraBand <= l_nBands;
7684 : iExtraBand++)
7685 : {
7686 630 : if (poSrcDS->GetRasterBand(iExtraBand)->GetColorInterpretation() ==
7687 : GCI_AlphaBand)
7688 : {
7689 145 : pasNewExtraSamples[iExtraBand - nBaseSamples - 1] = nAlpha;
7690 145 : if (!pszAlpha)
7691 : {
7692 : // Use the ALPHA metadata item from the source band, when
7693 : // present, if no explicit ALPHA creation option
7694 286 : pasNewExtraSamples[iExtraBand - nBaseSamples - 1] =
7695 143 : GTiffGetAlphaValue(
7696 143 : poSrcDS->GetRasterBand(iExtraBand)
7697 143 : ->GetMetadataItem("ALPHA", "IMAGE_STRUCTURE"),
7698 : nAlpha);
7699 : }
7700 : }
7701 : }
7702 265 : TIFFSetField(l_hTIFF, TIFFTAG_EXTRASAMPLES, nExtraSamples,
7703 : pasNewExtraSamples);
7704 :
7705 265 : CPLFree(pasNewExtraSamples);
7706 : }
7707 :
7708 : /* -------------------------------------------------------------------- */
7709 : /* If the output is jpeg compressed, and the input is RGB make */
7710 : /* sure we note that. */
7711 : /* -------------------------------------------------------------------- */
7712 :
7713 2127 : if (l_nCompression == COMPRESSION_JPEG)
7714 : {
7715 134 : if (l_nBands >= 3 &&
7716 58 : (poSrcDS->GetRasterBand(1)->GetColorInterpretation() ==
7717 0 : GCI_YCbCr_YBand) &&
7718 0 : (poSrcDS->GetRasterBand(2)->GetColorInterpretation() ==
7719 134 : GCI_YCbCr_CbBand) &&
7720 0 : (poSrcDS->GetRasterBand(3)->GetColorInterpretation() ==
7721 : GCI_YCbCr_CrBand))
7722 : {
7723 : // Do nothing.
7724 : }
7725 : else
7726 : {
7727 : // Assume RGB if it is not explicitly YCbCr.
7728 76 : CPLDebug("GTiff", "Setting JPEGCOLORMODE_RGB");
7729 76 : TIFFSetField(l_hTIFF, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
7730 : }
7731 : }
7732 :
7733 : /* -------------------------------------------------------------------- */
7734 : /* Does the source image consist of one band, with a palette? */
7735 : /* If so, copy over. */
7736 : /* -------------------------------------------------------------------- */
7737 1315 : if ((l_nBands == 1 || l_nBands == 2) &&
7738 3442 : poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
7739 : eType == GDT_UInt8)
7740 : {
7741 21 : unsigned short anTRed[256] = {0};
7742 21 : unsigned short anTGreen[256] = {0};
7743 21 : unsigned short anTBlue[256] = {0};
7744 21 : GDALColorTable *poCT = poSrcDS->GetRasterBand(1)->GetColorTable();
7745 :
7746 5397 : for (int iColor = 0; iColor < 256; ++iColor)
7747 : {
7748 5376 : if (iColor < poCT->GetColorEntryCount())
7749 : {
7750 4241 : GDALColorEntry sRGB = {0, 0, 0, 0};
7751 :
7752 4241 : poCT->GetColorEntryAsRGB(iColor, &sRGB);
7753 :
7754 8482 : anTRed[iColor] = GTiffDataset::ClampCTEntry(
7755 4241 : iColor, 1, sRGB.c1, nColorTableMultiplier);
7756 8482 : anTGreen[iColor] = GTiffDataset::ClampCTEntry(
7757 4241 : iColor, 2, sRGB.c2, nColorTableMultiplier);
7758 4241 : anTBlue[iColor] = GTiffDataset::ClampCTEntry(
7759 4241 : iColor, 3, sRGB.c3, nColorTableMultiplier);
7760 : }
7761 : else
7762 : {
7763 1135 : anTRed[iColor] = 0;
7764 1135 : anTGreen[iColor] = 0;
7765 1135 : anTBlue[iColor] = 0;
7766 : }
7767 : }
7768 :
7769 21 : if (!bForcePhotometric)
7770 21 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
7771 21 : TIFFSetField(l_hTIFF, TIFFTAG_COLORMAP, anTRed, anTGreen, anTBlue);
7772 : }
7773 1314 : else if ((l_nBands == 1 || l_nBands == 2) &&
7774 3420 : poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
7775 : eType == GDT_UInt16)
7776 : {
7777 : unsigned short *panTRed = static_cast<unsigned short *>(
7778 1 : CPLMalloc(65536 * sizeof(unsigned short)));
7779 : unsigned short *panTGreen = static_cast<unsigned short *>(
7780 1 : CPLMalloc(65536 * sizeof(unsigned short)));
7781 : unsigned short *panTBlue = static_cast<unsigned short *>(
7782 1 : CPLMalloc(65536 * sizeof(unsigned short)));
7783 :
7784 1 : GDALColorTable *poCT = poSrcDS->GetRasterBand(1)->GetColorTable();
7785 :
7786 65537 : for (int iColor = 0; iColor < 65536; ++iColor)
7787 : {
7788 65536 : if (iColor < poCT->GetColorEntryCount())
7789 : {
7790 65536 : GDALColorEntry sRGB = {0, 0, 0, 0};
7791 :
7792 65536 : poCT->GetColorEntryAsRGB(iColor, &sRGB);
7793 :
7794 131072 : panTRed[iColor] = GTiffDataset::ClampCTEntry(
7795 65536 : iColor, 1, sRGB.c1, nColorTableMultiplier);
7796 131072 : panTGreen[iColor] = GTiffDataset::ClampCTEntry(
7797 65536 : iColor, 2, sRGB.c2, nColorTableMultiplier);
7798 65536 : panTBlue[iColor] = GTiffDataset::ClampCTEntry(
7799 65536 : iColor, 3, sRGB.c3, nColorTableMultiplier);
7800 : }
7801 : else
7802 : {
7803 0 : panTRed[iColor] = 0;
7804 0 : panTGreen[iColor] = 0;
7805 0 : panTBlue[iColor] = 0;
7806 : }
7807 : }
7808 :
7809 1 : if (!bForcePhotometric)
7810 1 : TIFFSetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
7811 1 : TIFFSetField(l_hTIFF, TIFFTAG_COLORMAP, panTRed, panTGreen, panTBlue);
7812 :
7813 1 : CPLFree(panTRed);
7814 1 : CPLFree(panTGreen);
7815 1 : CPLFree(panTBlue);
7816 : }
7817 2105 : else if (poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr)
7818 1 : ReportError(
7819 : pszFilename, CE_Failure, CPLE_AppDefined,
7820 : "Unable to export color table to GeoTIFF file. Color tables "
7821 : "can only be written to 1 band or 2 bands Byte or "
7822 : "UInt16 GeoTIFF files.");
7823 :
7824 2127 : if (l_nCompression == COMPRESSION_JPEG)
7825 : {
7826 76 : uint16_t l_nPhotometric = 0;
7827 76 : TIFFGetField(l_hTIFF, TIFFTAG_PHOTOMETRIC, &l_nPhotometric);
7828 : // Check done in tif_jpeg.c later, but not with a very clear error
7829 : // message
7830 76 : if (l_nPhotometric == PHOTOMETRIC_PALETTE)
7831 : {
7832 1 : ReportError(pszFilename, CE_Failure, CPLE_NotSupported,
7833 : "JPEG compression not supported with paletted image");
7834 1 : XTIFFClose(l_hTIFF);
7835 1 : VSIUnlink(l_osTmpFilename);
7836 1 : CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
7837 1 : return nullptr;
7838 : }
7839 : }
7840 :
7841 2213 : if (l_nBands == 2 &&
7842 2126 : poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
7843 0 : (eType == GDT_UInt8 || eType == GDT_UInt16))
7844 : {
7845 1 : uint16_t v[1] = {EXTRASAMPLE_UNASSALPHA};
7846 :
7847 1 : TIFFSetField(l_hTIFF, TIFFTAG_EXTRASAMPLES, 1, v);
7848 : }
7849 :
7850 2126 : const int nMaskFlags = poSrcDS->GetRasterBand(1)->GetMaskFlags();
7851 2126 : bool bCreateMask = false;
7852 4252 : CPLString osHiddenStructuralMD;
7853 : const char *pszInterleave =
7854 2126 : CSLFetchNameValueDef(papszOptions, "INTERLEAVE", "PIXEL");
7855 2349 : if (bCopySrcOverviews &&
7856 223 : CPLTestBool(CSLFetchNameValueDef(papszOptions, "TILED", "NO")))
7857 : {
7858 211 : osHiddenStructuralMD += "LAYOUT=IFDS_BEFORE_DATA\n";
7859 211 : osHiddenStructuralMD += "BLOCK_ORDER=ROW_MAJOR\n";
7860 211 : osHiddenStructuralMD += "BLOCK_LEADER=SIZE_AS_UINT4\n";
7861 211 : osHiddenStructuralMD += "BLOCK_TRAILER=LAST_4_BYTES_REPEATED\n";
7862 211 : if (l_nBands > 1 && !EQUAL(pszInterleave, "PIXEL"))
7863 : {
7864 21 : osHiddenStructuralMD += "INTERLEAVE=";
7865 21 : osHiddenStructuralMD += CPLString(pszInterleave).toupper();
7866 21 : osHiddenStructuralMD += "\n";
7867 : }
7868 : osHiddenStructuralMD +=
7869 211 : "KNOWN_INCOMPATIBLE_EDITION=NO\n "; // Final space intended, so
7870 : // this can be replaced by YES
7871 : }
7872 2126 : if (!(nMaskFlags & (GMF_ALL_VALID | GMF_ALPHA | GMF_NODATA)) &&
7873 42 : (nMaskFlags & GMF_PER_DATASET) && !bStreaming)
7874 : {
7875 38 : bCreateMask = true;
7876 38 : if (GTiffDataset::MustCreateInternalMask() &&
7877 38 : !osHiddenStructuralMD.empty() && EQUAL(pszInterleave, "PIXEL"))
7878 : {
7879 21 : osHiddenStructuralMD += "MASK_INTERLEAVED_WITH_IMAGERY=YES\n";
7880 : }
7881 : }
7882 2337 : if (!osHiddenStructuralMD.empty() &&
7883 211 : CPLTestBool(CPLGetConfigOption("GTIFF_WRITE_COG_GHOST_AREA", "YES")))
7884 : {
7885 210 : const int nHiddenMDSize = static_cast<int>(osHiddenStructuralMD.size());
7886 : osHiddenStructuralMD =
7887 210 : CPLOPrintf("GDAL_STRUCTURAL_METADATA_SIZE=%06d bytes\n",
7888 420 : nHiddenMDSize) +
7889 210 : osHiddenStructuralMD;
7890 210 : VSI_TIFFWrite(l_hTIFF, osHiddenStructuralMD.c_str(),
7891 : osHiddenStructuralMD.size());
7892 : }
7893 :
7894 : // FIXME? libtiff writes extended tags in the order they are specified
7895 : // and not in increasing order.
7896 :
7897 : /* -------------------------------------------------------------------- */
7898 : /* Transfer some TIFF specific metadata, if available. */
7899 : /* The return value will tell us if we need to try again later with*/
7900 : /* PAM because the profile doesn't allow to write some metadata */
7901 : /* as TIFF tag */
7902 : /* -------------------------------------------------------------------- */
7903 2126 : const bool bHasWrittenMDInGeotiffTAG = GTiffDataset::WriteMetadata(
7904 : poSrcDS, l_hTIFF, false, eProfile, pszFilename, papszOptions);
7905 :
7906 : /* -------------------------------------------------------------------- */
7907 : /* Write NoData value, if exist. */
7908 : /* -------------------------------------------------------------------- */
7909 2126 : if (eProfile == GTiffProfile::GDALGEOTIFF)
7910 : {
7911 2105 : int bSuccess = FALSE;
7912 2105 : GDALRasterBand *poFirstBand = poSrcDS->GetRasterBand(1);
7913 2105 : if (poFirstBand->GetRasterDataType() == GDT_Int64)
7914 : {
7915 4 : const auto nNoData = poFirstBand->GetNoDataValueAsInt64(&bSuccess);
7916 4 : if (bSuccess)
7917 1 : GTiffDataset::WriteNoDataValue(l_hTIFF, nNoData);
7918 : }
7919 2101 : else if (poFirstBand->GetRasterDataType() == GDT_UInt64)
7920 : {
7921 4 : const auto nNoData = poFirstBand->GetNoDataValueAsUInt64(&bSuccess);
7922 4 : if (bSuccess)
7923 1 : GTiffDataset::WriteNoDataValue(l_hTIFF, nNoData);
7924 : }
7925 : else
7926 : {
7927 2097 : const auto dfNoData = poFirstBand->GetNoDataValue(&bSuccess);
7928 2097 : if (bSuccess)
7929 145 : GTiffDataset::WriteNoDataValue(l_hTIFF, dfNoData);
7930 : }
7931 : }
7932 :
7933 : /* -------------------------------------------------------------------- */
7934 : /* Are we addressing PixelIsPoint mode? */
7935 : /* -------------------------------------------------------------------- */
7936 2126 : bool bPixelIsPoint = false;
7937 2126 : bool bPointGeoIgnore = false;
7938 :
7939 3565 : if (poSrcDS->GetMetadataItem(GDALMD_AREA_OR_POINT) &&
7940 1439 : EQUAL(poSrcDS->GetMetadataItem(GDALMD_AREA_OR_POINT), GDALMD_AOP_POINT))
7941 : {
7942 10 : bPixelIsPoint = true;
7943 : bPointGeoIgnore =
7944 10 : CPLTestBool(CPLGetConfigOption("GTIFF_POINT_GEO_IGNORE", "FALSE"));
7945 : }
7946 :
7947 : /* -------------------------------------------------------------------- */
7948 : /* Write affine transform if it is meaningful. */
7949 : /* -------------------------------------------------------------------- */
7950 2126 : const OGRSpatialReference *l_poSRS = nullptr;
7951 2126 : GDALGeoTransform l_gt;
7952 2126 : if (poSrcDS->GetGeoTransform(l_gt) == CE_None)
7953 : {
7954 1686 : if (bGeoTIFF)
7955 : {
7956 1681 : l_poSRS = poSrcDS->GetSpatialRef();
7957 :
7958 1681 : if (l_gt.xrot == 0.0 && l_gt.yrot == 0.0 && l_gt.yscale < 0.0)
7959 : {
7960 1673 : double dfOffset = 0.0;
7961 : {
7962 : // In the case the SRS has a vertical component and we have
7963 : // a single band, encode its scale/offset in the GeoTIFF
7964 : // tags
7965 1673 : int bHasScale = FALSE;
7966 : double dfScale =
7967 1673 : poSrcDS->GetRasterBand(1)->GetScale(&bHasScale);
7968 1673 : int bHasOffset = FALSE;
7969 : dfOffset =
7970 1673 : poSrcDS->GetRasterBand(1)->GetOffset(&bHasOffset);
7971 : const bool bApplyScaleOffset =
7972 1677 : l_poSRS && l_poSRS->IsVertical() &&
7973 4 : poSrcDS->GetRasterCount() == 1;
7974 1673 : if (bApplyScaleOffset && !bHasScale)
7975 0 : dfScale = 1.0;
7976 1673 : if (!bApplyScaleOffset || !bHasOffset)
7977 1669 : dfOffset = 0.0;
7978 : const double adfPixelScale[3] = {
7979 1673 : l_gt.xscale, fabs(l_gt.yscale),
7980 1673 : bApplyScaleOffset ? dfScale : 0.0};
7981 :
7982 1673 : TIFFSetField(l_hTIFF, TIFFTAG_GEOPIXELSCALE, 3,
7983 : adfPixelScale);
7984 : }
7985 :
7986 1673 : double adfTiePoints[6] = {0.0, 0.0, 0.0,
7987 1673 : l_gt.xorig, l_gt.yorig, dfOffset};
7988 :
7989 1673 : if (bPixelIsPoint && !bPointGeoIgnore)
7990 : {
7991 6 : adfTiePoints[3] += l_gt.xscale * 0.5 + l_gt.xrot * 0.5;
7992 6 : adfTiePoints[4] += l_gt.yrot * 0.5 + l_gt.yscale * 0.5;
7993 : }
7994 :
7995 1673 : TIFFSetField(l_hTIFF, TIFFTAG_GEOTIEPOINTS, 6, adfTiePoints);
7996 : }
7997 : else
7998 : {
7999 8 : double adfMatrix[16] = {0.0};
8000 :
8001 8 : adfMatrix[0] = l_gt.xscale;
8002 8 : adfMatrix[1] = l_gt.xrot;
8003 8 : adfMatrix[3] = l_gt.xorig;
8004 8 : adfMatrix[4] = l_gt.yrot;
8005 8 : adfMatrix[5] = l_gt.yscale;
8006 8 : adfMatrix[7] = l_gt.yorig;
8007 8 : adfMatrix[15] = 1.0;
8008 :
8009 8 : if (bPixelIsPoint && !bPointGeoIgnore)
8010 : {
8011 0 : adfMatrix[3] += l_gt.xscale * 0.5 + l_gt.xrot * 0.5;
8012 0 : adfMatrix[7] += l_gt.yrot * 0.5 + l_gt.yscale * 0.5;
8013 : }
8014 :
8015 8 : TIFFSetField(l_hTIFF, TIFFTAG_GEOTRANSMATRIX, 16, adfMatrix);
8016 : }
8017 : }
8018 :
8019 : /* --------------------------------------------------------------------
8020 : */
8021 : /* Do we need a TFW file? */
8022 : /* --------------------------------------------------------------------
8023 : */
8024 1686 : if (CPLFetchBool(papszOptions, "TFW", false))
8025 2 : GDALWriteWorldFile(pszFilename, "tfw", l_gt.data());
8026 1684 : else if (CPLFetchBool(papszOptions, "WORLDFILE", false))
8027 1 : GDALWriteWorldFile(pszFilename, "wld", l_gt.data());
8028 : }
8029 :
8030 : /* -------------------------------------------------------------------- */
8031 : /* Otherwise write tiepoints if they are available. */
8032 : /* -------------------------------------------------------------------- */
8033 440 : else if (poSrcDS->GetGCPCount() > 0 && bGeoTIFF)
8034 : {
8035 12 : const GDAL_GCP *pasGCPs = poSrcDS->GetGCPs();
8036 : double *padfTiePoints = static_cast<double *>(
8037 12 : CPLMalloc(6 * sizeof(double) * poSrcDS->GetGCPCount()));
8038 :
8039 60 : for (int iGCP = 0; iGCP < poSrcDS->GetGCPCount(); ++iGCP)
8040 : {
8041 :
8042 48 : padfTiePoints[iGCP * 6 + 0] = pasGCPs[iGCP].dfGCPPixel;
8043 48 : padfTiePoints[iGCP * 6 + 1] = pasGCPs[iGCP].dfGCPLine;
8044 48 : padfTiePoints[iGCP * 6 + 2] = 0;
8045 48 : padfTiePoints[iGCP * 6 + 3] = pasGCPs[iGCP].dfGCPX;
8046 48 : padfTiePoints[iGCP * 6 + 4] = pasGCPs[iGCP].dfGCPY;
8047 48 : padfTiePoints[iGCP * 6 + 5] = pasGCPs[iGCP].dfGCPZ;
8048 :
8049 48 : if (bPixelIsPoint && !bPointGeoIgnore)
8050 : {
8051 4 : padfTiePoints[iGCP * 6 + 0] -= 0.5;
8052 4 : padfTiePoints[iGCP * 6 + 1] -= 0.5;
8053 : }
8054 : }
8055 :
8056 12 : TIFFSetField(l_hTIFF, TIFFTAG_GEOTIEPOINTS, 6 * poSrcDS->GetGCPCount(),
8057 : padfTiePoints);
8058 12 : CPLFree(padfTiePoints);
8059 :
8060 12 : l_poSRS = poSrcDS->GetGCPSpatialRef();
8061 :
8062 24 : if (CPLFetchBool(papszOptions, "TFW", false) ||
8063 12 : CPLFetchBool(papszOptions, "WORLDFILE", false))
8064 : {
8065 0 : ReportError(
8066 : pszFilename, CE_Warning, CPLE_AppDefined,
8067 : "TFW=ON or WORLDFILE=ON creation options are ignored when "
8068 : "GCPs are available");
8069 : }
8070 : }
8071 : else
8072 : {
8073 428 : l_poSRS = poSrcDS->GetSpatialRef();
8074 : }
8075 :
8076 : /* -------------------------------------------------------------------- */
8077 : /* Copy xml:XMP data */
8078 : /* -------------------------------------------------------------------- */
8079 2126 : CSLConstList papszXMP = poSrcDS->GetMetadata("xml:XMP");
8080 2126 : if (papszXMP != nullptr && *papszXMP != nullptr)
8081 : {
8082 9 : int nTagSize = static_cast<int>(strlen(*papszXMP));
8083 9 : TIFFSetField(l_hTIFF, TIFFTAG_XMLPACKET, nTagSize, *papszXMP);
8084 : }
8085 :
8086 : /* -------------------------------------------------------------------- */
8087 : /* Write the projection information, if possible. */
8088 : /* -------------------------------------------------------------------- */
8089 2126 : const bool bHasProjection = l_poSRS != nullptr;
8090 2126 : bool bExportSRSToPAM = false;
8091 2126 : if ((bHasProjection || bPixelIsPoint) && bGeoTIFF)
8092 : {
8093 1659 : GTIF *psGTIF = GTiffDataset::GTIFNew(l_hTIFF);
8094 :
8095 1659 : if (bHasProjection)
8096 : {
8097 1659 : const auto eGeoTIFFKeysFlavor = GetGTIFFKeysFlavor(papszOptions);
8098 1659 : if (IsSRSCompatibleOfGeoTIFF(l_poSRS, eGeoTIFFKeysFlavor))
8099 : {
8100 1659 : GTIFSetFromOGISDefnEx(
8101 : psGTIF,
8102 : OGRSpatialReference::ToHandle(
8103 : const_cast<OGRSpatialReference *>(l_poSRS)),
8104 : eGeoTIFFKeysFlavor, GetGeoTIFFVersion(papszOptions));
8105 : }
8106 : else
8107 : {
8108 0 : bExportSRSToPAM = true;
8109 : }
8110 : }
8111 :
8112 1659 : if (bPixelIsPoint)
8113 : {
8114 10 : GTIFKeySet(psGTIF, GTRasterTypeGeoKey, TYPE_SHORT, 1,
8115 : RasterPixelIsPoint);
8116 : }
8117 :
8118 1659 : GTIFWriteKeys(psGTIF);
8119 1659 : GTIFFree(psGTIF);
8120 : }
8121 :
8122 2126 : bool l_bDontReloadFirstBlock = false;
8123 :
8124 : #ifdef HAVE_LIBJPEG
8125 2126 : if (bCopyFromJPEG)
8126 : {
8127 12 : GTIFF_CopyFromJPEG_WriteAdditionalTags(l_hTIFF, poSrcDS);
8128 : }
8129 : #endif
8130 :
8131 : /* -------------------------------------------------------------------- */
8132 : /* Cleanup */
8133 : /* -------------------------------------------------------------------- */
8134 2126 : if (bCopySrcOverviews)
8135 : {
8136 223 : TIFFDeferStrileArrayWriting(l_hTIFF);
8137 : }
8138 2126 : TIFFWriteCheck(l_hTIFF, TIFFIsTiled(l_hTIFF), "GTiffCreateCopy()");
8139 2126 : TIFFWriteDirectory(l_hTIFF);
8140 2126 : if (bStreaming)
8141 : {
8142 : // We need to write twice the directory to be sure that custom
8143 : // TIFF tags are correctly sorted and that padding bytes have been
8144 : // added.
8145 5 : TIFFSetDirectory(l_hTIFF, 0);
8146 5 : TIFFWriteDirectory(l_hTIFF);
8147 :
8148 5 : if (VSIFSeekL(l_fpL, 0, SEEK_END) != 0)
8149 0 : ReportError(pszFilename, CE_Failure, CPLE_FileIO, "Cannot seek");
8150 5 : const int nSize = static_cast<int>(VSIFTellL(l_fpL));
8151 :
8152 5 : vsi_l_offset nDataLength = 0;
8153 5 : VSIGetMemFileBuffer(l_osTmpFilename, &nDataLength, FALSE);
8154 5 : TIFFSetDirectory(l_hTIFF, 0);
8155 5 : GTiffFillStreamableOffsetAndCount(l_hTIFF, nSize);
8156 5 : TIFFWriteDirectory(l_hTIFF);
8157 : }
8158 2126 : const auto nDirCount = TIFFNumberOfDirectories(l_hTIFF);
8159 2126 : if (nDirCount >= 1)
8160 : {
8161 2119 : TIFFSetDirectory(l_hTIFF, static_cast<tdir_t>(nDirCount - 1));
8162 : }
8163 2126 : const toff_t l_nDirOffset = TIFFCurrentDirOffset(l_hTIFF);
8164 2126 : TIFFFlush(l_hTIFF);
8165 2126 : XTIFFClose(l_hTIFF);
8166 :
8167 2126 : VSIFSeekL(l_fpL, 0, SEEK_SET);
8168 :
8169 : // fpStreaming will assigned to the instance and not closed here.
8170 2126 : VSILFILE *fpStreaming = nullptr;
8171 2126 : if (bStreaming)
8172 : {
8173 5 : vsi_l_offset nDataLength = 0;
8174 : void *pabyBuffer =
8175 5 : VSIGetMemFileBuffer(l_osTmpFilename, &nDataLength, FALSE);
8176 5 : fpStreaming = VSIFOpenL(pszFilename, "wb");
8177 5 : if (fpStreaming == nullptr)
8178 : {
8179 1 : VSIUnlink(l_osTmpFilename);
8180 1 : CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
8181 1 : return nullptr;
8182 : }
8183 4 : if (static_cast<vsi_l_offset>(VSIFWriteL(pabyBuffer, 1,
8184 : static_cast<int>(nDataLength),
8185 4 : fpStreaming)) != nDataLength)
8186 : {
8187 0 : ReportError(pszFilename, CE_Failure, CPLE_FileIO,
8188 : "Could not write %d bytes",
8189 : static_cast<int>(nDataLength));
8190 0 : CPL_IGNORE_RET_VAL(VSIFCloseL(fpStreaming));
8191 0 : VSIUnlink(l_osTmpFilename);
8192 0 : CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
8193 0 : return nullptr;
8194 : }
8195 : }
8196 :
8197 : /* -------------------------------------------------------------------- */
8198 : /* Re-open as a dataset and copy over missing metadata using */
8199 : /* PAM facilities. */
8200 : /* -------------------------------------------------------------------- */
8201 2125 : l_hTIFF = VSI_TIFFOpen(bStreaming ? l_osTmpFilename.c_str() : pszFilename,
8202 : "r+", l_fpL);
8203 2125 : if (l_hTIFF == nullptr)
8204 : {
8205 11 : if (bStreaming)
8206 0 : VSIUnlink(l_osTmpFilename);
8207 11 : l_fpL->CancelCreation();
8208 11 : CPL_IGNORE_RET_VAL(VSIFCloseL(l_fpL));
8209 11 : return nullptr;
8210 : }
8211 :
8212 : /* -------------------------------------------------------------------- */
8213 : /* Create a corresponding GDALDataset. */
8214 : /* -------------------------------------------------------------------- */
8215 4228 : auto poDS = std::make_unique<GTiffDataset>();
8216 : const bool bSuppressASAP =
8217 2114 : CPLTestBool(CSLFetchNameValueDef(papszOptions, "@SUPPRESS_ASAP", "NO"));
8218 2114 : if (bSuppressASAP)
8219 4 : poDS->MarkSuppressOnClose();
8220 2114 : poDS->SetDescription(pszFilename);
8221 2114 : poDS->eAccess = GA_Update;
8222 2114 : poDS->m_osFilename = pszFilename;
8223 2114 : poDS->m_fpL = l_fpL;
8224 2114 : poDS->m_bIMDRPCMetadataLoaded = true;
8225 2114 : poDS->m_nColorTableMultiplier = nColorTableMultiplier;
8226 2114 : poDS->m_bTileInterleave = bTileInterleaving;
8227 :
8228 2114 : if (bTileInterleaving)
8229 : {
8230 7 : poDS->m_oGTiffMDMD.SetMetadataItem("INTERLEAVE", "TILE",
8231 : "IMAGE_STRUCTURE");
8232 : }
8233 :
8234 2114 : const bool bAppend = CPLFetchBool(papszOptions, "APPEND_SUBDATASET", false);
8235 4227 : if (poDS->OpenOffset(l_hTIFF,
8236 2113 : bAppend ? l_nDirOffset : TIFFCurrentDirOffset(l_hTIFF),
8237 : GA_Update,
8238 : false, // bAllowRGBAInterface
8239 : true // bReadGeoTransform
8240 2114 : ) != CE_None)
8241 : {
8242 0 : l_fpL->CancelCreation();
8243 0 : poDS.reset();
8244 0 : if (bStreaming)
8245 0 : VSIUnlink(l_osTmpFilename);
8246 0 : return nullptr;
8247 : }
8248 :
8249 : // Legacy... Patch back GDT_Int8 type to GDT_UInt8 if the user used
8250 : // PIXELTYPE=SIGNEDBYTE
8251 2114 : const char *pszPixelType = CSLFetchNameValue(papszOptions, "PIXELTYPE");
8252 2114 : if (pszPixelType == nullptr)
8253 2109 : pszPixelType = "";
8254 2114 : if (eType == GDT_UInt8 && EQUAL(pszPixelType, "SIGNEDBYTE"))
8255 : {
8256 10 : for (int i = 0; i < poDS->nBands; ++i)
8257 : {
8258 5 : auto poBand = static_cast<GTiffRasterBand *>(poDS->papoBands[i]);
8259 5 : poBand->eDataType = GDT_UInt8;
8260 5 : poBand->EnablePixelTypeSignedByteWarning(false);
8261 5 : poBand->SetMetadataItem("PIXELTYPE", "SIGNEDBYTE",
8262 : "IMAGE_STRUCTURE");
8263 5 : poBand->EnablePixelTypeSignedByteWarning(true);
8264 : }
8265 : }
8266 :
8267 2114 : poDS->oOvManager.Initialize(poDS.get(), pszFilename);
8268 :
8269 2114 : if (bStreaming)
8270 : {
8271 4 : VSIUnlink(l_osTmpFilename);
8272 4 : poDS->m_fpToWrite = fpStreaming;
8273 : }
8274 2114 : poDS->m_eProfile = eProfile;
8275 :
8276 2114 : int nCloneInfoFlags = GCIF_PAM_DEFAULT & ~GCIF_MASK;
8277 :
8278 : // If we explicitly asked not to tag the alpha band as such, do not
8279 : // reintroduce this alpha color interpretation in PAM.
8280 2114 : if (poSrcDS->GetRasterBand(l_nBands)->GetColorInterpretation() ==
8281 2242 : GCI_AlphaBand &&
8282 128 : GTiffGetAlphaValue(
8283 : CPLGetConfigOption("GTIFF_ALPHA",
8284 : CSLFetchNameValue(papszOptions, "ALPHA")),
8285 : DEFAULT_ALPHA_TYPE) == EXTRASAMPLE_UNSPECIFIED)
8286 : {
8287 1 : nCloneInfoFlags &= ~GCIF_COLORINTERP;
8288 : }
8289 : // Ignore source band color interpretation if requesting PHOTOMETRIC=RGB
8290 3339 : else if (l_nBands >= 3 &&
8291 1226 : EQUAL(CSLFetchNameValueDef(papszOptions, "PHOTOMETRIC", ""),
8292 : "RGB"))
8293 : {
8294 28 : for (int i = 1; i <= 3; i++)
8295 : {
8296 21 : poDS->GetRasterBand(i)->SetColorInterpretation(
8297 21 : static_cast<GDALColorInterp>(GCI_RedBand + (i - 1)));
8298 : }
8299 7 : nCloneInfoFlags &= ~GCIF_COLORINTERP;
8300 9 : if (!(l_nBands == 4 &&
8301 2 : CSLFetchNameValue(papszOptions, "ALPHA") != nullptr))
8302 : {
8303 15 : for (int i = 4; i <= l_nBands; i++)
8304 : {
8305 18 : poDS->GetRasterBand(i)->SetColorInterpretation(
8306 9 : poSrcDS->GetRasterBand(i)->GetColorInterpretation());
8307 : }
8308 : }
8309 : }
8310 :
8311 : CPLString osOldGTIFF_REPORT_COMPD_CSVal(
8312 4228 : CPLGetConfigOption("GTIFF_REPORT_COMPD_CS", ""));
8313 2114 : CPLSetThreadLocalConfigOption("GTIFF_REPORT_COMPD_CS", "YES");
8314 2114 : poDS->CloneInfo(poSrcDS, nCloneInfoFlags);
8315 2114 : CPLSetThreadLocalConfigOption("GTIFF_REPORT_COMPD_CS",
8316 2114 : osOldGTIFF_REPORT_COMPD_CSVal.empty()
8317 : ? nullptr
8318 0 : : osOldGTIFF_REPORT_COMPD_CSVal.c_str());
8319 :
8320 2131 : if ((!bGeoTIFF || bExportSRSToPAM) &&
8321 17 : (poDS->GetPamFlags() & GPF_DISABLED) == 0)
8322 : {
8323 : // Copy georeferencing info to PAM if the profile is not GeoTIFF
8324 16 : poDS->GDALPamDataset::SetSpatialRef(poDS->GetSpatialRef());
8325 16 : GDALGeoTransform gt;
8326 16 : if (poDS->GetGeoTransform(gt) == CE_None)
8327 : {
8328 5 : poDS->GDALPamDataset::SetGeoTransform(gt);
8329 : }
8330 16 : poDS->GDALPamDataset::SetGCPs(poDS->GetGCPCount(), poDS->GetGCPs(),
8331 : poDS->GetGCPSpatialRef());
8332 : }
8333 :
8334 2114 : poDS->m_papszCreationOptions = CSLDuplicate(papszOptions);
8335 2114 : poDS->m_bDontReloadFirstBlock = l_bDontReloadFirstBlock;
8336 :
8337 : /* -------------------------------------------------------------------- */
8338 : /* CloneInfo() does not merge metadata, it just replaces it */
8339 : /* totally. So we have to merge it. */
8340 : /* -------------------------------------------------------------------- */
8341 :
8342 2114 : CSLConstList papszSRC_MD = poSrcDS->GetMetadata();
8343 2114 : char **papszDST_MD = CSLDuplicate(poDS->GetMetadata());
8344 :
8345 2114 : papszDST_MD = CSLMerge(papszDST_MD, papszSRC_MD);
8346 :
8347 2114 : poDS->SetMetadata(papszDST_MD);
8348 2114 : CSLDestroy(papszDST_MD);
8349 :
8350 : // Depending on the PHOTOMETRIC tag, the TIFF file may not have the same
8351 : // band count as the source. Will fail later in GDALDatasetCopyWholeRaster
8352 : // anyway.
8353 7151 : for (int nBand = 1;
8354 7151 : nBand <= std::min(poDS->GetRasterCount(), poSrcDS->GetRasterCount());
8355 : ++nBand)
8356 : {
8357 5037 : GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand(nBand);
8358 5037 : GDALRasterBand *poDstBand = poDS->GetRasterBand(nBand);
8359 5037 : papszSRC_MD = poSrcBand->GetMetadata();
8360 5037 : papszDST_MD = CSLDuplicate(poDstBand->GetMetadata());
8361 :
8362 5037 : papszDST_MD = CSLMerge(papszDST_MD, papszSRC_MD);
8363 :
8364 5037 : poDstBand->SetMetadata(papszDST_MD);
8365 5037 : CSLDestroy(papszDST_MD);
8366 :
8367 5037 : char **papszCatNames = poSrcBand->GetCategoryNames();
8368 5037 : if (nullptr != papszCatNames)
8369 0 : poDstBand->SetCategoryNames(papszCatNames);
8370 : }
8371 :
8372 2114 : l_hTIFF = static_cast<TIFF *>(poDS->GetInternalHandle("TIFF_HANDLE"));
8373 :
8374 : /* -------------------------------------------------------------------- */
8375 : /* Handle forcing xml:ESRI data to be written to PAM. */
8376 : /* -------------------------------------------------------------------- */
8377 2114 : if (CPLTestBool(CPLGetConfigOption("ESRI_XML_PAM", "NO")))
8378 : {
8379 1 : CSLConstList papszESRIMD = poSrcDS->GetMetadata("xml:ESRI");
8380 1 : if (papszESRIMD)
8381 : {
8382 1 : poDS->SetMetadata(papszESRIMD, "xml:ESRI");
8383 : }
8384 : }
8385 :
8386 : /* -------------------------------------------------------------------- */
8387 : /* Second chance: now that we have a PAM dataset, it is possible */
8388 : /* to write metadata that we could not write as a TIFF tag. */
8389 : /* -------------------------------------------------------------------- */
8390 2114 : if (!bHasWrittenMDInGeotiffTAG && !bStreaming)
8391 : {
8392 6 : GTiffDataset::WriteMetadata(
8393 6 : poDS.get(), l_hTIFF, true, eProfile, pszFilename, papszOptions,
8394 : true /* don't write RPC and IMD file again */);
8395 : }
8396 :
8397 2114 : if (!bStreaming)
8398 2110 : GTiffDataset::WriteRPC(poDS.get(), l_hTIFF, true, eProfile, pszFilename,
8399 : papszOptions,
8400 : true /* write only in PAM AND if needed */);
8401 :
8402 2114 : poDS->m_bWriteCOGLayout = bCopySrcOverviews;
8403 :
8404 : // To avoid unnecessary directory rewriting.
8405 2114 : poDS->m_bMetadataChanged = false;
8406 2114 : poDS->m_bGeoTIFFInfoChanged = false;
8407 2114 : poDS->m_bNoDataChanged = false;
8408 2114 : poDS->m_bForceUnsetGTOrGCPs = false;
8409 2114 : poDS->m_bForceUnsetProjection = false;
8410 2114 : poDS->m_bStreamingOut = bStreaming;
8411 :
8412 : // Don't try to load external metadata files (#6597).
8413 2114 : poDS->m_bIMDRPCMetadataLoaded = true;
8414 :
8415 : // We must re-set the compression level at this point, since it has been
8416 : // lost a few lines above when closing the newly create TIFF file The
8417 : // TIFFTAG_ZIPQUALITY & TIFFTAG_JPEGQUALITY are not store in the TIFF file.
8418 : // They are just TIFF session parameters.
8419 :
8420 2114 : poDS->m_nZLevel = GTiffGetZLevel(papszOptions);
8421 2114 : poDS->m_nLZMAPreset = GTiffGetLZMAPreset(papszOptions);
8422 2114 : poDS->m_nZSTDLevel = GTiffGetZSTDPreset(papszOptions);
8423 2114 : poDS->m_nWebPLevel = GTiffGetWebPLevel(papszOptions);
8424 2114 : poDS->m_bWebPLossless = GTiffGetWebPLossless(papszOptions);
8425 2117 : if (poDS->m_nWebPLevel != 100 && poDS->m_bWebPLossless &&
8426 3 : CSLFetchNameValue(papszOptions, "WEBP_LEVEL"))
8427 : {
8428 0 : CPLError(CE_Warning, CPLE_AppDefined,
8429 : "WEBP_LEVEL is specified, but WEBP_LOSSLESS=YES. "
8430 : "WEBP_LEVEL will be ignored.");
8431 : }
8432 2114 : poDS->m_nJpegQuality = GTiffGetJpegQuality(papszOptions);
8433 2114 : poDS->m_nJpegTablesMode = GTiffGetJpegTablesMode(papszOptions);
8434 2114 : poDS->GetDiscardLsbOption(papszOptions);
8435 2114 : poDS->m_dfMaxZError = GTiffGetLERCMaxZError(papszOptions);
8436 2114 : poDS->m_dfMaxZErrorOverview = GTiffGetLERCMaxZErrorOverview(papszOptions);
8437 : #if HAVE_JXL
8438 2114 : poDS->m_bJXLLossless = GTiffGetJXLLossless(papszOptions);
8439 2114 : poDS->m_nJXLEffort = GTiffGetJXLEffort(papszOptions);
8440 2114 : poDS->m_fJXLDistance = GTiffGetJXLDistance(papszOptions);
8441 2114 : poDS->m_fJXLAlphaDistance = GTiffGetJXLAlphaDistance(papszOptions);
8442 : #endif
8443 2114 : poDS->InitCreationOrOpenOptions(true, papszOptions);
8444 :
8445 2114 : if (l_nCompression == COMPRESSION_ADOBE_DEFLATE ||
8446 2086 : l_nCompression == COMPRESSION_LERC)
8447 : {
8448 99 : GTiffSetDeflateSubCodec(l_hTIFF);
8449 :
8450 99 : if (poDS->m_nZLevel != -1)
8451 : {
8452 12 : TIFFSetField(l_hTIFF, TIFFTAG_ZIPQUALITY, poDS->m_nZLevel);
8453 : }
8454 : }
8455 2114 : if (l_nCompression == COMPRESSION_JPEG)
8456 : {
8457 75 : if (poDS->m_nJpegQuality != -1)
8458 : {
8459 9 : TIFFSetField(l_hTIFF, TIFFTAG_JPEGQUALITY, poDS->m_nJpegQuality);
8460 : }
8461 75 : TIFFSetField(l_hTIFF, TIFFTAG_JPEGTABLESMODE, poDS->m_nJpegTablesMode);
8462 : }
8463 2114 : if (l_nCompression == COMPRESSION_LZMA)
8464 : {
8465 7 : if (poDS->m_nLZMAPreset != -1)
8466 : {
8467 6 : TIFFSetField(l_hTIFF, TIFFTAG_LZMAPRESET, poDS->m_nLZMAPreset);
8468 : }
8469 : }
8470 2114 : if (l_nCompression == COMPRESSION_ZSTD ||
8471 2103 : l_nCompression == COMPRESSION_LERC)
8472 : {
8473 82 : if (poDS->m_nZSTDLevel != -1)
8474 : {
8475 8 : TIFFSetField(l_hTIFF, TIFFTAG_ZSTD_LEVEL, poDS->m_nZSTDLevel);
8476 : }
8477 : }
8478 2114 : if (l_nCompression == COMPRESSION_LERC)
8479 : {
8480 71 : TIFFSetField(l_hTIFF, TIFFTAG_LERC_MAXZERROR, poDS->m_dfMaxZError);
8481 : }
8482 : #if HAVE_JXL
8483 2114 : if (l_nCompression == COMPRESSION_JXL ||
8484 2114 : l_nCompression == COMPRESSION_JXL_DNG_1_7)
8485 : {
8486 91 : TIFFSetField(l_hTIFF, TIFFTAG_JXL_LOSSYNESS,
8487 91 : poDS->m_bJXLLossless ? JXL_LOSSLESS : JXL_LOSSY);
8488 91 : TIFFSetField(l_hTIFF, TIFFTAG_JXL_EFFORT, poDS->m_nJXLEffort);
8489 91 : TIFFSetField(l_hTIFF, TIFFTAG_JXL_DISTANCE,
8490 91 : static_cast<double>(poDS->m_fJXLDistance));
8491 91 : TIFFSetField(l_hTIFF, TIFFTAG_JXL_ALPHA_DISTANCE,
8492 91 : static_cast<double>(poDS->m_fJXLAlphaDistance));
8493 : }
8494 : #endif
8495 2114 : if (l_nCompression == COMPRESSION_WEBP)
8496 : {
8497 14 : if (poDS->m_nWebPLevel != -1)
8498 : {
8499 14 : TIFFSetField(l_hTIFF, TIFFTAG_WEBP_LEVEL, poDS->m_nWebPLevel);
8500 : }
8501 :
8502 14 : if (poDS->m_bWebPLossless)
8503 : {
8504 5 : TIFFSetField(l_hTIFF, TIFFTAG_WEBP_LOSSLESS, poDS->m_bWebPLossless);
8505 : }
8506 : }
8507 :
8508 : /* -------------------------------------------------------------------- */
8509 : /* Do we want to ensure all blocks get written out on close to */
8510 : /* avoid sparse files? */
8511 : /* -------------------------------------------------------------------- */
8512 2114 : if (!CPLFetchBool(papszOptions, "SPARSE_OK", false))
8513 2086 : poDS->m_bFillEmptyTilesAtClosing = true;
8514 :
8515 2114 : poDS->m_bWriteEmptyTiles =
8516 4009 : (bCopySrcOverviews && poDS->m_bFillEmptyTilesAtClosing) || bStreaming ||
8517 1895 : (poDS->m_nCompression != COMPRESSION_NONE &&
8518 310 : poDS->m_bFillEmptyTilesAtClosing);
8519 : // Only required for people writing non-compressed striped files in the
8520 : // rightorder and wanting all tstrips to be written in the same order
8521 : // so that the end result can be memory mapped without knowledge of each
8522 : // strip offset
8523 2114 : if (CPLTestBool(CSLFetchNameValueDef(
8524 4228 : papszOptions, "WRITE_EMPTY_TILES_SYNCHRONOUSLY", "FALSE")) ||
8525 2114 : CPLTestBool(CSLFetchNameValueDef(
8526 : papszOptions, "@WRITE_EMPTY_TILES_SYNCHRONOUSLY", "FALSE")))
8527 : {
8528 0 : poDS->m_bWriteEmptyTiles = true;
8529 : }
8530 :
8531 : // Precreate (internal) mask, so that the IBuildOverviews() below
8532 : // has a chance to create also the overviews of the mask.
8533 2114 : CPLErr eErr = CE_None;
8534 :
8535 2114 : if (bCreateMask)
8536 : {
8537 38 : eErr = poDS->CreateMaskBand(nMaskFlags);
8538 38 : if (poDS->m_poMaskDS)
8539 : {
8540 37 : poDS->m_poMaskDS->m_bFillEmptyTilesAtClosing =
8541 37 : poDS->m_bFillEmptyTilesAtClosing;
8542 37 : poDS->m_poMaskDS->m_bWriteEmptyTiles = poDS->m_bWriteEmptyTiles;
8543 : }
8544 : }
8545 :
8546 : /* -------------------------------------------------------------------- */
8547 : /* Create and then copy existing overviews if requested */
8548 : /* We do it such that all the IFDs are at the beginning of the file, */
8549 : /* and that the imagery data for the smallest overview is written */
8550 : /* first, that way the file is more usable when embedded in a */
8551 : /* compressed stream. */
8552 : /* -------------------------------------------------------------------- */
8553 :
8554 : // For scaled progress due to overview copying.
8555 2114 : const int nBandsWidthMask = l_nBands + (bCreateMask ? 1 : 0);
8556 2114 : double dfTotalPixels =
8557 2114 : static_cast<double>(nXSize) * nYSize * nBandsWidthMask;
8558 2114 : double dfCurPixels = 0;
8559 :
8560 2114 : if (eErr == CE_None && bCopySrcOverviews)
8561 : {
8562 0 : std::unique_ptr<GDALDataset> poMaskOvrDS;
8563 : const char *pszMaskOvrDS =
8564 220 : CSLFetchNameValue(papszOptions, "@MASK_OVERVIEW_DATASET");
8565 220 : if (pszMaskOvrDS)
8566 : {
8567 6 : poMaskOvrDS.reset(GDALDataset::Open(pszMaskOvrDS));
8568 6 : if (!poMaskOvrDS)
8569 : {
8570 0 : l_fpL->CancelCreation();
8571 0 : return nullptr;
8572 : }
8573 6 : if (poMaskOvrDS->GetRasterCount() != 1)
8574 : {
8575 0 : l_fpL->CancelCreation();
8576 0 : return nullptr;
8577 : }
8578 : }
8579 220 : if (nSrcOverviews)
8580 : {
8581 69 : eErr = poDS->CreateOverviewsFromSrcOverviews(poSrcDS, poOvrDS.get(),
8582 : nSrcOverviews);
8583 :
8584 201 : if (eErr == CE_None &&
8585 69 : (poMaskOvrDS != nullptr ||
8586 63 : (poSrcDS->GetRasterBand(1)->GetOverview(0) &&
8587 35 : poSrcDS->GetRasterBand(1)->GetOverview(0)->GetMaskFlags() ==
8588 : GMF_PER_DATASET)))
8589 : {
8590 19 : int nOvrBlockXSize = 0;
8591 19 : int nOvrBlockYSize = 0;
8592 19 : GTIFFGetOverviewBlockSize(
8593 19 : GDALRasterBand::ToHandle(poDS->GetRasterBand(1)),
8594 : &nOvrBlockXSize, &nOvrBlockYSize, nullptr, nullptr);
8595 19 : eErr = poDS->CreateInternalMaskOverviews(nOvrBlockXSize,
8596 : nOvrBlockYSize);
8597 : }
8598 : }
8599 :
8600 220 : TIFFForceStrileArrayWriting(poDS->m_hTIFF);
8601 :
8602 220 : if (poDS->m_poMaskDS)
8603 : {
8604 27 : TIFFForceStrileArrayWriting(poDS->m_poMaskDS->m_hTIFF);
8605 : }
8606 :
8607 346 : for (auto &poIterOvrDS : poDS->m_apoOverviewDS)
8608 : {
8609 126 : TIFFForceStrileArrayWriting(poIterOvrDS->m_hTIFF);
8610 :
8611 126 : if (poIterOvrDS->m_poMaskDS)
8612 : {
8613 32 : TIFFForceStrileArrayWriting(poIterOvrDS->m_poMaskDS->m_hTIFF);
8614 : }
8615 : }
8616 :
8617 220 : if (eErr == CE_None && nSrcOverviews)
8618 : {
8619 69 : if (poDS->m_apoOverviewDS.size() !=
8620 69 : static_cast<size_t>(nSrcOverviews))
8621 : {
8622 0 : ReportError(
8623 : pszFilename, CE_Failure, CPLE_AppDefined,
8624 : "Did only manage to instantiate %d overview levels, "
8625 : "whereas source contains %d",
8626 0 : static_cast<int>(poDS->m_apoOverviewDS.size()),
8627 : nSrcOverviews);
8628 0 : eErr = CE_Failure;
8629 : }
8630 :
8631 195 : for (int i = 0; eErr == CE_None && i < nSrcOverviews; ++i)
8632 : {
8633 : GDALRasterBand *poOvrBand =
8634 : poOvrDS
8635 197 : ? (i == 0
8636 71 : ? poOvrDS->GetRasterBand(1)
8637 37 : : poOvrDS->GetRasterBand(1)->GetOverview(i - 1))
8638 181 : : poSrcDS->GetRasterBand(1)->GetOverview(i);
8639 : const double dfOvrPixels =
8640 126 : static_cast<double>(poOvrBand->GetXSize()) *
8641 126 : poOvrBand->GetYSize();
8642 126 : dfTotalPixels += dfOvrPixels * l_nBands;
8643 234 : if (poOvrBand->GetMaskFlags() == GMF_PER_DATASET ||
8644 108 : poMaskOvrDS != nullptr)
8645 : {
8646 32 : dfTotalPixels += dfOvrPixels;
8647 : }
8648 94 : else if (i == 0 && poDS->GetRasterBand(1)->GetMaskFlags() ==
8649 : GMF_PER_DATASET)
8650 : {
8651 1 : ReportError(pszFilename, CE_Warning, CPLE_AppDefined,
8652 : "Source dataset has a mask band on full "
8653 : "resolution, overviews on the regular bands, "
8654 : "but lacks overviews on the mask band.");
8655 : }
8656 : }
8657 :
8658 : // Now copy the imagery.
8659 : // Begin with the smallest overview.
8660 69 : for (int iOvrLevel = nSrcOverviews - 1;
8661 194 : eErr == CE_None && iOvrLevel >= 0; --iOvrLevel)
8662 : {
8663 125 : auto poDstDS = poDS->m_apoOverviewDS[iOvrLevel].get();
8664 :
8665 : // Create a fake dataset with the source overview level so that
8666 : // GDALDatasetCopyWholeRaster can cope with it.
8667 : GDALDataset *poSrcOvrDS =
8668 : poOvrDS
8669 162 : ? (iOvrLevel == 0 ? poOvrDS.get()
8670 37 : : GDALCreateOverviewDataset(
8671 : poOvrDS.get(), iOvrLevel - 1,
8672 : /* bThisLevelOnly = */ true))
8673 54 : : GDALCreateOverviewDataset(
8674 : poSrcDS, iOvrLevel,
8675 125 : /* bThisLevelOnly = */ true);
8676 : GDALRasterBand *poSrcOvrBand =
8677 196 : poOvrDS ? (iOvrLevel == 0
8678 71 : ? poOvrDS->GetRasterBand(1)
8679 74 : : poOvrDS->GetRasterBand(1)->GetOverview(
8680 37 : iOvrLevel - 1))
8681 179 : : poSrcDS->GetRasterBand(1)->GetOverview(iOvrLevel);
8682 : double dfNextCurPixels =
8683 : dfCurPixels +
8684 125 : static_cast<double>(poSrcOvrBand->GetXSize()) *
8685 125 : poSrcOvrBand->GetYSize() * l_nBands;
8686 :
8687 125 : poDstDS->m_bBlockOrderRowMajor = true;
8688 125 : poDstDS->m_bLeaderSizeAsUInt4 = true;
8689 125 : poDstDS->m_bTrailerRepeatedLast4BytesRepeated = true;
8690 125 : poDstDS->m_bFillEmptyTilesAtClosing =
8691 125 : poDS->m_bFillEmptyTilesAtClosing;
8692 125 : poDstDS->m_bWriteEmptyTiles = poDS->m_bWriteEmptyTiles;
8693 125 : poDstDS->m_bTileInterleave = poDS->m_bTileInterleave;
8694 125 : GDALRasterBand *poSrcMaskBand = nullptr;
8695 125 : if (poDstDS->m_poMaskDS)
8696 : {
8697 32 : poDstDS->m_poMaskDS->m_bBlockOrderRowMajor = true;
8698 32 : poDstDS->m_poMaskDS->m_bLeaderSizeAsUInt4 = true;
8699 32 : poDstDS->m_poMaskDS->m_bTrailerRepeatedLast4BytesRepeated =
8700 : true;
8701 64 : poDstDS->m_poMaskDS->m_bFillEmptyTilesAtClosing =
8702 32 : poDS->m_bFillEmptyTilesAtClosing;
8703 64 : poDstDS->m_poMaskDS->m_bWriteEmptyTiles =
8704 32 : poDS->m_bWriteEmptyTiles;
8705 :
8706 32 : poSrcMaskBand =
8707 : poMaskOvrDS
8708 46 : ? (iOvrLevel == 0
8709 14 : ? poMaskOvrDS->GetRasterBand(1)
8710 16 : : poMaskOvrDS->GetRasterBand(1)->GetOverview(
8711 8 : iOvrLevel - 1))
8712 50 : : poSrcOvrBand->GetMaskBand();
8713 : }
8714 :
8715 125 : if (poDstDS->m_poMaskDS)
8716 : {
8717 32 : dfNextCurPixels +=
8718 32 : static_cast<double>(poSrcOvrBand->GetXSize()) *
8719 32 : poSrcOvrBand->GetYSize();
8720 : }
8721 : void *pScaledData =
8722 125 : GDALCreateScaledProgress(dfCurPixels / dfTotalPixels,
8723 : dfNextCurPixels / dfTotalPixels,
8724 : pfnProgress, pProgressData);
8725 :
8726 125 : eErr = CopyImageryAndMask(poDstDS, poSrcOvrDS, poSrcMaskBand,
8727 : GDALScaledProgress, pScaledData);
8728 :
8729 125 : dfCurPixels = dfNextCurPixels;
8730 125 : GDALDestroyScaledProgress(pScaledData);
8731 :
8732 125 : if (poSrcOvrDS != poOvrDS.get())
8733 91 : delete poSrcOvrDS;
8734 125 : poSrcOvrDS = nullptr;
8735 : }
8736 : }
8737 : }
8738 :
8739 : /* -------------------------------------------------------------------- */
8740 : /* Copy actual imagery. */
8741 : /* -------------------------------------------------------------------- */
8742 2114 : double dfNextCurPixels =
8743 2114 : dfCurPixels + static_cast<double>(nXSize) * nYSize * l_nBands;
8744 2114 : void *pScaledData = GDALCreateScaledProgress(
8745 : dfCurPixels / dfTotalPixels, dfNextCurPixels / dfTotalPixels,
8746 : pfnProgress, pProgressData);
8747 :
8748 : #if defined(HAVE_LIBJPEG) || defined(JPEG_DIRECT_COPY)
8749 2114 : bool bTryCopy = true;
8750 : #endif
8751 :
8752 : #ifdef HAVE_LIBJPEG
8753 2114 : if (bCopyFromJPEG)
8754 : {
8755 12 : eErr = GTIFF_CopyFromJPEG(poDS.get(), poSrcDS, pfnProgress,
8756 : pProgressData, bTryCopy);
8757 :
8758 : // In case of failure in the decompression step, try normal copy.
8759 12 : if (bTryCopy)
8760 0 : eErr = CE_None;
8761 : }
8762 : #endif
8763 :
8764 : #ifdef JPEG_DIRECT_COPY
8765 : if (bDirectCopyFromJPEG)
8766 : {
8767 : eErr = GTIFF_DirectCopyFromJPEG(poDS.get(), poSrcDS, pfnProgress,
8768 : pProgressData, bTryCopy);
8769 :
8770 : // In case of failure in the reading step, try normal copy.
8771 : if (bTryCopy)
8772 : eErr = CE_None;
8773 : }
8774 : #endif
8775 :
8776 2114 : bool bWriteMask = true;
8777 2114 : if (
8778 : #if defined(HAVE_LIBJPEG) || defined(JPEG_DIRECT_COPY)
8779 4216 : bTryCopy &&
8780 : #endif
8781 2102 : (poDS->m_bTreatAsSplit || poDS->m_bTreatAsSplitBitmap))
8782 : {
8783 : // For split bands, we use TIFFWriteScanline() interface.
8784 9 : CPLAssert(poDS->m_nBitsPerSample == 8 || poDS->m_nBitsPerSample == 1);
8785 :
8786 9 : if (poDS->m_nPlanarConfig == PLANARCONFIG_CONTIG && poDS->nBands > 1)
8787 : {
8788 : GByte *pabyScanline = static_cast<GByte *>(
8789 3 : VSI_MALLOC_VERBOSE(TIFFScanlineSize(l_hTIFF)));
8790 3 : if (pabyScanline == nullptr)
8791 0 : eErr = CE_Failure;
8792 9052 : for (int j = 0; j < nYSize && eErr == CE_None; ++j)
8793 : {
8794 18098 : eErr = poSrcDS->RasterIO(GF_Read, 0, j, nXSize, 1, pabyScanline,
8795 : nXSize, 1, GDT_UInt8, l_nBands,
8796 9049 : nullptr, poDS->nBands, 0, 1, nullptr);
8797 18098 : if (eErr == CE_None &&
8798 9049 : TIFFWriteScanline(l_hTIFF, pabyScanline, j, 0) == -1)
8799 : {
8800 0 : ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
8801 : "TIFFWriteScanline() failed.");
8802 0 : eErr = CE_Failure;
8803 : }
8804 9049 : if (!GDALScaledProgress((j + 1) * 1.0 / nYSize, nullptr,
8805 : pScaledData))
8806 0 : eErr = CE_Failure;
8807 : }
8808 3 : CPLFree(pabyScanline);
8809 : }
8810 : else
8811 : {
8812 : GByte *pabyScanline =
8813 6 : static_cast<GByte *>(VSI_MALLOC_VERBOSE(nXSize));
8814 6 : if (pabyScanline == nullptr)
8815 0 : eErr = CE_Failure;
8816 : else
8817 6 : eErr = CE_None;
8818 14 : for (int iBand = 1; iBand <= l_nBands && eErr == CE_None; ++iBand)
8819 : {
8820 48211 : for (int j = 0; j < nYSize && eErr == CE_None; ++j)
8821 : {
8822 48203 : eErr = poSrcDS->GetRasterBand(iBand)->RasterIO(
8823 : GF_Read, 0, j, nXSize, 1, pabyScanline, nXSize, 1,
8824 : GDT_UInt8, 0, 0, nullptr);
8825 48203 : if (poDS->m_bTreatAsSplitBitmap)
8826 : {
8827 7225210 : for (int i = 0; i < nXSize; ++i)
8828 : {
8829 7216010 : const GByte byVal = pabyScanline[i];
8830 7216010 : if ((i & 0x7) == 0)
8831 902001 : pabyScanline[i >> 3] = 0;
8832 7216010 : if (byVal)
8833 7097220 : pabyScanline[i >> 3] |= 0x80 >> (i & 0x7);
8834 : }
8835 : }
8836 96406 : if (eErr == CE_None &&
8837 48203 : TIFFWriteScanline(l_hTIFF, pabyScanline, j,
8838 48203 : static_cast<uint16_t>(iBand - 1)) ==
8839 : -1)
8840 : {
8841 0 : ReportError(pszFilename, CE_Failure, CPLE_AppDefined,
8842 : "TIFFWriteScanline() failed.");
8843 0 : eErr = CE_Failure;
8844 : }
8845 48203 : if (!GDALScaledProgress((j + 1 + (iBand - 1) * nYSize) *
8846 48203 : 1.0 / (l_nBands * nYSize),
8847 : nullptr, pScaledData))
8848 0 : eErr = CE_Failure;
8849 : }
8850 : }
8851 6 : CPLFree(pabyScanline);
8852 : }
8853 :
8854 : // Necessary to be able to read the file without re-opening.
8855 9 : TIFFSizeProc pfnSizeProc = TIFFGetSizeProc(l_hTIFF);
8856 :
8857 9 : TIFFFlushData(l_hTIFF);
8858 :
8859 9 : toff_t nNewDirOffset = pfnSizeProc(TIFFClientdata(l_hTIFF));
8860 9 : if ((nNewDirOffset % 2) == 1)
8861 5 : ++nNewDirOffset;
8862 :
8863 9 : TIFFFlush(l_hTIFF);
8864 :
8865 9 : if (poDS->m_nDirOffset != TIFFCurrentDirOffset(l_hTIFF))
8866 : {
8867 0 : poDS->m_nDirOffset = nNewDirOffset;
8868 0 : CPLDebug("GTiff", "directory moved during flush.");
8869 : }
8870 : }
8871 2105 : else if (
8872 : #if defined(HAVE_LIBJPEG) || defined(JPEG_DIRECT_COPY)
8873 2093 : bTryCopy &&
8874 : #endif
8875 : eErr == CE_None)
8876 : {
8877 2092 : const char *papszCopyWholeRasterOptions[3] = {nullptr, nullptr,
8878 : nullptr};
8879 2092 : int iNextOption = 0;
8880 2092 : papszCopyWholeRasterOptions[iNextOption++] = "SKIP_HOLES=YES";
8881 2092 : if (l_nCompression != COMPRESSION_NONE)
8882 : {
8883 495 : papszCopyWholeRasterOptions[iNextOption++] = "COMPRESSED=YES";
8884 : }
8885 :
8886 : // For streaming with separate, we really want that bands are written
8887 : // after each other, even if the source is pixel interleaved.
8888 1597 : else if (bStreaming && poDS->m_nPlanarConfig == PLANARCONFIG_SEPARATE)
8889 : {
8890 1 : papszCopyWholeRasterOptions[iNextOption++] = "INTERLEAVE=BAND";
8891 : }
8892 :
8893 2092 : if (bCopySrcOverviews || bTileInterleaving)
8894 : {
8895 220 : poDS->m_bBlockOrderRowMajor = true;
8896 220 : poDS->m_bLeaderSizeAsUInt4 = bCopySrcOverviews;
8897 220 : poDS->m_bTrailerRepeatedLast4BytesRepeated = bCopySrcOverviews;
8898 220 : if (poDS->m_poMaskDS)
8899 : {
8900 27 : poDS->m_poMaskDS->m_bBlockOrderRowMajor = true;
8901 27 : poDS->m_poMaskDS->m_bLeaderSizeAsUInt4 = bCopySrcOverviews;
8902 27 : poDS->m_poMaskDS->m_bTrailerRepeatedLast4BytesRepeated =
8903 : bCopySrcOverviews;
8904 27 : GDALDestroyScaledProgress(pScaledData);
8905 : pScaledData =
8906 27 : GDALCreateScaledProgress(dfCurPixels / dfTotalPixels, 1.0,
8907 : pfnProgress, pProgressData);
8908 : }
8909 :
8910 220 : eErr = CopyImageryAndMask(poDS.get(), poSrcDS,
8911 220 : poSrcDS->GetRasterBand(1)->GetMaskBand(),
8912 : GDALScaledProgress, pScaledData);
8913 220 : if (poDS->m_poMaskDS)
8914 : {
8915 27 : bWriteMask = false;
8916 : }
8917 : }
8918 : else
8919 : {
8920 1872 : eErr = GDALDatasetCopyWholeRaster(GDALDataset::ToHandle(poSrcDS),
8921 1872 : GDALDataset::ToHandle(poDS.get()),
8922 : papszCopyWholeRasterOptions,
8923 : GDALScaledProgress, pScaledData);
8924 : }
8925 : }
8926 :
8927 2114 : GDALDestroyScaledProgress(pScaledData);
8928 :
8929 2114 : if (eErr == CE_None && !bStreaming && bWriteMask)
8930 : {
8931 2065 : pScaledData = GDALCreateScaledProgress(dfNextCurPixels / dfTotalPixels,
8932 : 1.0, pfnProgress, pProgressData);
8933 2065 : if (poDS->m_poMaskDS)
8934 : {
8935 10 : const char *l_papszOptions[2] = {"COMPRESSED=YES", nullptr};
8936 10 : eErr = GDALRasterBandCopyWholeRaster(
8937 10 : poSrcDS->GetRasterBand(1)->GetMaskBand(),
8938 10 : poDS->GetRasterBand(1)->GetMaskBand(),
8939 : const_cast<char **>(l_papszOptions), GDALScaledProgress,
8940 : pScaledData);
8941 : }
8942 : else
8943 : {
8944 2055 : eErr = GDALDriver::DefaultCopyMasks(poSrcDS, poDS.get(), bStrict,
8945 : nullptr, GDALScaledProgress,
8946 : pScaledData);
8947 : }
8948 2065 : GDALDestroyScaledProgress(pScaledData);
8949 : }
8950 :
8951 2114 : poDS->m_bWriteCOGLayout = false;
8952 :
8953 4210 : if (eErr == CE_None &&
8954 2096 : CPLTestBool(CSLFetchNameValueDef(poDS->m_papszCreationOptions,
8955 : "@FLUSHCACHE", "NO")))
8956 : {
8957 173 : if (poDS->FlushCache(false) != CE_None)
8958 : {
8959 0 : eErr = CE_Failure;
8960 : }
8961 : }
8962 :
8963 2114 : if (eErr == CE_Failure)
8964 : {
8965 18 : if (CPLTestBool(CPLGetConfigOption("GTIFF_DELETE_ON_ERROR", "YES")))
8966 : {
8967 17 : l_fpL->CancelCreation();
8968 17 : poDS.reset();
8969 :
8970 17 : if (!bStreaming)
8971 : {
8972 : // Should really delete more carefully.
8973 17 : VSIUnlink(pszFilename);
8974 : }
8975 : }
8976 : else
8977 : {
8978 1 : poDS.reset();
8979 : }
8980 : }
8981 :
8982 2114 : return poDS.release();
8983 : }
8984 :
8985 : /************************************************************************/
8986 : /* SetSpatialRef() */
8987 : /************************************************************************/
8988 :
8989 1509 : CPLErr GTiffDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
8990 :
8991 : {
8992 1509 : if (m_bStreamingOut && m_bCrystalized)
8993 : {
8994 1 : ReportError(CE_Failure, CPLE_NotSupported,
8995 : "Cannot modify projection at that point in "
8996 : "a streamed output file");
8997 1 : return CE_Failure;
8998 : }
8999 :
9000 1508 : LoadGeoreferencingAndPamIfNeeded();
9001 1508 : LookForProjection();
9002 :
9003 1508 : CPLErr eErr = CE_None;
9004 1508 : if (eAccess == GA_Update)
9005 : {
9006 1510 : if ((m_eProfile == GTiffProfile::BASELINE) &&
9007 7 : (GetPamFlags() & GPF_DISABLED) == 0)
9008 : {
9009 7 : eErr = GDALPamDataset::SetSpatialRef(poSRS);
9010 : }
9011 : else
9012 : {
9013 1496 : if (GDALPamDataset::GetSpatialRef() != nullptr)
9014 : {
9015 : // Cancel any existing SRS from PAM file.
9016 1 : GDALPamDataset::SetSpatialRef(nullptr);
9017 : }
9018 1496 : m_bGeoTIFFInfoChanged = true;
9019 : }
9020 : }
9021 : else
9022 : {
9023 5 : CPLDebug("GTIFF", "SetSpatialRef() goes to PAM instead of TIFF tags");
9024 5 : eErr = GDALPamDataset::SetSpatialRef(poSRS);
9025 : }
9026 :
9027 1508 : if (eErr == CE_None)
9028 : {
9029 1508 : if (poSRS == nullptr || poSRS->IsEmpty())
9030 : {
9031 14 : if (!m_oSRS.IsEmpty())
9032 : {
9033 4 : m_bForceUnsetProjection = true;
9034 : }
9035 14 : m_oSRS.Clear();
9036 : }
9037 : else
9038 : {
9039 1494 : m_oSRS = *poSRS;
9040 1494 : m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
9041 : }
9042 : }
9043 :
9044 1508 : return eErr;
9045 : }
9046 :
9047 : /************************************************************************/
9048 : /* SetGeoTransform() */
9049 : /************************************************************************/
9050 :
9051 1816 : CPLErr GTiffDataset::SetGeoTransform(const GDALGeoTransform >)
9052 :
9053 : {
9054 1816 : if (m_bStreamingOut && m_bCrystalized)
9055 : {
9056 1 : ReportError(CE_Failure, CPLE_NotSupported,
9057 : "Cannot modify geotransform at that point in a "
9058 : "streamed output file");
9059 1 : return CE_Failure;
9060 : }
9061 :
9062 1815 : LoadGeoreferencingAndPamIfNeeded();
9063 :
9064 1815 : CPLErr eErr = CE_None;
9065 1815 : if (eAccess == GA_Update)
9066 : {
9067 1809 : if (!m_aoGCPs.empty())
9068 : {
9069 1 : ReportError(CE_Warning, CPLE_AppDefined,
9070 : "GCPs previously set are going to be cleared "
9071 : "due to the setting of a geotransform.");
9072 1 : m_bForceUnsetGTOrGCPs = true;
9073 1 : m_aoGCPs.clear();
9074 : }
9075 1808 : else if (gt.xorig == 0.0 && gt.xscale == 0.0 && gt.xrot == 0.0 &&
9076 2 : gt.yorig == 0.0 && gt.yrot == 0.0 && gt.yscale == 0.0)
9077 : {
9078 2 : if (m_bGeoTransformValid)
9079 : {
9080 2 : m_bForceUnsetGTOrGCPs = true;
9081 2 : m_bGeoTIFFInfoChanged = true;
9082 : }
9083 2 : m_bGeoTransformValid = false;
9084 2 : m_gt = gt;
9085 2 : return CE_None;
9086 : }
9087 :
9088 3623 : if ((m_eProfile == GTiffProfile::BASELINE) &&
9089 9 : !CPLFetchBool(m_papszCreationOptions, "TFW", false) &&
9090 1821 : !CPLFetchBool(m_papszCreationOptions, "WORLDFILE", false) &&
9091 5 : (GetPamFlags() & GPF_DISABLED) == 0)
9092 : {
9093 5 : eErr = GDALPamDataset::SetGeoTransform(gt);
9094 : }
9095 : else
9096 : {
9097 : // Cancel any existing geotransform from PAM file.
9098 1802 : GDALPamDataset::DeleteGeoTransform();
9099 1802 : m_bGeoTIFFInfoChanged = true;
9100 : }
9101 : }
9102 : else
9103 : {
9104 6 : CPLDebug("GTIFF", "SetGeoTransform() goes to PAM instead of TIFF tags");
9105 6 : eErr = GDALPamDataset::SetGeoTransform(gt);
9106 : }
9107 :
9108 1813 : if (eErr == CE_None)
9109 : {
9110 1813 : m_gt = gt;
9111 1813 : m_bGeoTransformValid = true;
9112 : }
9113 :
9114 1813 : return eErr;
9115 : }
9116 :
9117 : /************************************************************************/
9118 : /* SetGCPs() */
9119 : /************************************************************************/
9120 :
9121 23 : CPLErr GTiffDataset::SetGCPs(int nGCPCountIn, const GDAL_GCP *pasGCPListIn,
9122 : const OGRSpatialReference *poGCPSRS)
9123 : {
9124 23 : CPLErr eErr = CE_None;
9125 23 : LoadGeoreferencingAndPamIfNeeded();
9126 23 : LookForProjection();
9127 :
9128 23 : if (eAccess == GA_Update)
9129 : {
9130 21 : if (!m_aoGCPs.empty() && nGCPCountIn == 0)
9131 : {
9132 3 : m_bForceUnsetGTOrGCPs = true;
9133 : }
9134 18 : else if (nGCPCountIn > 0 && m_bGeoTransformValid)
9135 : {
9136 5 : ReportError(CE_Warning, CPLE_AppDefined,
9137 : "A geotransform previously set is going to be cleared "
9138 : "due to the setting of GCPs.");
9139 5 : m_gt = GDALGeoTransform();
9140 5 : m_bGeoTransformValid = false;
9141 5 : m_bForceUnsetGTOrGCPs = true;
9142 : }
9143 21 : if ((m_eProfile == GTiffProfile::BASELINE) &&
9144 0 : (GetPamFlags() & GPF_DISABLED) == 0)
9145 : {
9146 0 : eErr = GDALPamDataset::SetGCPs(nGCPCountIn, pasGCPListIn, poGCPSRS);
9147 : }
9148 : else
9149 : {
9150 21 : if (nGCPCountIn > knMAX_GCP_COUNT)
9151 : {
9152 2 : if (GDALPamDataset::GetGCPCount() == 0 && !m_aoGCPs.empty())
9153 : {
9154 1 : m_bForceUnsetGTOrGCPs = true;
9155 : }
9156 2 : ReportError(CE_Warning, CPLE_AppDefined,
9157 : "Trying to write %d GCPs, whereas the maximum "
9158 : "supported in GeoTIFF tag is %d. "
9159 : "Falling back to writing them to PAM",
9160 : nGCPCountIn, knMAX_GCP_COUNT);
9161 2 : eErr = GDALPamDataset::SetGCPs(nGCPCountIn, pasGCPListIn,
9162 : poGCPSRS);
9163 : }
9164 19 : else if (GDALPamDataset::GetGCPCount() > 0)
9165 : {
9166 : // Cancel any existing GCPs from PAM file.
9167 1 : GDALPamDataset::SetGCPs(
9168 : 0, nullptr,
9169 : static_cast<const OGRSpatialReference *>(nullptr));
9170 : }
9171 21 : m_bGeoTIFFInfoChanged = true;
9172 : }
9173 : }
9174 : else
9175 : {
9176 2 : CPLDebug("GTIFF", "SetGCPs() goes to PAM instead of TIFF tags");
9177 2 : eErr = GDALPamDataset::SetGCPs(nGCPCountIn, pasGCPListIn, poGCPSRS);
9178 : }
9179 :
9180 23 : if (eErr == CE_None)
9181 : {
9182 23 : if (poGCPSRS == nullptr || poGCPSRS->IsEmpty())
9183 : {
9184 12 : if (!m_oSRS.IsEmpty())
9185 : {
9186 5 : m_bForceUnsetProjection = true;
9187 : }
9188 12 : m_oSRS.Clear();
9189 : }
9190 : else
9191 : {
9192 11 : m_oSRS = *poGCPSRS;
9193 11 : m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
9194 : }
9195 :
9196 23 : m_aoGCPs = gdal::GCP::fromC(pasGCPListIn, nGCPCountIn);
9197 : }
9198 :
9199 23 : return eErr;
9200 : }
9201 :
9202 : /************************************************************************/
9203 : /* SetMetadata() */
9204 : /************************************************************************/
9205 2704 : CPLErr GTiffDataset::SetMetadata(CSLConstList papszMD, const char *pszDomain)
9206 :
9207 : {
9208 2704 : LoadGeoreferencingAndPamIfNeeded();
9209 :
9210 2704 : if (m_bStreamingOut && m_bCrystalized)
9211 : {
9212 1 : ReportError(
9213 : CE_Failure, CPLE_NotSupported,
9214 : "Cannot modify metadata at that point in a streamed output file");
9215 1 : return CE_Failure;
9216 : }
9217 :
9218 2703 : if (pszDomain && EQUAL(pszDomain, "json:ISIS3"))
9219 : {
9220 5 : m_oISIS3Metadata.Deinit();
9221 5 : m_oMapISIS3MetadataItems.clear();
9222 : }
9223 :
9224 2703 : CPLErr eErr = CE_None;
9225 2703 : if (eAccess == GA_Update)
9226 : {
9227 2700 : if (pszDomain != nullptr && EQUAL(pszDomain, MD_DOMAIN_RPC))
9228 : {
9229 : // So that a subsequent GetMetadata() wouldn't override our new
9230 : // values
9231 22 : LoadMetadata();
9232 22 : m_bForceUnsetRPC = (CSLCount(papszMD) == 0);
9233 : }
9234 :
9235 2700 : if ((papszMD != nullptr) && (pszDomain != nullptr) &&
9236 1863 : EQUAL(pszDomain, "COLOR_PROFILE"))
9237 : {
9238 0 : m_bColorProfileMetadataChanged = true;
9239 : }
9240 2700 : else if (pszDomain == nullptr || !EQUAL(pszDomain, "_temporary_"))
9241 : {
9242 2700 : m_bMetadataChanged = true;
9243 : // Cancel any existing metadata from PAM file.
9244 2700 : if (GDALPamDataset::GetMetadata(pszDomain) != nullptr)
9245 1 : GDALPamDataset::SetMetadata(nullptr, pszDomain);
9246 : }
9247 :
9248 5364 : if ((pszDomain == nullptr || EQUAL(pszDomain, "")) &&
9249 2664 : CSLFetchNameValue(papszMD, GDALMD_AREA_OR_POINT) != nullptr)
9250 : {
9251 2028 : const char *pszPrevValue = GetMetadataItem(GDALMD_AREA_OR_POINT);
9252 : const char *pszNewValue =
9253 2028 : CSLFetchNameValue(papszMD, GDALMD_AREA_OR_POINT);
9254 2028 : if (pszPrevValue == nullptr || pszNewValue == nullptr ||
9255 1605 : !EQUAL(pszPrevValue, pszNewValue))
9256 : {
9257 427 : LookForProjection();
9258 427 : m_bGeoTIFFInfoChanged = true;
9259 : }
9260 : }
9261 :
9262 2700 : if (pszDomain != nullptr && EQUAL(pszDomain, "xml:XMP"))
9263 : {
9264 2 : if (papszMD != nullptr && *papszMD != nullptr)
9265 : {
9266 1 : int nTagSize = static_cast<int>(strlen(*papszMD));
9267 1 : TIFFSetField(m_hTIFF, TIFFTAG_XMLPACKET, nTagSize, *papszMD);
9268 : }
9269 : else
9270 : {
9271 1 : TIFFUnsetField(m_hTIFF, TIFFTAG_XMLPACKET);
9272 : }
9273 : }
9274 : }
9275 : else
9276 : {
9277 3 : CPLDebug(
9278 : "GTIFF",
9279 : "GTiffDataset::SetMetadata() goes to PAM instead of TIFF tags");
9280 3 : eErr = GDALPamDataset::SetMetadata(papszMD, pszDomain);
9281 : }
9282 :
9283 2703 : if (eErr == CE_None)
9284 : {
9285 2703 : eErr = m_oGTiffMDMD.SetMetadata(papszMD, pszDomain);
9286 : }
9287 2703 : return eErr;
9288 : }
9289 :
9290 : /************************************************************************/
9291 : /* SetMetadataItem() */
9292 : /************************************************************************/
9293 :
9294 5852 : CPLErr GTiffDataset::SetMetadataItem(const char *pszName, const char *pszValue,
9295 : const char *pszDomain)
9296 :
9297 : {
9298 5852 : LoadGeoreferencingAndPamIfNeeded();
9299 :
9300 5852 : if (m_bStreamingOut && m_bCrystalized)
9301 : {
9302 1 : ReportError(
9303 : CE_Failure, CPLE_NotSupported,
9304 : "Cannot modify metadata at that point in a streamed output file");
9305 1 : return CE_Failure;
9306 : }
9307 :
9308 5851 : if (pszDomain && EQUAL(pszDomain, "json:ISIS3"))
9309 : {
9310 1 : ReportError(CE_Failure, CPLE_NotSupported,
9311 : "Updating part of json:ISIS3 is not supported. "
9312 : "Use SetMetadata() instead");
9313 1 : return CE_Failure;
9314 : }
9315 :
9316 5850 : CPLErr eErr = CE_None;
9317 5850 : if (eAccess == GA_Update)
9318 : {
9319 5843 : if ((pszDomain != nullptr) && EQUAL(pszDomain, "COLOR_PROFILE"))
9320 : {
9321 8 : m_bColorProfileMetadataChanged = true;
9322 : }
9323 5835 : else if (pszDomain == nullptr || !EQUAL(pszDomain, "_temporary_"))
9324 : {
9325 5835 : m_bMetadataChanged = true;
9326 : // Cancel any existing metadata from PAM file.
9327 5835 : if (GDALPamDataset::GetMetadataItem(pszName, pszDomain) != nullptr)
9328 1 : GDALPamDataset::SetMetadataItem(pszName, nullptr, pszDomain);
9329 : }
9330 :
9331 5843 : if ((pszDomain == nullptr || EQUAL(pszDomain, "")) &&
9332 84 : pszName != nullptr && EQUAL(pszName, GDALMD_AREA_OR_POINT))
9333 : {
9334 7 : LookForProjection();
9335 7 : m_bGeoTIFFInfoChanged = true;
9336 : }
9337 : }
9338 : else
9339 : {
9340 7 : CPLDebug(
9341 : "GTIFF",
9342 : "GTiffDataset::SetMetadataItem() goes to PAM instead of TIFF tags");
9343 7 : eErr = GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
9344 : }
9345 :
9346 5850 : if (eErr == CE_None)
9347 : {
9348 5850 : eErr = m_oGTiffMDMD.SetMetadataItem(pszName, pszValue, pszDomain);
9349 : }
9350 :
9351 5850 : return eErr;
9352 : }
9353 :
9354 : /************************************************************************/
9355 : /* CreateMaskBand() */
9356 : /************************************************************************/
9357 :
9358 98 : CPLErr GTiffDataset::CreateMaskBand(int nFlagsIn)
9359 : {
9360 98 : ScanDirectories();
9361 :
9362 98 : if (m_poMaskDS != nullptr)
9363 : {
9364 1 : ReportError(CE_Failure, CPLE_AppDefined,
9365 : "This TIFF dataset has already an internal mask band");
9366 1 : return CE_Failure;
9367 : }
9368 97 : else if (MustCreateInternalMask())
9369 : {
9370 84 : if (nFlagsIn != GMF_PER_DATASET)
9371 : {
9372 1 : ReportError(CE_Failure, CPLE_AppDefined,
9373 : "The only flag value supported for internal mask is "
9374 : "GMF_PER_DATASET");
9375 1 : return CE_Failure;
9376 : }
9377 :
9378 83 : int l_nCompression = COMPRESSION_PACKBITS;
9379 83 : if (strstr(GDALGetMetadataItem(GDALGetDriverByName("GTiff"),
9380 : GDAL_DMD_CREATIONOPTIONLIST, nullptr),
9381 83 : "<Value>DEFLATE</Value>") != nullptr)
9382 83 : l_nCompression = COMPRESSION_ADOBE_DEFLATE;
9383 :
9384 : /* --------------------------------------------------------------------
9385 : */
9386 : /* If we don't have read access, then create the mask externally.
9387 : */
9388 : /* --------------------------------------------------------------------
9389 : */
9390 83 : if (GetAccess() != GA_Update)
9391 : {
9392 1 : ReportError(CE_Warning, CPLE_AppDefined,
9393 : "File open for read-only accessing, "
9394 : "creating mask externally.");
9395 :
9396 1 : return GDALPamDataset::CreateMaskBand(nFlagsIn);
9397 : }
9398 :
9399 82 : if (m_bLayoutIFDSBeforeData && !m_bKnownIncompatibleEdition &&
9400 0 : !m_bWriteKnownIncompatibleEdition)
9401 : {
9402 0 : ReportError(CE_Warning, CPLE_AppDefined,
9403 : "Adding a mask invalidates the "
9404 : "LAYOUT=IFDS_BEFORE_DATA property");
9405 0 : m_bKnownIncompatibleEdition = true;
9406 0 : m_bWriteKnownIncompatibleEdition = true;
9407 : }
9408 :
9409 82 : bool bIsOverview = false;
9410 82 : uint32_t nSubType = 0;
9411 82 : if (TIFFGetField(m_hTIFF, TIFFTAG_SUBFILETYPE, &nSubType))
9412 : {
9413 8 : bIsOverview = (nSubType & FILETYPE_REDUCEDIMAGE) != 0;
9414 :
9415 8 : if ((nSubType & FILETYPE_MASK) != 0)
9416 : {
9417 0 : ReportError(CE_Failure, CPLE_AppDefined,
9418 : "Cannot create a mask on a TIFF mask IFD !");
9419 0 : return CE_Failure;
9420 : }
9421 : }
9422 :
9423 82 : const int bIsTiled = TIFFIsTiled(m_hTIFF);
9424 :
9425 82 : FlushDirectory();
9426 :
9427 82 : const toff_t nOffset = GTIFFWriteDirectory(
9428 : m_hTIFF,
9429 : bIsOverview ? FILETYPE_REDUCEDIMAGE | FILETYPE_MASK : FILETYPE_MASK,
9430 : nRasterXSize, nRasterYSize, 1, PLANARCONFIG_CONTIG, 1,
9431 : m_nBlockXSize, m_nBlockYSize, bIsTiled, l_nCompression,
9432 : PHOTOMETRIC_MASK, PREDICTOR_NONE, SAMPLEFORMAT_UINT, nullptr,
9433 : nullptr, nullptr, 0, nullptr, "", nullptr, nullptr, nullptr,
9434 82 : nullptr, m_bWriteCOGLayout);
9435 :
9436 82 : ReloadDirectory();
9437 :
9438 82 : if (nOffset == 0)
9439 0 : return CE_Failure;
9440 :
9441 82 : m_poMaskDS = std::make_shared<GTiffDataset>();
9442 82 : m_poMaskDS->eAccess = GA_Update;
9443 82 : m_poMaskDS->m_poBaseDS = this;
9444 82 : m_poMaskDS->m_poImageryDS = this;
9445 82 : m_poMaskDS->ShareLockWithParentDataset(this);
9446 82 : m_poMaskDS->m_osFilename = m_osFilename;
9447 82 : m_poMaskDS->m_bPromoteTo8Bits = CPLTestBool(
9448 : CPLGetConfigOption("GDAL_TIFF_INTERNAL_MASK_TO_8BIT", "YES"));
9449 82 : return m_poMaskDS->OpenOffset(VSI_TIFFOpenChild(m_hTIFF), nOffset,
9450 82 : GA_Update);
9451 : }
9452 :
9453 13 : return GDALPamDataset::CreateMaskBand(nFlagsIn);
9454 : }
9455 :
9456 : /************************************************************************/
9457 : /* MustCreateInternalMask() */
9458 : /************************************************************************/
9459 :
9460 135 : bool GTiffDataset::MustCreateInternalMask()
9461 : {
9462 135 : return CPLTestBool(CPLGetConfigOption("GDAL_TIFF_INTERNAL_MASK", "YES"));
9463 : }
9464 :
9465 : /************************************************************************/
9466 : /* CreateMaskBand() */
9467 : /************************************************************************/
9468 :
9469 29 : CPLErr GTiffRasterBand::CreateMaskBand(int nFlagsIn)
9470 : {
9471 29 : m_poGDS->ScanDirectories();
9472 :
9473 29 : if (m_poGDS->m_poMaskDS != nullptr)
9474 : {
9475 5 : ReportError(CE_Failure, CPLE_AppDefined,
9476 : "This TIFF dataset has already an internal mask band");
9477 5 : return CE_Failure;
9478 : }
9479 :
9480 : const char *pszGDAL_TIFF_INTERNAL_MASK =
9481 24 : CPLGetConfigOption("GDAL_TIFF_INTERNAL_MASK", nullptr);
9482 27 : if ((pszGDAL_TIFF_INTERNAL_MASK &&
9483 24 : CPLTestBool(pszGDAL_TIFF_INTERNAL_MASK)) ||
9484 : nFlagsIn == GMF_PER_DATASET)
9485 : {
9486 16 : return m_poGDS->CreateMaskBand(nFlagsIn);
9487 : }
9488 :
9489 8 : return GDALPamRasterBand::CreateMaskBand(nFlagsIn);
9490 : }
9491 :
9492 : /************************************************************************/
9493 : /* ClampCTEntry() */
9494 : /************************************************************************/
9495 :
9496 236415 : /* static */ unsigned short GTiffDataset::ClampCTEntry(int iColor, int iComp,
9497 : int nCTEntryVal,
9498 : int nMultFactor)
9499 : {
9500 236415 : const int nVal = nCTEntryVal * nMultFactor;
9501 236415 : if (nVal < 0)
9502 : {
9503 0 : CPLError(CE_Warning, CPLE_AppDefined,
9504 : "Color table entry [%d][%d] = %d, clamped to 0", iColor, iComp,
9505 : nCTEntryVal);
9506 0 : return 0;
9507 : }
9508 236415 : if (nVal > 65535)
9509 : {
9510 2 : CPLError(CE_Warning, CPLE_AppDefined,
9511 : "Color table entry [%d][%d] = %d, clamped to 65535", iColor,
9512 : iComp, nCTEntryVal);
9513 2 : return 65535;
9514 : }
9515 236413 : return static_cast<unsigned short>(nVal);
9516 : }
|