Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: COG Driver
4 : * Purpose: Cloud optimized GeoTIFF write support.
5 : * Author: Even Rouault <even dot rouault at spatialys dot com>
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 2019, Even Rouault <even dot rouault at spatialys dot com>
9 : *
10 : * SPDX-License-Identifier: MIT
11 : ****************************************************************************/
12 :
13 : #include "cpl_port.h"
14 :
15 : #include "gdal_priv.h"
16 : #include "gtiff.h"
17 : #include "gt_overview.h"
18 : #include "gdal_utils.h"
19 : #include "gdalwarper.h"
20 : #include "cogdriver.h"
21 : #include "geotiff.h"
22 :
23 : #include "tilematrixset.hpp"
24 :
25 : #include <algorithm>
26 : #include <memory>
27 : #include <vector>
28 :
29 : static bool gbHasLZW = false;
30 :
31 : extern "C" CPL_DLL void GDALRegister_COG();
32 :
33 : /************************************************************************/
34 : /* HasZSTDCompression() */
35 : /************************************************************************/
36 :
37 168 : static bool HasZSTDCompression()
38 : {
39 168 : TIFFCodec *codecs = TIFFGetConfiguredCODECs();
40 168 : bool bHasZSTD = false;
41 3358 : for (TIFFCodec *c = codecs; c->name; ++c)
42 : {
43 3358 : if (c->scheme == COMPRESSION_ZSTD)
44 : {
45 168 : bHasZSTD = true;
46 168 : break;
47 : }
48 : }
49 168 : _TIFFfree(codecs);
50 168 : return bHasZSTD;
51 : }
52 :
53 : /************************************************************************/
54 : /* GetTmpFilename() */
55 : /************************************************************************/
56 :
57 72 : static CPLString GetTmpFilename(const char *pszFilename, const char *pszExt)
58 : {
59 : const bool bSupportsRandomWrite =
60 72 : VSISupportsRandomWrite(pszFilename, false);
61 72 : CPLString osTmpFilename;
62 142 : if (!bSupportsRandomWrite ||
63 70 : CPLGetConfigOption("CPL_TMPDIR", nullptr) != nullptr)
64 : {
65 2 : osTmpFilename = CPLGenerateTempFilenameSafe(
66 4 : CPLGetBasenameSafe(pszFilename).c_str());
67 : }
68 : else
69 70 : osTmpFilename = pszFilename;
70 72 : osTmpFilename += '.';
71 72 : osTmpFilename += pszExt;
72 72 : VSIUnlink(osTmpFilename);
73 72 : return osTmpFilename;
74 : }
75 :
76 : /************************************************************************/
77 : /* GetResampling() */
78 : /************************************************************************/
79 :
80 81 : static const char *GetResampling(GDALDataset *poSrcDS)
81 : {
82 81 : return poSrcDS->GetRasterBand(1)->GetColorTable() ? "NEAREST" : "CUBIC";
83 : }
84 :
85 : /************************************************************************/
86 : /* GetPredictor() */
87 : /************************************************************************/
88 282 : static const char *GetPredictor(GDALDataset *poSrcDS, const char *pszPredictor)
89 : {
90 282 : if (pszPredictor == nullptr)
91 0 : return nullptr;
92 :
93 282 : if (EQUAL(pszPredictor, "YES") || EQUAL(pszPredictor, "ON") ||
94 281 : EQUAL(pszPredictor, "TRUE"))
95 : {
96 1 : if (GDALDataTypeIsFloating(
97 1 : poSrcDS->GetRasterBand(1)->GetRasterDataType()))
98 0 : return "3";
99 : else
100 1 : return "2";
101 : }
102 281 : else if (EQUAL(pszPredictor, "STANDARD") || EQUAL(pszPredictor, "2"))
103 : {
104 1 : return "2";
105 : }
106 280 : else if (EQUAL(pszPredictor, "FLOATING_POINT") || EQUAL(pszPredictor, "3"))
107 : {
108 0 : return "3";
109 : }
110 280 : return nullptr;
111 : }
112 :
113 : /************************************************************************/
114 : /* COGGetTargetSRS() */
115 : /************************************************************************/
116 :
117 39 : static bool COGGetTargetSRS(const char *const *papszOptions,
118 : CPLString &osTargetSRS,
119 : std::unique_ptr<gdal::TileMatrixSet> &poTM)
120 : {
121 39 : osTargetSRS = CSLFetchNameValueDef(papszOptions, "TARGET_SRS", "");
122 : CPLString osTilingScheme(
123 78 : CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM"));
124 39 : if (EQUAL(osTargetSRS, "") && EQUAL(osTilingScheme, "CUSTOM"))
125 2 : return false;
126 :
127 37 : if (!EQUAL(osTilingScheme, "CUSTOM"))
128 : {
129 30 : poTM = gdal::TileMatrixSet::parse(osTilingScheme);
130 30 : if (poTM == nullptr)
131 0 : return false;
132 30 : if (!poTM->haveAllLevelsSameTopLeft())
133 : {
134 0 : CPLError(CE_Failure, CPLE_NotSupported,
135 : "Unsupported tiling scheme: not all zoom levels have same "
136 : "top left corner");
137 0 : return false;
138 : }
139 30 : if (!poTM->haveAllLevelsSameTileSize())
140 : {
141 0 : CPLError(CE_Failure, CPLE_NotSupported,
142 : "Unsupported tiling scheme: not all zoom levels have same "
143 : "tile size");
144 0 : return false;
145 : }
146 30 : if (poTM->hasVariableMatrixWidth())
147 : {
148 0 : CPLError(CE_Failure, CPLE_NotSupported,
149 : "Unsupported tiling scheme: some levels have variable "
150 : "matrix width");
151 0 : return false;
152 : }
153 30 : if (!osTargetSRS.empty())
154 : {
155 0 : CPLError(CE_Warning, CPLE_AppDefined, "Ignoring TARGET_SRS option");
156 : }
157 30 : osTargetSRS = poTM->crs();
158 :
159 : // "Normalize" SRS as AUTH:CODE
160 60 : OGRSpatialReference oTargetSRS;
161 30 : oTargetSRS.SetFromUserInput(
162 : osTargetSRS,
163 : OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get());
164 30 : const char *pszAuthCode = oTargetSRS.GetAuthorityCode(nullptr);
165 30 : const char *pszAuthName = oTargetSRS.GetAuthorityName(nullptr);
166 30 : if (pszAuthName && pszAuthCode)
167 : {
168 30 : osTargetSRS = pszAuthName;
169 30 : osTargetSRS += ':';
170 30 : osTargetSRS += pszAuthCode;
171 : }
172 : }
173 :
174 37 : return true;
175 : }
176 :
177 : // Used by gdalwarp
178 3 : bool COGGetTargetSRS(const char *const *papszOptions, CPLString &osTargetSRS)
179 : {
180 3 : std::unique_ptr<gdal::TileMatrixSet> poTM;
181 6 : return COGGetTargetSRS(papszOptions, osTargetSRS, poTM);
182 : }
183 :
184 : // Used by gdalwarp
185 34 : std::string COGGetResampling(GDALDataset *poSrcDS,
186 : const char *const *papszOptions)
187 : {
188 : return CSLFetchNameValueDef(papszOptions, "WARP_RESAMPLING",
189 : CSLFetchNameValueDef(papszOptions, "RESAMPLING",
190 34 : GetResampling(poSrcDS)));
191 : }
192 :
193 : /************************************************************************/
194 : /* COGGetWarpingCharacteristics() */
195 : /************************************************************************/
196 :
197 36 : static bool COGGetWarpingCharacteristics(
198 : GDALDataset *poSrcDS, const char *const *papszOptions,
199 : CPLString &osResampling, CPLString &osTargetSRS, int &nXSize, int &nYSize,
200 : double &dfMinX, double &dfMinY, double &dfMaxX, double &dfMaxY,
201 : double &dfRes, std::unique_ptr<gdal::TileMatrixSet> &poTM, int &nZoomLevel,
202 : int &nAlignedLevels)
203 : {
204 36 : if (!COGGetTargetSRS(papszOptions, osTargetSRS, poTM))
205 1 : return false;
206 :
207 70 : CPLStringList aosTO;
208 35 : aosTO.SetNameValue("DST_SRS", osTargetSRS);
209 35 : void *hTransformArg = nullptr;
210 :
211 70 : OGRSpatialReference oTargetSRS;
212 35 : oTargetSRS.SetFromUserInput(
213 : osTargetSRS,
214 : OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get());
215 35 : const char *pszAuthCode = oTargetSRS.GetAuthorityCode(nullptr);
216 35 : const int nEPSGCode = pszAuthCode ? atoi(pszAuthCode) : 0;
217 :
218 : // Hack to compensate for GDALSuggestedWarpOutput2() failure (or not
219 : // ideal suggestion with PROJ 8) when reprojecting latitude = +/- 90 to
220 : // EPSG:3857.
221 : double adfSrcGeoTransform[6];
222 35 : std::unique_ptr<GDALDataset> poTmpDS;
223 62 : if (nEPSGCode == 3857 &&
224 27 : poSrcDS->GetGeoTransform(adfSrcGeoTransform) == CE_None &&
225 89 : adfSrcGeoTransform[2] == 0 && adfSrcGeoTransform[4] == 0 &&
226 27 : adfSrcGeoTransform[5] < 0)
227 : {
228 27 : const auto poSrcSRS = poSrcDS->GetSpatialRef();
229 32 : if (poSrcSRS && poSrcSRS->IsGeographic() &&
230 5 : !poSrcSRS->IsDerivedGeographic())
231 : {
232 5 : double maxLat = adfSrcGeoTransform[3];
233 5 : double minLat = adfSrcGeoTransform[3] +
234 5 : poSrcDS->GetRasterYSize() * adfSrcGeoTransform[5];
235 : // Corresponds to the latitude of below MAX_GM
236 5 : constexpr double MAX_LAT = 85.0511287798066;
237 5 : bool bModified = false;
238 5 : if (maxLat > MAX_LAT)
239 : {
240 4 : maxLat = MAX_LAT;
241 4 : bModified = true;
242 : }
243 5 : if (minLat < -MAX_LAT)
244 : {
245 4 : minLat = -MAX_LAT;
246 4 : bModified = true;
247 : }
248 5 : if (bModified)
249 : {
250 4 : CPLStringList aosOptions;
251 4 : aosOptions.AddString("-of");
252 4 : aosOptions.AddString("VRT");
253 4 : aosOptions.AddString("-projwin");
254 : aosOptions.AddString(
255 4 : CPLSPrintf("%.17g", adfSrcGeoTransform[0]));
256 4 : aosOptions.AddString(CPLSPrintf("%.17g", maxLat));
257 : aosOptions.AddString(
258 4 : CPLSPrintf("%.17g", adfSrcGeoTransform[0] +
259 4 : poSrcDS->GetRasterXSize() *
260 4 : adfSrcGeoTransform[1]));
261 4 : aosOptions.AddString(CPLSPrintf("%.17g", minLat));
262 : auto psOptions =
263 4 : GDALTranslateOptionsNew(aosOptions.List(), nullptr);
264 4 : poTmpDS.reset(GDALDataset::FromHandle(GDALTranslate(
265 : "", GDALDataset::ToHandle(poSrcDS), psOptions, nullptr)));
266 4 : GDALTranslateOptionsFree(psOptions);
267 4 : if (poTmpDS)
268 : {
269 8 : hTransformArg = GDALCreateGenImgProjTransformer2(
270 4 : GDALDataset::FromHandle(poTmpDS.get()), nullptr,
271 : aosTO.List());
272 4 : if (hTransformArg == nullptr)
273 : {
274 0 : return false;
275 : }
276 : }
277 : }
278 : }
279 : }
280 35 : if (hTransformArg == nullptr)
281 : {
282 : hTransformArg =
283 31 : GDALCreateGenImgProjTransformer2(poSrcDS, nullptr, aosTO.List());
284 31 : if (hTransformArg == nullptr)
285 : {
286 0 : return false;
287 : }
288 : }
289 :
290 35 : GDALTransformerInfo *psInfo =
291 : static_cast<GDALTransformerInfo *>(hTransformArg);
292 : double adfGeoTransform[6];
293 : double adfExtent[4];
294 :
295 35 : if (GDALSuggestedWarpOutput2(poTmpDS ? poTmpDS.get() : poSrcDS,
296 : psInfo->pfnTransform, hTransformArg,
297 : adfGeoTransform, &nXSize, &nYSize, adfExtent,
298 35 : 0) != CE_None)
299 : {
300 0 : GDALDestroyGenImgProjTransformer(hTransformArg);
301 0 : return false;
302 : }
303 :
304 35 : GDALDestroyGenImgProjTransformer(hTransformArg);
305 35 : hTransformArg = nullptr;
306 35 : poTmpDS.reset();
307 :
308 35 : dfMinX = adfExtent[0];
309 35 : dfMinY = adfExtent[1];
310 35 : dfMaxX = adfExtent[2];
311 35 : dfMaxY = adfExtent[3];
312 35 : dfRes = adfGeoTransform[1];
313 :
314 70 : const CPLString osExtent(CSLFetchNameValueDef(papszOptions, "EXTENT", ""));
315 70 : const CPLString osRes(CSLFetchNameValueDef(papszOptions, "RES", ""));
316 35 : if (poTM)
317 : {
318 28 : if (!osExtent.empty())
319 : {
320 0 : CPLError(CE_Warning, CPLE_AppDefined, "Ignoring EXTENT option");
321 : }
322 28 : if (!osRes.empty())
323 : {
324 0 : CPLError(CE_Warning, CPLE_AppDefined, "Ignoring RES option");
325 : }
326 : const bool bInvertAxis =
327 56 : oTargetSRS.EPSGTreatsAsLatLong() != FALSE ||
328 28 : oTargetSRS.EPSGTreatsAsNorthingEasting() != FALSE;
329 :
330 28 : const auto &bbox = poTM->bbox();
331 28 : if (bbox.mCrs == poTM->crs())
332 : {
333 28 : if (dfMaxX <
334 56 : (bInvertAxis ? bbox.mLowerCornerY : bbox.mLowerCornerX) ||
335 28 : dfMinX >
336 56 : (bInvertAxis ? bbox.mUpperCornerY : bbox.mUpperCornerX) ||
337 28 : dfMaxY <
338 56 : (bInvertAxis ? bbox.mLowerCornerX : bbox.mLowerCornerY) ||
339 28 : dfMinY >
340 28 : (bInvertAxis ? bbox.mUpperCornerX : bbox.mUpperCornerY))
341 : {
342 0 : CPLError(CE_Failure, CPLE_AppDefined,
343 : "Raster extent completely outside of tile matrix set "
344 : "bounding box");
345 2 : return false;
346 : }
347 : }
348 :
349 28 : const auto &tmList = poTM->tileMatrixList();
350 28 : const int nBlockSize = atoi(CSLFetchNameValueDef(
351 28 : papszOptions, "BLOCKSIZE", CPLSPrintf("%d", tmList[0].mTileWidth)));
352 28 : dfRes = 0.0;
353 :
354 : const char *pszZoomLevel =
355 28 : CSLFetchNameValue(papszOptions, "ZOOM_LEVEL");
356 28 : if (pszZoomLevel)
357 : {
358 3 : nZoomLevel = atoi(pszZoomLevel);
359 3 : if (nZoomLevel < 0 || nZoomLevel >= static_cast<int>(tmList.size()))
360 : {
361 2 : CPLError(CE_Failure, CPLE_AppDefined,
362 : "Invalid zoom level: should be in [0,%d]",
363 2 : static_cast<int>(tmList.size()) - 1);
364 2 : return false;
365 : }
366 : }
367 : else
368 : {
369 25 : double dfComputedRes = adfGeoTransform[1];
370 25 : double dfPrevRes = 0.0;
371 280 : for (; nZoomLevel < static_cast<int>(tmList.size()); nZoomLevel++)
372 : {
373 280 : dfRes = tmList[nZoomLevel].mResX * tmList[0].mTileWidth /
374 : nBlockSize;
375 280 : if (dfComputedRes > dfRes ||
376 260 : fabs(dfComputedRes - dfRes) / dfRes <= 1e-8)
377 : break;
378 255 : dfPrevRes = dfRes;
379 : }
380 25 : if (nZoomLevel == static_cast<int>(tmList.size()))
381 : {
382 0 : CPLError(CE_Failure, CPLE_AppDefined,
383 : "Could not find an appropriate zoom level");
384 0 : return false;
385 : }
386 :
387 25 : if (nZoomLevel > 0 && fabs(dfComputedRes - dfRes) / dfRes > 1e-8)
388 : {
389 19 : const char *pszZoomLevelStrategy = CSLFetchNameValueDef(
390 : papszOptions, "ZOOM_LEVEL_STRATEGY", "AUTO");
391 19 : if (EQUAL(pszZoomLevelStrategy, "LOWER"))
392 : {
393 1 : nZoomLevel--;
394 : }
395 18 : else if (EQUAL(pszZoomLevelStrategy, "UPPER"))
396 : {
397 : /* do nothing */
398 : }
399 : else
400 : {
401 17 : if (dfPrevRes / dfComputedRes < dfComputedRes / dfRes)
402 15 : nZoomLevel--;
403 : }
404 : }
405 : }
406 26 : CPLDebug("COG", "Using ZOOM_LEVEL %d", nZoomLevel);
407 26 : dfRes = tmList[nZoomLevel].mResX * tmList[0].mTileWidth / nBlockSize;
408 :
409 : const double dfOriX =
410 26 : bInvertAxis ? tmList[0].mTopLeftY : tmList[0].mTopLeftX;
411 : const double dfOriY =
412 26 : bInvertAxis ? tmList[0].mTopLeftX : tmList[0].mTopLeftY;
413 26 : const double dfTileExtent = dfRes * nBlockSize;
414 26 : constexpr double TOLERANCE_IN_PIXEL = 0.499;
415 26 : const double dfEps = TOLERANCE_IN_PIXEL * dfRes;
416 26 : int nTLTileX = static_cast<int>(
417 26 : std::floor((dfMinX - dfOriX + dfEps) / dfTileExtent));
418 26 : int nTLTileY = static_cast<int>(
419 26 : std::floor((dfOriY - dfMaxY + dfEps) / dfTileExtent));
420 26 : int nBRTileX = static_cast<int>(
421 26 : std::ceil((dfMaxX - dfOriX - dfEps) / dfTileExtent));
422 26 : int nBRTileY = static_cast<int>(
423 26 : std::ceil((dfOriY - dfMinY - dfEps) / dfTileExtent));
424 :
425 26 : nAlignedLevels =
426 26 : std::min(std::min(10, atoi(CSLFetchNameValueDef(
427 : papszOptions, "ALIGNED_LEVELS", "0"))),
428 26 : nZoomLevel);
429 26 : int nAccDivisor = 1;
430 34 : for (int i = 0; i < nAlignedLevels - 1; i++)
431 : {
432 8 : const int nCurLevel = nZoomLevel - i;
433 : const double dfResRatio =
434 8 : tmList[nCurLevel - 1].mResX / tmList[nCurLevel].mResX;
435 : // Magical number that has a great number of divisors
436 : // For example if previous scale denom was 50K and current one
437 : // is 20K, then dfResRatio = 2.5 and dfScaledInvResRatio = 24
438 : // We must then simplify 60 / 24 as 5 / 2, and make sure to
439 : // align tile coordinates on multiple of the 5 numerator
440 8 : constexpr int MAGICAL = 60;
441 8 : const double dfScaledInvResRatio = MAGICAL / dfResRatio;
442 16 : if (dfScaledInvResRatio < 1 || dfScaledInvResRatio > 60 ||
443 8 : std::abs(std::round(dfScaledInvResRatio) -
444 : dfScaledInvResRatio) > 1e-10)
445 : {
446 0 : CPLError(CE_Failure, CPLE_AppDefined,
447 : "Unsupported ratio of resolution for "
448 : "ALIGNED_LEVELS between zoom level %d and %d = %g",
449 : nCurLevel - 1, nCurLevel, dfResRatio);
450 0 : return false;
451 : }
452 8 : const int nScaledInvResRatio =
453 8 : static_cast<int>(std::round(dfScaledInvResRatio));
454 8 : int nNumerator = 0;
455 32 : for (int nDivisor = nScaledInvResRatio; nDivisor >= 2; --nDivisor)
456 : {
457 32 : if ((MAGICAL % nDivisor) == 0 &&
458 12 : (nScaledInvResRatio % nDivisor) == 0)
459 : {
460 8 : nNumerator = MAGICAL / nDivisor;
461 8 : break;
462 : }
463 : }
464 8 : if (nNumerator == 0)
465 : {
466 0 : CPLError(CE_Failure, CPLE_AppDefined,
467 : "Unsupported ratio of resolution for "
468 : "ALIGNED_LEVELS between zoom level %d and %d = %g",
469 : nCurLevel - 1, nCurLevel, dfResRatio);
470 0 : return false;
471 : }
472 8 : nAccDivisor *= nNumerator;
473 : }
474 26 : if (nAccDivisor > 1)
475 : {
476 4 : nTLTileX = (nTLTileX / nAccDivisor) * nAccDivisor;
477 4 : nTLTileY = (nTLTileY / nAccDivisor) * nAccDivisor;
478 4 : nBRTileY =
479 4 : ((nBRTileY + nAccDivisor - 1) / nAccDivisor) * nAccDivisor;
480 4 : nBRTileX =
481 4 : ((nBRTileX + nAccDivisor - 1) / nAccDivisor) * nAccDivisor;
482 : }
483 :
484 26 : if (nTLTileX < 0 || nTLTileY < 0 ||
485 74 : nBRTileX > tmList[nZoomLevel].mMatrixWidth ||
486 22 : nBRTileY > tmList[nZoomLevel].mMatrixHeight)
487 : {
488 4 : CPLError(CE_Warning, CPLE_AppDefined,
489 : "Raster extent partially outside of tile matrix "
490 : "bounding box. Clamping it to it");
491 : }
492 26 : nTLTileX = std::max(0, nTLTileX);
493 26 : nTLTileY = std::max(0, nTLTileY);
494 26 : nBRTileX = std::min(tmList[nZoomLevel].mMatrixWidth, nBRTileX);
495 26 : nBRTileY = std::min(tmList[nZoomLevel].mMatrixHeight, nBRTileY);
496 :
497 26 : dfMinX = dfOriX + nTLTileX * dfTileExtent;
498 26 : dfMinY = dfOriY - nBRTileY * dfTileExtent;
499 26 : dfMaxX = dfOriX + nBRTileX * dfTileExtent;
500 26 : dfMaxY = dfOriY - nTLTileY * dfTileExtent;
501 : }
502 7 : else if (!osExtent.empty() || !osRes.empty())
503 : {
504 1 : CPLStringList aosTokens(CSLTokenizeString2(osExtent, ",", 0));
505 1 : if (aosTokens.size() != 4)
506 : {
507 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid value for EXTENT");
508 0 : return false;
509 : }
510 1 : dfMinX = CPLAtof(aosTokens[0]);
511 1 : dfMinY = CPLAtof(aosTokens[1]);
512 1 : dfMaxX = CPLAtof(aosTokens[2]);
513 1 : dfMaxY = CPLAtof(aosTokens[3]);
514 1 : if (!osRes.empty())
515 1 : dfRes = CPLAtof(osRes);
516 : }
517 :
518 33 : nXSize = static_cast<int>(std::round((dfMaxX - dfMinX) / dfRes));
519 33 : nYSize = static_cast<int>(std::round((dfMaxY - dfMinY) / dfRes));
520 :
521 33 : osResampling = COGGetResampling(poSrcDS, papszOptions);
522 :
523 33 : return true;
524 : }
525 :
526 : // Used by gdalwarp
527 3 : bool COGGetWarpingCharacteristics(GDALDataset *poSrcDS,
528 : const char *const *papszOptions,
529 : CPLString &osResampling,
530 : CPLString &osTargetSRS, int &nXSize,
531 : int &nYSize, double &dfMinX, double &dfMinY,
532 : double &dfMaxX, double &dfMaxY)
533 : {
534 3 : std::unique_ptr<gdal::TileMatrixSet> poTM;
535 3 : int nZoomLevel = 0;
536 3 : int nAlignedLevels = 0;
537 : double dfRes;
538 3 : return COGGetWarpingCharacteristics(poSrcDS, papszOptions, osResampling,
539 : osTargetSRS, nXSize, nYSize, dfMinX,
540 : dfMinY, dfMaxX, dfMaxY, dfRes, poTM,
541 6 : nZoomLevel, nAlignedLevels);
542 : }
543 :
544 : /************************************************************************/
545 : /* COGHasWarpingOptions() */
546 : /************************************************************************/
547 :
548 148 : bool COGHasWarpingOptions(CSLConstList papszOptions)
549 : {
550 289 : return CSLFetchNameValue(papszOptions, "TARGET_SRS") != nullptr ||
551 289 : !EQUAL(CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM"),
552 : "CUSTOM");
553 : }
554 :
555 : /************************************************************************/
556 : /* COGRemoveWarpingOptions() */
557 : /************************************************************************/
558 :
559 2 : void COGRemoveWarpingOptions(CPLStringList &aosOptions)
560 : {
561 2 : aosOptions.SetNameValue("TARGET_SRS", nullptr);
562 2 : aosOptions.SetNameValue("TILING_SCHEME", nullptr);
563 2 : aosOptions.SetNameValue("EXTENT", nullptr);
564 2 : aosOptions.SetNameValue("RES", nullptr);
565 2 : aosOptions.SetNameValue("ALIGNED_LEVELS", nullptr);
566 2 : aosOptions.SetNameValue("ZOOM_LEVEL_STRATEGY", nullptr);
567 2 : }
568 :
569 : /************************************************************************/
570 : /* CreateReprojectedDS() */
571 : /************************************************************************/
572 :
573 26 : static std::unique_ptr<GDALDataset> CreateReprojectedDS(
574 : const char *pszDstFilename, GDALDataset *poSrcDS,
575 : const char *const *papszOptions, const CPLString &osResampling,
576 : const CPLString &osTargetSRS, const int nXSize, const int nYSize,
577 : const double dfMinX, const double dfMinY, const double dfMaxX,
578 : const double dfMaxY, const double dfRes, GDALProgressFunc pfnProgress,
579 : void *pProgressData, double &dfCurPixels, double &dfTotalPixelsToProcess)
580 : {
581 26 : char **papszArg = nullptr;
582 : // We could have done a warped VRT, but overview building on it might be
583 : // slow, so materialize as GTiff
584 26 : papszArg = CSLAddString(papszArg, "-of");
585 26 : papszArg = CSLAddString(papszArg, "GTiff");
586 26 : papszArg = CSLAddString(papszArg, "-co");
587 26 : papszArg = CSLAddString(papszArg, "TILED=YES");
588 26 : papszArg = CSLAddString(papszArg, "-co");
589 26 : papszArg = CSLAddString(papszArg, "SPARSE_OK=YES");
590 26 : const char *pszBIGTIFF = CSLFetchNameValue(papszOptions, "BIGTIFF");
591 26 : if (pszBIGTIFF)
592 : {
593 0 : papszArg = CSLAddString(papszArg, "-co");
594 0 : papszArg = CSLAddString(papszArg,
595 0 : (CPLString("BIGTIFF=") + pszBIGTIFF).c_str());
596 : }
597 26 : papszArg = CSLAddString(papszArg, "-co");
598 26 : papszArg = CSLAddString(papszArg, HasZSTDCompression() ? "COMPRESS=ZSTD"
599 : : "COMPRESS=LZW");
600 26 : papszArg = CSLAddString(papszArg, "-t_srs");
601 26 : papszArg = CSLAddString(papszArg, osTargetSRS);
602 26 : papszArg = CSLAddString(papszArg, "-te");
603 26 : papszArg = CSLAddString(papszArg, CPLSPrintf("%.17g", dfMinX));
604 26 : papszArg = CSLAddString(papszArg, CPLSPrintf("%.17g", dfMinY));
605 26 : papszArg = CSLAddString(papszArg, CPLSPrintf("%.17g", dfMaxX));
606 26 : papszArg = CSLAddString(papszArg, CPLSPrintf("%.17g", dfMaxY));
607 26 : papszArg = CSLAddString(papszArg, "-ts");
608 26 : papszArg = CSLAddString(papszArg, CPLSPrintf("%d", nXSize));
609 26 : papszArg = CSLAddString(papszArg, CPLSPrintf("%d", nYSize));
610 :
611 : // to be kept in sync with gdalwarp_lib.cpp
612 26 : constexpr double RELATIVE_ERROR_RES_SHARED_BY_COG_AND_GDALWARP = 1e-8;
613 26 : if (fabs((dfMaxX - dfMinX) / dfRes - nXSize) <=
614 26 : RELATIVE_ERROR_RES_SHARED_BY_COG_AND_GDALWARP &&
615 26 : fabs((dfMaxY - dfMinY) / dfRes - nYSize) <=
616 : RELATIVE_ERROR_RES_SHARED_BY_COG_AND_GDALWARP)
617 : {
618 : // Try to produce exactly square pixels
619 26 : papszArg = CSLAddString(papszArg, "-tr");
620 26 : papszArg = CSLAddString(papszArg, CPLSPrintf("%.17g", dfRes));
621 26 : papszArg = CSLAddString(papszArg, CPLSPrintf("%.17g", dfRes));
622 : }
623 : else
624 : {
625 0 : CPLDebug("COG", "Cannot pass -tr option to GDALWarp() due to extent, "
626 : "size and resolution not consistent enough");
627 : }
628 :
629 26 : int bHasNoData = FALSE;
630 26 : poSrcDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
631 52 : if (!bHasNoData &&
632 26 : CPLTestBool(CSLFetchNameValueDef(papszOptions, "ADD_ALPHA", "YES")))
633 : {
634 26 : papszArg = CSLAddString(papszArg, "-dstalpha");
635 : }
636 26 : papszArg = CSLAddString(papszArg, "-r");
637 26 : papszArg = CSLAddString(papszArg, osResampling);
638 26 : papszArg = CSLAddString(papszArg, "-wo");
639 26 : papszArg = CSLAddString(papszArg, "SAMPLE_GRID=YES");
640 26 : const char *pszNumThreads = CSLFetchNameValue(papszOptions, "NUM_THREADS");
641 26 : if (pszNumThreads)
642 : {
643 0 : papszArg = CSLAddString(papszArg, "-wo");
644 0 : papszArg = CSLAddString(
645 0 : papszArg, (CPLString("NUM_THREADS=") + pszNumThreads).c_str());
646 : }
647 :
648 26 : const auto poFirstBand = poSrcDS->GetRasterBand(1);
649 26 : const bool bHasMask = poFirstBand->GetMaskFlags() == GMF_PER_DATASET;
650 :
651 26 : const int nBands = poSrcDS->GetRasterCount();
652 : const char *pszOverviews =
653 26 : CSLFetchNameValueDef(papszOptions, "OVERVIEWS", "AUTO");
654 52 : const bool bUseExistingOrNone = EQUAL(pszOverviews, "FORCE_USE_EXISTING") ||
655 26 : EQUAL(pszOverviews, "NONE");
656 26 : dfTotalPixelsToProcess =
657 26 : double(nXSize) * nYSize * (nBands + (bHasMask ? 1 : 0)) +
658 26 : ((bHasMask && !bUseExistingOrNone) ? double(nXSize) * nYSize / 3 : 0) +
659 26 : (!bUseExistingOrNone ? double(nXSize) * nYSize * nBands / 3 : 0) +
660 26 : double(nXSize) * nYSize * (nBands + (bHasMask ? 1 : 0)) * 4. / 3;
661 :
662 26 : auto psOptions = GDALWarpAppOptionsNew(papszArg, nullptr);
663 26 : CSLDestroy(papszArg);
664 26 : if (psOptions == nullptr)
665 1 : return nullptr;
666 :
667 25 : const double dfNextPixels =
668 25 : double(nXSize) * nYSize * (nBands + (bHasMask ? 1 : 0));
669 50 : void *pScaledProgress = GDALCreateScaledProgress(
670 25 : dfCurPixels / dfTotalPixelsToProcess,
671 25 : dfNextPixels / dfTotalPixelsToProcess, pfnProgress, pProgressData);
672 25 : dfCurPixels = dfNextPixels;
673 :
674 25 : CPLDebug("COG", "Reprojecting source dataset: start");
675 25 : GDALWarpAppOptionsSetProgress(psOptions, GDALScaledProgress,
676 : pScaledProgress);
677 50 : CPLString osTmpFile(GetTmpFilename(pszDstFilename, "warped.tif.tmp"));
678 25 : auto hSrcDS = GDALDataset::ToHandle(poSrcDS);
679 :
680 25 : std::unique_ptr<CPLConfigOptionSetter> poWarpThreadSetter;
681 25 : if (pszNumThreads)
682 : {
683 0 : poWarpThreadSetter.reset(new CPLConfigOptionSetter(
684 0 : "GDAL_NUM_THREADS", pszNumThreads, false));
685 : }
686 :
687 25 : auto hRet = GDALWarp(osTmpFile, nullptr, 1, &hSrcDS, psOptions, nullptr);
688 25 : GDALWarpAppOptionsFree(psOptions);
689 25 : CPLDebug("COG", "Reprojecting source dataset: end");
690 :
691 25 : GDALDestroyScaledProgress(pScaledProgress);
692 :
693 25 : return std::unique_ptr<GDALDataset>(GDALDataset::FromHandle(hRet));
694 : }
695 :
696 : /************************************************************************/
697 : /* GDALCOGCreator */
698 : /************************************************************************/
699 :
700 : struct GDALCOGCreator final
701 : {
702 : std::unique_ptr<GDALDataset> m_poReprojectedDS{};
703 : std::unique_ptr<GDALDataset> m_poRGBMaskDS{};
704 : std::unique_ptr<GDALDataset> m_poVRTWithOrWithoutStats{};
705 : CPLString m_osTmpOverviewFilename{};
706 : CPLString m_osTmpMskOverviewFilename{};
707 :
708 : ~GDALCOGCreator();
709 :
710 : GDALDataset *Create(const char *pszFilename, GDALDataset *const poSrcDS,
711 : char **papszOptions, GDALProgressFunc pfnProgress,
712 : void *pProgressData);
713 : };
714 :
715 : /************************************************************************/
716 : /* GDALCOGCreator::~GDALCOGCreator() */
717 : /************************************************************************/
718 :
719 147 : GDALCOGCreator::~GDALCOGCreator()
720 : {
721 : // Destroy m_poRGBMaskDS before m_poReprojectedDS since the former
722 : // may reference the later
723 147 : m_poRGBMaskDS.reset();
724 :
725 : // Config option just for testing purposes
726 : const bool bDeleteTempFiles =
727 147 : CPLTestBool(CPLGetConfigOption("COG_DELETE_TEMP_FILES", "YES"));
728 147 : if (bDeleteTempFiles)
729 : {
730 146 : if (m_poReprojectedDS)
731 : {
732 50 : CPLString osProjectedDSName(m_poReprojectedDS->GetDescription());
733 25 : m_poReprojectedDS.reset();
734 25 : VSIUnlink(osProjectedDSName);
735 : }
736 146 : if (!m_osTmpOverviewFilename.empty())
737 : {
738 36 : VSIUnlink(m_osTmpOverviewFilename);
739 : }
740 146 : if (!m_osTmpMskOverviewFilename.empty())
741 : {
742 9 : VSIUnlink(m_osTmpMskOverviewFilename);
743 : }
744 : }
745 147 : }
746 :
747 : /************************************************************************/
748 : /* GDALCOGCreator::Create() */
749 : /************************************************************************/
750 :
751 147 : GDALDataset *GDALCOGCreator::Create(const char *pszFilename,
752 : GDALDataset *const poSrcDS,
753 : char **papszOptions,
754 : GDALProgressFunc pfnProgress,
755 : void *pProgressData)
756 : {
757 147 : if (pfnProgress == nullptr)
758 0 : pfnProgress = GDALDummyProgress;
759 :
760 147 : if (poSrcDS->GetRasterCount() == 0)
761 : {
762 1 : CPLError(CE_Failure, CPLE_NotSupported,
763 : "COG driver does not support 0-band source raster");
764 1 : return nullptr;
765 : }
766 :
767 : const CPLString osCompress = CSLFetchNameValueDef(
768 292 : papszOptions, "COMPRESS", gbHasLZW ? "LZW" : "NONE");
769 :
770 : const char *pszInterleave =
771 146 : CSLFetchNameValueDef(papszOptions, "INTERLEAVE", "PIXEL");
772 146 : if (EQUAL(osCompress, "WEBP"))
773 : {
774 4 : if (!EQUAL(pszInterleave, "PIXEL"))
775 : {
776 1 : CPLError(CE_Failure, CPLE_NotSupported,
777 : "COMPRESS=WEBP only supported for INTERLEAVE=PIXEL");
778 1 : return nullptr;
779 : }
780 : }
781 :
782 : CPLConfigOptionSetter oSetterReportDirtyBlockFlushing(
783 290 : "GDAL_REPORT_DIRTY_BLOCK_FLUSHING", "NO", true);
784 :
785 : const char *pszStatistics =
786 145 : CSLFetchNameValueDef(papszOptions, "STATISTICS", "AUTO");
787 145 : auto poSrcFirstBand = poSrcDS->GetRasterBand(1);
788 : const bool bSrcHasStatistics =
789 145 : poSrcFirstBand->GetMetadataItem("STATISTICS_MINIMUM") &&
790 8 : poSrcFirstBand->GetMetadataItem("STATISTICS_MAXIMUM") &&
791 161 : poSrcFirstBand->GetMetadataItem("STATISTICS_MEAN") &&
792 8 : poSrcFirstBand->GetMetadataItem("STATISTICS_STDDEV");
793 145 : bool bNeedStats = false;
794 145 : bool bRemoveStats = false;
795 145 : bool bWrkHasStatistics = bSrcHasStatistics;
796 145 : if (EQUAL(pszStatistics, "AUTO"))
797 : {
798 : // nothing
799 : }
800 10 : else if (CPLTestBool(pszStatistics))
801 : {
802 5 : bNeedStats = true;
803 : }
804 : else
805 : {
806 5 : bRemoveStats = true;
807 : }
808 :
809 145 : double dfCurPixels = 0;
810 145 : double dfTotalPixelsToProcess = 0;
811 145 : GDALDataset *poCurDS = poSrcDS;
812 :
813 145 : std::unique_ptr<gdal::TileMatrixSet> poTM;
814 145 : int nZoomLevel = 0;
815 145 : int nAlignedLevels = 0;
816 145 : if (COGHasWarpingOptions(papszOptions))
817 : {
818 33 : CPLString osTargetResampling;
819 33 : CPLString osTargetSRS;
820 33 : int nTargetXSize = 0;
821 33 : int nTargetYSize = 0;
822 33 : double dfTargetMinX = 0;
823 33 : double dfTargetMinY = 0;
824 33 : double dfTargetMaxX = 0;
825 33 : double dfTargetMaxY = 0;
826 33 : double dfRes = 0;
827 33 : if (!COGGetWarpingCharacteristics(
828 : poCurDS, papszOptions, osTargetResampling, osTargetSRS,
829 : nTargetXSize, nTargetYSize, dfTargetMinX, dfTargetMinY,
830 : dfTargetMaxX, dfTargetMaxY, dfRes, poTM, nZoomLevel,
831 : nAlignedLevels))
832 : {
833 2 : return nullptr;
834 : }
835 :
836 : // Collect information on source dataset to see if it already
837 : // matches the warping specifications
838 31 : CPLString osSrcSRS;
839 31 : const auto poSrcSRS = poCurDS->GetSpatialRef();
840 31 : if (poSrcSRS)
841 : {
842 31 : const char *pszAuthName = poSrcSRS->GetAuthorityName(nullptr);
843 31 : const char *pszAuthCode = poSrcSRS->GetAuthorityCode(nullptr);
844 31 : if (pszAuthName && pszAuthCode)
845 : {
846 31 : osSrcSRS = pszAuthName;
847 31 : osSrcSRS += ':';
848 31 : osSrcSRS += pszAuthCode;
849 : }
850 : }
851 31 : double dfSrcMinX = 0;
852 31 : double dfSrcMinY = 0;
853 31 : double dfSrcMaxX = 0;
854 31 : double dfSrcMaxY = 0;
855 : double adfSrcGT[6];
856 31 : const int nSrcXSize = poCurDS->GetRasterXSize();
857 31 : const int nSrcYSize = poCurDS->GetRasterYSize();
858 31 : if (poCurDS->GetGeoTransform(adfSrcGT) == CE_None)
859 : {
860 31 : dfSrcMinX = adfSrcGT[0];
861 31 : dfSrcMaxY = adfSrcGT[3];
862 31 : dfSrcMaxX = adfSrcGT[0] + nSrcXSize * adfSrcGT[1];
863 31 : dfSrcMinY = adfSrcGT[3] + nSrcYSize * adfSrcGT[5];
864 : }
865 :
866 24 : if (nTargetXSize == nSrcXSize && nTargetYSize == nSrcYSize &&
867 12 : osTargetSRS == osSrcSRS &&
868 6 : fabs(dfSrcMinX - dfTargetMinX) < 1e-10 * fabs(dfSrcMinX) &&
869 5 : fabs(dfSrcMinY - dfTargetMinY) < 1e-10 * fabs(dfSrcMinY) &&
870 48 : fabs(dfSrcMaxX - dfTargetMaxX) < 1e-10 * fabs(dfSrcMaxX) &&
871 5 : fabs(dfSrcMaxY - dfTargetMaxY) < 1e-10 * fabs(dfSrcMaxY))
872 : {
873 5 : CPLDebug("COG",
874 : "Skipping reprojection step: "
875 : "source dataset matches reprojection specifications");
876 : }
877 : else
878 : {
879 52 : m_poReprojectedDS = CreateReprojectedDS(
880 : pszFilename, poCurDS, papszOptions, osTargetResampling,
881 : osTargetSRS, nTargetXSize, nTargetYSize, dfTargetMinX,
882 : dfTargetMinY, dfTargetMaxX, dfTargetMaxY, dfRes, pfnProgress,
883 26 : pProgressData, dfCurPixels, dfTotalPixelsToProcess);
884 26 : if (!m_poReprojectedDS)
885 1 : return nullptr;
886 25 : poCurDS = m_poReprojectedDS.get();
887 :
888 25 : if (bSrcHasStatistics && !bNeedStats && !bRemoveStats)
889 : {
890 1 : bNeedStats = true;
891 : }
892 25 : bWrkHasStatistics = false;
893 : }
894 : }
895 :
896 154 : if (EQUAL(osCompress, "JPEG") && EQUAL(pszInterleave, "PIXEL") &&
897 164 : (poCurDS->GetRasterCount() == 2 || poCurDS->GetRasterCount() == 4) &&
898 10 : poCurDS->GetRasterBand(poCurDS->GetRasterCount())
899 10 : ->GetColorInterpretation() == GCI_AlphaBand)
900 : {
901 10 : char **papszArg = nullptr;
902 10 : papszArg = CSLAddString(papszArg, "-of");
903 10 : papszArg = CSLAddString(papszArg, "VRT");
904 10 : papszArg = CSLAddString(papszArg, "-b");
905 10 : papszArg = CSLAddString(papszArg, "1");
906 10 : if (poCurDS->GetRasterCount() == 2)
907 : {
908 1 : papszArg = CSLAddString(papszArg, "-mask");
909 1 : papszArg = CSLAddString(papszArg, "2");
910 : }
911 : else
912 : {
913 9 : CPLAssert(poCurDS->GetRasterCount() == 4);
914 9 : papszArg = CSLAddString(papszArg, "-b");
915 9 : papszArg = CSLAddString(papszArg, "2");
916 9 : papszArg = CSLAddString(papszArg, "-b");
917 9 : papszArg = CSLAddString(papszArg, "3");
918 9 : papszArg = CSLAddString(papszArg, "-mask");
919 9 : papszArg = CSLAddString(papszArg, "4");
920 : }
921 : GDALTranslateOptions *psOptions =
922 10 : GDALTranslateOptionsNew(papszArg, nullptr);
923 10 : CSLDestroy(papszArg);
924 10 : GDALDatasetH hRGBMaskDS = GDALTranslate(
925 : "", GDALDataset::ToHandle(poCurDS), psOptions, nullptr);
926 10 : GDALTranslateOptionsFree(psOptions);
927 10 : if (!hRGBMaskDS)
928 : {
929 0 : return nullptr;
930 : }
931 10 : m_poRGBMaskDS.reset(GDALDataset::FromHandle(hRGBMaskDS));
932 10 : poCurDS = m_poRGBMaskDS.get();
933 :
934 10 : if (bSrcHasStatistics && !bNeedStats && !bRemoveStats)
935 : {
936 1 : bNeedStats = true;
937 : }
938 9 : else if (bRemoveStats && bWrkHasStatistics)
939 : {
940 1 : poCurDS->ClearStatistics();
941 1 : bRemoveStats = false;
942 : }
943 : }
944 :
945 142 : const int nBands = poCurDS->GetRasterCount();
946 142 : const int nXSize = poCurDS->GetRasterXSize();
947 142 : const int nYSize = poCurDS->GetRasterYSize();
948 :
949 8 : const auto CreateVRTWithOrWithoutStats = [this, &poCurDS]()
950 : {
951 2 : const char *const apszOptions[] = {"-of", "VRT", nullptr};
952 : GDALTranslateOptions *psOptions =
953 2 : GDALTranslateOptionsNew(const_cast<char **>(apszOptions), nullptr);
954 2 : GDALDatasetH hVRTDS = GDALTranslate("", GDALDataset::ToHandle(poCurDS),
955 : psOptions, nullptr);
956 2 : GDALTranslateOptionsFree(psOptions);
957 2 : if (!hVRTDS)
958 0 : return false;
959 2 : m_poVRTWithOrWithoutStats.reset(GDALDataset::FromHandle(hVRTDS));
960 2 : poCurDS = m_poVRTWithOrWithoutStats.get();
961 2 : return true;
962 142 : };
963 :
964 142 : if (bNeedStats && !bWrkHasStatistics)
965 : {
966 5 : if (poSrcDS == poCurDS && !CreateVRTWithOrWithoutStats())
967 : {
968 0 : return nullptr;
969 : }
970 :
971 : // Avoid source files to be modified
972 : CPLConfigOptionSetter enablePamDirtyDisabler(
973 10 : "GDAL_PAM_ENABLE_MARK_DIRTY", "NO", true);
974 :
975 15 : for (int i = 1; i <= nBands; ++i)
976 : {
977 10 : poCurDS->GetRasterBand(i)->ComputeStatistics(
978 : /*bApproxOK=*/FALSE, nullptr, nullptr, nullptr, nullptr,
979 10 : nullptr, nullptr);
980 5 : }
981 : }
982 137 : else if (bRemoveStats && bWrkHasStatistics)
983 : {
984 1 : if (!CreateVRTWithOrWithoutStats())
985 0 : return nullptr;
986 :
987 1 : m_poVRTWithOrWithoutStats->ClearStatistics();
988 : }
989 :
990 284 : CPLString osBlockSize(CSLFetchNameValueDef(papszOptions, "BLOCKSIZE", ""));
991 142 : if (osBlockSize.empty())
992 : {
993 118 : if (poTM)
994 : {
995 20 : osBlockSize.Printf("%d", poTM->tileMatrixList()[0].mTileWidth);
996 : }
997 : else
998 : {
999 98 : osBlockSize = "512";
1000 : }
1001 : }
1002 :
1003 142 : const int nOvrThresholdSize = atoi(osBlockSize);
1004 :
1005 142 : const auto poFirstBand = poCurDS->GetRasterBand(1);
1006 142 : const bool bHasMask = poFirstBand->GetMaskFlags() == GMF_PER_DATASET;
1007 :
1008 : CPLString osOverviews =
1009 284 : CSLFetchNameValueDef(papszOptions, "OVERVIEWS", "AUTO");
1010 : const bool bUseExistingOrNone =
1011 142 : EQUAL(osOverviews, "FORCE_USE_EXISTING") || EQUAL(osOverviews, "NONE");
1012 :
1013 : const int nOverviewCount =
1014 142 : atoi(CSLFetchNameValueDef(papszOptions, "OVERVIEW_COUNT", "-1"));
1015 :
1016 : const bool bGenerateMskOvr =
1017 138 : !bUseExistingOrNone && bHasMask &&
1018 7 : (nXSize > nOvrThresholdSize || nYSize > nOvrThresholdSize ||
1019 280 : nOverviewCount > 0) &&
1020 13 : (EQUAL(osOverviews, "IGNORE_EXISTING") ||
1021 13 : poFirstBand->GetMaskBand()->GetOverviewCount() == 0);
1022 : const bool bGenerateOvr =
1023 138 : !bUseExistingOrNone &&
1024 97 : (nXSize > nOvrThresholdSize || nYSize > nOvrThresholdSize ||
1025 280 : nOverviewCount > 0) &&
1026 45 : (EQUAL(osOverviews, "IGNORE_EXISTING") ||
1027 43 : poFirstBand->GetOverviewCount() == 0);
1028 :
1029 284 : std::vector<std::pair<int, int>> asOverviewDims;
1030 142 : int nTmpXSize = nXSize;
1031 142 : int nTmpYSize = nYSize;
1032 142 : if (poTM)
1033 : {
1034 23 : const auto &tmList = poTM->tileMatrixList();
1035 23 : int nCurLevel = nZoomLevel;
1036 : while (true)
1037 : {
1038 47 : if (nOverviewCount < 0)
1039 : {
1040 33 : if (nTmpXSize <= nOvrThresholdSize &&
1041 21 : nTmpYSize <= nOvrThresholdSize)
1042 20 : break;
1043 : }
1044 14 : else if (static_cast<int>(asOverviewDims.size()) ==
1045 26 : nOverviewCount ||
1046 12 : (nTmpXSize == 1 && nTmpYSize == 1))
1047 : {
1048 3 : break;
1049 : }
1050 : const double dfResRatio =
1051 : (nCurLevel >= 1)
1052 24 : ? tmList[nCurLevel - 1].mResX / tmList[nCurLevel].mResX
1053 24 : : 2;
1054 24 : nTmpXSize = static_cast<int>(nTmpXSize / dfResRatio + 0.5);
1055 24 : nTmpYSize = static_cast<int>(nTmpYSize / dfResRatio + 0.5);
1056 24 : if (nTmpXSize == 0)
1057 0 : nTmpXSize = 1;
1058 24 : if (nTmpYSize == 0)
1059 0 : nTmpYSize = 1;
1060 24 : asOverviewDims.emplace_back(std::pair(nTmpXSize, nTmpYSize));
1061 24 : nCurLevel--;
1062 24 : }
1063 : }
1064 119 : else if (bGenerateMskOvr || bGenerateOvr)
1065 : {
1066 31 : if (!bGenerateOvr)
1067 : {
1068 : // If generating only .msk.ovr, use the exact overview size as
1069 : // the overviews of the imagery.
1070 1 : int nIters = poFirstBand->GetOverviewCount();
1071 1 : if (nOverviewCount >= 0 && nOverviewCount < nIters)
1072 0 : nIters = nOverviewCount;
1073 2 : for (int i = 0; i < nIters; i++)
1074 : {
1075 1 : auto poOvrBand = poFirstBand->GetOverview(i);
1076 : asOverviewDims.emplace_back(
1077 1 : std::pair(poOvrBand->GetXSize(), poOvrBand->GetYSize()));
1078 : }
1079 : }
1080 : else
1081 : {
1082 : while (true)
1083 : {
1084 88 : if (nOverviewCount < 0)
1085 : {
1086 70 : if (nTmpXSize <= nOvrThresholdSize &&
1087 26 : nTmpYSize <= nOvrThresholdSize)
1088 26 : break;
1089 : }
1090 18 : else if (static_cast<int>(asOverviewDims.size()) ==
1091 33 : nOverviewCount ||
1092 15 : (nTmpXSize == 1 && nTmpYSize == 1))
1093 : {
1094 4 : break;
1095 : }
1096 58 : nTmpXSize /= 2;
1097 58 : nTmpYSize /= 2;
1098 58 : if (nTmpXSize == 0)
1099 0 : nTmpXSize = 1;
1100 58 : if (nTmpYSize == 0)
1101 1 : nTmpYSize = 1;
1102 58 : asOverviewDims.emplace_back(std::pair(nTmpXSize, nTmpYSize));
1103 : }
1104 : }
1105 : }
1106 :
1107 142 : if (dfTotalPixelsToProcess == 0.0)
1108 : {
1109 117 : dfTotalPixelsToProcess =
1110 117 : (bGenerateMskOvr ? double(nXSize) * nYSize / 3 : 0) +
1111 117 : (bGenerateOvr ? double(nXSize) * nYSize * nBands / 3 : 0) +
1112 117 : double(nXSize) * nYSize * (nBands + (bHasMask ? 1 : 0)) * 4. / 3;
1113 : }
1114 :
1115 284 : CPLStringList aosOverviewOptions;
1116 : aosOverviewOptions.SetNameValue(
1117 : "COMPRESS",
1118 : CPLGetConfigOption("COG_TMP_COMPRESSION", // only for debug purposes
1119 142 : HasZSTDCompression() ? "ZSTD" : "LZW"));
1120 : aosOverviewOptions.SetNameValue(
1121 142 : "NUM_THREADS", CSLFetchNameValue(papszOptions, "NUM_THREADS"));
1122 142 : aosOverviewOptions.SetNameValue("BIGTIFF", "YES");
1123 142 : aosOverviewOptions.SetNameValue("SPARSE_OK", "YES");
1124 :
1125 142 : if (bGenerateMskOvr)
1126 : {
1127 10 : CPLDebug("COG", "Generating overviews of the mask: start");
1128 10 : m_osTmpMskOverviewFilename = GetTmpFilename(pszFilename, "msk.ovr.tmp");
1129 10 : GDALRasterBand *poSrcMask = poFirstBand->GetMaskBand();
1130 10 : const char *pszResampling = CSLFetchNameValueDef(
1131 : papszOptions, "OVERVIEW_RESAMPLING",
1132 : CSLFetchNameValueDef(papszOptions, "RESAMPLING",
1133 : GetResampling(poSrcDS)));
1134 :
1135 10 : double dfNextPixels = dfCurPixels + double(nXSize) * nYSize / 3;
1136 10 : void *pScaledProgress = GDALCreateScaledProgress(
1137 : dfCurPixels / dfTotalPixelsToProcess,
1138 : dfNextPixels / dfTotalPixelsToProcess, pfnProgress, pProgressData);
1139 10 : dfCurPixels = dfNextPixels;
1140 :
1141 10 : CPLErr eErr = GTIFFBuildOverviewsEx(
1142 : m_osTmpMskOverviewFilename, 1, &poSrcMask,
1143 10 : static_cast<int>(asOverviewDims.size()), nullptr,
1144 10 : asOverviewDims.data(), pszResampling, aosOverviewOptions.List(),
1145 : GDALScaledProgress, pScaledProgress);
1146 10 : CPLDebug("COG", "Generating overviews of the mask: end");
1147 :
1148 10 : GDALDestroyScaledProgress(pScaledProgress);
1149 10 : if (eErr != CE_None)
1150 : {
1151 0 : return nullptr;
1152 : }
1153 : }
1154 :
1155 142 : if (bGenerateOvr)
1156 : {
1157 37 : CPLDebug("COG", "Generating overviews of the imagery: start");
1158 37 : m_osTmpOverviewFilename = GetTmpFilename(pszFilename, "ovr.tmp");
1159 37 : std::vector<GDALRasterBand *> apoSrcBands;
1160 117 : for (int i = 0; i < nBands; i++)
1161 80 : apoSrcBands.push_back(poCurDS->GetRasterBand(i + 1));
1162 37 : const char *pszResampling = CSLFetchNameValueDef(
1163 : papszOptions, "OVERVIEW_RESAMPLING",
1164 : CSLFetchNameValueDef(papszOptions, "RESAMPLING",
1165 : GetResampling(poSrcDS)));
1166 :
1167 37 : double dfNextPixels =
1168 37 : dfCurPixels + double(nXSize) * nYSize * nBands / 3;
1169 37 : void *pScaledProgress = GDALCreateScaledProgress(
1170 : dfCurPixels / dfTotalPixelsToProcess,
1171 : dfNextPixels / dfTotalPixelsToProcess, pfnProgress, pProgressData);
1172 37 : dfCurPixels = dfNextPixels;
1173 :
1174 37 : if (nBands > 1)
1175 : {
1176 22 : aosOverviewOptions.SetNameValue("INTERLEAVE", "PIXEL");
1177 : }
1178 37 : if (!m_osTmpMskOverviewFilename.empty())
1179 : {
1180 : aosOverviewOptions.SetNameValue("MASK_OVERVIEW_DATASET",
1181 9 : m_osTmpMskOverviewFilename);
1182 : }
1183 37 : CPLErr eErr = GTIFFBuildOverviewsEx(
1184 37 : m_osTmpOverviewFilename, nBands, &apoSrcBands[0],
1185 37 : static_cast<int>(asOverviewDims.size()), nullptr,
1186 37 : asOverviewDims.data(), pszResampling, aosOverviewOptions.List(),
1187 : GDALScaledProgress, pScaledProgress);
1188 37 : CPLDebug("COG", "Generating overviews of the imagery: end");
1189 :
1190 37 : GDALDestroyScaledProgress(pScaledProgress);
1191 37 : if (eErr != CE_None)
1192 : {
1193 1 : return nullptr;
1194 : }
1195 : }
1196 :
1197 282 : CPLStringList aosOptions;
1198 141 : aosOptions.SetNameValue("COPY_SRC_OVERVIEWS", "YES");
1199 141 : aosOptions.SetNameValue("COMPRESS", osCompress);
1200 141 : aosOptions.SetNameValue("TILED", "YES");
1201 141 : aosOptions.SetNameValue("BLOCKXSIZE", osBlockSize);
1202 141 : aosOptions.SetNameValue("BLOCKYSIZE", osBlockSize);
1203 : const char *pszPredictor =
1204 141 : CSLFetchNameValueDef(papszOptions, "PREDICTOR", "FALSE");
1205 141 : const char *pszPredictorValue = GetPredictor(poSrcDS, pszPredictor);
1206 141 : if (pszPredictorValue != nullptr)
1207 : {
1208 2 : aosOptions.SetNameValue("PREDICTOR", pszPredictorValue);
1209 : }
1210 :
1211 141 : const char *pszQuality = CSLFetchNameValue(papszOptions, "QUALITY");
1212 141 : if (EQUAL(osCompress, "JPEG"))
1213 : {
1214 12 : aosOptions.SetNameValue("JPEG_QUALITY", pszQuality);
1215 12 : if (nBands == 3 && EQUAL(pszInterleave, "PIXEL"))
1216 10 : aosOptions.SetNameValue("PHOTOMETRIC", "YCBCR");
1217 : }
1218 129 : else if (EQUAL(osCompress, "WEBP"))
1219 : {
1220 3 : if (pszQuality && atoi(pszQuality) == 100)
1221 2 : aosOptions.SetNameValue("WEBP_LOSSLESS", "YES");
1222 3 : aosOptions.SetNameValue("WEBP_LEVEL", pszQuality);
1223 : }
1224 126 : else if (EQUAL(osCompress, "DEFLATE") || EQUAL(osCompress, "LERC_DEFLATE"))
1225 : {
1226 : aosOptions.SetNameValue("ZLEVEL",
1227 8 : CSLFetchNameValue(papszOptions, "LEVEL"));
1228 : }
1229 118 : else if (EQUAL(osCompress, "ZSTD") || EQUAL(osCompress, "LERC_ZSTD"))
1230 : {
1231 : aosOptions.SetNameValue("ZSTD_LEVEL",
1232 3 : CSLFetchNameValue(papszOptions, "LEVEL"));
1233 : }
1234 115 : else if (EQUAL(osCompress, "LZMA"))
1235 : {
1236 : aosOptions.SetNameValue("LZMA_PRESET",
1237 1 : CSLFetchNameValue(papszOptions, "LEVEL"));
1238 : }
1239 :
1240 141 : if (STARTS_WITH_CI(osCompress, "LERC"))
1241 : {
1242 : aosOptions.SetNameValue("MAX_Z_ERROR",
1243 8 : CSLFetchNameValue(papszOptions, "MAX_Z_ERROR"));
1244 : aosOptions.SetNameValue(
1245 : "MAX_Z_ERROR_OVERVIEW",
1246 8 : CSLFetchNameValue(papszOptions, "MAX_Z_ERROR_OVERVIEW"));
1247 : }
1248 :
1249 141 : if (STARTS_WITH_CI(osCompress, "JXL"))
1250 : {
1251 8 : for (const char *pszKey : {"JXL_LOSSLESS", "JXL_EFFORT", "JXL_DISTANCE",
1252 10 : "JXL_ALPHA_DISTANCE"})
1253 : {
1254 8 : const char *pszValue = CSLFetchNameValue(papszOptions, pszKey);
1255 8 : if (pszValue)
1256 3 : aosOptions.SetNameValue(pszKey, pszValue);
1257 : }
1258 : }
1259 :
1260 : aosOptions.SetNameValue("BIGTIFF",
1261 141 : CSLFetchNameValue(papszOptions, "BIGTIFF"));
1262 : aosOptions.SetNameValue("NUM_THREADS",
1263 141 : CSLFetchNameValue(papszOptions, "NUM_THREADS"));
1264 : aosOptions.SetNameValue("GEOTIFF_VERSION",
1265 141 : CSLFetchNameValue(papszOptions, "GEOTIFF_VERSION"));
1266 : aosOptions.SetNameValue("SPARSE_OK",
1267 141 : CSLFetchNameValue(papszOptions, "SPARSE_OK"));
1268 141 : aosOptions.SetNameValue("NBITS", CSLFetchNameValue(papszOptions, "NBITS"));
1269 :
1270 141 : if (EQUAL(osOverviews, "NONE"))
1271 : {
1272 2 : aosOptions.SetNameValue("@OVERVIEW_DATASET", "");
1273 : }
1274 : else
1275 : {
1276 139 : if (!m_osTmpOverviewFilename.empty())
1277 : {
1278 : aosOptions.SetNameValue("@OVERVIEW_DATASET",
1279 36 : m_osTmpOverviewFilename);
1280 : }
1281 139 : if (!m_osTmpMskOverviewFilename.empty())
1282 : {
1283 : aosOptions.SetNameValue("@MASK_OVERVIEW_DATASET",
1284 10 : m_osTmpMskOverviewFilename);
1285 : }
1286 : aosOptions.SetNameValue(
1287 : "@OVERVIEW_COUNT",
1288 139 : CSLFetchNameValue(papszOptions, "OVERVIEW_COUNT"));
1289 : }
1290 :
1291 : const CPLString osTilingScheme(
1292 282 : CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM"));
1293 141 : if (osTilingScheme != "CUSTOM")
1294 : {
1295 23 : aosOptions.SetNameValue("@TILING_SCHEME_NAME", osTilingScheme);
1296 : aosOptions.SetNameValue("@TILING_SCHEME_ZOOM_LEVEL",
1297 23 : CPLSPrintf("%d", nZoomLevel));
1298 23 : if (nAlignedLevels > 0)
1299 : {
1300 : aosOptions.SetNameValue("@TILING_SCHEME_ALIGNED_LEVELS",
1301 4 : CPLSPrintf("%d", nAlignedLevels));
1302 : }
1303 : }
1304 141 : const char *pszOverviewCompress = CSLFetchNameValueDef(
1305 : papszOptions, "OVERVIEW_COMPRESS", osCompress.c_str());
1306 :
1307 : CPLConfigOptionSetter ovrCompressSetter("COMPRESS_OVERVIEW",
1308 282 : pszOverviewCompress, true);
1309 : const char *pszOverviewQuality =
1310 141 : CSLFetchNameValue(papszOptions, "OVERVIEW_QUALITY");
1311 : CPLConfigOptionSetter ovrQualityJpegSetter("JPEG_QUALITY_OVERVIEW",
1312 282 : pszOverviewQuality, true);
1313 :
1314 141 : std::unique_ptr<CPLConfigOptionSetter> poWebpLosslessSetter;
1315 141 : std::unique_ptr<CPLConfigOptionSetter> poWebpLevelSetter;
1316 141 : if (EQUAL(pszOverviewCompress, "WEBP"))
1317 : {
1318 3 : if (pszOverviewQuality && CPLAtof(pszOverviewQuality) == 100.0)
1319 : {
1320 0 : poWebpLosslessSetter.reset(new CPLConfigOptionSetter(
1321 0 : "WEBP_LOSSLESS_OVERVIEW", "TRUE", true));
1322 : }
1323 : else
1324 : {
1325 3 : poWebpLosslessSetter.reset(new CPLConfigOptionSetter(
1326 3 : "WEBP_LOSSLESS_OVERVIEW", "FALSE", true));
1327 3 : poWebpLevelSetter.reset(new CPLConfigOptionSetter(
1328 3 : "WEBP_LEVEL_OVERVIEW", pszOverviewQuality, true));
1329 : }
1330 : }
1331 :
1332 141 : std::unique_ptr<CPLConfigOptionSetter> poPhotometricSetter;
1333 141 : if (nBands == 3 && EQUAL(pszOverviewCompress, "JPEG") &&
1334 11 : EQUAL(pszInterleave, "PIXEL"))
1335 : {
1336 10 : poPhotometricSetter.reset(
1337 10 : new CPLConfigOptionSetter("PHOTOMETRIC_OVERVIEW", "YCBCR", true));
1338 : }
1339 :
1340 : const char *osOvrPredictor =
1341 141 : CSLFetchNameValueDef(papszOptions, "OVERVIEW_PREDICTOR", "FALSE");
1342 141 : const char *pszOvrPredictorValue = GetPredictor(poSrcDS, osOvrPredictor);
1343 : CPLConfigOptionSetter ovrPredictorSetter("PREDICTOR_OVERVIEW",
1344 282 : pszOvrPredictorValue, true);
1345 :
1346 : GDALDriver *poGTiffDrv =
1347 141 : GDALDriver::FromHandle(GDALGetDriverByName("GTiff"));
1348 141 : if (!poGTiffDrv)
1349 0 : return nullptr;
1350 141 : void *pScaledProgress = GDALCreateScaledProgress(
1351 : dfCurPixels / dfTotalPixelsToProcess, 1.0, pfnProgress, pProgressData);
1352 :
1353 : CPLConfigOptionSetter oSetterInternalMask("GDAL_TIFF_INTERNAL_MASK", "YES",
1354 141 : false);
1355 :
1356 141 : const char *pszCopySrcMDD = CSLFetchNameValue(papszOptions, "COPY_SRC_MDD");
1357 141 : if (pszCopySrcMDD)
1358 2 : aosOptions.SetNameValue("COPY_SRC_MDD", pszCopySrcMDD);
1359 141 : char **papszSrcMDD = CSLFetchNameValueMultiple(papszOptions, "SRC_MDD");
1360 144 : for (CSLConstList papszSrcMDDIter = papszSrcMDD;
1361 144 : papszSrcMDDIter && *papszSrcMDDIter; ++papszSrcMDDIter)
1362 3 : aosOptions.AddNameValue("SRC_MDD", *papszSrcMDDIter);
1363 141 : CSLDestroy(papszSrcMDD);
1364 :
1365 141 : if (EQUAL(pszInterleave, "TILE"))
1366 : {
1367 5 : aosOptions.SetNameValue("INTERLEAVE", "BAND");
1368 5 : aosOptions.SetNameValue("@TILE_INTERLEAVE", "YES");
1369 : }
1370 : else
1371 : {
1372 136 : aosOptions.SetNameValue("INTERLEAVE", pszInterleave);
1373 : }
1374 :
1375 141 : CPLDebug("COG", "Generating final product: start");
1376 : auto poRet =
1377 141 : poGTiffDrv->CreateCopy(pszFilename, poCurDS, false, aosOptions.List(),
1378 : GDALScaledProgress, pScaledProgress);
1379 :
1380 141 : GDALDestroyScaledProgress(pScaledProgress);
1381 :
1382 141 : if (poRet)
1383 129 : poRet->FlushCache(false);
1384 :
1385 141 : CPLDebug("COG", "Generating final product: end");
1386 141 : return poRet;
1387 : }
1388 :
1389 : /************************************************************************/
1390 : /* COGCreateCopy() */
1391 : /************************************************************************/
1392 :
1393 147 : static GDALDataset *COGCreateCopy(const char *pszFilename, GDALDataset *poSrcDS,
1394 : int /*bStrict*/, char **papszOptions,
1395 : GDALProgressFunc pfnProgress,
1396 : void *pProgressData)
1397 : {
1398 294 : return GDALCOGCreator().Create(pszFilename, poSrcDS, papszOptions,
1399 294 : pfnProgress, pProgressData);
1400 : }
1401 :
1402 : /************************************************************************/
1403 : /* GDALRegister_COG() */
1404 : /************************************************************************/
1405 :
1406 : class GDALCOGDriver final : public GDALDriver
1407 : {
1408 : bool m_bInitialized = false;
1409 :
1410 : bool bHasLZW = false;
1411 : bool bHasDEFLATE = false;
1412 : bool bHasLZMA = false;
1413 : bool bHasZSTD = false;
1414 : bool bHasJPEG = false;
1415 : bool bHasWebP = false;
1416 : bool bHasLERC = false;
1417 : std::string osCompressValues{};
1418 :
1419 : void InitializeCreationOptionList();
1420 :
1421 : public:
1422 : GDALCOGDriver();
1423 :
1424 40498 : const char *GetMetadataItem(const char *pszName,
1425 : const char *pszDomain) override
1426 : {
1427 40498 : if (EQUAL(pszName, GDAL_DMD_CREATIONOPTIONLIST))
1428 : {
1429 172 : InitializeCreationOptionList();
1430 : }
1431 40498 : return GDALDriver::GetMetadataItem(pszName, pszDomain);
1432 : }
1433 :
1434 62 : char **GetMetadata(const char *pszDomain) override
1435 : {
1436 62 : InitializeCreationOptionList();
1437 62 : return GDALDriver::GetMetadata(pszDomain);
1438 : }
1439 : };
1440 :
1441 1384 : GDALCOGDriver::GDALCOGDriver()
1442 : {
1443 : // We could defer this in InitializeCreationOptionList() but with currently
1444 : // released libtiff versions where there was a bug (now fixed) in
1445 : // TIFFGetConfiguredCODECs(), this wouldn't work properly if the LERC codec
1446 : // had been registered in between
1447 1384 : osCompressValues = GTiffGetCompressValues(bHasLZW, bHasDEFLATE, bHasLZMA,
1448 1384 : bHasZSTD, bHasJPEG, bHasWebP,
1449 1384 : bHasLERC, true /* bForCOG */);
1450 1384 : gbHasLZW = bHasLZW;
1451 1384 : }
1452 :
1453 234 : void GDALCOGDriver::InitializeCreationOptionList()
1454 : {
1455 234 : if (m_bInitialized)
1456 222 : return;
1457 12 : m_bInitialized = true;
1458 :
1459 24 : CPLString osOptions;
1460 : osOptions = "<CreationOptionList>"
1461 12 : " <Option name='COMPRESS' type='string-select' default='";
1462 12 : osOptions += bHasLZW ? "LZW" : "NONE";
1463 12 : osOptions += "'>";
1464 12 : osOptions += osCompressValues;
1465 12 : osOptions += " </Option>";
1466 :
1467 : osOptions +=
1468 12 : " <Option name='OVERVIEW_COMPRESS' type='string-select' default='";
1469 12 : osOptions += bHasLZW ? "LZW" : "NONE";
1470 12 : osOptions += "'>";
1471 12 : osOptions += osCompressValues;
1472 12 : osOptions += " </Option>";
1473 :
1474 12 : if (bHasLZW || bHasDEFLATE || bHasZSTD || bHasLZMA)
1475 : {
1476 12 : const char *osPredictorOptions =
1477 : " <Value>YES</Value>"
1478 : " <Value>NO</Value>"
1479 : " <Value alias='2'>STANDARD</Value>"
1480 : " <Value alias='3'>FLOATING_POINT</Value>";
1481 :
1482 : osOptions +=
1483 : " <Option name='LEVEL' type='int' "
1484 12 : "description='DEFLATE/ZSTD/LZMA compression level: 1 (fastest)'/>";
1485 :
1486 : osOptions +=
1487 12 : " <Option name='PREDICTOR' type='string-select' default='FALSE'>";
1488 12 : osOptions += osPredictorOptions;
1489 : osOptions += " </Option>"
1490 : " <Option name='OVERVIEW_PREDICTOR' "
1491 12 : "type='string-select' default='FALSE'>";
1492 12 : osOptions += osPredictorOptions;
1493 12 : osOptions += " </Option>";
1494 : }
1495 12 : if (bHasJPEG || bHasWebP)
1496 : {
1497 12 : std::string osJPEG_WEBP;
1498 12 : if (bHasJPEG)
1499 12 : osJPEG_WEBP = "JPEG";
1500 12 : if (bHasWebP)
1501 : {
1502 12 : if (!osJPEG_WEBP.empty())
1503 12 : osJPEG_WEBP += '/';
1504 12 : osJPEG_WEBP += "WEBP";
1505 : }
1506 : osOptions += " <Option name='QUALITY' type='int' "
1507 24 : "description='" +
1508 24 : osJPEG_WEBP +
1509 : " quality 1-100' min='1' max='100' default='75'/>"
1510 : " <Option name='OVERVIEW_QUALITY' type='int' "
1511 24 : "description='Overview " +
1512 24 : osJPEG_WEBP +
1513 : " quality 1-100' min='1' max='100' "
1514 12 : "default='75'/>";
1515 : }
1516 12 : if (bHasLERC)
1517 : {
1518 : osOptions +=
1519 : ""
1520 : " <Option name='MAX_Z_ERROR' type='float' description='Maximum "
1521 : "error for LERC compression' default='0'/>"
1522 : " <Option name='MAX_Z_ERROR_OVERVIEW' type='float' "
1523 : "description='Maximum error for LERC compression in overviews' "
1524 12 : "default='0'/>";
1525 : }
1526 : #ifdef HAVE_JXL
1527 : osOptions +=
1528 : ""
1529 : " <Option name='JXL_LOSSLESS' type='boolean' description='Whether "
1530 : "JPEGXL compression should be lossless' default='YES'/>"
1531 : " <Option name='JXL_EFFORT' type='int' description='Level of effort "
1532 : "1(fast)-9(slow)' min='1' max='9' default='5'/>"
1533 : " <Option name='JXL_DISTANCE' type='float' description='Distance "
1534 : "level for lossy compression (0=mathematically lossless, 1.0=visually "
1535 12 : "lossless, usual range [0.5,3])' default='1.0' min='0.01' max='25.0'/>";
1536 : #ifdef HAVE_JxlEncoderSetExtraChannelDistance
1537 : osOptions += " <Option name='JXL_ALPHA_DISTANCE' type='float' "
1538 : "description='Distance level for alpha channel "
1539 : "(-1=same as non-alpha channels, "
1540 : "0=mathematically lossless, 1.0=visually lossless, "
1541 12 : "usual range [0.5,3])' default='-1' min='-1' max='25.0'/>";
1542 : #endif
1543 : #endif
1544 : osOptions +=
1545 : " <Option name='NUM_THREADS' type='string' "
1546 : "description='Number of worker threads for compression. "
1547 : "Can be set to ALL_CPUS' default='1'/>"
1548 : " <Option name='NBITS' type='int' description='BITS for sub-byte "
1549 : "files (1-7), sub-uint16_t (9-15), sub-uint32_t (17-31), or float32 "
1550 : "(16)'/>"
1551 : " <Option name='BLOCKSIZE' type='int' "
1552 : "description='Tile size in pixels' min='128' default='512'/>"
1553 : " <Option name='INTERLEAVE' type='string-select' default='PIXEL'>"
1554 : " <Value>BAND</Value>"
1555 : " <Value>PIXEL</Value>"
1556 : " <Value>TILE</Value>"
1557 : " </Option>"
1558 : " <Option name='BIGTIFF' type='string-select' description='"
1559 : "Force creation of BigTIFF file'>"
1560 : " <Value>YES</Value>"
1561 : " <Value>NO</Value>"
1562 : " <Value>IF_NEEDED</Value>"
1563 : " <Value>IF_SAFER</Value>"
1564 : " </Option>"
1565 : " <Option name='RESAMPLING' type='string' "
1566 : "description='Resampling method for overviews or warping'/>"
1567 : " <Option name='OVERVIEW_RESAMPLING' type='string' "
1568 : "description='Resampling method for overviews'/>"
1569 : " <Option name='WARP_RESAMPLING' type='string' "
1570 : "description='Resampling method for warping'/>"
1571 : " <Option name='OVERVIEWS' type='string-select' description='"
1572 : "Behavior regarding overviews'>"
1573 : " <Value>AUTO</Value>"
1574 : " <Value>IGNORE_EXISTING</Value>"
1575 : " <Value>FORCE_USE_EXISTING</Value>"
1576 : " <Value>NONE</Value>"
1577 : " </Option>"
1578 : " <Option name='OVERVIEW_COUNT' type='int' min='0' "
1579 : "description='Number of overviews'/>"
1580 : " <Option name='TILING_SCHEME' type='string-select' description='"
1581 : "Which tiling scheme to use pre-defined value or custom inline/outline "
1582 : "JSON definition' default='CUSTOM'>"
1583 12 : " <Value>CUSTOM</Value>";
1584 :
1585 24 : const auto tmsList = gdal::TileMatrixSet::listPredefinedTileMatrixSets();
1586 84 : for (const auto &tmsName : tmsList)
1587 : {
1588 144 : const auto poTM = gdal::TileMatrixSet::parse(tmsName.c_str());
1589 144 : if (poTM && poTM->haveAllLevelsSameTopLeft() &&
1590 216 : poTM->haveAllLevelsSameTileSize() &&
1591 72 : !poTM->hasVariableMatrixWidth())
1592 : {
1593 72 : osOptions += " <Value>";
1594 72 : osOptions += tmsName;
1595 72 : osOptions += "</Value>";
1596 : }
1597 : }
1598 :
1599 : osOptions +=
1600 : " </Option>"
1601 : " <Option name='ZOOM_LEVEL' type='int' description='Target zoom "
1602 : "level. "
1603 : "Only used for TILING_SCHEME != CUSTOM'/>"
1604 : " <Option name='ZOOM_LEVEL_STRATEGY' type='string-select' "
1605 : "description='Strategy to determine zoom level. "
1606 : "Only used for TILING_SCHEME != CUSTOM' default='AUTO'>"
1607 : " <Value>AUTO</Value>"
1608 : " <Value>LOWER</Value>"
1609 : " <Value>UPPER</Value>"
1610 : " </Option>"
1611 : " <Option name='TARGET_SRS' type='string' "
1612 : "description='Target SRS as EPSG:XXXX, WKT or PROJ string for "
1613 : "reprojection'/>"
1614 : " <Option name='RES' type='float' description='"
1615 : "Target resolution for reprojection'/>"
1616 : " <Option name='EXTENT' type='string' description='"
1617 : "Target extent as minx,miny,maxx,maxy for reprojection'/>"
1618 : " <Option name='ALIGNED_LEVELS' type='int' description='"
1619 : "Number of resolution levels for which the tiles from GeoTIFF and the "
1620 : "specified tiling scheme match'/>"
1621 : " <Option name='ADD_ALPHA' type='boolean' description='Can be set to "
1622 : "NO to "
1623 : "disable the addition of an alpha band in case of reprojection' "
1624 : "default='YES'/>"
1625 : #if LIBGEOTIFF_VERSION >= 1600
1626 : " <Option name='GEOTIFF_VERSION' type='string-select' default='AUTO' "
1627 : "description='Which version of GeoTIFF must be used'>"
1628 : " <Value>AUTO</Value>"
1629 : " <Value>1.0</Value>"
1630 : " <Value>1.1</Value>"
1631 : " </Option>"
1632 : #endif
1633 : " <Option name='SPARSE_OK' type='boolean' description='Should empty "
1634 : "blocks be omitted on disk?' default='FALSE'/>"
1635 : " <Option name='STATISTICS' type='string-select' default='AUTO' "
1636 : "description='Which to add statistics to the output file'>"
1637 : " <Value>AUTO</Value>"
1638 : " <Value>YES</Value>"
1639 : " <Value>NO</Value>"
1640 : " </Option>"
1641 12 : "</CreationOptionList>";
1642 :
1643 12 : SetMetadataItem(GDAL_DMD_CREATIONOPTIONLIST, osOptions.c_str());
1644 : }
1645 :
1646 1686 : void GDALRegister_COG()
1647 :
1648 : {
1649 1686 : if (GDALGetDriverByName("COG") != nullptr)
1650 302 : return;
1651 :
1652 1384 : auto poDriver = new GDALCOGDriver();
1653 1384 : poDriver->SetDescription("COG");
1654 1384 : poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
1655 1384 : poDriver->SetMetadataItem(GDAL_DMD_LONGNAME,
1656 1384 : "Cloud optimized GeoTIFF generator");
1657 1384 : poDriver->SetMetadataItem(GDAL_DMD_HELPTOPIC, "drivers/raster/cog.html");
1658 1384 : poDriver->SetMetadataItem(GDAL_DMD_EXTENSIONS, "tif tiff");
1659 :
1660 1384 : poDriver->SetMetadataItem(
1661 : GDAL_DMD_CREATIONDATATYPES,
1662 : "Byte Int8 UInt16 Int16 UInt32 Int32 UInt64 Int64 Float32 "
1663 1384 : "Float64 CInt16 CInt32 CFloat32 CFloat64");
1664 :
1665 1384 : poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
1666 :
1667 1384 : poDriver->SetMetadataItem(GDAL_DCAP_COORDINATE_EPOCH, "YES");
1668 :
1669 1384 : poDriver->pfnCreateCopy = COGCreateCopy;
1670 :
1671 1384 : GetGDALDriverManager()->RegisterDriver(poDriver);
1672 : }
|