Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: GeoTIFF Driver
4 : * Purpose: GDAL GeoTIFF support.
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 "cpl_port.h" // Must be first.
15 :
16 : #include "gtiff.h"
17 :
18 : #include "tiff_common.h"
19 :
20 : #include "cpl_conv.h"
21 : #include "cpl_error.h"
22 : #include "gdal.h"
23 : #include "gdal_mdreader.h" // RPC_xxx
24 : #include "gtiffdataset.h"
25 : #include "tiffio.h"
26 : #include "tif_jxl.h"
27 : #include "xtiffio.h"
28 : #include <cctype>
29 : #include <cmath>
30 :
31 : // Needed to expose WEBP_LOSSLESS option
32 : #ifdef WEBP_SUPPORT
33 : #include "webp/encode.h"
34 : #endif
35 :
36 : #ifdef LERC_SUPPORT
37 : #include "Lerc_c_api.h"
38 : #endif
39 :
40 : #define STRINGIFY(x) #x
41 : #define XSTRINGIFY(x) STRINGIFY(x)
42 :
43 : static thread_local bool bThreadLocalInExternalOvr = false;
44 :
45 : static thread_local int gnThreadLocalLibtiffError = 0;
46 :
47 4274940 : int >IFFGetThreadLocalLibtiffError()
48 : {
49 4274940 : return gnThreadLocalLibtiffError;
50 : }
51 :
52 : /************************************************************************/
53 : /* GTIFFSupportsPredictor() */
54 : /************************************************************************/
55 :
56 58142 : bool GTIFFSupportsPredictor(int nCompression)
57 : {
58 45779 : return nCompression == COMPRESSION_LZW ||
59 103921 : nCompression == COMPRESSION_ADOBE_DEFLATE ||
60 58142 : nCompression == COMPRESSION_ZSTD;
61 : }
62 :
63 : /************************************************************************/
64 : /* GTIFFSetThreadLocalInExternalOvr() */
65 : /************************************************************************/
66 :
67 424 : void GTIFFSetThreadLocalInExternalOvr(bool b)
68 : {
69 424 : bThreadLocalInExternalOvr = b;
70 424 : }
71 :
72 : /************************************************************************/
73 : /* GTIFFGetOverviewBlockSize() */
74 : /************************************************************************/
75 :
76 521 : void GTIFFGetOverviewBlockSize(GDALRasterBandH hBand, int *pnBlockXSize,
77 : int *pnBlockYSize)
78 : {
79 521 : const char *pszVal = CPLGetConfigOption("GDAL_TIFF_OVR_BLOCKSIZE", nullptr);
80 521 : if (!pszVal)
81 : {
82 513 : GDALRasterBand *const poBand = GDALRasterBand::FromHandle(hBand);
83 513 : poBand->GetBlockSize(pnBlockXSize, pnBlockYSize);
84 294 : if (*pnBlockXSize != *pnBlockYSize || *pnBlockXSize < 64 ||
85 807 : *pnBlockXSize > 4096 || !CPLIsPowerOfTwo(*pnBlockXSize))
86 : {
87 414 : *pnBlockXSize = *pnBlockYSize = 128;
88 : }
89 : }
90 : else
91 : {
92 8 : int nOvrBlockSize = atoi(pszVal);
93 16 : if (nOvrBlockSize < 64 || nOvrBlockSize > 4096 ||
94 8 : !CPLIsPowerOfTwo(nOvrBlockSize))
95 : {
96 0 : CPLErrorOnce(CE_Warning, CPLE_NotSupported,
97 : "Wrong value for GDAL_TIFF_OVR_BLOCKSIZE : %s. "
98 : "Should be a power of 2 between 64 and 4096. "
99 : "Defaulting to 128",
100 : pszVal);
101 0 : nOvrBlockSize = 128;
102 : }
103 :
104 8 : *pnBlockXSize = nOvrBlockSize;
105 8 : *pnBlockYSize = nOvrBlockSize;
106 : }
107 521 : }
108 :
109 : /************************************************************************/
110 : /* GTIFFSetJpegQuality() */
111 : /* Called by GTIFFBuildOverviews() to set the jpeg quality on the IFD */
112 : /* of the .ovr file. */
113 : /************************************************************************/
114 :
115 4 : void GTIFFSetJpegQuality(GDALDatasetH hGTIFFDS, int nJpegQuality)
116 : {
117 4 : CPLAssert(
118 : EQUAL(GDALGetDriverShortName(GDALGetDatasetDriver(hGTIFFDS)), "GTIFF"));
119 :
120 4 : GTiffDataset *const poDS = static_cast<GTiffDataset *>(hGTIFFDS);
121 4 : poDS->m_nJpegQuality = static_cast<signed char>(nJpegQuality);
122 :
123 4 : poDS->ScanDirectories();
124 :
125 7 : for (int i = 0; i < poDS->m_nOverviewCount; ++i)
126 3 : poDS->m_papoOverviewDS[i]->m_nJpegQuality = poDS->m_nJpegQuality;
127 4 : }
128 :
129 : /************************************************************************/
130 : /* GTIFFSetWebPLevel() */
131 : /* Called by GTIFFBuildOverviews() to set the jpeg quality on the IFD */
132 : /* of the .ovr file. */
133 : /************************************************************************/
134 :
135 3 : void GTIFFSetWebPLevel(GDALDatasetH hGTIFFDS, int nWebpLevel)
136 : {
137 3 : CPLAssert(
138 : EQUAL(GDALGetDriverShortName(GDALGetDatasetDriver(hGTIFFDS)), "GTIFF"));
139 :
140 3 : GTiffDataset *const poDS = static_cast<GTiffDataset *>(hGTIFFDS);
141 3 : poDS->m_nWebPLevel = static_cast<signed char>(nWebpLevel);
142 :
143 3 : poDS->ScanDirectories();
144 :
145 6 : for (int i = 0; i < poDS->m_nOverviewCount; ++i)
146 3 : poDS->m_papoOverviewDS[i]->m_nWebPLevel = poDS->m_nWebPLevel;
147 3 : }
148 :
149 : /************************************************************************/
150 : /* GTIFFSetWebPLossless() */
151 : /* Called by GTIFFBuildOverviews() to set webp lossless on the IFD */
152 : /* of the .ovr file. */
153 : /************************************************************************/
154 :
155 1 : void GTIFFSetWebPLossless(GDALDatasetH hGTIFFDS, bool bWebpLossless)
156 : {
157 1 : CPLAssert(
158 : EQUAL(GDALGetDriverShortName(GDALGetDatasetDriver(hGTIFFDS)), "GTIFF"));
159 :
160 1 : GTiffDataset *const poDS = static_cast<GTiffDataset *>(hGTIFFDS);
161 1 : poDS->m_bWebPLossless = bWebpLossless;
162 :
163 1 : poDS->ScanDirectories();
164 :
165 1 : for (int i = 0; i < poDS->m_nOverviewCount; ++i)
166 0 : poDS->m_papoOverviewDS[i]->m_bWebPLossless = poDS->m_bWebPLossless;
167 1 : }
168 :
169 : /************************************************************************/
170 : /* GTIFFSetJpegTablesMode() */
171 : /* Called by GTIFFBuildOverviews() to set the jpeg tables mode on the */
172 : /* of the .ovr file. */
173 : /************************************************************************/
174 :
175 0 : void GTIFFSetJpegTablesMode(GDALDatasetH hGTIFFDS, int nJpegTablesMode)
176 : {
177 0 : CPLAssert(
178 : EQUAL(GDALGetDriverShortName(GDALGetDatasetDriver(hGTIFFDS)), "GTIFF"));
179 :
180 0 : GTiffDataset *const poDS = static_cast<GTiffDataset *>(hGTIFFDS);
181 0 : poDS->m_nJpegTablesMode = static_cast<signed char>(nJpegTablesMode);
182 :
183 0 : poDS->ScanDirectories();
184 :
185 0 : for (int i = 0; i < poDS->m_nOverviewCount; ++i)
186 0 : poDS->m_papoOverviewDS[i]->m_nJpegTablesMode = poDS->m_nJpegTablesMode;
187 0 : }
188 :
189 : /************************************************************************/
190 : /* GTIFFSetZLevel() */
191 : /* Called by GTIFFBuildOverviews() to set the deflate level on the IFD */
192 : /* of the .ovr file. */
193 : /************************************************************************/
194 :
195 2 : void GTIFFSetZLevel(GDALDatasetH hGTIFFDS, int nZLevel)
196 : {
197 2 : CPLAssert(
198 : EQUAL(GDALGetDriverShortName(GDALGetDatasetDriver(hGTIFFDS)), "GTIFF"));
199 :
200 2 : GTiffDataset *const poDS = static_cast<GTiffDataset *>(hGTIFFDS);
201 2 : poDS->m_nZLevel = static_cast<signed char>(nZLevel);
202 :
203 2 : poDS->ScanDirectories();
204 :
205 4 : for (int i = 0; i < poDS->m_nOverviewCount; ++i)
206 2 : poDS->m_papoOverviewDS[i]->m_nZLevel = poDS->m_nZLevel;
207 2 : }
208 :
209 : /************************************************************************/
210 : /* GTIFFSetZSTDLevel() */
211 : /* Called by GTIFFBuildOverviews() to set the ZSTD level on the IFD */
212 : /* of the .ovr file. */
213 : /************************************************************************/
214 :
215 2 : void GTIFFSetZSTDLevel(GDALDatasetH hGTIFFDS, int nZSTDLevel)
216 : {
217 2 : CPLAssert(
218 : EQUAL(GDALGetDriverShortName(GDALGetDatasetDriver(hGTIFFDS)), "GTIFF"));
219 :
220 2 : GTiffDataset *const poDS = static_cast<GTiffDataset *>(hGTIFFDS);
221 2 : poDS->m_nZSTDLevel = static_cast<signed char>(nZSTDLevel);
222 :
223 2 : poDS->ScanDirectories();
224 :
225 4 : for (int i = 0; i < poDS->m_nOverviewCount; ++i)
226 2 : poDS->m_papoOverviewDS[i]->m_nZSTDLevel = poDS->m_nZSTDLevel;
227 2 : }
228 :
229 : /************************************************************************/
230 : /* GTIFFSetMaxZError() */
231 : /* Called by GTIFFBuildOverviews() to set the Lerc max error on the IFD */
232 : /* of the .ovr file. */
233 : /************************************************************************/
234 :
235 10 : void GTIFFSetMaxZError(GDALDatasetH hGTIFFDS, double dfMaxZError)
236 : {
237 10 : CPLAssert(
238 : EQUAL(GDALGetDriverShortName(GDALGetDatasetDriver(hGTIFFDS)), "GTIFF"));
239 :
240 10 : GTiffDataset *const poDS = static_cast<GTiffDataset *>(hGTIFFDS);
241 10 : poDS->m_dfMaxZError = dfMaxZError;
242 10 : poDS->m_dfMaxZErrorOverview = dfMaxZError;
243 :
244 10 : poDS->ScanDirectories();
245 :
246 20 : for (int i = 0; i < poDS->m_nOverviewCount; ++i)
247 : {
248 10 : poDS->m_papoOverviewDS[i]->m_dfMaxZError = poDS->m_dfMaxZError;
249 10 : poDS->m_papoOverviewDS[i]->m_dfMaxZErrorOverview =
250 10 : poDS->m_dfMaxZErrorOverview;
251 : }
252 10 : }
253 :
254 : #if HAVE_JXL
255 :
256 : /************************************************************************/
257 : /* GTIFFSetJXLLossless() */
258 : /* Called by GTIFFBuildOverviews() to set the JXL lossyness on the IFD */
259 : /* of the .ovr file. */
260 : /************************************************************************/
261 :
262 5 : void GTIFFSetJXLLossless(GDALDatasetH hGTIFFDS, bool bIsLossless)
263 : {
264 5 : CPLAssert(
265 : EQUAL(GDALGetDriverShortName(GDALGetDatasetDriver(hGTIFFDS)), "GTIFF"));
266 :
267 5 : GTiffDataset *const poDS = static_cast<GTiffDataset *>(hGTIFFDS);
268 5 : poDS->m_bJXLLossless = bIsLossless;
269 :
270 5 : poDS->ScanDirectories();
271 :
272 5 : for (int i = 0; i < poDS->m_nOverviewCount; ++i)
273 : {
274 0 : poDS->m_papoOverviewDS[i]->m_bJXLLossless = poDS->m_bJXLLossless;
275 : }
276 5 : }
277 :
278 : /************************************************************************/
279 : /* GTIFFSetJXLEffort() */
280 : /* Called by GTIFFBuildOverviews() to set the JXL effort on the IFD */
281 : /* of the .ovr file. */
282 : /************************************************************************/
283 :
284 0 : void GTIFFSetJXLEffort(GDALDatasetH hGTIFFDS, int nEffort)
285 : {
286 0 : CPLAssert(
287 : EQUAL(GDALGetDriverShortName(GDALGetDatasetDriver(hGTIFFDS)), "GTIFF"));
288 :
289 0 : GTiffDataset *const poDS = static_cast<GTiffDataset *>(hGTIFFDS);
290 0 : poDS->m_nJXLEffort = nEffort;
291 :
292 0 : poDS->ScanDirectories();
293 :
294 0 : for (int i = 0; i < poDS->m_nOverviewCount; ++i)
295 : {
296 0 : poDS->m_papoOverviewDS[i]->m_nJXLEffort = poDS->m_nJXLEffort;
297 : }
298 0 : }
299 :
300 : /************************************************************************/
301 : /* GTIFFSetJXLDistance() */
302 : /* Called by GTIFFBuildOverviews() to set the JXL distance on the IFD */
303 : /* of the .ovr file. */
304 : /************************************************************************/
305 :
306 1 : void GTIFFSetJXLDistance(GDALDatasetH hGTIFFDS, float fDistance)
307 : {
308 1 : CPLAssert(
309 : EQUAL(GDALGetDriverShortName(GDALGetDatasetDriver(hGTIFFDS)), "GTIFF"));
310 :
311 1 : GTiffDataset *const poDS = static_cast<GTiffDataset *>(hGTIFFDS);
312 1 : poDS->m_fJXLDistance = fDistance;
313 :
314 1 : poDS->ScanDirectories();
315 :
316 1 : for (int i = 0; i < poDS->m_nOverviewCount; ++i)
317 : {
318 0 : poDS->m_papoOverviewDS[i]->m_fJXLDistance = poDS->m_fJXLDistance;
319 : }
320 1 : }
321 :
322 : /************************************************************************/
323 : /* GTIFFSetJXLAlphaDistance() */
324 : /* Called by GTIFFBuildOverviews() to set the JXL alpha distance on the */
325 : /* IFD of the .ovr file. */
326 : /************************************************************************/
327 :
328 1 : void GTIFFSetJXLAlphaDistance(GDALDatasetH hGTIFFDS, float fAlphaDistance)
329 : {
330 1 : CPLAssert(
331 : EQUAL(GDALGetDriverShortName(GDALGetDatasetDriver(hGTIFFDS)), "GTIFF"));
332 :
333 1 : GTiffDataset *const poDS = static_cast<GTiffDataset *>(hGTIFFDS);
334 1 : poDS->m_fJXLAlphaDistance = fAlphaDistance;
335 :
336 1 : poDS->ScanDirectories();
337 :
338 1 : for (int i = 0; i < poDS->m_nOverviewCount; ++i)
339 : {
340 0 : poDS->m_papoOverviewDS[i]->m_fJXLAlphaDistance =
341 0 : poDS->m_fJXLAlphaDistance;
342 : }
343 1 : }
344 :
345 : #endif // HAVE_JXL
346 :
347 : /************************************************************************/
348 : /* GTiffGetAlphaValue() */
349 : /************************************************************************/
350 :
351 2418 : uint16_t GTiffGetAlphaValue(const char *pszValue, uint16_t nDefault)
352 : {
353 2418 : if (pszValue == nullptr)
354 2394 : return nDefault;
355 24 : if (EQUAL(pszValue, "YES"))
356 14 : return DEFAULT_ALPHA_TYPE;
357 10 : if (EQUAL(pszValue, "PREMULTIPLIED"))
358 5 : return EXTRASAMPLE_ASSOCALPHA;
359 5 : if (EQUAL(pszValue, "NON-PREMULTIPLIED"))
360 0 : return EXTRASAMPLE_UNASSALPHA;
361 5 : if (EQUAL(pszValue, "NO") || EQUAL(pszValue, "UNSPECIFIED"))
362 5 : return EXTRASAMPLE_UNSPECIFIED;
363 :
364 0 : return nDefault;
365 : }
366 :
367 : /************************************************************************/
368 : /* GTIFFIsStandardColorInterpretation() */
369 : /************************************************************************/
370 :
371 5407 : bool GTIFFIsStandardColorInterpretation(GDALDatasetH hSrcDS,
372 : uint16_t nPhotometric,
373 : CSLConstList papszCreationOptions)
374 : {
375 5407 : GDALDataset *poSrcDS = GDALDataset::FromHandle(hSrcDS);
376 5407 : bool bStandardColorInterp = true;
377 5407 : if (nPhotometric == PHOTOMETRIC_MINISBLACK)
378 : {
379 205110 : for (int i = 0; i < poSrcDS->GetRasterCount(); ++i)
380 : {
381 : const GDALColorInterp eInterp =
382 201335 : poSrcDS->GetRasterBand(i + 1)->GetColorInterpretation();
383 201335 : if (!(eInterp == GCI_GrayIndex || eInterp == GCI_Undefined ||
384 98 : (i > 0 && eInterp == GCI_AlphaBand)))
385 : {
386 41 : bStandardColorInterp = false;
387 41 : break;
388 : }
389 : }
390 : }
391 1591 : else if (nPhotometric == PHOTOMETRIC_PALETTE)
392 : {
393 46 : bStandardColorInterp =
394 46 : poSrcDS->GetRasterBand(1)->GetColorInterpretation() ==
395 : GCI_PaletteIndex;
396 : }
397 1545 : else if (nPhotometric == PHOTOMETRIC_RGB)
398 : {
399 1476 : int iStart = 0;
400 1476 : if (EQUAL(CSLFetchNameValueDef(papszCreationOptions, "PHOTOMETRIC", ""),
401 : "RGB"))
402 : {
403 50 : iStart = 3;
404 72 : if (poSrcDS->GetRasterCount() == 4 &&
405 22 : CSLFetchNameValue(papszCreationOptions, "ALPHA") != nullptr)
406 : {
407 5 : iStart = 4;
408 : }
409 : }
410 5879 : for (int i = iStart; i < poSrcDS->GetRasterCount(); ++i)
411 : {
412 : const GDALColorInterp eInterp =
413 4444 : poSrcDS->GetRasterBand(i + 1)->GetColorInterpretation();
414 4733 : if (!((i == 0 && eInterp == GCI_RedBand) ||
415 3059 : (i == 1 && eInterp == GCI_GreenBand) ||
416 1385 : (i == 2 && eInterp == GCI_BlueBand) ||
417 248 : (i >= 3 &&
418 203 : (eInterp == GCI_Undefined || eInterp == GCI_AlphaBand))))
419 : {
420 41 : bStandardColorInterp = false;
421 41 : break;
422 : }
423 : }
424 : }
425 130 : else if (nPhotometric == PHOTOMETRIC_YCBCR &&
426 61 : poSrcDS->GetRasterCount() == 3)
427 : {
428 : // do nothing
429 : }
430 : else
431 : {
432 8 : bStandardColorInterp = false;
433 : }
434 5407 : return bStandardColorInterp;
435 : }
436 :
437 : /************************************************************************/
438 : /* GTiffDatasetWriteRPCTag() */
439 : /* */
440 : /* Format a TAG according to: */
441 : /* */
442 : /* http://geotiff.maptools.org/rpc_prop.html */
443 : /************************************************************************/
444 :
445 12 : void GTiffDatasetWriteRPCTag(TIFF *hTIFF, char **papszRPCMD)
446 :
447 : {
448 : GDALRPCInfoV2 sRPC;
449 :
450 12 : if (!GDALExtractRPCInfoV2(papszRPCMD, &sRPC))
451 0 : return;
452 :
453 12 : double adfRPCTag[92] = {};
454 12 : adfRPCTag[0] = sRPC.dfERR_BIAS; // Error Bias
455 12 : adfRPCTag[1] = sRPC.dfERR_RAND; // Error Random
456 :
457 12 : adfRPCTag[2] = sRPC.dfLINE_OFF;
458 12 : adfRPCTag[3] = sRPC.dfSAMP_OFF;
459 12 : adfRPCTag[4] = sRPC.dfLAT_OFF;
460 12 : adfRPCTag[5] = sRPC.dfLONG_OFF;
461 12 : adfRPCTag[6] = sRPC.dfHEIGHT_OFF;
462 12 : adfRPCTag[7] = sRPC.dfLINE_SCALE;
463 12 : adfRPCTag[8] = sRPC.dfSAMP_SCALE;
464 12 : adfRPCTag[9] = sRPC.dfLAT_SCALE;
465 12 : adfRPCTag[10] = sRPC.dfLONG_SCALE;
466 12 : adfRPCTag[11] = sRPC.dfHEIGHT_SCALE;
467 :
468 12 : memcpy(adfRPCTag + 12, sRPC.adfLINE_NUM_COEFF, sizeof(double) * 20);
469 12 : memcpy(adfRPCTag + 32, sRPC.adfLINE_DEN_COEFF, sizeof(double) * 20);
470 12 : memcpy(adfRPCTag + 52, sRPC.adfSAMP_NUM_COEFF, sizeof(double) * 20);
471 12 : memcpy(adfRPCTag + 72, sRPC.adfSAMP_DEN_COEFF, sizeof(double) * 20);
472 :
473 12 : TIFFSetField(hTIFF, TIFFTAG_RPCCOEFFICIENT, 92, adfRPCTag);
474 : }
475 :
476 : /************************************************************************/
477 : /* ReadRPCTag() */
478 : /* */
479 : /* Format a TAG according to: */
480 : /* */
481 : /* http://geotiff.maptools.org/rpc_prop.html */
482 : /************************************************************************/
483 :
484 4848 : char **GTiffDatasetReadRPCTag(TIFF *hTIFF)
485 :
486 : {
487 4848 : double *padfRPCTag = nullptr;
488 : uint16_t nCount;
489 :
490 4882 : if (!TIFFGetField(hTIFF, TIFFTAG_RPCCOEFFICIENT, &nCount, &padfRPCTag) ||
491 34 : nCount != 92)
492 4814 : return nullptr;
493 :
494 34 : return gdal::tiff_common::TIFFRPCTagToRPCMetadata(padfRPCTag).StealList();
495 : }
496 :
497 : /************************************************************************/
498 : /* GTiffFormatGDALNoDataTagValue() */
499 : /************************************************************************/
500 :
501 413 : CPLString GTiffFormatGDALNoDataTagValue(double dfNoData)
502 : {
503 413 : CPLString osVal;
504 413 : if (std::isnan(dfNoData))
505 11 : osVal = "nan";
506 : else
507 402 : osVal.Printf("%.17g", dfNoData);
508 413 : return osVal;
509 : }
510 :
511 : /************************************************************************/
512 : /* GTIFFUpdatePhotometric() */
513 : /************************************************************************/
514 :
515 510 : bool GTIFFUpdatePhotometric(const char *pszPhotometric,
516 : const char *pszOptionKey, int nCompression,
517 : const char *pszInterleave, int nBands,
518 : uint16_t &nPhotometric, uint16_t &nPlanarConfig)
519 : {
520 510 : if (pszPhotometric != nullptr && pszPhotometric[0] != '\0')
521 : {
522 17 : if (EQUAL(pszPhotometric, "MINISBLACK"))
523 0 : nPhotometric = PHOTOMETRIC_MINISBLACK;
524 17 : else if (EQUAL(pszPhotometric, "MINISWHITE"))
525 0 : nPhotometric = PHOTOMETRIC_MINISWHITE;
526 17 : else if (EQUAL(pszPhotometric, "RGB"))
527 : {
528 0 : nPhotometric = PHOTOMETRIC_RGB;
529 : }
530 17 : else if (EQUAL(pszPhotometric, "CMYK"))
531 : {
532 0 : nPhotometric = PHOTOMETRIC_SEPARATED;
533 : }
534 17 : else if (EQUAL(pszPhotometric, "YCBCR"))
535 : {
536 17 : nPhotometric = PHOTOMETRIC_YCBCR;
537 :
538 : // Because of subsampling, setting YCBCR without JPEG compression
539 : // leads to a crash currently. Would need to make
540 : // GTiffRasterBand::IWriteBlock() aware of subsampling so that it
541 : // doesn't overrun buffer size returned by libtiff.
542 17 : if (nCompression != COMPRESSION_JPEG)
543 : {
544 0 : CPLError(CE_Failure, CPLE_NotSupported,
545 : "Currently, %s=YCBCR requires JPEG compression",
546 : pszOptionKey);
547 0 : return false;
548 : }
549 :
550 17 : if (pszInterleave != nullptr && pszInterleave[0] != '\0' &&
551 2 : nPlanarConfig == PLANARCONFIG_SEPARATE)
552 : {
553 0 : CPLError(CE_Failure, CPLE_NotSupported,
554 : "%s=YCBCR requires PIXEL interleaving", pszOptionKey);
555 0 : return false;
556 : }
557 : else
558 : {
559 17 : nPlanarConfig = PLANARCONFIG_CONTIG;
560 : }
561 :
562 : // YCBCR strictly requires 3 bands. Not less, not more
563 : // Issue an explicit error message as libtiff one is a bit cryptic:
564 : // JPEGLib:Bogus input colorspace.
565 17 : if (nBands != 3)
566 : {
567 0 : CPLError(CE_Failure, CPLE_NotSupported,
568 : "%s=YCBCR requires a source raster "
569 : "with only 3 bands (RGB)",
570 : pszOptionKey);
571 0 : return false;
572 : }
573 : }
574 0 : else if (EQUAL(pszPhotometric, "CIELAB"))
575 : {
576 0 : nPhotometric = PHOTOMETRIC_CIELAB;
577 : }
578 0 : else if (EQUAL(pszPhotometric, "ICCLAB"))
579 : {
580 0 : nPhotometric = PHOTOMETRIC_ICCLAB;
581 : }
582 0 : else if (EQUAL(pszPhotometric, "ITULAB"))
583 : {
584 0 : nPhotometric = PHOTOMETRIC_ITULAB;
585 : }
586 : else
587 : {
588 0 : CPLError(CE_Warning, CPLE_IllegalArg,
589 : "%s=%s value not recognised, ignoring.", pszOptionKey,
590 : pszPhotometric);
591 : }
592 : }
593 510 : return true;
594 : }
595 :
596 : /************************************************************************/
597 : /* GTiffWriteJPEGTables() */
598 : /* */
599 : /* Sets the TIFFTAG_JPEGTABLES (and TIFFTAG_REFERENCEBLACKWHITE) */
600 : /* tags immediately, instead of relying on the TIFF JPEG codec */
601 : /* to write them when it starts compressing imagery. This avoids */
602 : /* an IFD rewrite at the end of the file. */
603 : /* Must be used after having set TIFFTAG_SAMPLESPERPIXEL, */
604 : /* TIFFTAG_BITSPERSAMPLE. */
605 : /************************************************************************/
606 :
607 1071 : void GTiffWriteJPEGTables(TIFF *hTIFF, const char *pszPhotometric,
608 : const char *pszJPEGQuality,
609 : const char *pszJPEGTablesMode)
610 : {
611 : // This trick
612 : // creates a temporary in-memory file and fetches its JPEG tables so that
613 : // we can directly set them, before tif_jpeg.c compute them at the first
614 : // strip/tile writing, which is too late, since we have already crystalized
615 : // the directory. This way we avoid a directory rewriting.
616 1071 : uint16_t nBands = 0;
617 1071 : if (!TIFFGetField(hTIFF, TIFFTAG_SAMPLESPERPIXEL, &nBands))
618 0 : nBands = 1;
619 :
620 1071 : uint16_t l_nBitsPerSample = 0;
621 1071 : if (!TIFFGetField(hTIFF, TIFFTAG_BITSPERSAMPLE, &(l_nBitsPerSample)))
622 0 : l_nBitsPerSample = 1;
623 :
624 : const CPLString osTmpFilenameIn(
625 2142 : VSIMemGenerateHiddenFilename("gtiffdataset_jpg_tmp"));
626 1071 : VSILFILE *fpTmp = nullptr;
627 2142 : CPLString osTmp;
628 1071 : char **papszLocalParameters = nullptr;
629 1071 : const int nInMemImageWidth = 16;
630 1071 : const int nInMemImageHeight = 16;
631 : papszLocalParameters =
632 1071 : CSLSetNameValue(papszLocalParameters, "COMPRESS", "JPEG");
633 : papszLocalParameters =
634 1071 : CSLSetNameValue(papszLocalParameters, "JPEG_QUALITY", pszJPEGQuality);
635 1071 : if (nBands <= 4)
636 : {
637 1071 : papszLocalParameters = CSLSetNameValue(papszLocalParameters,
638 : "PHOTOMETRIC", pszPhotometric);
639 : }
640 1071 : papszLocalParameters = CSLSetNameValue(papszLocalParameters, "BLOCKYSIZE",
641 : CPLSPrintf("%u", nInMemImageHeight));
642 1071 : papszLocalParameters = CSLSetNameValue(papszLocalParameters, "NBITS",
643 : CPLSPrintf("%u", l_nBitsPerSample));
644 1071 : papszLocalParameters = CSLSetNameValue(papszLocalParameters,
645 : "JPEGTABLESMODE", pszJPEGTablesMode);
646 : papszLocalParameters =
647 1071 : CSLSetNameValue(papszLocalParameters, "WRITE_JPEGTABLE_TAG", "NO");
648 :
649 : TIFF *hTIFFTmp =
650 2142 : GTiffDataset::CreateLL(osTmpFilenameIn, nInMemImageWidth,
651 1071 : nInMemImageHeight, (nBands <= 4) ? nBands : 1,
652 1071 : (l_nBitsPerSample <= 8) ? GDT_Byte : GDT_UInt16,
653 : 0.0, 0, papszLocalParameters, &fpTmp, osTmp);
654 1071 : CSLDestroy(papszLocalParameters);
655 1071 : if (hTIFFTmp)
656 : {
657 1071 : uint16_t l_nPhotometric = 0;
658 1071 : int nJpegTablesModeIn = 0;
659 1071 : TIFFGetField(hTIFFTmp, TIFFTAG_PHOTOMETRIC, &(l_nPhotometric));
660 1071 : TIFFGetField(hTIFFTmp, TIFFTAG_JPEGTABLESMODE, &nJpegTablesModeIn);
661 1071 : TIFFWriteCheck(hTIFFTmp, FALSE, "CreateLL");
662 1071 : TIFFWriteDirectory(hTIFFTmp);
663 1071 : TIFFSetDirectory(hTIFFTmp, 0);
664 : // Now, reset quality and jpegcolormode.
665 1071 : const int l_nJpegQuality = pszJPEGQuality ? atoi(pszJPEGQuality) : 0;
666 1071 : if (l_nJpegQuality > 0)
667 967 : TIFFSetField(hTIFFTmp, TIFFTAG_JPEGQUALITY, l_nJpegQuality);
668 1459 : if (l_nPhotometric == PHOTOMETRIC_YCBCR &&
669 388 : CPLTestBool(CPLGetConfigOption("CONVERT_YCBCR_TO_RGB", "YES")))
670 : {
671 388 : TIFFSetField(hTIFFTmp, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
672 : }
673 1071 : if (nJpegTablesModeIn >= 0)
674 1067 : TIFFSetField(hTIFFTmp, TIFFTAG_JPEGTABLESMODE, nJpegTablesModeIn);
675 :
676 1071 : GPtrDiff_t nBlockSize = static_cast<GPtrDiff_t>(nInMemImageWidth) *
677 : nInMemImageHeight *
678 1071 : ((nBands <= 4) ? nBands : 1);
679 1071 : if (l_nBitsPerSample == 12)
680 590 : nBlockSize = (nBlockSize * 3) / 2;
681 1071 : std::vector<GByte> abyZeroData(nBlockSize, 0);
682 1071 : TIFFWriteEncodedStrip(hTIFFTmp, 0, &abyZeroData[0], nBlockSize);
683 :
684 1071 : uint32_t nJPEGTableSize = 0;
685 1071 : void *pJPEGTable = nullptr;
686 1071 : if (TIFFGetField(hTIFFTmp, TIFFTAG_JPEGTABLES, &nJPEGTableSize,
687 1071 : &pJPEGTable))
688 1068 : TIFFSetField(hTIFF, TIFFTAG_JPEGTABLES, nJPEGTableSize, pJPEGTable);
689 :
690 1071 : float *ref = nullptr;
691 1071 : if (TIFFGetField(hTIFFTmp, TIFFTAG_REFERENCEBLACKWHITE, &ref))
692 388 : TIFFSetField(hTIFF, TIFFTAG_REFERENCEBLACKWHITE, ref);
693 :
694 1071 : XTIFFClose(hTIFFTmp);
695 1071 : CPL_IGNORE_RET_VAL(VSIFCloseL(fpTmp));
696 : }
697 1071 : VSIUnlink(osTmpFilenameIn);
698 1071 : }
699 :
700 : #if !defined(SUPPORTS_LIBTIFF_OPEN_OPTIONS)
701 :
702 : /************************************************************************/
703 : /* GTiffWarningHandler() */
704 : /************************************************************************/
705 : static void GTiffWarningHandler(const char *module, const char *fmt, va_list ap)
706 : {
707 : if (GTIFFGetThreadLocalLibtiffError() > 0)
708 : {
709 : GTIFFGetThreadLocalLibtiffError()++;
710 : if (GTIFFGetThreadLocalLibtiffError() > 10)
711 : return;
712 : }
713 :
714 : if (strstr(fmt, "nknown field") != nullptr)
715 : return;
716 :
717 : char *pszModFmt = gdal::tiff_common::PrepareTIFFErrorFormat(module, fmt);
718 : if (strstr(fmt, "does not end in null byte") != nullptr)
719 : {
720 : CPLString osMsg;
721 : osMsg.vPrintf(pszModFmt, ap);
722 : CPLDebug("GTiff", "%s", osMsg.c_str());
723 : }
724 : else
725 : {
726 : CPLErrorV(CE_Warning, CPLE_AppDefined, pszModFmt, ap);
727 : }
728 : CPLFree(pszModFmt);
729 : return;
730 : }
731 :
732 : /************************************************************************/
733 : /* GTiffErrorHandler() */
734 : /************************************************************************/
735 : static void GTiffErrorHandler(const char *module, const char *fmt, va_list ap)
736 : {
737 : if (GTIFFGetThreadLocalLibtiffError() > 0)
738 : {
739 : GTIFFGetThreadLocalLibtiffError()++;
740 : if (GTIFFGetThreadLocalLibtiffError() > 10)
741 : return;
742 : }
743 :
744 : if (strcmp(fmt, "Maximum TIFF file size exceeded") == 0)
745 : {
746 : if (bThreadLocalInExternalOvr)
747 : fmt = "Maximum TIFF file size exceeded. "
748 : "Use --config BIGTIFF_OVERVIEW YES configuration option.";
749 : else
750 : fmt = "Maximum TIFF file size exceeded. "
751 : "Use BIGTIFF=YES creation option.";
752 : }
753 :
754 : char *pszModFmt = gdal::tiff_common::PrepareTIFFErrorFormat(module, fmt);
755 : CPLErrorV(CE_Failure, CPLE_AppDefined, pszModFmt, ap);
756 : CPLFree(pszModFmt);
757 : return;
758 : }
759 : #else
760 :
761 : /************************************************************************/
762 : /* GTiffWarningHandlerExt() */
763 : /************************************************************************/
764 : extern int GTiffWarningHandlerExt(TIFF *tif, void *user_data,
765 : const char *module, const char *fmt,
766 : va_list ap);
767 :
768 327 : int GTiffWarningHandlerExt(TIFF *tif, void *user_data, const char *module,
769 : const char *fmt, va_list ap)
770 : {
771 : (void)tif;
772 : (void)user_data;
773 327 : auto &nLibtiffErrors = GTIFFGetThreadLocalLibtiffError();
774 : // cppcheck-suppress knownConditionTrueFalse
775 327 : if (nLibtiffErrors > 0)
776 : {
777 217 : nLibtiffErrors++;
778 : // cppcheck-suppress knownConditionTrueFalse
779 217 : if (nLibtiffErrors > 10)
780 0 : return 1;
781 : }
782 :
783 327 : if (strstr(fmt, "nknown field") != nullptr)
784 0 : return 1;
785 :
786 327 : char *pszModFmt = gdal::tiff_common::PrepareTIFFErrorFormat(module, fmt);
787 327 : if (strstr(fmt, "does not end in null byte") != nullptr)
788 : {
789 2 : CPLString osMsg;
790 1 : osMsg.vPrintf(pszModFmt, ap);
791 1 : CPLDebug("GTiff", "%s", osMsg.c_str());
792 : }
793 : else
794 : {
795 326 : CPLErrorV(CE_Warning, CPLE_AppDefined, pszModFmt, ap);
796 : }
797 327 : CPLFree(pszModFmt);
798 327 : return 1;
799 : }
800 :
801 : /************************************************************************/
802 : /* GTiffErrorHandlerExt() */
803 : /************************************************************************/
804 : extern int GTiffErrorHandlerExt(TIFF *tif, void *user_data, const char *module,
805 : const char *fmt, va_list ap);
806 :
807 245 : int GTiffErrorHandlerExt(TIFF *tif, void *user_data, const char *module,
808 : const char *fmt, va_list ap)
809 : {
810 : (void)tif;
811 : (void)user_data;
812 245 : auto &nLibtiffErrors = GTIFFGetThreadLocalLibtiffError();
813 : // cppcheck-suppress knownConditionTrueFalse
814 245 : if (nLibtiffErrors > 0)
815 : {
816 108 : nLibtiffErrors++;
817 : // cppcheck-suppress knownConditionTrueFalse
818 108 : if (nLibtiffErrors > 10)
819 0 : return 1;
820 : }
821 :
822 245 : if (strcmp(fmt, "Maximum TIFF file size exceeded") == 0)
823 : {
824 0 : if (bThreadLocalInExternalOvr)
825 0 : fmt = "Maximum TIFF file size exceeded. "
826 : "Use --config BIGTIFF_OVERVIEW YES configuration option.";
827 : else
828 0 : fmt = "Maximum TIFF file size exceeded. "
829 : "Use BIGTIFF=YES creation option.";
830 : }
831 :
832 245 : char *pszModFmt = gdal::tiff_common::PrepareTIFFErrorFormat(module, fmt);
833 245 : CPLErrorV(CE_Failure, CPLE_AppDefined, pszModFmt, ap);
834 245 : CPLFree(pszModFmt);
835 245 : return 1;
836 : }
837 :
838 : #endif
839 :
840 : /************************************************************************/
841 : /* GTiffTagExtender() */
842 : /* */
843 : /* Install tags specially known to GDAL. */
844 : /************************************************************************/
845 :
846 : static TIFFExtendProc _ParentExtender = nullptr;
847 :
848 119750 : static void GTiffTagExtender(TIFF *tif)
849 :
850 : {
851 119750 : const TIFFFieldInfo xtiffFieldInfo[] = {
852 : {TIFFTAG_GDAL_METADATA, -1, -1, TIFF_ASCII, FIELD_CUSTOM, TRUE, FALSE,
853 : const_cast<char *>("GDALMetadata")},
854 : {TIFFTAG_GDAL_NODATA, -1, -1, TIFF_ASCII, FIELD_CUSTOM, TRUE, FALSE,
855 : const_cast<char *>("GDALNoDataValue")},
856 : {TIFFTAG_RPCCOEFFICIENT, -1, -1, TIFF_DOUBLE, FIELD_CUSTOM, TRUE, TRUE,
857 : const_cast<char *>("RPCCoefficient")},
858 : {TIFFTAG_TIFF_RSID, -1, -1, TIFF_ASCII, FIELD_CUSTOM, TRUE, FALSE,
859 : const_cast<char *>("TIFF_RSID")},
860 : {TIFFTAG_GEO_METADATA, TIFF_VARIABLE2, TIFF_VARIABLE2, TIFF_BYTE,
861 : FIELD_CUSTOM, TRUE, TRUE, const_cast<char *>("GEO_METADATA")}};
862 :
863 119750 : if (_ParentExtender)
864 0 : (*_ParentExtender)(tif);
865 :
866 119750 : TIFFMergeFieldInfo(tif, xtiffFieldInfo,
867 : sizeof(xtiffFieldInfo) / sizeof(xtiffFieldInfo[0]));
868 119756 : }
869 :
870 : /************************************************************************/
871 : /* GTiffOneTimeInit() */
872 : /* */
873 : /* This is stuff that is initialized for the TIFF library just */
874 : /* once. We deliberately defer the initialization till the */
875 : /* first time we are likely to call into libtiff to avoid */
876 : /* unnecessary paging in of the library for GDAL apps that */
877 : /* don't use it. */
878 : /************************************************************************/
879 :
880 : static std::mutex oDeleteMutex;
881 : #ifdef HAVE_JXL
882 : static TIFFCodec *pJXLCodec = nullptr;
883 : static TIFFCodec *pJXLCodecDNG17 = nullptr;
884 : #endif
885 :
886 28011 : void GTiffOneTimeInit()
887 :
888 : {
889 28011 : std::lock_guard<std::mutex> oLock(oDeleteMutex);
890 :
891 : static bool bOneTimeInitDone = false;
892 28022 : if (bOneTimeInitDone)
893 27401 : return;
894 :
895 621 : bOneTimeInitDone = true;
896 :
897 : #ifdef HAVE_JXL
898 621 : if (pJXLCodec == nullptr)
899 : {
900 621 : pJXLCodec = TIFFRegisterCODEC(COMPRESSION_JXL, "JXL", TIFFInitJXL);
901 621 : pJXLCodecDNG17 =
902 621 : TIFFRegisterCODEC(COMPRESSION_JXL_DNG_1_7, "JXL", TIFFInitJXL);
903 : }
904 : #endif
905 :
906 621 : _ParentExtender = TIFFSetTagExtender(GTiffTagExtender);
907 :
908 : #if !defined(SUPPORTS_LIBTIFF_OPEN_OPTIONS)
909 : TIFFSetWarningHandler(GTiffWarningHandler);
910 : TIFFSetErrorHandler(GTiffErrorHandler);
911 : #endif
912 :
913 621 : LibgeotiffOneTimeInit();
914 : }
915 :
916 : /************************************************************************/
917 : /* GDALDeregister_GTiff() */
918 : /************************************************************************/
919 :
920 941 : static void GDALDeregister_GTiff(GDALDriver *)
921 :
922 : {
923 : #ifdef HAVE_JXL
924 941 : if (pJXLCodec)
925 450 : TIFFUnRegisterCODEC(pJXLCodec);
926 941 : pJXLCodec = nullptr;
927 941 : if (pJXLCodecDNG17)
928 450 : TIFFUnRegisterCODEC(pJXLCodecDNG17);
929 941 : pJXLCodecDNG17 = nullptr;
930 : #endif
931 941 : }
932 :
933 : #define COMPRESSION_ENTRY(x, bWriteSupported) \
934 : { \
935 : COMPRESSION_##x, STRINGIFY(x), bWriteSupported \
936 : }
937 :
938 : static const struct
939 : {
940 : int nCode;
941 : const char *pszText;
942 : bool bWriteSupported;
943 : } asCompressionNames[] = {
944 : // Compression methods in read/write mode
945 : COMPRESSION_ENTRY(NONE, true),
946 : COMPRESSION_ENTRY(CCITTRLE, true),
947 : COMPRESSION_ENTRY(CCITTFAX3, true),
948 : {COMPRESSION_CCITTFAX3, "FAX3", true}, // alternate name for write side
949 : COMPRESSION_ENTRY(CCITTFAX4, true),
950 : {COMPRESSION_CCITTFAX4, "FAX4", true}, // alternate name for write side
951 : COMPRESSION_ENTRY(LZW, true),
952 : COMPRESSION_ENTRY(JPEG, true),
953 : COMPRESSION_ENTRY(PACKBITS, true),
954 : {COMPRESSION_ADOBE_DEFLATE, "DEFLATE",
955 : true}, // manual entry since we want the user friendly name to be DEFLATE
956 : {COMPRESSION_ADOBE_DEFLATE, "ZIP", true}, // alternate name for write side
957 : COMPRESSION_ENTRY(LZMA, true),
958 : COMPRESSION_ENTRY(ZSTD, true),
959 : COMPRESSION_ENTRY(LERC, true),
960 : {COMPRESSION_LERC, "LERC_DEFLATE", true},
961 : {COMPRESSION_LERC, "LERC_ZSTD", true},
962 : COMPRESSION_ENTRY(WEBP, true),
963 : // COMPRESSION_JXL_DNG_1_7 must be *before* COMPRESSION_JXL
964 : {COMPRESSION_JXL_DNG_1_7, "JXL", true},
965 : {COMPRESSION_JXL, "JXL",
966 : true}, // deprecated. No longer used for writing since GDAL 3.11
967 :
968 : // Compression methods in read-only
969 : COMPRESSION_ENTRY(OJPEG, false),
970 : COMPRESSION_ENTRY(NEXT, false),
971 : COMPRESSION_ENTRY(CCITTRLEW, false),
972 : COMPRESSION_ENTRY(THUNDERSCAN, false),
973 : COMPRESSION_ENTRY(PIXARFILM, false),
974 : COMPRESSION_ENTRY(PIXARLOG, false),
975 : COMPRESSION_ENTRY(DEFLATE, false), // COMPRESSION_DEFLATE is deprecated
976 : COMPRESSION_ENTRY(DCS, false),
977 : COMPRESSION_ENTRY(JBIG, false),
978 : COMPRESSION_ENTRY(SGILOG, false),
979 : COMPRESSION_ENTRY(SGILOG24, false),
980 : COMPRESSION_ENTRY(JP2000, false),
981 : };
982 :
983 : /************************************************************************/
984 : /* GTIFFGetCompressionMethodName() */
985 : /************************************************************************/
986 :
987 3223 : const char *GTIFFGetCompressionMethodName(int nCompressionCode)
988 : {
989 38441 : for (const auto &entry : asCompressionNames)
990 : {
991 38439 : if (entry.nCode == nCompressionCode)
992 : {
993 3221 : return entry.pszText;
994 : }
995 : }
996 2 : return nullptr;
997 : }
998 :
999 : /************************************************************************/
1000 : /* GTIFFGetCompressionMethod() */
1001 : /************************************************************************/
1002 :
1003 3232 : int GTIFFGetCompressionMethod(const char *pszValue, const char *pszVariableName)
1004 : {
1005 3232 : int nCompression = COMPRESSION_NONE;
1006 3232 : bool bFoundMatch = false;
1007 28244 : for (const auto &entry : asCompressionNames)
1008 : {
1009 28242 : if (entry.bWriteSupported && EQUAL(entry.pszText, pszValue))
1010 : {
1011 3230 : bFoundMatch = true;
1012 3230 : nCompression = entry.nCode;
1013 3230 : break;
1014 : }
1015 : }
1016 :
1017 3232 : if (!bFoundMatch)
1018 : {
1019 2 : CPLError(CE_Warning, CPLE_IllegalArg,
1020 : "%s=%s value not recognised, ignoring.", pszVariableName,
1021 : pszValue);
1022 : }
1023 :
1024 6460 : if (nCompression != COMPRESSION_NONE &&
1025 3228 : !TIFFIsCODECConfigured(static_cast<uint16_t>(nCompression)))
1026 : {
1027 0 : CPLError(CE_Failure, CPLE_AppDefined,
1028 : "Cannot create TIFF file due to missing codec for %s.",
1029 : pszValue);
1030 0 : return -1;
1031 : }
1032 :
1033 3232 : return nCompression;
1034 : }
1035 :
1036 : /************************************************************************/
1037 : /* GTiffGetCompressValues() */
1038 : /************************************************************************/
1039 :
1040 2762 : CPLString GTiffGetCompressValues(bool &bHasLZW, bool &bHasDEFLATE,
1041 : bool &bHasLZMA, bool &bHasZSTD, bool &bHasJPEG,
1042 : bool &bHasWebP, bool &bHasLERC, bool bForCOG)
1043 : {
1044 2762 : bHasLZW = false;
1045 2762 : bHasDEFLATE = false;
1046 2762 : bHasLZMA = false;
1047 2762 : bHasZSTD = false;
1048 2762 : bHasJPEG = false;
1049 2762 : bHasWebP = false;
1050 2762 : bHasLERC = false;
1051 :
1052 : /* -------------------------------------------------------------------- */
1053 : /* Determine which compression codecs are available that we */
1054 : /* want to advertise. If we are using an old libtiff we won't */
1055 : /* be able to find out so we just assume all are available. */
1056 : /* -------------------------------------------------------------------- */
1057 2762 : CPLString osCompressValues = " <Value>NONE</Value>";
1058 :
1059 2762 : TIFFCodec *codecs = TIFFGetConfiguredCODECs();
1060 :
1061 58002 : for (TIFFCodec *c = codecs; c->name; ++c)
1062 : {
1063 55240 : if (c->scheme == COMPRESSION_PACKBITS && !bForCOG)
1064 : {
1065 1381 : osCompressValues += " <Value>PACKBITS</Value>";
1066 : }
1067 53859 : else if (c->scheme == COMPRESSION_JPEG)
1068 : {
1069 2762 : bHasJPEG = true;
1070 2762 : osCompressValues += " <Value>JPEG</Value>";
1071 : }
1072 51097 : else if (c->scheme == COMPRESSION_LZW)
1073 : {
1074 2762 : bHasLZW = true;
1075 2762 : osCompressValues += " <Value>LZW</Value>";
1076 : }
1077 48335 : else if (c->scheme == COMPRESSION_ADOBE_DEFLATE)
1078 : {
1079 2762 : bHasDEFLATE = true;
1080 2762 : osCompressValues += " <Value>DEFLATE</Value>";
1081 : }
1082 45573 : else if (c->scheme == COMPRESSION_CCITTRLE && !bForCOG)
1083 : {
1084 1381 : osCompressValues += " <Value>CCITTRLE</Value>";
1085 : }
1086 44192 : else if (c->scheme == COMPRESSION_CCITTFAX3 && !bForCOG)
1087 : {
1088 1381 : osCompressValues += " <Value>CCITTFAX3</Value>";
1089 : }
1090 42811 : else if (c->scheme == COMPRESSION_CCITTFAX4 && !bForCOG)
1091 : {
1092 1381 : osCompressValues += " <Value>CCITTFAX4</Value>";
1093 : }
1094 41430 : else if (c->scheme == COMPRESSION_LZMA)
1095 : {
1096 2762 : bHasLZMA = true;
1097 2762 : osCompressValues += " <Value>LZMA</Value>";
1098 : }
1099 38668 : else if (c->scheme == COMPRESSION_ZSTD)
1100 : {
1101 2762 : bHasZSTD = true;
1102 2762 : osCompressValues += " <Value>ZSTD</Value>";
1103 : }
1104 35906 : else if (c->scheme == COMPRESSION_WEBP)
1105 : {
1106 2762 : bHasWebP = true;
1107 2762 : osCompressValues += " <Value>WEBP</Value>";
1108 : }
1109 33144 : else if (c->scheme == COMPRESSION_LERC)
1110 : {
1111 2762 : bHasLERC = true;
1112 : }
1113 : }
1114 2762 : if (bHasLERC)
1115 : {
1116 : osCompressValues += " <Value>LERC</Value>"
1117 2762 : " <Value>LERC_DEFLATE</Value>";
1118 2762 : if (bHasZSTD)
1119 : {
1120 2762 : osCompressValues += " <Value>LERC_ZSTD</Value>";
1121 : }
1122 : }
1123 : #ifdef HAVE_JXL
1124 2762 : osCompressValues += " <Value>JXL</Value>";
1125 : #endif
1126 2762 : _TIFFfree(codecs);
1127 :
1128 2762 : return osCompressValues;
1129 : }
1130 :
1131 : /************************************************************************/
1132 : /* OGRGTiffDriverGetSubdatasetInfo() */
1133 : /************************************************************************/
1134 :
1135 : struct GTiffDriverSubdatasetInfo : public GDALSubdatasetInfo
1136 : {
1137 : public:
1138 7 : explicit GTiffDriverSubdatasetInfo(const std::string &fileName)
1139 7 : : GDALSubdatasetInfo(fileName)
1140 : {
1141 7 : }
1142 :
1143 : // GDALSubdatasetInfo interface
1144 : private:
1145 7 : void parseFileName() override
1146 : {
1147 7 : if (!STARTS_WITH_CI(m_fileName.c_str(), "GTIFF_DIR:"))
1148 : {
1149 0 : return;
1150 : }
1151 :
1152 7 : CPLStringList aosParts{CSLTokenizeString2(m_fileName.c_str(), ":", 0)};
1153 7 : const int iPartsCount{CSLCount(aosParts)};
1154 :
1155 7 : if (iPartsCount == 3 || iPartsCount == 4)
1156 : {
1157 :
1158 7 : m_driverPrefixComponent = aosParts[0];
1159 :
1160 : const bool hasDriveLetter{
1161 9 : strlen(aosParts[2]) == 1 &&
1162 2 : std::isalpha(static_cast<unsigned char>(aosParts[2][0]))};
1163 :
1164 : // Check for drive letter
1165 7 : if (iPartsCount == 4)
1166 : {
1167 : // Invalid
1168 2 : if (!hasDriveLetter)
1169 : {
1170 0 : return;
1171 : }
1172 2 : m_pathComponent = aosParts[2];
1173 2 : m_pathComponent.append(":");
1174 2 : m_pathComponent.append(aosParts[3]);
1175 : }
1176 : else // count is 3
1177 : {
1178 5 : if (hasDriveLetter)
1179 : {
1180 0 : return;
1181 : }
1182 5 : m_pathComponent = aosParts[2];
1183 : }
1184 :
1185 7 : m_subdatasetComponent = aosParts[1];
1186 : }
1187 : }
1188 : };
1189 :
1190 2710 : static GDALSubdatasetInfo *GTiffDriverGetSubdatasetInfo(const char *pszFileName)
1191 : {
1192 2710 : if (STARTS_WITH_CI(pszFileName, "GTIFF_DIR:"))
1193 : {
1194 : std::unique_ptr<GDALSubdatasetInfo> info =
1195 7 : std::make_unique<GTiffDriverSubdatasetInfo>(pszFileName);
1196 21 : if (!info->GetSubdatasetComponent().empty() &&
1197 14 : !info->GetPathComponent().empty())
1198 : {
1199 7 : return info.release();
1200 : }
1201 : }
1202 2703 : return nullptr;
1203 : }
1204 :
1205 : /************************************************************************/
1206 : /* GDALRegister_GTiff() */
1207 : /************************************************************************/
1208 :
1209 1682 : void GDALRegister_GTiff()
1210 :
1211 : {
1212 1682 : if (GDALGetDriverByName("GTiff") != nullptr)
1213 301 : return;
1214 :
1215 2762 : CPLString osOptions;
1216 :
1217 1381 : bool bHasLZW = false;
1218 1381 : bool bHasDEFLATE = false;
1219 1381 : bool bHasLZMA = false;
1220 1381 : bool bHasZSTD = false;
1221 1381 : bool bHasJPEG = false;
1222 1381 : bool bHasWebP = false;
1223 1381 : bool bHasLERC = false;
1224 : CPLString osCompressValues(GTiffGetCompressValues(
1225 : bHasLZW, bHasDEFLATE, bHasLZMA, bHasZSTD, bHasJPEG, bHasWebP, bHasLERC,
1226 2762 : false /* bForCOG */));
1227 :
1228 1381 : GDALDriver *poDriver = new GDALDriver();
1229 :
1230 : /* -------------------------------------------------------------------- */
1231 : /* Build full creation option list. */
1232 : /* -------------------------------------------------------------------- */
1233 : osOptions = "<CreationOptionList>"
1234 1381 : " <Option name='COMPRESS' type='string-select'>";
1235 1381 : osOptions += osCompressValues;
1236 1381 : osOptions += " </Option>";
1237 1381 : if (bHasLZW || bHasDEFLATE || bHasZSTD)
1238 : osOptions += ""
1239 : " <Option name='PREDICTOR' type='int' "
1240 : "description='Predictor Type (1=default, 2=horizontal "
1241 1381 : "differencing, 3=floating point prediction)'/>";
1242 : osOptions +=
1243 : ""
1244 : " <Option name='DISCARD_LSB' type='string' description='Number of "
1245 : "least-significant bits to set to clear as a single value or "
1246 1381 : "comma-separated list of values for per-band values'/>";
1247 1381 : if (bHasJPEG)
1248 : {
1249 : osOptions +=
1250 : ""
1251 : " <Option name='JPEG_QUALITY' type='int' description='JPEG "
1252 : "quality 1-100' min='1' max='100' default='75'/>"
1253 : " <Option name='JPEGTABLESMODE' type='int' description='Content "
1254 : "of JPEGTABLES tag. 0=no JPEGTABLES tag, 1=Quantization tables "
1255 1381 : "only, 2=Huffman tables only, 3=Both' default='1'/>";
1256 : #ifdef JPEG_DIRECT_COPY
1257 : osOptions +=
1258 : ""
1259 : " <Option name='JPEG_DIRECT_COPY' type='boolean' description='To "
1260 : "copy without any decompression/recompression a JPEG source file' "
1261 : "default='NO'/>";
1262 : #endif
1263 : }
1264 1381 : if (bHasDEFLATE)
1265 : {
1266 : #ifdef LIBDEFLATE_SUPPORT
1267 : osOptions += ""
1268 : " <Option name='ZLEVEL' type='int' description='DEFLATE "
1269 1381 : "compression level 1-12' min='1' max='12' default='6'/>";
1270 : #else
1271 : osOptions += ""
1272 : " <Option name='ZLEVEL' type='int' description='DEFLATE "
1273 : "compression level 1-9' min='1' max='9' default='6'/>";
1274 : #endif
1275 : }
1276 1381 : if (bHasLZMA)
1277 : osOptions +=
1278 : ""
1279 : " <Option name='LZMA_PRESET' type='int' description='LZMA "
1280 1381 : "compression level 0(fast)-9(slow)' min='0' max='9' default='6'/>";
1281 1381 : if (bHasZSTD)
1282 : osOptions +=
1283 : ""
1284 : " <Option name='ZSTD_LEVEL' type='int' description='ZSTD "
1285 : "compression level 1(fast)-22(slow)' min='1' max='22' "
1286 1381 : "default='9'/>";
1287 1381 : if (bHasLERC)
1288 : {
1289 : osOptions +=
1290 : ""
1291 : " <Option name='MAX_Z_ERROR' type='float' description='Maximum "
1292 : "error for LERC compression' default='0'/>"
1293 : " <Option name='MAX_Z_ERROR_OVERVIEW' type='float' "
1294 : "description='Maximum error for LERC compression in overviews' "
1295 1381 : "default='0'/>";
1296 : }
1297 1381 : if (bHasWebP)
1298 : {
1299 : #ifndef DEFAULT_WEBP_LEVEL
1300 : #error "DEFAULT_WEBP_LEVEL should be defined"
1301 : #endif
1302 : osOptions +=
1303 : ""
1304 : #if WEBP_ENCODER_ABI_VERSION >= 0x0100
1305 : " <Option name='WEBP_LOSSLESS' type='boolean' "
1306 : "description='Whether lossless compression should be used' "
1307 : "default='FALSE'/>"
1308 : #endif
1309 : " <Option name='WEBP_LEVEL' type='int' description='WEBP quality "
1310 : "level. Low values result in higher compression ratios' "
1311 1381 : "default='" XSTRINGIFY(DEFAULT_WEBP_LEVEL) "'/>";
1312 : }
1313 : #ifdef HAVE_JXL
1314 : osOptions +=
1315 : ""
1316 : " <Option name='JXL_LOSSLESS' type='boolean' description='Whether "
1317 : "JPEGXL compression should be lossless' default='YES'/>"
1318 : " <Option name='JXL_EFFORT' type='int' description='Level of effort "
1319 : "1(fast)-9(slow)' min='1' max='9' default='5'/>"
1320 : " <Option name='JXL_DISTANCE' type='float' description='Distance "
1321 : "level for lossy compression (0=mathematically lossless, 1.0=visually "
1322 1381 : "lossless, usual range [0.5,3])' default='1.0' min='0.01' max='25.0'/>";
1323 : #ifdef HAVE_JxlEncoderSetExtraChannelDistance
1324 : osOptions += " <Option name='JXL_ALPHA_DISTANCE' type='float' "
1325 : "description='Distance level for alpha channel "
1326 : "(-1=same as non-alpha channels, "
1327 : "0=mathematically lossless, 1.0=visually lossless, "
1328 1381 : "usual range [0.5,3])' default='-1' min='-1' max='25.0'/>";
1329 : #endif
1330 : #endif
1331 : osOptions +=
1332 : ""
1333 : " <Option name='NUM_THREADS' type='string' description='Number of "
1334 : "worker threads for compression. Can be set to ALL_CPUS' default='1'/>"
1335 : " <Option name='NBITS' type='int' description='BITS for sub-byte "
1336 : "files (1-7), sub-uint16_t (9-15), sub-uint32_t (17-31), or float32 "
1337 : "(16)'/>"
1338 : " <Option name='INTERLEAVE' type='string-select' default='PIXEL'>"
1339 : " <Value>BAND</Value>"
1340 : " <Value>PIXEL</Value>"
1341 : " </Option>"
1342 : " <Option name='TILED' type='boolean' description='Switch to tiled "
1343 : "format'/>"
1344 : " <Option name='TFW' type='boolean' description='Write out world "
1345 : "file'/>"
1346 : " <Option name='RPB' type='boolean' description='Write out .RPB "
1347 : "(RPC) file'/>"
1348 : " <Option name='RPCTXT' type='boolean' description='Write out "
1349 : "_RPC.TXT file'/>"
1350 : " <Option name='BLOCKXSIZE' type='int' description='Tile Width'/>"
1351 : " <Option name='BLOCKYSIZE' type='int' description='Tile/Strip "
1352 : "Height'/>"
1353 : " <Option name='PHOTOMETRIC' type='string-select'>"
1354 : " <Value>MINISBLACK</Value>"
1355 : " <Value>MINISWHITE</Value>"
1356 : " <Value>PALETTE</Value>"
1357 : " <Value>RGB</Value>"
1358 : " <Value>CMYK</Value>"
1359 : " <Value>YCBCR</Value>"
1360 : " <Value>CIELAB</Value>"
1361 : " <Value>ICCLAB</Value>"
1362 : " <Value>ITULAB</Value>"
1363 : " </Option>"
1364 : " <Option name='SPARSE_OK' type='boolean' description='Should empty "
1365 : "blocks be omitted on disk?' default='FALSE'/>"
1366 : " <Option name='ALPHA' type='string-select' description='Mark first "
1367 : "extrasample as being alpha'>"
1368 : " <Value>NON-PREMULTIPLIED</Value>"
1369 : " <Value>PREMULTIPLIED</Value>"
1370 : " <Value>UNSPECIFIED</Value>"
1371 : " <Value aliasOf='NON-PREMULTIPLIED'>YES</Value>"
1372 : " <Value aliasOf='UNSPECIFIED'>NO</Value>"
1373 : " </Option>"
1374 : " <Option name='PROFILE' type='string-select' default='GDALGeoTIFF'>"
1375 : " <Value>GDALGeoTIFF</Value>"
1376 : " <Value>GeoTIFF</Value>"
1377 : " <Value>BASELINE</Value>"
1378 : " </Option>"
1379 : " <Option name='PIXELTYPE' type='string-select' "
1380 : "description='(deprecated, use Int8 datatype)'>"
1381 : " <Value>DEFAULT</Value>"
1382 : " <Value>SIGNEDBYTE</Value>"
1383 : " </Option>"
1384 : " <Option name='BIGTIFF' type='string-select' description='Force "
1385 : "creation of BigTIFF file'>"
1386 : " <Value>YES</Value>"
1387 : " <Value>NO</Value>"
1388 : " <Value>IF_NEEDED</Value>"
1389 : " <Value>IF_SAFER</Value>"
1390 : " </Option>"
1391 : " <Option name='ENDIANNESS' type='string-select' default='NATIVE' "
1392 : "description='Force endianness of created file. For DEBUG purpose "
1393 : "mostly'>"
1394 : " <Value>NATIVE</Value>"
1395 : " <Value>INVERTED</Value>"
1396 : " <Value>LITTLE</Value>"
1397 : " <Value>BIG</Value>"
1398 : " </Option>"
1399 : " <Option name='COPY_SRC_OVERVIEWS' type='boolean' default='NO' "
1400 : "description='Force copy of overviews of source dataset "
1401 : "(CreateCopy())'/>"
1402 : " <Option name='SOURCE_ICC_PROFILE' type='string' description='ICC "
1403 : "profile'/>"
1404 : " <Option name='SOURCE_PRIMARIES_RED' type='string' "
1405 : "description='x,y,1.0 (xyY) red chromaticity'/>"
1406 : " <Option name='SOURCE_PRIMARIES_GREEN' type='string' "
1407 : "description='x,y,1.0 (xyY) green chromaticity'/>"
1408 : " <Option name='SOURCE_PRIMARIES_BLUE' type='string' "
1409 : "description='x,y,1.0 (xyY) blue chromaticity'/>"
1410 : " <Option name='SOURCE_WHITEPOINT' type='string' "
1411 : "description='x,y,1.0 (xyY) whitepoint'/>"
1412 : " <Option name='TIFFTAG_TRANSFERFUNCTION_RED' type='string' "
1413 : "description='Transfer function for red'/>"
1414 : " <Option name='TIFFTAG_TRANSFERFUNCTION_GREEN' type='string' "
1415 : "description='Transfer function for green'/>"
1416 : " <Option name='TIFFTAG_TRANSFERFUNCTION_BLUE' type='string' "
1417 : "description='Transfer function for blue'/>"
1418 : " <Option name='TIFFTAG_TRANSFERRANGE_BLACK' type='string' "
1419 : "description='Transfer range for black'/>"
1420 : " <Option name='TIFFTAG_TRANSFERRANGE_WHITE' type='string' "
1421 : "description='Transfer range for white'/>"
1422 : " <Option name='STREAMABLE_OUTPUT' type='boolean' default='NO' "
1423 : "description='Enforce a mode compatible with a streamable file'/>"
1424 : " <Option name='GEOTIFF_KEYS_FLAVOR' type='string-select' "
1425 : "default='STANDARD' description='Which flavor of GeoTIFF keys must be "
1426 : "used'>"
1427 : " <Value>STANDARD</Value>"
1428 : " <Value>ESRI_PE</Value>"
1429 : " </Option>"
1430 : #if LIBGEOTIFF_VERSION >= 1600
1431 : " <Option name='GEOTIFF_VERSION' type='string-select' default='AUTO' "
1432 : "description='Which version of GeoTIFF must be used'>"
1433 : " <Value>AUTO</Value>"
1434 : " <Value>1.0</Value>"
1435 : " <Value>1.1</Value>"
1436 : " </Option>"
1437 : #endif
1438 : " <Option name='COLOR_TABLE_MULTIPLIER' type='string-select' "
1439 : "description='Multiplication factor to apply to go from GDAL color "
1440 : "table to TIFF color table' "
1441 : "default='257'>"
1442 : " <Value>1</Value>"
1443 : " <Value>256</Value>"
1444 : " <Value>257</Value>"
1445 : " </Option>"
1446 1381 : "</CreationOptionList>";
1447 :
1448 : /* -------------------------------------------------------------------- */
1449 : /* Set the driver details. */
1450 : /* -------------------------------------------------------------------- */
1451 1381 : poDriver->SetDescription("GTiff");
1452 1381 : poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
1453 1381 : poDriver->SetMetadataItem(GDAL_DMD_LONGNAME, "GeoTIFF");
1454 1381 : poDriver->SetMetadataItem(GDAL_DMD_HELPTOPIC, "drivers/raster/gtiff.html");
1455 1381 : poDriver->SetMetadataItem(GDAL_DMD_MIMETYPE, "image/tiff");
1456 1381 : poDriver->SetMetadataItem(GDAL_DMD_EXTENSION, "tif");
1457 1381 : poDriver->SetMetadataItem(GDAL_DMD_EXTENSIONS, "tif tiff");
1458 1381 : poDriver->SetMetadataItem(GDAL_DMD_CREATIONDATATYPES,
1459 : "Byte Int8 UInt16 Int16 UInt32 Int32 Float32 "
1460 1381 : "Float64 CInt16 CInt32 CFloat32 CFloat64");
1461 1381 : poDriver->SetMetadataItem(GDAL_DMD_CREATIONOPTIONLIST, osOptions);
1462 1381 : poDriver->SetMetadataItem(
1463 : GDAL_DMD_OPENOPTIONLIST,
1464 : "<OpenOptionList>"
1465 : " <Option name='NUM_THREADS' type='string' description='Number of "
1466 : "worker threads for compression. Can be set to ALL_CPUS' default='1'/>"
1467 : " <Option name='GEOTIFF_KEYS_FLAVOR' type='string-select' "
1468 : "default='STANDARD' description='Which flavor of GeoTIFF keys must be "
1469 : "used (for writing)'>"
1470 : " <Value>STANDARD</Value>"
1471 : " <Value>ESRI_PE</Value>"
1472 : " </Option>"
1473 : " <Option name='GEOREF_SOURCES' type='string' description='Comma "
1474 : "separated list made with values "
1475 : "INTERNAL/TABFILE/WORLDFILE/PAM/XML/NONE "
1476 : "that describe the priority order for georeferencing' "
1477 : "default='PAM,INTERNAL,TABFILE,WORLDFILE,XML'/>"
1478 : " <Option name='SPARSE_OK' type='boolean' description='Should empty "
1479 : "blocks be omitted on disk?' default='FALSE'/>"
1480 : " <Option name='IGNORE_COG_LAYOUT_BREAK' type='boolean' "
1481 : "description='Allow update mode on files with COG structure' "
1482 : "default='FALSE'/>"
1483 : " <Option name='COLOR_TABLE_MULTIPLIER' type='string-select' "
1484 : "description='Multiplication factor to apply to go from GDAL color "
1485 : "table to TIFF color table' "
1486 : "default='AUTO'>"
1487 : " <Value>AUTO</Value>"
1488 : " <Value>1</Value>"
1489 : " <Value>256</Value>"
1490 : " <Value>257</Value>"
1491 : " </Option>"
1492 1381 : "</OpenOptionList>");
1493 1381 : poDriver->SetMetadataItem(GDAL_DMD_SUBDATASETS, "YES");
1494 1381 : poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
1495 :
1496 : #ifdef INTERNAL_LIBTIFF
1497 1381 : poDriver->SetMetadataItem("LIBTIFF", "INTERNAL");
1498 : #else
1499 : poDriver->SetMetadataItem("LIBTIFF", TIFFLIB_VERSION_STR);
1500 : #endif
1501 :
1502 1381 : poDriver->SetMetadataItem("LIBGEOTIFF", XSTRINGIFY(LIBGEOTIFF_VERSION));
1503 :
1504 : #if defined(LERC_SUPPORT) && defined(LERC_VERSION_MAJOR)
1505 : poDriver->SetMetadataItem("LERC_VERSION_MAJOR",
1506 : XSTRINGIFY(LERC_VERSION_MAJOR), "LERC");
1507 : poDriver->SetMetadataItem("LERC_VERSION_MINOR",
1508 : XSTRINGIFY(LERC_VERSION_MINOR), "LERC");
1509 : poDriver->SetMetadataItem("LERC_VERSION_PATCH",
1510 : XSTRINGIFY(LERC_VERSION_PATCH), "LERC");
1511 : #endif
1512 :
1513 1381 : poDriver->SetMetadataItem(GDAL_DCAP_COORDINATE_EPOCH, "YES");
1514 :
1515 1381 : poDriver->pfnOpen = GTiffDataset::Open;
1516 1381 : poDriver->pfnCreate = GTiffDataset::Create;
1517 1381 : poDriver->pfnCreateCopy = GTiffDataset::CreateCopy;
1518 1381 : poDriver->pfnUnloadDriver = GDALDeregister_GTiff;
1519 1381 : poDriver->pfnIdentify = GTiffDataset::Identify;
1520 1381 : poDriver->pfnGetSubdatasetInfoFunc = GTiffDriverGetSubdatasetInfo;
1521 :
1522 1381 : GetGDALDriverManager()->RegisterDriver(poDriver);
1523 : }
|