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