Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: Virtual GDAL Datasets
4 : * Purpose: Tile index based VRT
5 : * Author: Even Rouault <even dot rouault at spatialys.com>
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 2023, Even Rouault <even dot rouault at spatialys.com>
9 : *
10 : * SPDX-License-Identifier: MIT
11 : ****************************************************************************/
12 :
13 : /*! @cond Doxygen_Suppress */
14 :
15 : #include <array>
16 : #include <algorithm>
17 : #include <atomic>
18 : #include <cmath>
19 : #include <limits>
20 : #include <mutex>
21 : #include <set>
22 : #include <tuple>
23 : #include <utility>
24 : #include <vector>
25 :
26 : #include "cpl_port.h"
27 : #include "cpl_error_internal.h"
28 : #include "cpl_json.h"
29 : #include "cpl_mem_cache.h"
30 : #include "cpl_minixml.h"
31 : #include "cpl_quad_tree.h"
32 : #include "vrtdataset.h"
33 : #include "vrt_priv.h"
34 : #include "ogrsf_frmts.h"
35 : #include "ogrwarpedlayer.h"
36 : #include "gdal_frmts.h"
37 : #include "gdal_proxy.h"
38 : #include "gdalsubdatasetinfo.h"
39 : #include "gdal_thread_pool.h"
40 : #include "gdal_utils.h"
41 :
42 : #include "gdalalg_raster_index.h"
43 :
44 : #ifdef USE_NEON_OPTIMIZATIONS
45 : #define USE_SSE2_OPTIM
46 : #define USE_SSE41_OPTIM
47 : #include "include_sse2neon.h"
48 : #elif defined(__SSE2__) || defined(_M_X64)
49 : #define USE_SSE2_OPTIM
50 : #include <emmintrin.h>
51 : // MSVC doesn't define __SSE4_1__, but if -arch:AVX2 is enabled, we do have SSE4.1
52 : #if defined(__SSE4_1__) || defined(__AVX2__)
53 : #define USE_SSE41_OPTIM
54 : #include <smmintrin.h>
55 : #endif
56 : #endif
57 :
58 : #ifndef _
59 : #define _(x) (x)
60 : #endif
61 :
62 : // Semantincs of indices of a GeoTransform (double[6]) matrix
63 : constexpr int GT_TOPLEFT_X = 0;
64 : constexpr int GT_WE_RES = 1;
65 : constexpr int GT_ROTATION_PARAM1 = 2;
66 : constexpr int GT_TOPLEFT_Y = 3;
67 : constexpr int GT_ROTATION_PARAM2 = 4;
68 : constexpr int GT_NS_RES = 5;
69 :
70 : constexpr const char *GTI_PREFIX = "GTI:";
71 :
72 : constexpr const char *MD_DS_TILE_INDEX_LAYER = "TILE_INDEX_LAYER";
73 : constexpr const char *MD_DS_TILE_INDEX_SQL = "TILE_INDEX_SQL";
74 : constexpr const char *MD_DS_TILE_INDEX_SPATIAL_SQL = "TILE_INDEX_SPATIAL_SQL";
75 :
76 : constexpr const char *MD_RESX = "RESX";
77 : constexpr const char *MD_RESY = "RESY";
78 : constexpr const char *MD_BAND_COUNT = "BAND_COUNT";
79 : constexpr const char *MD_DATA_TYPE = "DATA_TYPE";
80 : constexpr const char *MD_NODATA = "NODATA";
81 : constexpr const char *MD_MINX = "MINX";
82 : constexpr const char *MD_MINY = "MINY";
83 : constexpr const char *MD_MAXX = "MAXX";
84 : constexpr const char *MD_MAXY = "MAXY";
85 : constexpr const char *MD_GEOTRANSFORM = "GEOTRANSFORM";
86 : constexpr const char *MD_XSIZE = "XSIZE";
87 : constexpr const char *MD_YSIZE = "YSIZE";
88 : constexpr const char *MD_COLOR_INTERPRETATION = "COLOR_INTERPRETATION";
89 : constexpr const char *MD_SRS = "SRS";
90 : constexpr const char *MD_LOCATION_FIELD = "LOCATION_FIELD";
91 : constexpr const char *MD_SORT_FIELD = "SORT_FIELD";
92 : constexpr const char *MD_SORT_FIELD_ASC = "SORT_FIELD_ASC";
93 : constexpr const char *MD_BLOCK_X_SIZE = "BLOCKXSIZE";
94 : constexpr const char *MD_BLOCK_Y_SIZE = "BLOCKYSIZE";
95 : constexpr const char *MD_MASK_BAND = "MASK_BAND";
96 : constexpr const char *MD_RESAMPLING = "RESAMPLING";
97 :
98 : constexpr const char *const apszTIOptions[] = {MD_RESX,
99 : MD_RESY,
100 : MD_BAND_COUNT,
101 : MD_DATA_TYPE,
102 : MD_NODATA,
103 : MD_MINX,
104 : MD_MINY,
105 : MD_MAXX,
106 : MD_MAXY,
107 : MD_GEOTRANSFORM,
108 : MD_XSIZE,
109 : MD_YSIZE,
110 : MD_COLOR_INTERPRETATION,
111 : MD_SRS,
112 : MD_LOCATION_FIELD,
113 : MD_SORT_FIELD,
114 : MD_SORT_FIELD_ASC,
115 : MD_BLOCK_X_SIZE,
116 : MD_BLOCK_Y_SIZE,
117 : MD_MASK_BAND,
118 : MD_RESAMPLING};
119 :
120 : constexpr const char *const MD_BAND_OFFSET = "OFFSET";
121 : constexpr const char *const MD_BAND_SCALE = "SCALE";
122 : constexpr const char *const MD_BAND_UNITTYPE = "UNITTYPE";
123 : constexpr const char *const apszReservedBandItems[] = {
124 : MD_BAND_OFFSET, MD_BAND_SCALE, MD_BAND_UNITTYPE};
125 :
126 : constexpr const char *GTI_XML_BANDCOUNT = "BandCount";
127 : constexpr const char *GTI_XML_DATATYPE = "DataType";
128 : constexpr const char *GTI_XML_NODATAVALUE = "NoDataValue";
129 : constexpr const char *GTI_XML_COLORINTERP = "ColorInterp";
130 : constexpr const char *GTI_XML_LOCATIONFIELD = "LocationField";
131 : constexpr const char *GTI_XML_SORTFIELD = "SortField";
132 : constexpr const char *GTI_XML_SORTFIELDASC = "SortFieldAsc";
133 : constexpr const char *GTI_XML_MASKBAND = "MaskBand";
134 : constexpr const char *GTI_XML_OVERVIEW_ELEMENT = "Overview";
135 : constexpr const char *GTI_XML_OVERVIEW_DATASET = "Dataset";
136 : constexpr const char *GTI_XML_OVERVIEW_LAYER = "Layer";
137 : constexpr const char *GTI_XML_OVERVIEW_FACTOR = "Factor";
138 :
139 : constexpr const char *GTI_XML_BAND_ELEMENT = "Band";
140 : constexpr const char *GTI_XML_BAND_NUMBER = "band";
141 : constexpr const char *GTI_XML_BAND_DATATYPE = "dataType";
142 : constexpr const char *GTI_XML_BAND_DESCRIPTION = "Description";
143 : constexpr const char *GTI_XML_BAND_OFFSET = "Offset";
144 : constexpr const char *GTI_XML_BAND_SCALE = "Scale";
145 : constexpr const char *GTI_XML_BAND_NODATAVALUE = "NoDataValue";
146 : constexpr const char *GTI_XML_BAND_UNITTYPE = "UnitType";
147 : constexpr const char *GTI_XML_BAND_COLORINTERP = "ColorInterp";
148 : constexpr const char *GTI_XML_CATEGORYNAMES = "CategoryNames";
149 : constexpr const char *GTI_XML_COLORTABLE = "ColorTable";
150 : constexpr const char *GTI_XML_RAT = "GDALRasterAttributeTable";
151 :
152 : /************************************************************************/
153 : /* ENDS_WITH_CI() */
154 : /************************************************************************/
155 :
156 64503 : static inline bool ENDS_WITH_CI(const char *a, const char *b)
157 : {
158 64503 : return strlen(a) >= strlen(b) && EQUAL(a + strlen(a) - strlen(b), b);
159 : }
160 :
161 : /************************************************************************/
162 : /* GDALTileIndexDataset */
163 : /************************************************************************/
164 :
165 : class GDALTileIndexBand;
166 :
167 : class GDALTileIndexDataset final : public GDALPamDataset
168 : {
169 : public:
170 : GDALTileIndexDataset();
171 : ~GDALTileIndexDataset() override;
172 :
173 : bool Open(GDALOpenInfo *poOpenInfo);
174 :
175 : CPLErr FlushCache(bool bAtClosing) override;
176 :
177 : CPLErr GetGeoTransform(GDALGeoTransform >) const override;
178 : const OGRSpatialReference *GetSpatialRef() const override;
179 :
180 : CPLErr IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize,
181 : int nYSize, void *pData, int nBufXSize, int nBufYSize,
182 : GDALDataType eBufType, int nBandCount,
183 : BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
184 : GSpacing nLineSpace, GSpacing nBandSpace,
185 : GDALRasterIOExtraArg *psExtraArg) override;
186 :
187 : const char *GetMetadataItem(const char *pszName,
188 : const char *pszDomain) override;
189 : CPLErr SetMetadataItem(const char *pszName, const char *pszValue,
190 : const char *pszDomain) override;
191 : CPLErr SetMetadata(char **papszMD, const char *pszDomain) override;
192 :
193 : void LoadOverviews();
194 :
195 : std::vector<GTISourceDesc> GetSourcesMoreRecentThan(int64_t mTime);
196 :
197 : private:
198 : friend class GDALTileIndexBand;
199 :
200 : //! Optional GTI XML
201 : CPLXMLTreeCloser m_psXMLTree{nullptr};
202 :
203 : //! Whether the GTI XML might be modified (by SetMetadata/SetMetadataItem)
204 : bool m_bXMLUpdatable = false;
205 :
206 : //! Whether the GTI XML has been modified (by SetMetadata/SetMetadataItem)
207 : bool m_bXMLModified = false;
208 :
209 : //! Unique string (without the process) for this tile index. Passed to
210 : //! GDALProxyPoolDataset to ensure that sources are unique for a given owner
211 : const std::string m_osUniqueHandle;
212 :
213 : //! Vector dataset with the sources
214 : std::unique_ptr<GDALDataset> m_poVectorDS{};
215 :
216 : //! Generic SQL request to return features. May be empty.
217 : std::string m_osSQL{};
218 :
219 : //! SQL request to return features with placeholders for spatial filtering. May be empty
220 : std::string m_osSpatialSQL{};
221 :
222 : //! Vector layer with the sources
223 : OGRLayer *m_poLayer = nullptr;
224 :
225 : //! Whether m_poLayer should be freed with m_poVectorDS->ReleaseResultSet()
226 : bool m_bIsSQLResultLayer = false;
227 :
228 : //! When the SRS of m_poLayer is not the one we expose
229 : std::unique_ptr<OGRLayer> m_poWarpedLayerKeeper{};
230 :
231 : //! Geotransform matrix of the tile index
232 : GDALGeoTransform m_gt{};
233 :
234 : //! Index of the "location" (or alternate name given by user) field
235 : //! (within m_poLayer->GetLayerDefn()), that contain source dataset names.
236 : int m_nLocationFieldIndex = -1;
237 :
238 : //! SRS of the tile index.
239 : OGRSpatialReference m_oSRS{};
240 :
241 : //! Cache from dataset name to dataset handle.
242 : //! Note that the dataset objects are ultimately GDALProxyPoolDataset,
243 : //! and that the GDALProxyPoolDataset limits the number of simultaneously
244 : //! opened real datasets (controlled by GDAL_MAX_DATASET_POOL_SIZE). Hence 500 is not too big.
245 : lru11::Cache<std::string, std::shared_ptr<GDALDataset>> m_oMapSharedSources{
246 : 500};
247 :
248 : //! Mask band (e.g. for JPEG compressed + mask band)
249 : std::unique_ptr<GDALTileIndexBand> m_poMaskBand{};
250 :
251 : //! Whether all bands of the tile index have the same data type.
252 : bool m_bSameDataType = true;
253 :
254 : //! Whether all bands of the tile index have the same nodata value.
255 : bool m_bSameNoData = true;
256 :
257 : //! Minimum X of the current pixel request, in georeferenced units.
258 : double m_dfLastMinXFilter = std::numeric_limits<double>::quiet_NaN();
259 :
260 : //! Minimum Y of the current pixel request, in georeferenced units.
261 : double m_dfLastMinYFilter = std::numeric_limits<double>::quiet_NaN();
262 :
263 : //! Maximum X of the current pixel request, in georeferenced units.
264 : double m_dfLastMaxXFilter = std::numeric_limits<double>::quiet_NaN();
265 :
266 : //! Maximum Y of the current pixel request, in georeferenced units.
267 : double m_dfLastMaxYFilter = std::numeric_limits<double>::quiet_NaN();
268 :
269 : //! Index of the field (within m_poLayer->GetLayerDefn()) used to sort, or -1 if none.
270 : int m_nSortFieldIndex = -1;
271 :
272 : //! Whether sorting must be ascending (true) or descending (false).
273 : bool m_bSortFieldAsc = true;
274 :
275 : //! Resampling method by default for warping or when a source has not
276 : //! the same resolution as the tile index.
277 : std::string m_osResampling = "near";
278 : GDALRIOResampleAlg m_eResampling = GRIORA_NearestNeighbour;
279 :
280 : //! WKT2 representation of the tile index SRS (if needed, typically for on-the-fly warping).
281 : std::string m_osWKT{};
282 :
283 : //! Whether we had to open of the sources at tile index opening.
284 : bool m_bScannedOneFeatureAtOpening = false;
285 :
286 : //! Array of overview descriptors.
287 : //! Each descriptor is a tuple (dataset_name, concatenated_open_options, layer_name, overview_factor).
288 : std::vector<std::tuple<std::string, CPLStringList, std::string, double>>
289 : m_aoOverviewDescriptor{};
290 :
291 : //! Array of overview datasets.
292 : std::vector<std::unique_ptr<GDALDataset>> m_apoOverviews{};
293 :
294 : //! Cache of buffers used by VRTComplexSource to avoid memory reallocation.
295 : VRTSource::WorkingState m_oWorkingState{};
296 :
297 : //! Used by IRasterIO() when using multi-threading
298 : struct QueueWorkingStates
299 : {
300 : std::mutex oMutex{};
301 : std::vector<std::unique_ptr<VRTSource::WorkingState>> oStates{};
302 : };
303 :
304 : //! Used by IRasterIO() when using multi-threading
305 : QueueWorkingStates m_oQueueWorkingStates{};
306 :
307 : //! Structure describing one of the source raster in the tile index.
308 : struct SourceDesc
309 : {
310 : //! Source dataset name.
311 : std::string osName{};
312 :
313 : //! Source dataset handle.
314 : std::shared_ptr<GDALDataset> poDS{};
315 :
316 : //! VRTSimpleSource or VRTComplexSource for the source.
317 : std::unique_ptr<VRTSimpleSource> poSource{};
318 :
319 : //! OGRFeature corresponding to the source in the tile index.
320 : std::unique_ptr<OGRFeature> poFeature{};
321 :
322 : //! Work buffer containing the value of the mask band for the current pixel query.
323 : mutable std::vector<GByte> abyMask{};
324 :
325 : //! Whether the source covers the whole area of interest of the current pixel query.
326 : bool bCoversWholeAOI = false;
327 :
328 : //! Whether the source has a nodata value at least in one of its band.
329 : bool bHasNoData = false;
330 :
331 : //! Whether all bands of the source have the same nodata value.
332 : bool bSameNoData = false;
333 :
334 : //! Nodata value of all bands (when bSameNoData == true).
335 : double dfSameNoData = 0;
336 :
337 : //! Mask band of the source.
338 : GDALRasterBand *poMaskBand = nullptr;
339 : };
340 :
341 : //! Array of sources participating to the current pixel query.
342 : std::vector<SourceDesc> m_aoSourceDesc{};
343 :
344 : //! Maximum number of threads. Updated by CollectSources().
345 : int m_nNumThreads = -1;
346 :
347 : //! Whereas the multi-threading rendering code path must be used. Updated by CollectSources().
348 : bool m_bLastMustUseMultiThreading = false;
349 :
350 : //! From a source dataset name, return its SourceDesc description structure.
351 : bool GetSourceDesc(const std::string &osTileName, SourceDesc &oSourceDesc,
352 : std::mutex *pMutex);
353 :
354 : //! Collect sources corresponding to the georeferenced window of interest,
355 : //! and store them in m_aoSourceDesc[].
356 : bool CollectSources(double dfXOff, double dfYOff, double dfXSize,
357 : double dfYSize, bool bMultiThreadAllowed);
358 :
359 : //! Sort sources according to m_nSortFieldIndex.
360 : void SortSourceDesc();
361 :
362 : //! Whether the output buffer needs to be nodata initialized, or if
363 : //! sources are fully covering it.
364 : bool NeedInitBuffer(int nBandCount, const int *panBandMap) const;
365 :
366 : //! Nodata initialize the output buffer.
367 : void InitBuffer(void *pData, int nBufXSize, int nBufYSize,
368 : GDALDataType eBufType, int nBandCount,
369 : const int *panBandMap, GSpacing nPixelSpace,
370 : GSpacing nLineSpace, GSpacing nBandSpace) const;
371 :
372 : //! Render one source. Used by IRasterIO()
373 : CPLErr RenderSource(const SourceDesc &oSourceDesc, bool bNeedInitBuffer,
374 : int nBandNrMax, int nXOff, int nYOff, int nXSize,
375 : int nYSize, double dfXOff, double dfYOff,
376 : double dfXSize, double dfYSize, int nBufXSize,
377 : int nBufYSize, void *pData, GDALDataType eBufType,
378 : int nBandCount, BANDMAP_TYPE panBandMap,
379 : GSpacing nPixelSpace, GSpacing nLineSpace,
380 : GSpacing nBandSpace, GDALRasterIOExtraArg *psExtraArg,
381 : VRTSource::WorkingState &oWorkingState) const;
382 :
383 : //! Whether m_poVectorDS supports SetMetadata()/SetMetadataItem()
384 : bool TileIndexSupportsEditingLayerMetadata() const;
385 :
386 : //! Return number of threads that can be used
387 : int GetNumThreads() const;
388 :
389 : /** Structure used to declare a threaded job to satisfy IRasterIO()
390 : * on a given source.
391 : */
392 : struct RasterIOJob
393 : {
394 : std::atomic<int> *pnCompletedJobs = nullptr;
395 : std::atomic<bool> *pbSuccess = nullptr;
396 : CPLErrorAccumulator *poErrorAccumulator = nullptr;
397 : GDALTileIndexDataset *poDS = nullptr;
398 : GDALTileIndexDataset::QueueWorkingStates *poQueueWorkingStates =
399 : nullptr;
400 : int nBandNrMax = 0;
401 :
402 : int nXOff = 0;
403 : int nYOff = 0;
404 : int nXSize = 0;
405 : int nYSize = 0;
406 : void *pData = nullptr;
407 : int nBufXSize = 0;
408 : int nBufYSize = 0;
409 : int nBandCount = 0;
410 : BANDMAP_TYPE panBandMap = nullptr;
411 : GDALDataType eBufType = GDT_Unknown;
412 : GSpacing nPixelSpace = 0;
413 : GSpacing nLineSpace = 0;
414 : GSpacing nBandSpace = 0;
415 : GDALRasterIOExtraArg *psExtraArg = nullptr;
416 :
417 : std::string osTileName{};
418 :
419 : static void Func(void *pData);
420 : };
421 :
422 : CPL_DISALLOW_COPY_ASSIGN(GDALTileIndexDataset)
423 : };
424 :
425 : /************************************************************************/
426 : /* GDALTileIndexBand */
427 : /************************************************************************/
428 :
429 : class GDALTileIndexBand final : public GDALPamRasterBand
430 : {
431 : public:
432 : GDALTileIndexBand(GDALTileIndexDataset *poDSIn, int nBandIn,
433 : GDALDataType eDT, int nBlockXSizeIn, int nBlockYSizeIn);
434 :
435 105 : double GetNoDataValue(int *pbHasNoData) override
436 : {
437 105 : if (pbHasNoData)
438 102 : *pbHasNoData = m_bNoDataValueSet;
439 105 : return m_dfNoDataValue;
440 : }
441 :
442 58 : GDALColorInterp GetColorInterpretation() override
443 : {
444 58 : return m_eColorInterp;
445 : }
446 :
447 : CPLErr IReadBlock(int nBlockXOff, int nBlockYOff, void *pData) override;
448 :
449 : CPLErr IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize,
450 : int nYSize, void *pData, int nBufXSize, int nBufYSize,
451 : GDALDataType eBufType, GSpacing nPixelSpace,
452 : GSpacing nLineSpace,
453 : GDALRasterIOExtraArg *psExtraArg) override;
454 :
455 : int IGetDataCoverageStatus(int nXOff, int nYOff, int nXSize, int nYSize,
456 : int nMaskFlagStop, double *pdfDataPct) override;
457 :
458 32 : int GetMaskFlags() override
459 : {
460 32 : if (m_poDS->m_poMaskBand && m_poDS->m_poMaskBand.get() != this)
461 4 : return GMF_PER_DATASET;
462 28 : return GDALPamRasterBand::GetMaskFlags();
463 : }
464 :
465 34 : GDALRasterBand *GetMaskBand() override
466 : {
467 34 : if (m_poDS->m_poMaskBand && m_poDS->m_poMaskBand.get() != this)
468 7 : return m_poDS->m_poMaskBand.get();
469 27 : return GDALPamRasterBand::GetMaskBand();
470 : }
471 :
472 13 : double GetOffset(int *pbHasValue) override
473 : {
474 13 : int bHasValue = FALSE;
475 13 : double dfVal = GDALPamRasterBand::GetOffset(&bHasValue);
476 13 : if (bHasValue)
477 : {
478 0 : if (pbHasValue)
479 0 : *pbHasValue = true;
480 0 : return dfVal;
481 : }
482 13 : if (pbHasValue)
483 10 : *pbHasValue = !std::isnan(m_dfOffset);
484 13 : return std::isnan(m_dfOffset) ? 0.0 : m_dfOffset;
485 : }
486 :
487 13 : double GetScale(int *pbHasValue) override
488 : {
489 13 : int bHasValue = FALSE;
490 13 : double dfVal = GDALPamRasterBand::GetScale(&bHasValue);
491 13 : if (bHasValue)
492 : {
493 0 : if (pbHasValue)
494 0 : *pbHasValue = true;
495 0 : return dfVal;
496 : }
497 13 : if (pbHasValue)
498 10 : *pbHasValue = !std::isnan(m_dfScale);
499 13 : return std::isnan(m_dfScale) ? 1.0 : m_dfScale;
500 : }
501 :
502 9 : const char *GetUnitType() override
503 : {
504 9 : const char *pszVal = GDALPamRasterBand::GetUnitType();
505 9 : if (pszVal && *pszVal)
506 0 : return pszVal;
507 9 : return m_osUnit.c_str();
508 : }
509 :
510 5 : char **GetCategoryNames() override
511 : {
512 5 : return m_aosCategoryNames.List();
513 : }
514 :
515 11 : GDALColorTable *GetColorTable() override
516 : {
517 11 : return m_poColorTable.get();
518 : }
519 :
520 5 : GDALRasterAttributeTable *GetDefaultRAT() override
521 : {
522 5 : return m_poRAT.get();
523 : }
524 :
525 : int GetOverviewCount() override;
526 : GDALRasterBand *GetOverview(int iOvr) override;
527 :
528 : char **GetMetadataDomainList() override;
529 : const char *GetMetadataItem(const char *pszName,
530 : const char *pszDomain) override;
531 : CPLErr SetMetadataItem(const char *pszName, const char *pszValue,
532 : const char *pszDomain) override;
533 : CPLErr SetMetadata(char **papszMD, const char *pszDomain) override;
534 :
535 : private:
536 : friend class GDALTileIndexDataset;
537 :
538 : //! Dataset that owns this band.
539 : GDALTileIndexDataset *m_poDS = nullptr;
540 :
541 : //! Whether a nodata value is set to this band.
542 : bool m_bNoDataValueSet = false;
543 :
544 : //! Nodata value.
545 : double m_dfNoDataValue = 0;
546 :
547 : //! Color interpretation.
548 : GDALColorInterp m_eColorInterp = GCI_Undefined;
549 :
550 : //! Cached value for GetMetadataItem("Pixel_X_Y", "LocationInfo").
551 : std::string m_osLastLocationInfo{};
552 :
553 : //! Scale value (returned by GetScale())
554 : double m_dfScale = std::numeric_limits<double>::quiet_NaN();
555 :
556 : //! Offset value (returned by GetOffset())
557 : double m_dfOffset = std::numeric_limits<double>::quiet_NaN();
558 :
559 : //! Unit type (returned by GetUnitType()).
560 : std::string m_osUnit{};
561 :
562 : //! Category names (returned by GetCategoryNames()).
563 : CPLStringList m_aosCategoryNames{};
564 :
565 : //! Color table (returned by GetColorTable()).
566 : std::unique_ptr<GDALColorTable> m_poColorTable{};
567 :
568 : //! Raster attribute table (returned by GetDefaultRAT()).
569 : std::unique_ptr<GDALRasterAttributeTable> m_poRAT{};
570 :
571 : CPL_DISALLOW_COPY_ASSIGN(GDALTileIndexBand)
572 : };
573 :
574 : /************************************************************************/
575 : /* IsSameNaNAware() */
576 : /************************************************************************/
577 :
578 292 : static inline bool IsSameNaNAware(double a, double b)
579 : {
580 292 : return a == b || (std::isnan(a) && std::isnan(b));
581 : }
582 :
583 : /************************************************************************/
584 : /* GDALTileIndexDataset() */
585 : /************************************************************************/
586 :
587 277 : GDALTileIndexDataset::GDALTileIndexDataset()
588 277 : : m_osUniqueHandle(CPLSPrintf("%p", this))
589 : {
590 277 : }
591 :
592 : /************************************************************************/
593 : /* GetAbsoluteFileName() */
594 : /************************************************************************/
595 :
596 594 : static std::string GetAbsoluteFileName(const char *pszTileName,
597 : const char *pszVRTName)
598 : {
599 1782 : std::string osRet = VSIURIToVSIPath(pszTileName);
600 594 : if (osRet != pszTileName)
601 5 : return osRet;
602 :
603 589 : if (CPLIsFilenameRelative(pszTileName) &&
604 598 : !STARTS_WITH(pszTileName, "<VRTDataset") &&
605 9 : !STARTS_WITH(pszVRTName, "<GDALTileIndexDataset"))
606 : {
607 9 : const auto oSubDSInfo(GDALGetSubdatasetInfo(pszTileName));
608 9 : if (oSubDSInfo && !oSubDSInfo->GetPathComponent().empty())
609 : {
610 4 : const std::string osPath(oSubDSInfo->GetPathComponent());
611 2 : osRet = CPLIsFilenameRelative(osPath.c_str())
612 5 : ? oSubDSInfo->ModifyPathComponent(
613 4 : CPLProjectRelativeFilenameSafe(
614 3 : CPLGetPathSafe(pszVRTName).c_str(),
615 : osPath.c_str()))
616 2 : : std::string(pszTileName);
617 2 : GDALDestroySubdatasetInfo(oSubDSInfo);
618 2 : return osRet;
619 : }
620 :
621 : std::string osRelativeMadeAbsolute = CPLProjectRelativeFilenameSafe(
622 7 : CPLGetPathSafe(pszVRTName).c_str(), pszTileName);
623 : VSIStatBufL sStat;
624 7 : if (VSIStatL(osRelativeMadeAbsolute.c_str(), &sStat) == 0)
625 7 : return osRelativeMadeAbsolute;
626 : }
627 580 : return pszTileName;
628 : }
629 :
630 : /************************************************************************/
631 : /* GTIDoPaletteExpansionIfNeeded() */
632 : /************************************************************************/
633 :
634 : //! Do palette -> RGB(A) expansion
635 : static bool
636 460 : GTIDoPaletteExpansionIfNeeded(std::shared_ptr<GDALDataset> &poTileDS,
637 : int nBandCount)
638 : {
639 732 : if (poTileDS->GetRasterCount() == 1 &&
640 734 : (nBandCount == 3 || nBandCount == 4) &&
641 4 : poTileDS->GetRasterBand(1)->GetColorTable() != nullptr)
642 : {
643 :
644 4 : CPLStringList aosOptions;
645 4 : aosOptions.AddString("-of");
646 4 : aosOptions.AddString("VRT");
647 :
648 4 : aosOptions.AddString("-expand");
649 4 : aosOptions.AddString(nBandCount == 3 ? "rgb" : "rgba");
650 :
651 : GDALTranslateOptions *psOptions =
652 4 : GDALTranslateOptionsNew(aosOptions.List(), nullptr);
653 4 : int bUsageError = false;
654 : auto poRGBDS = std::unique_ptr<GDALDataset>(GDALDataset::FromHandle(
655 : GDALTranslate("", GDALDataset::ToHandle(poTileDS.get()), psOptions,
656 4 : &bUsageError)));
657 4 : GDALTranslateOptionsFree(psOptions);
658 4 : if (!poRGBDS)
659 : {
660 0 : return false;
661 : }
662 :
663 4 : poTileDS.reset(poRGBDS.release());
664 : }
665 460 : return true;
666 : }
667 :
668 : /************************************************************************/
669 : /* Open() */
670 : /************************************************************************/
671 :
672 277 : bool GDALTileIndexDataset::Open(GDALOpenInfo *poOpenInfo)
673 : {
674 277 : eAccess = poOpenInfo->eAccess;
675 :
676 277 : CPLXMLNode *psRoot = nullptr;
677 277 : const char *pszIndexDataset = poOpenInfo->pszFilename;
678 :
679 277 : if (STARTS_WITH(poOpenInfo->pszFilename, GTI_PREFIX))
680 : {
681 11 : pszIndexDataset = poOpenInfo->pszFilename + strlen(GTI_PREFIX);
682 : }
683 266 : else if (STARTS_WITH(poOpenInfo->pszFilename, "<GDALTileIndexDataset"))
684 : {
685 : // CPLParseXMLString() emits an error in case of failure
686 25 : m_psXMLTree.reset(CPLParseXMLString(poOpenInfo->pszFilename));
687 25 : if (m_psXMLTree == nullptr)
688 1 : return false;
689 : }
690 241 : else if (poOpenInfo->nHeaderBytes > 0 &&
691 241 : strstr(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
692 : "<GDALTileIndexDataset"))
693 : {
694 : // CPLParseXMLFile() emits an error in case of failure
695 6 : m_psXMLTree.reset(CPLParseXMLFile(poOpenInfo->pszFilename));
696 6 : if (m_psXMLTree == nullptr)
697 1 : return false;
698 5 : m_bXMLUpdatable = (poOpenInfo->eAccess == GA_Update);
699 : }
700 :
701 275 : if (m_psXMLTree)
702 : {
703 29 : psRoot = CPLGetXMLNode(m_psXMLTree.get(), "=GDALTileIndexDataset");
704 29 : if (psRoot == nullptr)
705 : {
706 1 : CPLError(CE_Failure, CPLE_AppDefined,
707 : "Missing GDALTileIndexDataset root element.");
708 1 : return false;
709 : }
710 :
711 28 : pszIndexDataset = CPLGetXMLValue(psRoot, "IndexDataset", nullptr);
712 28 : if (!pszIndexDataset)
713 : {
714 1 : CPLError(CE_Failure, CPLE_AppDefined,
715 : "Missing IndexDataset element.");
716 1 : return false;
717 : }
718 : }
719 :
720 273 : if (ENDS_WITH_CI(pszIndexDataset, ".gti.gpkg") &&
721 511 : poOpenInfo->nHeaderBytes >= 100 &&
722 238 : STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
723 : "SQLite format 3"))
724 : {
725 234 : const char *const apszAllowedDrivers[] = {"GPKG", nullptr};
726 234 : m_poVectorDS.reset(GDALDataset::Open(
727 468 : std::string("GPKG:\"").append(pszIndexDataset).append("\"").c_str(),
728 234 : GDAL_OF_VECTOR | GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR |
729 234 : ((poOpenInfo->nOpenFlags & GDAL_OF_UPDATE) ? GDAL_OF_UPDATE
730 : : GDAL_OF_READONLY),
731 : apszAllowedDrivers));
732 234 : if (!m_poVectorDS)
733 : {
734 1 : return false;
735 : }
736 236 : if (m_poVectorDS->GetLayerCount() == 0 &&
737 2 : (m_poVectorDS->GetRasterCount() != 0 ||
738 1 : m_poVectorDS->GetMetadata("SUBDATASETS") != nullptr))
739 : {
740 1 : return false;
741 : }
742 : }
743 : else
744 : {
745 39 : m_poVectorDS.reset(GDALDataset::Open(
746 39 : pszIndexDataset, GDAL_OF_VECTOR | GDAL_OF_VERBOSE_ERROR |
747 39 : ((poOpenInfo->nOpenFlags & GDAL_OF_UPDATE)
748 39 : ? GDAL_OF_UPDATE
749 : : GDAL_OF_READONLY)));
750 39 : if (!m_poVectorDS)
751 : {
752 1 : return false;
753 : }
754 : }
755 :
756 271 : if (m_poVectorDS->GetLayerCount() == 0)
757 : {
758 1 : CPLError(CE_Failure, CPLE_AppDefined, "%s has no vector layer",
759 : poOpenInfo->pszFilename);
760 1 : return false;
761 : }
762 :
763 270 : double dfOvrFactor = 1.0;
764 270 : if (const char *pszFactor =
765 270 : CSLFetchNameValue(poOpenInfo->papszOpenOptions, "FACTOR"))
766 : {
767 5 : dfOvrFactor = CPLAtof(pszFactor);
768 5 : if (!(dfOvrFactor > 1.0))
769 : {
770 1 : CPLError(CE_Failure, CPLE_AppDefined, "Wrong overview factor");
771 1 : return false;
772 : }
773 : }
774 :
775 269 : m_osSQL = CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "SQL", "");
776 269 : if (m_osSQL.empty())
777 : {
778 266 : if (!psRoot)
779 : {
780 240 : if (const char *pszVal =
781 240 : m_poVectorDS->GetMetadataItem(MD_DS_TILE_INDEX_SQL))
782 0 : m_osSQL = pszVal;
783 : }
784 : else
785 26 : m_osSQL = CPLGetXMLValue(psRoot, "SQL", "");
786 : }
787 :
788 269 : if (!m_osSQL.empty())
789 : {
790 5 : m_osSpatialSQL = CSLFetchNameValueDef(poOpenInfo->papszOpenOptions,
791 5 : "SPATIAL_SQL", "");
792 5 : if (m_osSpatialSQL.empty())
793 : {
794 3 : if (!psRoot)
795 : {
796 2 : if (const char *pszVal = m_poVectorDS->GetMetadataItem(
797 1 : MD_DS_TILE_INDEX_SPATIAL_SQL))
798 0 : m_osSpatialSQL = pszVal;
799 : }
800 : else
801 2 : m_osSpatialSQL = CPLGetXMLValue(psRoot, "SpatialSQL", "");
802 : }
803 : }
804 :
805 : const char *pszLayerName;
806 :
807 269 : if ((pszLayerName = CSLFetchNameValue(poOpenInfo->papszOpenOptions,
808 269 : "LAYER")) != nullptr)
809 : {
810 6 : m_poLayer = m_poVectorDS->GetLayerByName(pszLayerName);
811 6 : if (!m_poLayer)
812 : {
813 2 : CPLError(CE_Failure, CPLE_AppDefined, "Layer %s does not exist",
814 : pszLayerName);
815 2 : return false;
816 : }
817 : }
818 263 : else if (psRoot && (pszLayerName = CPLGetXMLValue(psRoot, "IndexLayer",
819 : nullptr)) != nullptr)
820 : {
821 8 : m_poLayer = m_poVectorDS->GetLayerByName(pszLayerName);
822 8 : if (!m_poLayer)
823 : {
824 1 : CPLError(CE_Failure, CPLE_AppDefined, "Layer %s does not exist",
825 : pszLayerName);
826 1 : return false;
827 : }
828 : }
829 496 : else if (!psRoot && (pszLayerName = m_poVectorDS->GetMetadataItem(
830 241 : MD_DS_TILE_INDEX_LAYER)) != nullptr)
831 : {
832 2 : m_poLayer = m_poVectorDS->GetLayerByName(pszLayerName);
833 2 : if (!m_poLayer)
834 : {
835 1 : CPLError(CE_Failure, CPLE_AppDefined, "Layer %s does not exist",
836 : pszLayerName);
837 1 : return false;
838 : }
839 : }
840 253 : else if (!m_osSQL.empty())
841 : {
842 5 : m_poLayer = m_poVectorDS->ExecuteSQL(m_osSQL.c_str(), nullptr, nullptr);
843 5 : if (!m_poLayer)
844 : {
845 1 : CPLError(CE_Failure, CPLE_AppDefined, "SQL request %s failed",
846 : m_osSQL.c_str());
847 1 : return false;
848 : }
849 4 : m_bIsSQLResultLayer = true;
850 : }
851 248 : else if (m_poVectorDS->GetLayerCount() == 1)
852 : {
853 246 : m_poLayer = m_poVectorDS->GetLayer(0);
854 246 : if (!m_poLayer)
855 : {
856 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot open layer 0");
857 0 : return false;
858 : }
859 : }
860 : else
861 : {
862 2 : if (STARTS_WITH(poOpenInfo->pszFilename, GTI_PREFIX))
863 : {
864 1 : CPLError(CE_Failure, CPLE_AppDefined,
865 : "%s has more than one layer. LAYER open option "
866 : "must be defined to specify which one to "
867 : "use as the tile index",
868 : pszIndexDataset);
869 : }
870 1 : else if (psRoot)
871 : {
872 0 : CPLError(CE_Failure, CPLE_AppDefined,
873 : "%s has more than one layer. IndexLayer element must be "
874 : "defined to specify which one to "
875 : "use as the tile index",
876 : pszIndexDataset);
877 : }
878 : else
879 : {
880 1 : CPLError(CE_Failure, CPLE_AppDefined,
881 : "%s has more than one layer. %s "
882 : "metadata item must be defined to specify which one to "
883 : "use as the tile index",
884 : pszIndexDataset, MD_DS_TILE_INDEX_LAYER);
885 : }
886 2 : return false;
887 : }
888 :
889 : // Try to get the metadata from an embedded xml:GTI domain
890 262 : if (!m_psXMLTree)
891 : {
892 238 : char **papszMD = m_poLayer->GetMetadata("xml:GTI");
893 238 : if (papszMD && papszMD[0])
894 : {
895 1 : m_psXMLTree.reset(CPLParseXMLString(papszMD[0]));
896 1 : if (m_psXMLTree == nullptr)
897 0 : return false;
898 :
899 1 : psRoot = CPLGetXMLNode(m_psXMLTree.get(), "=GDALTileIndexDataset");
900 1 : if (psRoot == nullptr)
901 : {
902 0 : CPLError(CE_Failure, CPLE_AppDefined,
903 : "Missing GDALTileIndexDataset root element.");
904 0 : return false;
905 : }
906 : }
907 : }
908 :
909 : // Get the value of an option.
910 : // The order of lookup is the following one (first to last):
911 : // - open options
912 : // - XML file
913 : // - Layer metadata items.
914 23772 : const auto GetOption = [poOpenInfo, psRoot, this](const char *pszItem)
915 : {
916 : const char *pszVal =
917 7567 : CSLFetchNameValue(poOpenInfo->papszOpenOptions, pszItem);
918 7567 : if (pszVal)
919 10 : return pszVal;
920 :
921 7557 : if (psRoot)
922 : {
923 576 : pszVal = CPLGetXMLValue(psRoot, pszItem, nullptr);
924 576 : if (pszVal)
925 27 : return pszVal;
926 :
927 549 : if (EQUAL(pszItem, MD_BAND_COUNT))
928 22 : pszItem = GTI_XML_BANDCOUNT;
929 527 : else if (EQUAL(pszItem, MD_DATA_TYPE))
930 25 : pszItem = GTI_XML_DATATYPE;
931 502 : else if (EQUAL(pszItem, MD_NODATA))
932 20 : pszItem = GTI_XML_NODATAVALUE;
933 482 : else if (EQUAL(pszItem, MD_COLOR_INTERPRETATION))
934 25 : pszItem = GTI_XML_COLORINTERP;
935 457 : else if (EQUAL(pszItem, MD_LOCATION_FIELD))
936 25 : pszItem = GTI_XML_LOCATIONFIELD;
937 432 : else if (EQUAL(pszItem, MD_SORT_FIELD))
938 25 : pszItem = GTI_XML_SORTFIELD;
939 407 : else if (EQUAL(pszItem, MD_SORT_FIELD_ASC))
940 2 : pszItem = GTI_XML_SORTFIELDASC;
941 405 : else if (EQUAL(pszItem, MD_MASK_BAND))
942 20 : pszItem = GTI_XML_MASKBAND;
943 549 : pszVal = CPLGetXMLValue(psRoot, pszItem, nullptr);
944 549 : if (pszVal)
945 7 : return pszVal;
946 : }
947 :
948 7523 : return m_poLayer->GetMetadataItem(pszItem);
949 262 : };
950 :
951 262 : const char *pszFilter = GetOption("Filter");
952 262 : if (pszFilter)
953 : {
954 1 : if (m_poLayer->SetAttributeFilter(pszFilter) != OGRERR_NONE)
955 0 : return false;
956 : }
957 :
958 262 : const OGRFeatureDefn *poLayerDefn = m_poLayer->GetLayerDefn();
959 :
960 524 : std::string osLocationFieldName;
961 : {
962 262 : const char *pszLocationFieldName = GetOption(MD_LOCATION_FIELD);
963 262 : if (pszLocationFieldName)
964 : {
965 4 : osLocationFieldName = pszLocationFieldName;
966 : }
967 : else
968 : {
969 : // Is this a https://stac-utils.github.io/stac-geoparquet/latest/spec/stac-geoparquet-spec ?
970 258 : if (poLayerDefn->GetFieldIndex("assets.data.href") >= 0)
971 : {
972 0 : osLocationFieldName = "assets.data.href";
973 0 : CPLDebug("GTI", "Using %s as location field",
974 : osLocationFieldName.c_str());
975 : }
976 258 : else if (poLayerDefn->GetFieldIndex("assets.image.href") >= 0)
977 : {
978 1 : osLocationFieldName = "assets.image.href";
979 1 : CPLDebug("GTI", "Using %s as location field",
980 : osLocationFieldName.c_str());
981 : }
982 510 : else if (poLayerDefn->GetFieldIndex("stac_version") >= 0 ||
983 253 : poLayerDefn->GetFieldIndex("stac_extensions") >= 0)
984 : {
985 4 : const int nFieldCount = poLayerDefn->GetFieldCount();
986 : // Look for "assets.xxxxx.href" fields
987 4 : int nAssetCount = 0;
988 60 : for (int i = 0; i < nFieldCount; ++i)
989 : {
990 56 : const auto poFDefn = poLayerDefn->GetFieldDefn(i);
991 56 : const char *pszFieldName = poFDefn->GetNameRef();
992 56 : if (STARTS_WITH(pszFieldName, "assets.") &&
993 44 : EQUAL(pszFieldName + strlen(pszFieldName) -
994 : strlen(".href"),
995 4 : ".href") &&
996 : // Assets with "metadata" in them are very much likely
997 : // not rasters... We could potentially confirm that by
998 : // inspecting the value of the assets.XXX.type or
999 : // assets.XXX.roles fields of one feature
1000 4 : !strstr(pszFieldName, "metadata"))
1001 : {
1002 4 : ++nAssetCount;
1003 4 : if (!osLocationFieldName.empty())
1004 : {
1005 0 : osLocationFieldName += ", ";
1006 : }
1007 4 : osLocationFieldName += pszFieldName;
1008 : }
1009 : }
1010 4 : if (nAssetCount > 1)
1011 : {
1012 0 : CPLError(CE_Failure, CPLE_AppDefined,
1013 : "Several potential STAC assets. Please select one "
1014 : "among %s with the LOCATION_FIELD open option",
1015 : osLocationFieldName.c_str());
1016 0 : return false;
1017 : }
1018 4 : else if (nAssetCount == 0)
1019 : {
1020 0 : CPLError(CE_Failure, CPLE_AppDefined,
1021 : "File has stac_version or stac_extensions "
1022 : "property but lacks assets");
1023 0 : return false;
1024 : }
1025 : }
1026 : else
1027 : {
1028 253 : constexpr const char *DEFAULT_LOCATION_FIELD_NAME = "location";
1029 253 : osLocationFieldName = DEFAULT_LOCATION_FIELD_NAME;
1030 : }
1031 : }
1032 : }
1033 :
1034 262 : m_nLocationFieldIndex =
1035 262 : poLayerDefn->GetFieldIndex(osLocationFieldName.c_str());
1036 262 : if (m_nLocationFieldIndex < 0)
1037 : {
1038 1 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find field %s",
1039 : osLocationFieldName.c_str());
1040 1 : return false;
1041 : }
1042 261 : if (poLayerDefn->GetFieldDefn(m_nLocationFieldIndex)->GetType() !=
1043 : OFTString)
1044 : {
1045 1 : CPLError(CE_Failure, CPLE_AppDefined, "Field %s is not of type string",
1046 : osLocationFieldName.c_str());
1047 1 : return false;
1048 : }
1049 :
1050 260 : const char *pszSortFieldName = GetOption(MD_SORT_FIELD);
1051 260 : if (pszSortFieldName)
1052 : {
1053 96 : m_nSortFieldIndex = poLayerDefn->GetFieldIndex(pszSortFieldName);
1054 96 : if (m_nSortFieldIndex < 0)
1055 : {
1056 1 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot find field %s",
1057 : pszSortFieldName);
1058 1 : return false;
1059 : }
1060 :
1061 : const auto eFieldType =
1062 95 : poLayerDefn->GetFieldDefn(m_nSortFieldIndex)->GetType();
1063 95 : if (eFieldType != OFTString && eFieldType != OFTInteger &&
1064 61 : eFieldType != OFTInteger64 && eFieldType != OFTReal &&
1065 19 : eFieldType != OFTDate && eFieldType != OFTDateTime)
1066 : {
1067 1 : CPLError(CE_Failure, CPLE_AppDefined,
1068 : "Unsupported type for field %s", pszSortFieldName);
1069 1 : return false;
1070 : }
1071 :
1072 94 : const char *pszSortFieldAsc = GetOption(MD_SORT_FIELD_ASC);
1073 94 : if (pszSortFieldAsc)
1074 : {
1075 3 : m_bSortFieldAsc = CPLTestBool(pszSortFieldAsc);
1076 : }
1077 : }
1078 :
1079 258 : const char *pszResX = GetOption(MD_RESX);
1080 258 : const char *pszResY = GetOption(MD_RESY);
1081 258 : if (pszResX && !pszResY)
1082 : {
1083 1 : CPLError(CE_Failure, CPLE_AppDefined,
1084 : "%s metadata item defined, but not %s", MD_RESX, MD_RESY);
1085 1 : return false;
1086 : }
1087 257 : if (!pszResX && pszResY)
1088 : {
1089 1 : CPLError(CE_Failure, CPLE_AppDefined,
1090 : "%s metadata item defined, but not %s", MD_RESY, MD_RESX);
1091 1 : return false;
1092 : }
1093 :
1094 256 : const char *pszResampling = GetOption(MD_RESAMPLING);
1095 256 : if (pszResampling)
1096 : {
1097 8 : const auto nErrorCountBefore = CPLGetErrorCounter();
1098 8 : m_eResampling = GDALRasterIOGetResampleAlg(pszResampling);
1099 8 : if (nErrorCountBefore != CPLGetErrorCounter())
1100 : {
1101 0 : return false;
1102 : }
1103 8 : m_osResampling = pszResampling;
1104 : }
1105 :
1106 256 : const char *pszMinX = GetOption(MD_MINX);
1107 256 : const char *pszMinY = GetOption(MD_MINY);
1108 256 : const char *pszMaxX = GetOption(MD_MAXX);
1109 256 : const char *pszMaxY = GetOption(MD_MAXY);
1110 256 : int nCountMinMaxXY = (pszMinX ? 1 : 0) + (pszMinY ? 1 : 0) +
1111 256 : (pszMaxX ? 1 : 0) + (pszMaxY ? 1 : 0);
1112 256 : if (nCountMinMaxXY != 0 && nCountMinMaxXY != 4)
1113 : {
1114 4 : CPLError(CE_Failure, CPLE_AppDefined,
1115 : "None or all of %s, %s, %s and %s must be specified", MD_MINX,
1116 : MD_MINY, MD_MAXX, MD_MAXY);
1117 4 : return false;
1118 : }
1119 :
1120 252 : const char *pszXSize = GetOption(MD_XSIZE);
1121 252 : const char *pszYSize = GetOption(MD_YSIZE);
1122 252 : const char *pszGeoTransform = GetOption(MD_GEOTRANSFORM);
1123 252 : const int nCountXSizeYSizeGT =
1124 252 : (pszXSize ? 1 : 0) + (pszYSize ? 1 : 0) + (pszGeoTransform ? 1 : 0);
1125 252 : if (nCountXSizeYSizeGT != 0 && nCountXSizeYSizeGT != 3)
1126 : {
1127 3 : CPLError(CE_Failure, CPLE_AppDefined,
1128 : "None or all of %s, %s, %s must be specified", MD_XSIZE,
1129 : MD_YSIZE, MD_GEOTRANSFORM);
1130 3 : return false;
1131 : }
1132 :
1133 249 : const char *pszDataType = GetOption(MD_DATA_TYPE);
1134 249 : const char *pszColorInterp = GetOption(MD_COLOR_INTERPRETATION);
1135 249 : int nBandCount = 0;
1136 498 : std::vector<GDALDataType> aeDataTypes;
1137 498 : std::vector<std::pair<bool, double>> aNoData;
1138 498 : std::vector<GDALColorInterp> aeColorInterp;
1139 :
1140 249 : const char *pszSRS = GetOption(MD_SRS);
1141 249 : m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
1142 249 : if (pszSRS)
1143 : {
1144 2 : if (m_oSRS.SetFromUserInput(
1145 : pszSRS,
1146 2 : OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get()) !=
1147 : OGRERR_NONE)
1148 : {
1149 1 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid %s", MD_SRS);
1150 1 : return false;
1151 : }
1152 : }
1153 247 : else if (const auto poSRS = m_poLayer->GetSpatialRef())
1154 : {
1155 : // Ignore GPKG "Undefined geographic SRS" and "Undefined Cartesian SRS"
1156 124 : if (!STARTS_WITH(poSRS->GetName(), "Undefined "))
1157 124 : m_oSRS = *poSRS;
1158 : }
1159 :
1160 496 : std::vector<const CPLXMLNode *> apoXMLNodeBands;
1161 248 : if (psRoot)
1162 : {
1163 25 : int nExpectedBandNumber = 1;
1164 113 : for (const CPLXMLNode *psIter = psRoot->psChild; psIter;
1165 88 : psIter = psIter->psNext)
1166 : {
1167 91 : if (psIter->eType == CXT_Element &&
1168 91 : strcmp(psIter->pszValue, GTI_XML_BAND_ELEMENT) == 0)
1169 : {
1170 : const char *pszBand =
1171 8 : CPLGetXMLValue(psIter, GTI_XML_BAND_NUMBER, nullptr);
1172 8 : if (!pszBand)
1173 : {
1174 1 : CPLError(CE_Failure, CPLE_AppDefined,
1175 : "%s attribute missing on %s element",
1176 : GTI_XML_BAND_NUMBER, GTI_XML_BAND_ELEMENT);
1177 3 : return false;
1178 : }
1179 7 : const int nBand = atoi(pszBand);
1180 7 : if (nBand <= 0)
1181 : {
1182 1 : CPLError(CE_Failure, CPLE_AppDefined,
1183 : "Invalid band number");
1184 1 : return false;
1185 : }
1186 6 : if (nBand != nExpectedBandNumber)
1187 : {
1188 1 : CPLError(CE_Failure, CPLE_AppDefined,
1189 : "Invalid band number: found %d, expected %d",
1190 : nBand, nExpectedBandNumber);
1191 1 : return false;
1192 : }
1193 5 : apoXMLNodeBands.push_back(psIter);
1194 5 : ++nExpectedBandNumber;
1195 : }
1196 : }
1197 : }
1198 :
1199 245 : const char *pszBandCount = GetOption(MD_BAND_COUNT);
1200 245 : if (pszBandCount)
1201 22 : nBandCount = atoi(pszBandCount);
1202 :
1203 245 : if (!apoXMLNodeBands.empty())
1204 : {
1205 5 : if (!pszBandCount)
1206 4 : nBandCount = static_cast<int>(apoXMLNodeBands.size());
1207 1 : else if (nBandCount != static_cast<int>(apoXMLNodeBands.size()))
1208 : {
1209 1 : CPLError(CE_Failure, CPLE_AppDefined,
1210 : "Inconsistent %s with actual number of %s elements",
1211 : GTI_XML_BANDCOUNT, GTI_XML_BAND_ELEMENT);
1212 1 : return false;
1213 : }
1214 : }
1215 :
1216 : // Take into STAC GeoParquet proj:code / proj:epsg / proj:wkt2 / proj:projjson
1217 : // and proj:transform fields
1218 244 : std::unique_ptr<OGRFeature> poFeature;
1219 488 : std::string osResX, osResY, osMinX, osMinY, osMaxX, osMaxY;
1220 244 : int iProjCode = -1;
1221 244 : int iProjEPSG = -1;
1222 244 : int iProjWKT2 = -1;
1223 244 : int iProjPROJSON = -1;
1224 244 : int iProjTransform = -1;
1225 :
1226 : const bool bIsStacGeoParquet =
1227 249 : STARTS_WITH(osLocationFieldName.c_str(), "assets.") &&
1228 5 : EQUAL(osLocationFieldName.c_str() + osLocationFieldName.size() -
1229 : strlen(".href"),
1230 : ".href");
1231 488 : std::string osAssetName;
1232 244 : if (bIsStacGeoParquet)
1233 : {
1234 10 : osAssetName = osLocationFieldName.substr(
1235 : strlen("assets."),
1236 10 : osLocationFieldName.size() - strlen("assets.") - strlen(".href"));
1237 : }
1238 :
1239 : const auto GetAssetFieldIndex =
1240 30 : [poLayerDefn, &osAssetName](const char *pszFieldName)
1241 : {
1242 17 : const int idx = poLayerDefn->GetFieldIndex(
1243 17 : CPLSPrintf("assets.%s.%s", osAssetName.c_str(), pszFieldName));
1244 17 : if (idx >= 0)
1245 4 : return idx;
1246 13 : return poLayerDefn->GetFieldIndex(pszFieldName);
1247 244 : };
1248 :
1249 5 : if (bIsStacGeoParquet && !pszSRS && !pszResX && !pszResY && !pszMinX &&
1250 5 : !pszMinY && !pszMaxX && !pszMaxY &&
1251 5 : ((iProjCode = GetAssetFieldIndex("proj:code")) >= 0 ||
1252 4 : (iProjEPSG = GetAssetFieldIndex("proj:epsg")) >= 0 ||
1253 2 : (iProjWKT2 = GetAssetFieldIndex("proj:wkt2")) >= 0 ||
1254 250 : (iProjPROJSON = GetAssetFieldIndex("proj:projjson")) >= 0) &&
1255 5 : ((iProjTransform = GetAssetFieldIndex("proj:transform")) >= 0))
1256 : {
1257 5 : poFeature.reset(m_poLayer->GetNextFeature());
1258 : const auto poProjTransformField =
1259 5 : poLayerDefn->GetFieldDefn(iProjTransform);
1260 5 : if (poFeature &&
1261 5 : ((iProjCode >= 0 && poFeature->IsFieldSet(iProjCode)) ||
1262 4 : (iProjEPSG >= 0 && poFeature->IsFieldSet(iProjEPSG)) ||
1263 2 : (iProjWKT2 >= 0 && poFeature->IsFieldSet(iProjWKT2)) ||
1264 6 : (iProjPROJSON >= 0 && poFeature->IsFieldSet(iProjPROJSON))) &&
1265 19 : poFeature->IsFieldSet(iProjTransform) &&
1266 9 : (poProjTransformField->GetType() == OFTRealList ||
1267 4 : poProjTransformField->GetType() == OFTIntegerList ||
1268 0 : poProjTransformField->GetType() == OFTInteger64List))
1269 : {
1270 10 : OGRSpatialReference oSTACSRS;
1271 5 : oSTACSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
1272 :
1273 5 : if (iProjCode >= 0 && poFeature->IsFieldSet(iProjCode))
1274 1 : oSTACSRS.SetFromUserInput(
1275 : poFeature->GetFieldAsString(iProjCode),
1276 : OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get());
1277 :
1278 4 : else if (iProjEPSG >= 0 && poFeature->IsFieldSet(iProjEPSG))
1279 2 : oSTACSRS.importFromEPSG(
1280 : poFeature->GetFieldAsInteger(iProjEPSG));
1281 :
1282 2 : else if (iProjWKT2 >= 0 && poFeature->IsFieldSet(iProjWKT2))
1283 1 : oSTACSRS.SetFromUserInput(
1284 : poFeature->GetFieldAsString(iProjWKT2),
1285 : OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get());
1286 :
1287 1 : else if (iProjPROJSON >= 0 && poFeature->IsFieldSet(iProjPROJSON))
1288 1 : oSTACSRS.SetFromUserInput(
1289 : poFeature->GetFieldAsString(iProjPROJSON),
1290 : OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get());
1291 :
1292 5 : if (!oSTACSRS.IsEmpty())
1293 : {
1294 5 : int nTransformCount = 0;
1295 : // Note: different coefficient ordering than GDAL geotransform
1296 5 : double adfProjTransform[6] = {0, 0, 0, 0, 0, 0};
1297 5 : if (poProjTransformField->GetType() == OFTRealList)
1298 : {
1299 : const auto padfFeatureTransform =
1300 1 : poFeature->GetFieldAsDoubleList(iProjTransform,
1301 : &nTransformCount);
1302 1 : if (nTransformCount >= 6)
1303 1 : memcpy(adfProjTransform, padfFeatureTransform,
1304 : 6 * sizeof(double));
1305 : }
1306 4 : else if (poProjTransformField->GetType() == OFTInteger64List)
1307 : {
1308 : const auto paFeatureTransform =
1309 0 : poFeature->GetFieldAsInteger64List(iProjTransform,
1310 : &nTransformCount);
1311 0 : if (nTransformCount >= 6)
1312 : {
1313 0 : for (int i = 0; i < 6; ++i)
1314 0 : adfProjTransform[i] =
1315 0 : static_cast<double>(paFeatureTransform[i]);
1316 : }
1317 : }
1318 4 : else if (poProjTransformField->GetType() == OFTIntegerList)
1319 : {
1320 : const auto paFeatureTransform =
1321 4 : poFeature->GetFieldAsIntegerList(iProjTransform,
1322 : &nTransformCount);
1323 4 : if (nTransformCount >= 6)
1324 : {
1325 28 : for (int i = 0; i < 6; ++i)
1326 24 : adfProjTransform[i] = paFeatureTransform[i];
1327 : }
1328 : }
1329 5 : OGREnvelope sEnvelope;
1330 10 : if (nTransformCount >= 6 && m_poLayer->GetSpatialRef() &&
1331 5 : m_poLayer->GetExtent(&sEnvelope, /* bForce = */ true) ==
1332 : OGRERR_NONE)
1333 : {
1334 5 : const double dfResX = adfProjTransform[0];
1335 5 : osResX = CPLSPrintf("%.17g", dfResX);
1336 5 : const double dfResY = std::fabs(adfProjTransform[4]);
1337 5 : osResY = CPLSPrintf("%.17g", dfResY);
1338 :
1339 : auto poCT = std::unique_ptr<OGRCoordinateTransformation>(
1340 : OGRCreateCoordinateTransformation(
1341 10 : m_poLayer->GetSpatialRef(), &oSTACSRS));
1342 : auto poInvCT = std::unique_ptr<OGRCoordinateTransformation>(
1343 10 : poCT ? poCT->GetInverse() : nullptr);
1344 5 : double dfOutMinX = 0;
1345 5 : double dfOutMinY = 0;
1346 5 : double dfOutMaxX = 0;
1347 5 : double dfOutMaxY = 0;
1348 10 : if (dfResX > 0 && dfResY > 0 && poCT && poInvCT &&
1349 10 : poCT->TransformBounds(sEnvelope.MinX, sEnvelope.MinY,
1350 : sEnvelope.MaxX, sEnvelope.MaxY,
1351 : &dfOutMinX, &dfOutMinY,
1352 5 : &dfOutMaxX, &dfOutMaxY, 21))
1353 : {
1354 5 : constexpr double EPSILON = 1e-3;
1355 : const bool bTileAlignedOnRes =
1356 5 : (fmod(std::fabs(adfProjTransform[3]), dfResX) <=
1357 10 : EPSILON * dfResX &&
1358 5 : fmod(std::fabs(adfProjTransform[5]), dfResY) <=
1359 5 : EPSILON * dfResY);
1360 :
1361 : osMinX = CPLSPrintf(
1362 : "%.17g",
1363 : !bTileAlignedOnRes
1364 : ? dfOutMinX
1365 5 : : std::floor(dfOutMinX / dfResX) * dfResX);
1366 : osMinY = CPLSPrintf(
1367 : "%.17g",
1368 : !bTileAlignedOnRes
1369 : ? dfOutMinY
1370 5 : : std::floor(dfOutMinY / dfResY) * dfResY);
1371 : osMaxX = CPLSPrintf(
1372 : "%.17g",
1373 : !bTileAlignedOnRes
1374 : ? dfOutMaxX
1375 5 : : std::ceil(dfOutMaxX / dfResX) * dfResX);
1376 : osMaxY = CPLSPrintf(
1377 : "%.17g",
1378 : !bTileAlignedOnRes
1379 : ? dfOutMaxY
1380 5 : : std::ceil(dfOutMaxY / dfResY) * dfResY);
1381 :
1382 5 : m_oSRS = std::move(oSTACSRS);
1383 5 : pszResX = osResX.c_str();
1384 5 : pszResY = osResY.c_str();
1385 5 : pszMinX = osMinX.c_str();
1386 5 : pszMinY = osMinY.c_str();
1387 5 : pszMaxX = osMaxX.c_str();
1388 5 : pszMaxY = osMaxY.c_str();
1389 5 : nCountMinMaxXY = 4;
1390 :
1391 5 : poFeature.reset();
1392 5 : m_poLayer->ResetReading();
1393 :
1394 : m_poWarpedLayerKeeper =
1395 5 : std::make_unique<OGRWarpedLayer>(
1396 0 : m_poLayer, /* iGeomField = */ 0,
1397 5 : /* bTakeOwnership = */ false, poCT.release(),
1398 10 : poInvCT.release());
1399 5 : m_poLayer = m_poWarpedLayerKeeper.get();
1400 5 : poLayerDefn = m_poLayer->GetLayerDefn();
1401 : }
1402 : }
1403 : }
1404 : }
1405 : }
1406 :
1407 244 : OGREnvelope sEnvelope;
1408 244 : if (nCountMinMaxXY == 4)
1409 : {
1410 16 : sEnvelope.MinX = CPLAtof(pszMinX);
1411 16 : sEnvelope.MinY = CPLAtof(pszMinY);
1412 16 : sEnvelope.MaxX = CPLAtof(pszMaxX);
1413 16 : sEnvelope.MaxY = CPLAtof(pszMaxY);
1414 16 : if (!(sEnvelope.MaxX > sEnvelope.MinX))
1415 : {
1416 1 : CPLError(CE_Failure, CPLE_AppDefined,
1417 : "%s metadata item must be > %s", MD_MAXX, MD_MINX);
1418 1 : return false;
1419 : }
1420 15 : if (!(sEnvelope.MaxY > sEnvelope.MinY))
1421 : {
1422 1 : CPLError(CE_Failure, CPLE_AppDefined,
1423 : "%s metadata item must be > %s", MD_MAXY, MD_MINY);
1424 1 : return false;
1425 : }
1426 : }
1427 :
1428 242 : bool bHasMaskBand = false;
1429 242 : std::unique_ptr<GDALColorTable> poSingleColorTable;
1430 267 : if ((!pszBandCount && apoXMLNodeBands.empty()) ||
1431 25 : (!(pszResX && pszResY) && nCountXSizeYSizeGT == 0))
1432 : {
1433 231 : CPLDebug("GTI", "Inspecting one feature due to missing metadata items");
1434 231 : m_bScannedOneFeatureAtOpening = true;
1435 :
1436 231 : if (!poFeature)
1437 231 : poFeature.reset(m_poLayer->GetNextFeature());
1438 460 : if (!poFeature ||
1439 229 : !poFeature->IsFieldSetAndNotNull(m_nLocationFieldIndex))
1440 : {
1441 2 : CPLError(
1442 : CE_Failure, CPLE_AppDefined,
1443 : "BAND_COUNT(+DATA_TYPE+COLOR_INTERPRETATION)+ (RESX+RESY or "
1444 : "XSIZE+YSIZE+GEOTRANSFORM) metadata items "
1445 : "missing");
1446 10 : return false;
1447 : }
1448 :
1449 : const char *pszTileName =
1450 229 : poFeature->GetFieldAsString(m_nLocationFieldIndex);
1451 : const std::string osTileName(
1452 229 : GetAbsoluteFileName(pszTileName, poOpenInfo->pszFilename));
1453 229 : pszTileName = osTileName.c_str();
1454 :
1455 : auto poTileDS = std::shared_ptr<GDALDataset>(
1456 : GDALDataset::Open(pszTileName,
1457 : GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR),
1458 229 : GDALDatasetUniquePtrReleaser());
1459 229 : if (!poTileDS)
1460 : {
1461 1 : return false;
1462 : }
1463 :
1464 : // do palette -> RGB(A) expansion if needed
1465 228 : if (!GTIDoPaletteExpansionIfNeeded(poTileDS, nBandCount))
1466 0 : return false;
1467 :
1468 228 : const int nTileBandCount = poTileDS->GetRasterCount();
1469 518 : for (int i = 0; i < nTileBandCount; ++i)
1470 : {
1471 290 : auto poTileBand = poTileDS->GetRasterBand(i + 1);
1472 290 : aeDataTypes.push_back(poTileBand->GetRasterDataType());
1473 290 : int bHasNoData = FALSE;
1474 290 : const double dfNoData = poTileBand->GetNoDataValue(&bHasNoData);
1475 290 : aNoData.emplace_back(CPL_TO_BOOL(bHasNoData), dfNoData);
1476 290 : aeColorInterp.push_back(poTileBand->GetColorInterpretation());
1477 290 : if (nTileBandCount == 1)
1478 : {
1479 198 : if (auto poCT = poTileBand->GetColorTable())
1480 : {
1481 : // We assume that this will apply to all tiles...
1482 : // TODO: detect if that it is really the case, and warn
1483 : // if not, or do approximate palette matching like
1484 : // done in GDALRasterBand::GetIndexColorTranslationTo()
1485 0 : poSingleColorTable.reset(poCT->Clone());
1486 : }
1487 : }
1488 :
1489 290 : if (poTileBand->GetMaskFlags() == GMF_PER_DATASET)
1490 1 : bHasMaskBand = true;
1491 : }
1492 228 : if (!pszBandCount && nBandCount == 0)
1493 214 : nBandCount = nTileBandCount;
1494 :
1495 228 : auto poTileSRS = poTileDS->GetSpatialRef();
1496 228 : if (!m_oSRS.IsEmpty() && poTileSRS && !m_oSRS.IsSame(poTileSRS))
1497 : {
1498 7 : CPLStringList aosOptions;
1499 7 : aosOptions.AddString("-of");
1500 7 : aosOptions.AddString("VRT");
1501 :
1502 7 : char *pszWKT = nullptr;
1503 7 : const char *const apszWKTOptions[] = {"FORMAT=WKT2_2019", nullptr};
1504 7 : m_oSRS.exportToWkt(&pszWKT, apszWKTOptions);
1505 7 : if (pszWKT)
1506 7 : m_osWKT = pszWKT;
1507 7 : CPLFree(pszWKT);
1508 :
1509 7 : if (m_osWKT.empty())
1510 : {
1511 0 : CPLError(CE_Failure, CPLE_AppDefined,
1512 : "Cannot export VRT SRS to WKT2");
1513 0 : return false;
1514 : }
1515 :
1516 7 : aosOptions.AddString("-t_srs");
1517 7 : aosOptions.AddString(m_osWKT.c_str());
1518 :
1519 : GDALWarpAppOptions *psWarpOptions =
1520 7 : GDALWarpAppOptionsNew(aosOptions.List(), nullptr);
1521 7 : GDALDatasetH ahSrcDS[] = {GDALDataset::ToHandle(poTileDS.get())};
1522 7 : int bUsageError = false;
1523 : auto poWarpDS =
1524 : std::unique_ptr<GDALDataset>(GDALDataset::FromHandle(GDALWarp(
1525 7 : "", nullptr, 1, ahSrcDS, psWarpOptions, &bUsageError)));
1526 7 : GDALWarpAppOptionsFree(psWarpOptions);
1527 7 : if (!poWarpDS)
1528 : {
1529 0 : return false;
1530 : }
1531 :
1532 7 : poTileDS.reset(poWarpDS.release());
1533 7 : poTileSRS = poTileDS->GetSpatialRef();
1534 7 : CPL_IGNORE_RET_VAL(poTileSRS);
1535 : }
1536 :
1537 228 : GDALGeoTransform gtTile;
1538 228 : if (poTileDS->GetGeoTransform(gtTile) != CE_None)
1539 : {
1540 1 : CPLError(CE_Failure, CPLE_AppDefined,
1541 : "Cannot find geotransform on %s", pszTileName);
1542 1 : return false;
1543 : }
1544 227 : if (!(gtTile[GT_ROTATION_PARAM1] == 0))
1545 : {
1546 1 : CPLError(CE_Failure, CPLE_AppDefined,
1547 : "3rd value of GeoTransform of %s must be 0", pszTileName);
1548 1 : return false;
1549 : }
1550 226 : if (!(gtTile[GT_ROTATION_PARAM2] == 0))
1551 : {
1552 1 : CPLError(CE_Failure, CPLE_AppDefined,
1553 : "5th value of GeoTransform of %s must be 0", pszTileName);
1554 1 : return false;
1555 : }
1556 :
1557 225 : const double dfResX = gtTile[GT_WE_RES];
1558 225 : const double dfResY = gtTile[GT_NS_RES];
1559 225 : if (!(dfResX > 0))
1560 : {
1561 1 : CPLError(CE_Failure, CPLE_AppDefined,
1562 : "2nd value of GeoTransform of %s must be > 0",
1563 : pszTileName);
1564 1 : return false;
1565 : }
1566 224 : if (!(dfResY != 0))
1567 : {
1568 0 : CPLError(CE_Failure, CPLE_AppDefined,
1569 : "6th value of GeoTransform of %s must be != 0",
1570 : pszTileName);
1571 0 : return false;
1572 : }
1573 :
1574 437 : if (!sEnvelope.IsInit() &&
1575 213 : m_poLayer->GetExtent(&sEnvelope, /* bForce = */ false) ==
1576 : OGRERR_FAILURE)
1577 : {
1578 1 : if (m_poLayer->GetExtent(&sEnvelope, /* bForce = */ true) ==
1579 : OGRERR_FAILURE)
1580 : {
1581 1 : CPLError(CE_Failure, CPLE_AppDefined,
1582 : "Cannot get layer extent");
1583 1 : return false;
1584 : }
1585 0 : CPLError(CE_Warning, CPLE_AppDefined,
1586 : "Could get layer extent, but using a slower method");
1587 : }
1588 :
1589 223 : const double dfXSize = (sEnvelope.MaxX - sEnvelope.MinX) / dfResX;
1590 223 : if (!(dfXSize >= 0 && dfXSize < INT_MAX))
1591 : {
1592 1 : CPLError(CE_Failure, CPLE_AppDefined,
1593 : "Too small %s, or wrong layer extent", MD_RESX);
1594 1 : return false;
1595 : }
1596 :
1597 222 : const double dfYSize =
1598 222 : (sEnvelope.MaxY - sEnvelope.MinY) / std::fabs(dfResY);
1599 222 : if (!(dfYSize >= 0 && dfYSize < INT_MAX))
1600 : {
1601 1 : CPLError(CE_Failure, CPLE_AppDefined,
1602 : "Too small %s, or wrong layer extent", MD_RESY);
1603 1 : return false;
1604 : }
1605 :
1606 221 : m_gt[GT_TOPLEFT_X] = sEnvelope.MinX;
1607 221 : m_gt[GT_WE_RES] = dfResX;
1608 221 : m_gt[GT_ROTATION_PARAM1] = 0;
1609 221 : m_gt[GT_TOPLEFT_Y] = sEnvelope.MaxY;
1610 221 : m_gt[GT_ROTATION_PARAM2] = 0;
1611 221 : m_gt[GT_NS_RES] = -std::fabs(dfResY);
1612 :
1613 221 : nRasterXSize = static_cast<int>(std::ceil(dfXSize));
1614 221 : nRasterYSize = static_cast<int>(std::ceil(dfYSize));
1615 : }
1616 :
1617 232 : if (pszXSize && pszYSize && pszGeoTransform)
1618 : {
1619 12 : const int nXSize = atoi(pszXSize);
1620 12 : if (nXSize <= 0)
1621 : {
1622 1 : CPLError(CE_Failure, CPLE_AppDefined,
1623 : "%s metadata item must be > 0", MD_XSIZE);
1624 6 : return false;
1625 : }
1626 :
1627 11 : const int nYSize = atoi(pszYSize);
1628 11 : if (nYSize <= 0)
1629 : {
1630 1 : CPLError(CE_Failure, CPLE_AppDefined,
1631 : "%s metadata item must be > 0", MD_YSIZE);
1632 1 : return false;
1633 : }
1634 :
1635 : const CPLStringList aosTokens(
1636 10 : CSLTokenizeString2(pszGeoTransform, ",", 0));
1637 10 : if (aosTokens.size() != 6)
1638 : {
1639 1 : CPLError(CE_Failure, CPLE_AppDefined,
1640 : "%s metadata item must be 6 numeric values "
1641 : "separated with comma",
1642 : MD_GEOTRANSFORM);
1643 1 : return false;
1644 : }
1645 63 : for (int i = 0; i < 6; ++i)
1646 : {
1647 54 : m_gt[i] = CPLAtof(aosTokens[i]);
1648 : }
1649 9 : if (!(m_gt[GT_WE_RES] > 0))
1650 : {
1651 0 : CPLError(CE_Failure, CPLE_AppDefined, "2nd value of %s must be > 0",
1652 : MD_GEOTRANSFORM);
1653 0 : return false;
1654 : }
1655 9 : if (!(m_gt[GT_ROTATION_PARAM1] == 0))
1656 : {
1657 1 : CPLError(CE_Failure, CPLE_AppDefined, "3rd value of %s must be 0",
1658 : MD_GEOTRANSFORM);
1659 1 : return false;
1660 : }
1661 8 : if (!(m_gt[GT_ROTATION_PARAM2] == 0))
1662 : {
1663 1 : CPLError(CE_Failure, CPLE_AppDefined, "5th value of %s must be 0",
1664 : MD_GEOTRANSFORM);
1665 1 : return false;
1666 : }
1667 7 : if (!(m_gt[GT_NS_RES] < 0))
1668 : {
1669 1 : CPLError(CE_Failure, CPLE_AppDefined, "6th value of %s must be < 0",
1670 : MD_GEOTRANSFORM);
1671 1 : return false;
1672 : }
1673 6 : nRasterXSize = nXSize;
1674 12 : nRasterYSize = nYSize;
1675 : }
1676 220 : else if (pszResX && pszResY)
1677 : {
1678 19 : const double dfResX = CPLAtof(pszResX);
1679 19 : if (!(dfResX > 0))
1680 : {
1681 1 : CPLError(CE_Failure, CPLE_AppDefined,
1682 : "RESX metadata item must be > 0");
1683 1 : return false;
1684 : }
1685 18 : const double dfResY = CPLAtof(pszResY);
1686 18 : if (!(dfResY > 0))
1687 : {
1688 1 : CPLError(CE_Failure, CPLE_AppDefined,
1689 : "RESY metadata item must be > 0");
1690 1 : return false;
1691 : }
1692 :
1693 17 : if (nCountMinMaxXY == 4)
1694 : {
1695 10 : if (pszXSize || pszYSize || pszGeoTransform)
1696 : {
1697 0 : CPLError(CE_Warning, CPLE_AppDefined,
1698 : "Ignoring %s, %s and %s when %s, "
1699 : "%s, %s and %s are specified",
1700 : MD_XSIZE, MD_YSIZE, MD_GEOTRANSFORM, MD_MINX, MD_MINY,
1701 : MD_MAXX, MD_MAXY);
1702 : }
1703 : }
1704 9 : else if (!sEnvelope.IsInit() &&
1705 2 : m_poLayer->GetExtent(&sEnvelope, /* bForce = */ false) ==
1706 : OGRERR_FAILURE)
1707 : {
1708 0 : if (m_poLayer->GetExtent(&sEnvelope, /* bForce = */ true) ==
1709 : OGRERR_FAILURE)
1710 : {
1711 0 : CPLError(CE_Failure, CPLE_AppDefined,
1712 : "Cannot get layer extent");
1713 0 : return false;
1714 : }
1715 0 : CPLError(CE_Warning, CPLE_AppDefined,
1716 : "Could get layer extent, but using a slower method");
1717 : }
1718 :
1719 17 : const double dfXSize = (sEnvelope.MaxX - sEnvelope.MinX) / dfResX;
1720 17 : if (!(dfXSize >= 0 && dfXSize < INT_MAX))
1721 : {
1722 1 : CPLError(CE_Failure, CPLE_AppDefined,
1723 : "Too small %s, or wrong layer extent", MD_RESX);
1724 1 : return false;
1725 : }
1726 :
1727 16 : const double dfYSize = (sEnvelope.MaxY - sEnvelope.MinY) / dfResY;
1728 16 : if (!(dfYSize >= 0 && dfYSize < INT_MAX))
1729 : {
1730 1 : CPLError(CE_Failure, CPLE_AppDefined,
1731 : "Too small %s, or wrong layer extent", MD_RESY);
1732 1 : return false;
1733 : }
1734 :
1735 15 : m_gt[GT_TOPLEFT_X] = sEnvelope.MinX;
1736 15 : m_gt[GT_WE_RES] = dfResX;
1737 15 : m_gt[GT_ROTATION_PARAM1] = 0;
1738 15 : m_gt[GT_TOPLEFT_Y] = sEnvelope.MaxY;
1739 15 : m_gt[GT_ROTATION_PARAM2] = 0;
1740 15 : m_gt[GT_NS_RES] = -dfResY;
1741 15 : nRasterXSize = static_cast<int>(std::ceil(dfXSize));
1742 15 : nRasterYSize = static_cast<int>(std::ceil(dfYSize));
1743 : }
1744 :
1745 222 : if (nBandCount == 0 && !pszBandCount)
1746 : {
1747 0 : CPLError(CE_Failure, CPLE_AppDefined, "%s metadata item missing",
1748 : MD_BAND_COUNT);
1749 0 : return false;
1750 : }
1751 :
1752 222 : if (!GDALCheckBandCount(nBandCount, false))
1753 1 : return false;
1754 :
1755 221 : if (aeDataTypes.empty() && !pszDataType)
1756 : {
1757 9 : aeDataTypes.resize(nBandCount, GDT_Byte);
1758 : }
1759 212 : else if (pszDataType)
1760 : {
1761 8 : aeDataTypes.clear();
1762 8 : const CPLStringList aosTokens(CSLTokenizeString2(pszDataType, ", ", 0));
1763 8 : if (aosTokens.size() == 1)
1764 : {
1765 6 : const auto eDataType = GDALGetDataTypeByName(aosTokens[0]);
1766 6 : if (eDataType == GDT_Unknown)
1767 : {
1768 1 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid value for %s",
1769 : MD_DATA_TYPE);
1770 1 : return false;
1771 : }
1772 5 : aeDataTypes.resize(nBandCount, eDataType);
1773 : }
1774 2 : else if (aosTokens.size() == nBandCount)
1775 : {
1776 2 : for (int i = 0; i < nBandCount; ++i)
1777 : {
1778 2 : const auto eDataType = GDALGetDataTypeByName(aosTokens[i]);
1779 2 : if (eDataType == GDT_Unknown)
1780 : {
1781 1 : CPLError(CE_Failure, CPLE_AppDefined,
1782 : "Invalid value for %s", MD_DATA_TYPE);
1783 1 : return false;
1784 : }
1785 1 : aeDataTypes.push_back(eDataType);
1786 : }
1787 : }
1788 : else
1789 : {
1790 1 : CPLError(CE_Failure, CPLE_AppDefined,
1791 : "Number of values in %s must be 1 or %s", MD_DATA_TYPE,
1792 : MD_BAND_COUNT);
1793 1 : return false;
1794 : }
1795 : }
1796 :
1797 218 : const char *pszNoData = GetOption(MD_NODATA);
1798 218 : if (pszNoData)
1799 : {
1800 20 : const auto IsValidNoDataStr = [](const char *pszStr)
1801 : {
1802 20 : if (EQUAL(pszStr, "inf") || EQUAL(pszStr, "-inf") ||
1803 16 : EQUAL(pszStr, "nan"))
1804 6 : return true;
1805 14 : const auto eType = CPLGetValueType(pszStr);
1806 14 : return eType == CPL_VALUE_INTEGER || eType == CPL_VALUE_REAL;
1807 : };
1808 :
1809 18 : aNoData.clear();
1810 18 : const CPLStringList aosTokens(CSLTokenizeString2(pszNoData, ", ", 0));
1811 18 : if (aosTokens.size() == 1)
1812 : {
1813 14 : if (!EQUAL(aosTokens[0], "NONE"))
1814 : {
1815 11 : if (!IsValidNoDataStr(aosTokens[0]))
1816 : {
1817 1 : CPLError(CE_Failure, CPLE_AppDefined,
1818 : "Invalid value for %s", MD_NODATA);
1819 1 : return false;
1820 : }
1821 10 : aNoData.resize(nBandCount,
1822 20 : std::pair(true, CPLAtof(aosTokens[0])));
1823 : }
1824 : }
1825 4 : else if (aosTokens.size() == nBandCount)
1826 : {
1827 12 : for (int i = 0; i < nBandCount; ++i)
1828 : {
1829 10 : if (EQUAL(aosTokens[i], "NONE"))
1830 : {
1831 1 : aNoData.emplace_back(false, 0);
1832 : }
1833 9 : else if (IsValidNoDataStr(aosTokens[i]))
1834 : {
1835 8 : aNoData.emplace_back(true, CPLAtof(aosTokens[i]));
1836 : }
1837 : else
1838 : {
1839 1 : CPLError(CE_Failure, CPLE_AppDefined,
1840 : "Invalid value for %s", MD_NODATA);
1841 1 : return false;
1842 : }
1843 : }
1844 : }
1845 : else
1846 : {
1847 1 : CPLError(CE_Failure, CPLE_AppDefined,
1848 : "Number of values in %s must be 1 or %s", MD_NODATA,
1849 : MD_BAND_COUNT);
1850 1 : return false;
1851 : }
1852 : }
1853 :
1854 215 : if (pszColorInterp)
1855 : {
1856 11 : aeColorInterp.clear();
1857 : const CPLStringList aosTokens(
1858 11 : CSLTokenizeString2(pszColorInterp, ", ", 0));
1859 11 : if (aosTokens.size() == 1)
1860 : {
1861 7 : const auto eInterp = GDALGetColorInterpretationByName(aosTokens[0]);
1862 12 : if (eInterp == GCI_Undefined &&
1863 5 : !EQUAL(aosTokens[0],
1864 : GDALGetColorInterpretationName(GCI_Undefined)))
1865 : {
1866 1 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid value for %s",
1867 : MD_COLOR_INTERPRETATION);
1868 1 : return false;
1869 : }
1870 6 : aeColorInterp.resize(nBandCount, eInterp);
1871 : }
1872 4 : else if (aosTokens.size() == nBandCount)
1873 : {
1874 11 : for (int i = 0; i < nBandCount; ++i)
1875 : {
1876 : const auto eInterp =
1877 9 : GDALGetColorInterpretationByName(aosTokens[i]);
1878 11 : if (eInterp == GCI_Undefined &&
1879 2 : !EQUAL(aosTokens[i],
1880 : GDALGetColorInterpretationName(GCI_Undefined)))
1881 : {
1882 1 : CPLError(CE_Failure, CPLE_AppDefined,
1883 : "Invalid value for %s", MD_COLOR_INTERPRETATION);
1884 1 : return false;
1885 : }
1886 8 : aeColorInterp.emplace_back(eInterp);
1887 : }
1888 : }
1889 : else
1890 : {
1891 1 : CPLError(CE_Failure, CPLE_AppDefined,
1892 : "Number of values in %s must be 1 or "
1893 : "%s",
1894 : MD_COLOR_INTERPRETATION, MD_BAND_COUNT);
1895 1 : return false;
1896 : }
1897 : }
1898 :
1899 : /* -------------------------------------------------------------------- */
1900 : /* Create bands. */
1901 : /* -------------------------------------------------------------------- */
1902 212 : if (aeDataTypes.size() != static_cast<size_t>(nBandCount))
1903 : {
1904 1 : CPLError(
1905 : CE_Failure, CPLE_AppDefined,
1906 : "Number of data types values found not matching number of bands");
1907 1 : return false;
1908 : }
1909 211 : if (!aNoData.empty() && aNoData.size() != static_cast<size_t>(nBandCount))
1910 : {
1911 1 : CPLError(CE_Failure, CPLE_AppDefined,
1912 : "Number of nodata values found not matching number of bands");
1913 1 : return false;
1914 : }
1915 412 : if (!aeColorInterp.empty() &&
1916 202 : aeColorInterp.size() != static_cast<size_t>(nBandCount))
1917 : {
1918 1 : CPLError(CE_Failure, CPLE_AppDefined,
1919 : "Number of color interpretation values found not matching "
1920 : "number of bands");
1921 1 : return false;
1922 : }
1923 :
1924 209 : int nBlockXSize = 256;
1925 209 : const char *pszBlockXSize = GetOption(MD_BLOCK_X_SIZE);
1926 209 : if (pszBlockXSize)
1927 : {
1928 3 : nBlockXSize = atoi(pszBlockXSize);
1929 3 : if (nBlockXSize <= 0)
1930 : {
1931 1 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid %s",
1932 : MD_BLOCK_X_SIZE);
1933 1 : return false;
1934 : }
1935 : }
1936 :
1937 208 : int nBlockYSize = 256;
1938 208 : const char *pszBlockYSize = GetOption(MD_BLOCK_Y_SIZE);
1939 208 : if (pszBlockYSize)
1940 : {
1941 3 : nBlockYSize = atoi(pszBlockYSize);
1942 3 : if (nBlockYSize <= 0)
1943 : {
1944 1 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid %s",
1945 : MD_BLOCK_Y_SIZE);
1946 1 : return false;
1947 : }
1948 : }
1949 :
1950 207 : if (nBlockXSize > INT_MAX / nBlockYSize)
1951 : {
1952 1 : CPLError(CE_Failure, CPLE_AppDefined, "Too big %s * %s",
1953 : MD_BLOCK_X_SIZE, MD_BLOCK_Y_SIZE);
1954 1 : return false;
1955 : }
1956 :
1957 206 : if (dfOvrFactor > 1.0)
1958 : {
1959 4 : m_gt[GT_WE_RES] *= dfOvrFactor;
1960 4 : m_gt[GT_NS_RES] *= dfOvrFactor;
1961 4 : nRasterXSize = static_cast<int>(std::ceil(nRasterXSize / dfOvrFactor));
1962 4 : nRasterYSize = static_cast<int>(std::ceil(nRasterYSize / dfOvrFactor));
1963 : }
1964 :
1965 412 : std::vector<std::string> aosDescriptions;
1966 412 : std::vector<double> adfCenterWavelength;
1967 412 : std::vector<double> adfFullWidthHalfMax;
1968 412 : std::vector<double> adfScale;
1969 412 : std::vector<double> adfOffset;
1970 206 : if (bIsStacGeoParquet && poFeature)
1971 : {
1972 5 : const int nEOBandsIdx = poLayerDefn->GetFieldIndex(
1973 5 : CPLSPrintf("assets.%s.eo:bands", osAssetName.c_str()));
1974 5 : if (nEOBandsIdx >= 0 &&
1975 10 : poLayerDefn->GetFieldDefn(nEOBandsIdx)->GetSubType() == OFSTJSON &&
1976 5 : poFeature->IsFieldSet(nEOBandsIdx))
1977 : {
1978 5 : const char *pszStr = poFeature->GetFieldAsString(nEOBandsIdx);
1979 10 : CPLJSONDocument oDoc;
1980 15 : if (oDoc.LoadMemory(pszStr) &&
1981 10 : oDoc.GetRoot().GetType() == CPLJSONObject::Type::Array)
1982 : {
1983 10 : const auto oArray = oDoc.GetRoot().ToArray();
1984 5 : if (oArray.Size() == nBandCount)
1985 : {
1986 5 : int i = 0;
1987 5 : aosDescriptions.resize(nBandCount);
1988 5 : adfCenterWavelength.resize(nBandCount);
1989 5 : adfFullWidthHalfMax.resize(nBandCount);
1990 13 : for (const auto &oObj : oArray)
1991 : {
1992 8 : if (oObj.GetType() == CPLJSONObject::Type::Object)
1993 : {
1994 : const auto osCommonName =
1995 24 : oObj.GetString("common_name");
1996 : const auto eInterp =
1997 8 : GDALGetColorInterpFromSTACCommonName(
1998 : osCommonName.c_str());
1999 8 : if (eInterp != GCI_Undefined)
2000 8 : aeColorInterp[i] = eInterp;
2001 :
2002 8 : aosDescriptions[i] = oObj.GetString("name");
2003 :
2004 : std::string osDescription =
2005 16 : oObj.GetString("description");
2006 8 : if (!osDescription.empty())
2007 : {
2008 1 : if (aosDescriptions[i].empty())
2009 0 : aosDescriptions[i] =
2010 0 : std::move(osDescription);
2011 : else
2012 1 : aosDescriptions[i]
2013 1 : .append(" (")
2014 1 : .append(osDescription)
2015 1 : .append(")");
2016 : }
2017 :
2018 16 : adfCenterWavelength[i] =
2019 8 : oObj.GetDouble("center_wavelength");
2020 16 : adfFullWidthHalfMax[i] =
2021 8 : oObj.GetDouble("full_width_half_max");
2022 : }
2023 8 : ++i;
2024 : }
2025 : }
2026 : }
2027 : }
2028 :
2029 5 : const int nRasterBandsIdx = poLayerDefn->GetFieldIndex(
2030 5 : CPLSPrintf("assets.%s.raster:bands", osAssetName.c_str()));
2031 4 : if (nRasterBandsIdx >= 0 &&
2032 4 : poLayerDefn->GetFieldDefn(nRasterBandsIdx)->GetSubType() ==
2033 9 : OFSTJSON &&
2034 4 : poFeature->IsFieldSet(nRasterBandsIdx))
2035 : {
2036 4 : const char *pszStr = poFeature->GetFieldAsString(nRasterBandsIdx);
2037 8 : CPLJSONDocument oDoc;
2038 12 : if (oDoc.LoadMemory(pszStr) &&
2039 8 : oDoc.GetRoot().GetType() == CPLJSONObject::Type::Array)
2040 : {
2041 8 : const auto oArray = oDoc.GetRoot().ToArray();
2042 4 : if (oArray.Size() == nBandCount)
2043 : {
2044 4 : int i = 0;
2045 4 : adfScale.resize(nBandCount,
2046 4 : std::numeric_limits<double>::quiet_NaN());
2047 4 : adfOffset.resize(nBandCount,
2048 4 : std::numeric_limits<double>::quiet_NaN());
2049 8 : for (const auto &oObj : oArray)
2050 : {
2051 4 : if (oObj.GetType() == CPLJSONObject::Type::Object)
2052 : {
2053 4 : adfScale[i] = oObj.GetDouble(
2054 : "scale",
2055 : std::numeric_limits<double>::quiet_NaN());
2056 4 : adfOffset[i] = oObj.GetDouble(
2057 : "offset",
2058 : std::numeric_limits<double>::quiet_NaN());
2059 : }
2060 4 : ++i;
2061 : }
2062 : }
2063 : }
2064 : }
2065 : }
2066 :
2067 206 : GDALTileIndexBand *poFirstBand = nullptr;
2068 482 : for (int i = 0; i < nBandCount; ++i)
2069 : {
2070 276 : GDALDataType eDataType = aeDataTypes[i];
2071 276 : if (!apoXMLNodeBands.empty())
2072 : {
2073 4 : const char *pszVal = CPLGetXMLValue(apoXMLNodeBands[i],
2074 : GTI_XML_BAND_DATATYPE, nullptr);
2075 4 : if (pszVal)
2076 : {
2077 3 : eDataType = GDALGetDataTypeByName(pszVal);
2078 3 : if (eDataType == GDT_Unknown)
2079 0 : return false;
2080 : }
2081 : }
2082 : auto poBandUniquePtr = std::make_unique<GDALTileIndexBand>(
2083 552 : this, i + 1, eDataType, nBlockXSize, nBlockYSize);
2084 276 : auto poBand = poBandUniquePtr.get();
2085 276 : SetBand(i + 1, poBandUniquePtr.release());
2086 276 : if (!poFirstBand)
2087 206 : poFirstBand = poBand;
2088 276 : if (poBand->GetRasterDataType() != poFirstBand->GetRasterDataType())
2089 : {
2090 0 : m_bSameDataType = false;
2091 : }
2092 :
2093 276 : if (!aosDescriptions.empty() && !aosDescriptions[i].empty())
2094 : {
2095 8 : poBand->GDALRasterBand::SetDescription(aosDescriptions[i].c_str());
2096 : }
2097 276 : if (!apoXMLNodeBands.empty())
2098 : {
2099 4 : const char *pszVal = CPLGetXMLValue(
2100 4 : apoXMLNodeBands[i], GTI_XML_BAND_DESCRIPTION, nullptr);
2101 4 : if (pszVal)
2102 : {
2103 2 : poBand->GDALRasterBand::SetDescription(pszVal);
2104 : }
2105 : }
2106 :
2107 276 : if (!aNoData.empty() && aNoData[i].first)
2108 : {
2109 28 : poBand->m_bNoDataValueSet = true;
2110 28 : poBand->m_dfNoDataValue = aNoData[i].second;
2111 : }
2112 276 : if (!apoXMLNodeBands.empty())
2113 : {
2114 4 : const char *pszVal = CPLGetXMLValue(
2115 4 : apoXMLNodeBands[i], GTI_XML_BAND_NODATAVALUE, nullptr);
2116 4 : if (pszVal)
2117 : {
2118 3 : poBand->m_bNoDataValueSet = true;
2119 3 : poBand->m_dfNoDataValue = CPLAtof(pszVal);
2120 : }
2121 : }
2122 551 : if (poBand->m_bNoDataValueSet != poFirstBand->m_bNoDataValueSet ||
2123 275 : !IsSameNaNAware(poBand->m_dfNoDataValue,
2124 : poFirstBand->m_dfNoDataValue))
2125 : {
2126 6 : m_bSameNoData = false;
2127 : }
2128 :
2129 276 : if (!aeColorInterp.empty())
2130 : {
2131 265 : poBand->m_eColorInterp = aeColorInterp[i];
2132 : }
2133 276 : if (!apoXMLNodeBands.empty())
2134 : {
2135 4 : const char *pszVal = CPLGetXMLValue(
2136 4 : apoXMLNodeBands[i], GTI_XML_BAND_COLORINTERP, nullptr);
2137 4 : if (pszVal)
2138 : {
2139 4 : poBand->m_eColorInterp =
2140 4 : GDALGetColorInterpretationByName(pszVal);
2141 : }
2142 : }
2143 :
2144 280 : if (static_cast<int>(adfScale.size()) == nBandCount &&
2145 4 : !std::isnan(adfScale[i]))
2146 : {
2147 4 : poBand->m_dfScale = adfScale[i];
2148 : }
2149 276 : if (const char *pszScale =
2150 276 : GetOption(CPLSPrintf("BAND_%d_%s", i + 1, MD_BAND_SCALE)))
2151 : {
2152 6 : poBand->m_dfScale = CPLAtof(pszScale);
2153 : }
2154 276 : if (!apoXMLNodeBands.empty())
2155 : {
2156 : const char *pszVal =
2157 4 : CPLGetXMLValue(apoXMLNodeBands[i], GTI_XML_BAND_SCALE, nullptr);
2158 4 : if (pszVal)
2159 : {
2160 2 : poBand->m_dfScale = CPLAtof(pszVal);
2161 : }
2162 : }
2163 :
2164 280 : if (static_cast<int>(adfOffset.size()) == nBandCount &&
2165 4 : !std::isnan(adfOffset[i]))
2166 : {
2167 4 : poBand->m_dfOffset = adfOffset[i];
2168 : }
2169 276 : if (const char *pszOffset =
2170 276 : GetOption(CPLSPrintf("BAND_%d_%s", i + 1, MD_BAND_OFFSET)))
2171 : {
2172 6 : poBand->m_dfOffset = CPLAtof(pszOffset);
2173 : }
2174 276 : if (!apoXMLNodeBands.empty())
2175 : {
2176 4 : const char *pszVal = CPLGetXMLValue(apoXMLNodeBands[i],
2177 : GTI_XML_BAND_OFFSET, nullptr);
2178 4 : if (pszVal)
2179 : {
2180 2 : poBand->m_dfOffset = CPLAtof(pszVal);
2181 : }
2182 : }
2183 :
2184 276 : if (const char *pszUnit =
2185 276 : GetOption(CPLSPrintf("BAND_%d_%s", i + 1, MD_BAND_UNITTYPE)))
2186 : {
2187 6 : poBand->m_osUnit = pszUnit;
2188 : }
2189 276 : if (!apoXMLNodeBands.empty())
2190 : {
2191 4 : const char *pszVal = CPLGetXMLValue(apoXMLNodeBands[i],
2192 : GTI_XML_BAND_UNITTYPE, nullptr);
2193 4 : if (pszVal)
2194 : {
2195 2 : poBand->m_osUnit = pszVal;
2196 : }
2197 : }
2198 :
2199 276 : if (!apoXMLNodeBands.empty())
2200 : {
2201 4 : const CPLXMLNode *psBandNode = apoXMLNodeBands[i];
2202 4 : poBand->oMDMD.XMLInit(psBandNode, TRUE);
2203 :
2204 4 : if (const CPLXMLNode *psCategoryNames =
2205 4 : CPLGetXMLNode(psBandNode, GTI_XML_CATEGORYNAMES))
2206 : {
2207 : poBand->m_aosCategoryNames =
2208 2 : VRTParseCategoryNames(psCategoryNames);
2209 : }
2210 :
2211 4 : if (const CPLXMLNode *psColorTable =
2212 4 : CPLGetXMLNode(psBandNode, GTI_XML_COLORTABLE))
2213 : {
2214 2 : poBand->m_poColorTable = VRTParseColorTable(psColorTable);
2215 : }
2216 :
2217 4 : if (const CPLXMLNode *psRAT =
2218 4 : CPLGetXMLNode(psBandNode, GTI_XML_RAT))
2219 : {
2220 : poBand->m_poRAT =
2221 2 : std::make_unique<GDALDefaultRasterAttributeTable>();
2222 2 : poBand->m_poRAT->XMLInit(psRAT, "");
2223 : }
2224 : }
2225 :
2226 284 : if (static_cast<int>(adfCenterWavelength.size()) == nBandCount &&
2227 8 : adfCenterWavelength[i] != 0)
2228 : {
2229 4 : poBand->GDALRasterBand::SetMetadataItem(
2230 : "CENTRAL_WAVELENGTH_UM",
2231 4 : CPLSPrintf("%g", adfCenterWavelength[i]), "IMAGERY");
2232 : }
2233 :
2234 284 : if (static_cast<int>(adfFullWidthHalfMax.size()) == nBandCount &&
2235 8 : adfFullWidthHalfMax[i] != 0)
2236 : {
2237 4 : poBand->GDALRasterBand::SetMetadataItem(
2238 4 : "FWHM_UM", CPLSPrintf("%g", adfFullWidthHalfMax[i]), "IMAGERY");
2239 : }
2240 : }
2241 :
2242 206 : if (nBandCount == 1 && poFirstBand && poSingleColorTable &&
2243 0 : !poFirstBand->m_poColorTable)
2244 0 : poFirstBand->m_poColorTable = std::move(poSingleColorTable);
2245 :
2246 206 : const char *pszMaskBand = GetOption(MD_MASK_BAND);
2247 206 : if (pszMaskBand)
2248 7 : bHasMaskBand = CPLTestBool(pszMaskBand);
2249 206 : if (bHasMaskBand)
2250 : {
2251 8 : m_poMaskBand = std::make_unique<GDALTileIndexBand>(
2252 16 : this, 0, GDT_Byte, nBlockXSize, nBlockYSize);
2253 : }
2254 :
2255 206 : if (dfOvrFactor == 1.0)
2256 : {
2257 202 : if (psRoot)
2258 : {
2259 84 : for (const CPLXMLNode *psIter = psRoot->psChild; psIter;
2260 66 : psIter = psIter->psNext)
2261 : {
2262 67 : if (psIter->eType == CXT_Element &&
2263 67 : strcmp(psIter->pszValue, GTI_XML_OVERVIEW_ELEMENT) == 0)
2264 : {
2265 9 : const char *pszDataset = CPLGetXMLValue(
2266 : psIter, GTI_XML_OVERVIEW_DATASET, nullptr);
2267 : const char *pszLayer =
2268 9 : CPLGetXMLValue(psIter, GTI_XML_OVERVIEW_LAYER, nullptr);
2269 9 : const char *pszFactor = CPLGetXMLValue(
2270 : psIter, GTI_XML_OVERVIEW_FACTOR, nullptr);
2271 9 : if (!pszDataset && !pszLayer && !pszFactor)
2272 : {
2273 1 : CPLError(
2274 : CE_Failure, CPLE_AppDefined,
2275 : "At least one of %s, %s or %s element "
2276 : "must be present as an %s child",
2277 : GTI_XML_OVERVIEW_DATASET, GTI_XML_OVERVIEW_LAYER,
2278 : GTI_XML_OVERVIEW_FACTOR, GTI_XML_OVERVIEW_ELEMENT);
2279 1 : return false;
2280 : }
2281 : m_aoOverviewDescriptor.emplace_back(
2282 16 : std::string(pszDataset ? pszDataset : ""),
2283 16 : CPLStringList(
2284 : GDALDeserializeOpenOptionsFromXML(psIter)),
2285 16 : std::string(pszLayer ? pszLayer : ""),
2286 24 : pszFactor ? CPLAtof(pszFactor) : 0.0);
2287 : }
2288 : }
2289 : }
2290 : else
2291 : {
2292 184 : for (int iOvr = 0;; ++iOvr)
2293 : {
2294 : const char *pszOvrDSName =
2295 369 : GetOption(CPLSPrintf("OVERVIEW_%d_DATASET", iOvr));
2296 : const char *pszOpenOptions =
2297 369 : GetOption(CPLSPrintf("OVERVIEW_%d_OPEN_OPTIONS", iOvr));
2298 : const char *pszOvrLayer =
2299 369 : GetOption(CPLSPrintf("OVERVIEW_%d_LAYER", iOvr));
2300 : const char *pszOvrFactor =
2301 369 : GetOption(CPLSPrintf("OVERVIEW_%d_FACTOR", iOvr));
2302 369 : if (!pszOvrDSName && !pszOvrLayer && !pszOvrFactor)
2303 : {
2304 : // Before GDAL 3.9.2, we started the iteration at 1.
2305 362 : if (iOvr == 0)
2306 178 : continue;
2307 184 : break;
2308 : }
2309 : m_aoOverviewDescriptor.emplace_back(
2310 14 : std::string(pszOvrDSName ? pszOvrDSName : ""),
2311 14 : pszOpenOptions ? CPLStringList(CSLTokenizeString2(
2312 : pszOpenOptions, ",", 0))
2313 : : CPLStringList(),
2314 14 : std::string(pszOvrLayer ? pszOvrLayer : ""),
2315 21 : pszOvrFactor ? CPLAtof(pszOvrFactor) : 0.0);
2316 185 : }
2317 : }
2318 : }
2319 :
2320 205 : if (psRoot)
2321 : {
2322 19 : oMDMD.XMLInit(psRoot, TRUE);
2323 : }
2324 : else
2325 : {
2326 : // Set on the dataset all metadata items from the index layer which are
2327 : // not "reserved" keywords.
2328 186 : CSLConstList papszLayerMD = m_poLayer->GetMetadata();
2329 500 : for (const auto &[pszKey, pszValue] :
2330 686 : cpl::IterateNameValue(papszLayerMD))
2331 : {
2332 250 : if (STARTS_WITH_CI(pszKey, "OVERVIEW_"))
2333 : {
2334 10 : continue;
2335 : }
2336 :
2337 240 : bool bIsVRTItem = false;
2338 3573 : for (const char *pszTest : apszTIOptions)
2339 : {
2340 3513 : if (EQUAL(pszKey, pszTest))
2341 : {
2342 180 : bIsVRTItem = true;
2343 180 : break;
2344 : }
2345 : }
2346 240 : if (!bIsVRTItem)
2347 : {
2348 60 : if (STARTS_WITH_CI(pszKey, "BAND_"))
2349 : {
2350 52 : const int nBandNr = atoi(pszKey + strlen("BAND_"));
2351 : const char *pszNextUnderscore =
2352 52 : strchr(pszKey + strlen("BAND_"), '_');
2353 52 : if (pszNextUnderscore && nBandNr >= 1 && nBandNr <= nBands)
2354 : {
2355 42 : const char *pszKeyWithoutBand = pszNextUnderscore + 1;
2356 42 : bool bIsReservedBandItem = false;
2357 132 : for (const char *pszItem : apszReservedBandItems)
2358 : {
2359 108 : if (EQUAL(pszKeyWithoutBand, pszItem))
2360 : {
2361 18 : bIsReservedBandItem = true;
2362 18 : break;
2363 : }
2364 : }
2365 42 : if (!bIsReservedBandItem)
2366 : {
2367 24 : GetRasterBand(nBandNr)
2368 24 : ->GDALRasterBand::SetMetadataItem(
2369 : pszKeyWithoutBand, pszValue);
2370 : }
2371 : }
2372 : }
2373 : else
2374 : {
2375 8 : GDALDataset::SetMetadataItem(pszKey, pszValue);
2376 : }
2377 : }
2378 : }
2379 : }
2380 :
2381 205 : if (nBandCount > 1 && !GetMetadata("IMAGE_STRUCTURE"))
2382 : {
2383 34 : GDALDataset::SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
2384 : }
2385 :
2386 : /* -------------------------------------------------------------------- */
2387 : /* Initialize any PAM information. */
2388 : /* -------------------------------------------------------------------- */
2389 205 : SetDescription(poOpenInfo->pszFilename);
2390 205 : TryLoadXML();
2391 :
2392 : /* -------------------------------------------------------------------- */
2393 : /* Check for overviews. */
2394 : /* -------------------------------------------------------------------- */
2395 205 : oOvManager.Initialize(this, poOpenInfo->pszFilename);
2396 :
2397 205 : return true;
2398 : }
2399 :
2400 : /************************************************************************/
2401 : /* GetMetadataItem() */
2402 : /************************************************************************/
2403 :
2404 105 : const char *GDALTileIndexDataset::GetMetadataItem(const char *pszName,
2405 : const char *pszDomain)
2406 : {
2407 105 : if (pszName && pszDomain && EQUAL(pszDomain, "__DEBUG__"))
2408 : {
2409 20 : if (EQUAL(pszName, "SCANNED_ONE_FEATURE_AT_OPENING"))
2410 : {
2411 4 : return m_bScannedOneFeatureAtOpening ? "YES" : "NO";
2412 : }
2413 16 : else if (EQUAL(pszName, "NUMBER_OF_CONTRIBUTING_SOURCES"))
2414 : {
2415 5 : return CPLSPrintf("%d", static_cast<int>(m_aoSourceDesc.size()));
2416 : }
2417 11 : else if (EQUAL(pszName, "MULTI_THREADED_RASTERIO_LAST_USED"))
2418 : {
2419 11 : return m_bLastMustUseMultiThreading ? "1" : "0";
2420 : }
2421 : }
2422 85 : return GDALPamDataset::GetMetadataItem(pszName, pszDomain);
2423 : }
2424 :
2425 : /************************************************************************/
2426 : /* TileIndexSupportsEditingLayerMetadata() */
2427 : /************************************************************************/
2428 :
2429 17 : bool GDALTileIndexDataset::TileIndexSupportsEditingLayerMetadata() const
2430 : {
2431 27 : return eAccess == GA_Update && m_poVectorDS->GetDriver() &&
2432 27 : EQUAL(m_poVectorDS->GetDriver()->GetDescription(), "GPKG");
2433 : }
2434 :
2435 : /************************************************************************/
2436 : /* SetMetadataItem() */
2437 : /************************************************************************/
2438 :
2439 3 : CPLErr GDALTileIndexDataset::SetMetadataItem(const char *pszName,
2440 : const char *pszValue,
2441 : const char *pszDomain)
2442 : {
2443 3 : if (m_bXMLUpdatable)
2444 : {
2445 1 : m_bXMLModified = true;
2446 1 : return GDALDataset::SetMetadataItem(pszName, pszValue, pszDomain);
2447 : }
2448 2 : else if (TileIndexSupportsEditingLayerMetadata())
2449 : {
2450 1 : m_poLayer->SetMetadataItem(pszName, pszValue, pszDomain);
2451 1 : return GDALDataset::SetMetadataItem(pszName, pszValue, pszDomain);
2452 : }
2453 : else
2454 : {
2455 1 : return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
2456 : }
2457 : }
2458 :
2459 : /************************************************************************/
2460 : /* SetMetadata() */
2461 : /************************************************************************/
2462 :
2463 3 : CPLErr GDALTileIndexDataset::SetMetadata(char **papszMD, const char *pszDomain)
2464 : {
2465 3 : if (m_bXMLUpdatable)
2466 : {
2467 1 : m_bXMLModified = true;
2468 1 : return GDALDataset::SetMetadata(papszMD, pszDomain);
2469 : }
2470 2 : else if (TileIndexSupportsEditingLayerMetadata())
2471 : {
2472 2 : if (!pszDomain || pszDomain[0] == 0)
2473 : {
2474 4 : CPLStringList aosMD(CSLDuplicate(papszMD));
2475 :
2476 : // Reinject dataset reserved items
2477 44 : for (const char *pszItem : apszTIOptions)
2478 : {
2479 42 : if (!aosMD.FetchNameValue(pszItem))
2480 : {
2481 42 : const char *pszValue = m_poLayer->GetMetadataItem(pszItem);
2482 42 : if (pszValue)
2483 : {
2484 2 : aosMD.SetNameValue(pszItem, pszValue);
2485 : }
2486 : }
2487 : }
2488 :
2489 : // Reinject band metadata
2490 2 : char **papszExistingLayerMD = m_poLayer->GetMetadata();
2491 17 : for (int i = 0; papszExistingLayerMD && papszExistingLayerMD[i];
2492 : ++i)
2493 : {
2494 15 : if (STARTS_WITH_CI(papszExistingLayerMD[i], "BAND_"))
2495 : {
2496 12 : aosMD.AddString(papszExistingLayerMD[i]);
2497 : }
2498 : }
2499 :
2500 4 : m_poLayer->SetMetadata(aosMD.List(), pszDomain);
2501 : }
2502 : else
2503 : {
2504 0 : m_poLayer->SetMetadata(papszMD, pszDomain);
2505 : }
2506 2 : return GDALDataset::SetMetadata(papszMD, pszDomain);
2507 : }
2508 : else
2509 : {
2510 0 : return GDALPamDataset::SetMetadata(papszMD, pszDomain);
2511 : }
2512 : }
2513 :
2514 : /************************************************************************/
2515 : /* GDALTileIndexDatasetIdentify() */
2516 : /************************************************************************/
2517 :
2518 90593 : static int GDALTileIndexDatasetIdentify(GDALOpenInfo *poOpenInfo)
2519 : {
2520 90593 : if (STARTS_WITH(poOpenInfo->pszFilename, GTI_PREFIX))
2521 22 : return true;
2522 :
2523 90571 : if (STARTS_WITH(poOpenInfo->pszFilename, "<GDALTileIndexDataset"))
2524 50 : return true;
2525 :
2526 90521 : if (poOpenInfo->nHeaderBytes >= 100 &&
2527 31575 : STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
2528 : "SQLite format 3"))
2529 : {
2530 924 : if (ENDS_WITH_CI(poOpenInfo->pszFilename, ".gti.gpkg"))
2531 : {
2532 : // Most likely handled by GTI driver, but we can't be sure
2533 499 : return GDAL_IDENTIFY_UNKNOWN;
2534 : }
2535 427 : else if (poOpenInfo->IsSingleAllowedDriver("GTI") &&
2536 2 : poOpenInfo->IsExtensionEqualToCI("gpkg"))
2537 : {
2538 2 : return true;
2539 : }
2540 : }
2541 :
2542 90020 : if (poOpenInfo->nHeaderBytes > 0 &&
2543 31668 : (poOpenInfo->nOpenFlags & GDAL_OF_RASTER) != 0)
2544 : {
2545 63338 : if (strstr(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
2546 31654 : "<GDALTileIndexDataset") ||
2547 63323 : ENDS_WITH_CI(poOpenInfo->pszFilename, ".gti.fgb") ||
2548 31655 : ENDS_WITH_CI(poOpenInfo->pszFilename, ".gti.parquet"))
2549 : {
2550 12 : return true;
2551 : }
2552 31657 : else if (poOpenInfo->IsSingleAllowedDriver("GTI") &&
2553 0 : (poOpenInfo->IsExtensionEqualToCI("fgb") ||
2554 0 : poOpenInfo->IsExtensionEqualToCI("parquet")))
2555 : {
2556 0 : return true;
2557 : }
2558 : }
2559 :
2560 90007 : return false;
2561 : }
2562 :
2563 : /************************************************************************/
2564 : /* GDALTileIndexDatasetOpen() */
2565 : /************************************************************************/
2566 :
2567 277 : static GDALDataset *GDALTileIndexDatasetOpen(GDALOpenInfo *poOpenInfo)
2568 : {
2569 277 : if (GDALTileIndexDatasetIdentify(poOpenInfo) == GDAL_IDENTIFY_FALSE)
2570 0 : return nullptr;
2571 554 : auto poDS = std::make_unique<GDALTileIndexDataset>();
2572 277 : if (!poDS->Open(poOpenInfo))
2573 72 : return nullptr;
2574 205 : return poDS.release();
2575 : }
2576 :
2577 : /************************************************************************/
2578 : /* ~GDALTileIndexDataset() */
2579 : /************************************************************************/
2580 :
2581 554 : GDALTileIndexDataset::~GDALTileIndexDataset()
2582 : {
2583 277 : if (m_poVectorDS && m_bIsSQLResultLayer)
2584 4 : m_poVectorDS->ReleaseResultSet(m_poLayer);
2585 :
2586 277 : GDALTileIndexDataset::FlushCache(true);
2587 554 : }
2588 :
2589 : /************************************************************************/
2590 : /* FlushCache() */
2591 : /************************************************************************/
2592 :
2593 278 : CPLErr GDALTileIndexDataset::FlushCache(bool bAtClosing)
2594 : {
2595 278 : CPLErr eErr = CE_None;
2596 278 : if (bAtClosing && m_bXMLModified)
2597 : {
2598 : CPLXMLNode *psRoot =
2599 1 : CPLGetXMLNode(m_psXMLTree.get(), "=GDALTileIndexDataset");
2600 :
2601 : // Suppress existing dataset metadata
2602 : while (true)
2603 : {
2604 1 : CPLXMLNode *psExistingMetadata = CPLGetXMLNode(psRoot, "Metadata");
2605 1 : if (!psExistingMetadata)
2606 1 : break;
2607 0 : CPLRemoveXMLChild(psRoot, psExistingMetadata);
2608 0 : }
2609 :
2610 : // Serialize new dataset metadata
2611 1 : if (CPLXMLNode *psMD = oMDMD.Serialize())
2612 1 : CPLAddXMLChild(psRoot, psMD);
2613 :
2614 : // Update existing band metadata
2615 1 : if (CPLGetXMLNode(psRoot, GTI_XML_BAND_ELEMENT))
2616 : {
2617 0 : for (CPLXMLNode *psIter = psRoot->psChild; psIter;
2618 0 : psIter = psIter->psNext)
2619 : {
2620 0 : if (psIter->eType == CXT_Element &&
2621 0 : strcmp(psIter->pszValue, GTI_XML_BAND_ELEMENT))
2622 : {
2623 : const char *pszBand =
2624 0 : CPLGetXMLValue(psIter, GTI_XML_BAND_NUMBER, nullptr);
2625 0 : if (pszBand)
2626 : {
2627 0 : const int nBand = atoi(pszBand);
2628 0 : if (nBand >= 1 && nBand <= nBands)
2629 : {
2630 : while (true)
2631 : {
2632 : CPLXMLNode *psExistingMetadata =
2633 0 : CPLGetXMLNode(psIter, "Metadata");
2634 0 : if (!psExistingMetadata)
2635 0 : break;
2636 0 : CPLRemoveXMLChild(psIter, psExistingMetadata);
2637 0 : }
2638 :
2639 0 : auto poBand = cpl::down_cast<GDALTileIndexBand *>(
2640 0 : papoBands[nBand - 1]);
2641 0 : if (CPLXMLNode *psMD = poBand->oMDMD.Serialize())
2642 0 : CPLAddXMLChild(psIter, psMD);
2643 : }
2644 : }
2645 : }
2646 : }
2647 : }
2648 : else
2649 : {
2650 : // Create new band objects if they have metadata
2651 2 : std::vector<CPLXMLTreeCloser> aoBandXML;
2652 1 : bool bHasBandMD = false;
2653 2 : for (int i = 1; i <= nBands; ++i)
2654 : {
2655 : auto poBand =
2656 1 : cpl::down_cast<GDALTileIndexBand *>(papoBands[i - 1]);
2657 1 : auto psMD = poBand->oMDMD.Serialize();
2658 1 : if (psMD)
2659 1 : bHasBandMD = true;
2660 1 : aoBandXML.emplace_back(CPLXMLTreeCloser(psMD));
2661 : }
2662 1 : if (bHasBandMD)
2663 : {
2664 2 : for (int i = 1; i <= nBands; ++i)
2665 : {
2666 : auto poBand =
2667 1 : cpl::down_cast<GDALTileIndexBand *>(papoBands[i - 1]);
2668 :
2669 1 : CPLXMLNode *psBand = CPLCreateXMLNode(psRoot, CXT_Element,
2670 : GTI_XML_BAND_ELEMENT);
2671 1 : CPLAddXMLAttributeAndValue(psBand, GTI_XML_BAND_NUMBER,
2672 : CPLSPrintf("%d", i));
2673 1 : CPLAddXMLAttributeAndValue(
2674 : psBand, GTI_XML_BAND_DATATYPE,
2675 : GDALGetDataTypeName(poBand->GetRasterDataType()));
2676 :
2677 1 : const char *pszDescription = poBand->GetDescription();
2678 1 : if (pszDescription && pszDescription[0])
2679 0 : CPLSetXMLValue(psBand, GTI_XML_BAND_DESCRIPTION,
2680 : pszDescription);
2681 :
2682 1 : const auto eColorInterp = poBand->GetColorInterpretation();
2683 1 : if (eColorInterp != GCI_Undefined)
2684 1 : CPLSetXMLValue(
2685 : psBand, GTI_XML_BAND_COLORINTERP,
2686 : GDALGetColorInterpretationName(eColorInterp));
2687 :
2688 1 : if (!std::isnan(poBand->m_dfOffset))
2689 0 : CPLSetXMLValue(psBand, GTI_XML_BAND_OFFSET,
2690 : CPLSPrintf("%.16g", poBand->m_dfOffset));
2691 :
2692 1 : if (!std::isnan(poBand->m_dfScale))
2693 0 : CPLSetXMLValue(psBand, GTI_XML_BAND_SCALE,
2694 : CPLSPrintf("%.16g", poBand->m_dfScale));
2695 :
2696 1 : if (!poBand->m_osUnit.empty())
2697 0 : CPLSetXMLValue(psBand, GTI_XML_BAND_UNITTYPE,
2698 : poBand->m_osUnit.c_str());
2699 :
2700 1 : if (poBand->m_bNoDataValueSet)
2701 : {
2702 0 : CPLSetXMLValue(
2703 : psBand, GTI_XML_BAND_NODATAVALUE,
2704 0 : VRTSerializeNoData(poBand->m_dfNoDataValue,
2705 : poBand->GetRasterDataType(), 18)
2706 : .c_str());
2707 : }
2708 1 : if (aoBandXML[i - 1])
2709 : {
2710 1 : CPLAddXMLChild(psBand, aoBandXML[i - 1].release());
2711 : }
2712 : }
2713 : }
2714 : }
2715 :
2716 1 : if (!CPLSerializeXMLTreeToFile(m_psXMLTree.get(), GetDescription()))
2717 0 : eErr = CE_Failure;
2718 : }
2719 :
2720 : // We also clear the cache of opened sources, in case the user would
2721 : // change the content of a source and would want the GTI dataset to see
2722 : // the refreshed content.
2723 278 : m_oMapSharedSources.clear();
2724 278 : m_dfLastMinXFilter = std::numeric_limits<double>::quiet_NaN();
2725 278 : m_dfLastMinYFilter = std::numeric_limits<double>::quiet_NaN();
2726 278 : m_dfLastMaxXFilter = std::numeric_limits<double>::quiet_NaN();
2727 278 : m_dfLastMaxYFilter = std::numeric_limits<double>::quiet_NaN();
2728 278 : m_aoSourceDesc.clear();
2729 278 : if (GDALPamDataset::FlushCache(bAtClosing) != CE_None)
2730 0 : eErr = CE_Failure;
2731 278 : return eErr;
2732 : }
2733 :
2734 : /************************************************************************/
2735 : /* LoadOverviews() */
2736 : /************************************************************************/
2737 :
2738 44 : void GDALTileIndexDataset::LoadOverviews()
2739 : {
2740 44 : if (m_apoOverviews.empty() && !m_aoOverviewDescriptor.empty())
2741 : {
2742 28 : for (const auto &[osDSName, aosOpenOptions, osLyrName, dfFactor] :
2743 42 : m_aoOverviewDescriptor)
2744 : {
2745 28 : CPLStringList aosNewOpenOptions(aosOpenOptions);
2746 14 : if (dfFactor != 0)
2747 : {
2748 : aosNewOpenOptions.SetNameValue("@FACTOR",
2749 4 : CPLSPrintf("%.17g", dfFactor));
2750 : }
2751 14 : if (!osLyrName.empty())
2752 : {
2753 5 : aosNewOpenOptions.SetNameValue("@LAYER", osLyrName.c_str());
2754 : }
2755 :
2756 : std::unique_ptr<GDALDataset> poOvrDS(GDALDataset::Open(
2757 28 : !osDSName.empty() ? osDSName.c_str() : GetDescription(),
2758 : GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR, nullptr,
2759 56 : aosNewOpenOptions.List(), nullptr));
2760 :
2761 : const auto IsSmaller =
2762 10 : [](const GDALDataset *a, const GDALDataset *b)
2763 : {
2764 10 : return (a->GetRasterXSize() < b->GetRasterXSize() &&
2765 11 : a->GetRasterYSize() <= b->GetRasterYSize()) ||
2766 1 : (a->GetRasterYSize() < b->GetRasterYSize() &&
2767 10 : a->GetRasterXSize() <= b->GetRasterXSize());
2768 : };
2769 :
2770 32 : if (poOvrDS &&
2771 18 : ((m_apoOverviews.empty() && IsSmaller(poOvrDS.get(), this)) ||
2772 1 : ((!m_apoOverviews.empty() &&
2773 14 : IsSmaller(poOvrDS.get(), m_apoOverviews.back().get())))))
2774 : {
2775 8 : if (poOvrDS->GetRasterCount() == GetRasterCount())
2776 : {
2777 8 : m_apoOverviews.emplace_back(std::move(poOvrDS));
2778 : // Add the overviews of the overview, unless the OVERVIEW_LEVEL
2779 : // option option is specified
2780 8 : if (aosOpenOptions.FetchNameValue("OVERVIEW_LEVEL") ==
2781 : nullptr)
2782 : {
2783 7 : const int nOverviewCount = m_apoOverviews.back()
2784 7 : ->GetRasterBand(1)
2785 7 : ->GetOverviewCount();
2786 8 : for (int i = 0; i < nOverviewCount; ++i)
2787 : {
2788 : aosNewOpenOptions.SetNameValue("OVERVIEW_LEVEL",
2789 1 : CPLSPrintf("%d", i));
2790 : std::unique_ptr<GDALDataset> poOvrOfOvrDS(
2791 : GDALDataset::Open(
2792 2 : !osDSName.empty() ? osDSName.c_str()
2793 0 : : GetDescription(),
2794 : GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR,
2795 1 : nullptr, aosNewOpenOptions.List(),
2796 3 : nullptr));
2797 2 : if (poOvrOfOvrDS &&
2798 1 : poOvrOfOvrDS->GetRasterCount() ==
2799 3 : GetRasterCount() &&
2800 1 : IsSmaller(poOvrOfOvrDS.get(),
2801 1 : m_apoOverviews.back().get()))
2802 : {
2803 : m_apoOverviews.emplace_back(
2804 1 : std::move(poOvrOfOvrDS));
2805 : }
2806 : }
2807 : }
2808 : }
2809 : else
2810 : {
2811 0 : CPLError(CE_Warning, CPLE_AppDefined,
2812 : "%s has not the same number of bands as %s",
2813 0 : poOvrDS->GetDescription(), GetDescription());
2814 : }
2815 : }
2816 : }
2817 : }
2818 44 : }
2819 :
2820 : /************************************************************************/
2821 : /* GetOverviewCount() */
2822 : /************************************************************************/
2823 :
2824 68 : int GDALTileIndexBand::GetOverviewCount()
2825 : {
2826 68 : const int nPAMOverviews = GDALPamRasterBand::GetOverviewCount();
2827 68 : if (nPAMOverviews)
2828 24 : return nPAMOverviews;
2829 :
2830 44 : m_poDS->LoadOverviews();
2831 44 : return static_cast<int>(m_poDS->m_apoOverviews.size());
2832 : }
2833 :
2834 : /************************************************************************/
2835 : /* GetOverview() */
2836 : /************************************************************************/
2837 :
2838 35 : GDALRasterBand *GDALTileIndexBand::GetOverview(int iOvr)
2839 : {
2840 35 : if (iOvr < 0 || iOvr >= GetOverviewCount())
2841 6 : return nullptr;
2842 :
2843 29 : const int nPAMOverviews = GDALPamRasterBand::GetOverviewCount();
2844 29 : if (nPAMOverviews)
2845 16 : return GDALPamRasterBand::GetOverview(iOvr);
2846 :
2847 13 : if (nBand == 0)
2848 : {
2849 1 : auto poBand = m_poDS->m_apoOverviews[iOvr]->GetRasterBand(1);
2850 1 : if (!poBand)
2851 0 : return nullptr;
2852 1 : return poBand->GetMaskBand();
2853 : }
2854 : else
2855 : {
2856 12 : return m_poDS->m_apoOverviews[iOvr]->GetRasterBand(nBand);
2857 : }
2858 : }
2859 :
2860 : /************************************************************************/
2861 : /* GetGeoTransform() */
2862 : /************************************************************************/
2863 :
2864 23 : CPLErr GDALTileIndexDataset::GetGeoTransform(GDALGeoTransform >) const
2865 : {
2866 23 : gt = m_gt;
2867 23 : return CE_None;
2868 : }
2869 :
2870 : /************************************************************************/
2871 : /* GetSpatialRef() */
2872 : /************************************************************************/
2873 :
2874 18 : const OGRSpatialReference *GDALTileIndexDataset::GetSpatialRef() const
2875 : {
2876 18 : return m_oSRS.IsEmpty() ? nullptr : &m_oSRS;
2877 : }
2878 :
2879 : /************************************************************************/
2880 : /* GDALTileIndexBand() */
2881 : /************************************************************************/
2882 :
2883 284 : GDALTileIndexBand::GDALTileIndexBand(GDALTileIndexDataset *poDSIn, int nBandIn,
2884 : GDALDataType eDT, int nBlockXSizeIn,
2885 284 : int nBlockYSizeIn)
2886 : {
2887 284 : m_poDS = poDSIn;
2888 284 : nBand = nBandIn;
2889 284 : eDataType = eDT;
2890 284 : nRasterXSize = poDSIn->GetRasterXSize();
2891 284 : nRasterYSize = poDSIn->GetRasterYSize();
2892 284 : nBlockXSize = nBlockXSizeIn;
2893 284 : nBlockYSize = nBlockYSizeIn;
2894 284 : }
2895 :
2896 : /************************************************************************/
2897 : /* IReadBlock() */
2898 : /************************************************************************/
2899 :
2900 13 : CPLErr GDALTileIndexBand::IReadBlock(int nBlockXOff, int nBlockYOff,
2901 : void *pImage)
2902 :
2903 : {
2904 13 : const int nPixelSize = GDALGetDataTypeSizeBytes(eDataType);
2905 :
2906 13 : int nReadXSize = nBlockXSize;
2907 13 : int nReadYSize = nBlockYSize;
2908 13 : GetActualBlockSize(nBlockXOff, nBlockYOff, &nReadXSize, &nReadYSize);
2909 :
2910 : GDALRasterIOExtraArg sExtraArg;
2911 13 : INIT_RASTERIO_EXTRA_ARG(sExtraArg);
2912 :
2913 26 : return IRasterIO(
2914 13 : GF_Read, nBlockXOff * nBlockXSize, nBlockYOff * nBlockYSize, nReadXSize,
2915 : nReadYSize, pImage, nReadXSize, nReadYSize, eDataType, nPixelSize,
2916 26 : static_cast<GSpacing>(nPixelSize) * nBlockXSize, &sExtraArg);
2917 : }
2918 :
2919 : /************************************************************************/
2920 : /* IRasterIO() */
2921 : /************************************************************************/
2922 :
2923 141 : CPLErr GDALTileIndexBand::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
2924 : int nXSize, int nYSize, void *pData,
2925 : int nBufXSize, int nBufYSize,
2926 : GDALDataType eBufType, GSpacing nPixelSpace,
2927 : GSpacing nLineSpace,
2928 : GDALRasterIOExtraArg *psExtraArg)
2929 : {
2930 141 : int anBand[] = {nBand};
2931 :
2932 141 : return m_poDS->IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize, pData,
2933 : nBufXSize, nBufYSize, eBufType, 1, anBand,
2934 282 : nPixelSpace, nLineSpace, 0, psExtraArg);
2935 : }
2936 :
2937 : /************************************************************************/
2938 : /* IGetDataCoverageStatus() */
2939 : /************************************************************************/
2940 :
2941 : #ifndef HAVE_GEOS
2942 : int GDALTileIndexBand::IGetDataCoverageStatus(int /* nXOff */, int /* nYOff */,
2943 : int /* nXSize */,
2944 : int /* nYSize */,
2945 : int /* nMaskFlagStop */,
2946 : double *pdfDataPct)
2947 : {
2948 : if (pdfDataPct != nullptr)
2949 : *pdfDataPct = -1.0;
2950 : return GDAL_DATA_COVERAGE_STATUS_UNIMPLEMENTED |
2951 : GDAL_DATA_COVERAGE_STATUS_DATA;
2952 : }
2953 : #else
2954 9 : int GDALTileIndexBand::IGetDataCoverageStatus(int nXOff, int nYOff, int nXSize,
2955 : int nYSize, int nMaskFlagStop,
2956 : double *pdfDataPct)
2957 : {
2958 9 : if (pdfDataPct != nullptr)
2959 9 : *pdfDataPct = -1.0;
2960 :
2961 : const double dfMinX =
2962 9 : m_poDS->m_gt[GT_TOPLEFT_X] + nXOff * m_poDS->m_gt[GT_WE_RES];
2963 9 : const double dfMaxX = dfMinX + nXSize * m_poDS->m_gt[GT_WE_RES];
2964 : const double dfMaxY =
2965 9 : m_poDS->m_gt[GT_TOPLEFT_Y] + nYOff * m_poDS->m_gt[GT_NS_RES];
2966 9 : const double dfMinY = dfMaxY + nYSize * m_poDS->m_gt[GT_NS_RES];
2967 :
2968 9 : OGRLayer *poSQLLayer = nullptr;
2969 9 : if (!m_poDS->m_osSpatialSQL.empty())
2970 : {
2971 : const std::string osSQL =
2972 2 : CPLString(m_poDS->m_osSpatialSQL)
2973 4 : .replaceAll("{XMIN}", CPLSPrintf("%.17g", dfMinX))
2974 4 : .replaceAll("{YMIN}", CPLSPrintf("%.17g", dfMinY))
2975 4 : .replaceAll("{XMAX}", CPLSPrintf("%.17g", dfMaxX))
2976 4 : .replaceAll("{YMAX}", CPLSPrintf("%.17g", dfMaxY));
2977 : poSQLLayer =
2978 2 : m_poDS->m_poVectorDS->ExecuteSQL(osSQL.c_str(), nullptr, nullptr);
2979 2 : if (!poSQLLayer)
2980 1 : return 0;
2981 : }
2982 : else
2983 : {
2984 7 : m_poDS->m_poLayer->SetSpatialFilterRect(dfMinX, dfMinY, dfMaxX, dfMaxY);
2985 7 : m_poDS->m_poLayer->ResetReading();
2986 : }
2987 :
2988 8 : OGRLayer *const poLayer = poSQLLayer ? poSQLLayer : m_poDS->m_poLayer;
2989 :
2990 8 : int nStatus = 0;
2991 :
2992 16 : auto poPolyNonCoveredBySources = std::make_unique<OGRPolygon>();
2993 : {
2994 16 : auto poLR = std::make_unique<OGRLinearRing>();
2995 8 : poLR->addPoint(nXOff, nYOff);
2996 8 : poLR->addPoint(nXOff, nYOff + nYSize);
2997 8 : poLR->addPoint(nXOff + nXSize, nYOff + nYSize);
2998 8 : poLR->addPoint(nXOff + nXSize, nYOff);
2999 8 : poLR->addPoint(nXOff, nYOff);
3000 8 : poPolyNonCoveredBySources->addRingDirectly(poLR.release());
3001 : }
3002 : while (true)
3003 : {
3004 12 : auto poFeature = std::unique_ptr<OGRFeature>(poLayer->GetNextFeature());
3005 12 : if (!poFeature)
3006 2 : break;
3007 10 : if (!poFeature->IsFieldSetAndNotNull(m_poDS->m_nLocationFieldIndex))
3008 : {
3009 0 : continue;
3010 : }
3011 :
3012 10 : const auto poGeom = poFeature->GetGeometryRef();
3013 10 : if (!poGeom || poGeom->IsEmpty())
3014 0 : continue;
3015 :
3016 10 : OGREnvelope sSourceEnvelope;
3017 10 : poGeom->getEnvelope(&sSourceEnvelope);
3018 :
3019 : const double dfDstXOff = std::max<double>(
3020 10 : nXOff, (sSourceEnvelope.MinX - m_poDS->m_gt[GT_TOPLEFT_X]) /
3021 10 : m_poDS->m_gt[GT_WE_RES]);
3022 : const double dfDstXOff2 =
3023 30 : std::min<double>(nXOff + nXSize, (sSourceEnvelope.MaxX -
3024 10 : m_poDS->m_gt[GT_TOPLEFT_X]) /
3025 10 : m_poDS->m_gt[GT_WE_RES]);
3026 : const double dfDstYOff = std::max<double>(
3027 10 : nYOff, (sSourceEnvelope.MaxY - m_poDS->m_gt[GT_TOPLEFT_Y]) /
3028 10 : m_poDS->m_gt[GT_NS_RES]);
3029 : const double dfDstYOff2 =
3030 30 : std::min<double>(nYOff + nYSize, (sSourceEnvelope.MinY -
3031 10 : m_poDS->m_gt[GT_TOPLEFT_Y]) /
3032 10 : m_poDS->m_gt[GT_NS_RES]);
3033 :
3034 : // CPLDebug("GTI", "dfDstXOff=%f, dfDstXOff2=%f, dfDstYOff=%f, dfDstYOff2=%f",
3035 : // dfDstXOff, dfDstXOff2, dfDstYOff, dfDstXOff2);
3036 :
3037 : // Check if the AOI is fully inside the source
3038 10 : if (nXOff >= dfDstXOff && nYOff >= dfDstYOff &&
3039 7 : nXOff + nXSize <= dfDstXOff2 && nYOff + nYSize <= dfDstYOff2)
3040 : {
3041 4 : if (pdfDataPct)
3042 4 : *pdfDataPct = 100.0;
3043 4 : return GDAL_DATA_COVERAGE_STATUS_DATA;
3044 : }
3045 :
3046 : // Check intersection of bounding boxes.
3047 6 : if (dfDstXOff2 > nXOff && dfDstYOff2 > nYOff &&
3048 6 : dfDstXOff < nXOff + nXSize && dfDstYOff < nYOff + nYSize)
3049 : {
3050 6 : nStatus |= GDAL_DATA_COVERAGE_STATUS_DATA;
3051 6 : if (poPolyNonCoveredBySources)
3052 : {
3053 6 : OGRPolygon oPolySource;
3054 6 : auto poLR = std::make_unique<OGRLinearRing>();
3055 6 : poLR->addPoint(dfDstXOff, dfDstYOff);
3056 6 : poLR->addPoint(dfDstXOff, dfDstYOff2);
3057 6 : poLR->addPoint(dfDstXOff2, dfDstYOff2);
3058 6 : poLR->addPoint(dfDstXOff2, dfDstYOff);
3059 6 : poLR->addPoint(dfDstXOff, dfDstYOff);
3060 6 : oPolySource.addRingDirectly(poLR.release());
3061 : auto poRes = std::unique_ptr<OGRGeometry>(
3062 6 : poPolyNonCoveredBySources->Difference(&oPolySource));
3063 6 : if (poRes && poRes->IsEmpty())
3064 : {
3065 2 : if (pdfDataPct)
3066 2 : *pdfDataPct = 100.0;
3067 2 : return GDAL_DATA_COVERAGE_STATUS_DATA;
3068 : }
3069 4 : else if (poRes && poRes->getGeometryType() == wkbPolygon)
3070 : {
3071 4 : poPolyNonCoveredBySources.reset(
3072 : poRes.release()->toPolygon());
3073 : }
3074 : else
3075 : {
3076 0 : poPolyNonCoveredBySources.reset();
3077 : }
3078 : }
3079 : }
3080 4 : if (nMaskFlagStop != 0 && (nStatus & nMaskFlagStop) != 0)
3081 : {
3082 0 : if (poSQLLayer)
3083 0 : m_poDS->ReleaseResultSet(poSQLLayer);
3084 0 : return nStatus;
3085 : }
3086 4 : }
3087 :
3088 2 : if (poSQLLayer)
3089 0 : m_poDS->ReleaseResultSet(poSQLLayer);
3090 :
3091 2 : if (poPolyNonCoveredBySources)
3092 : {
3093 2 : if (!poPolyNonCoveredBySources->IsEmpty())
3094 2 : nStatus |= GDAL_DATA_COVERAGE_STATUS_EMPTY;
3095 2 : if (pdfDataPct)
3096 2 : *pdfDataPct = 100.0 * (1.0 - poPolyNonCoveredBySources->get_Area() /
3097 2 : nXSize / nYSize);
3098 : }
3099 2 : return nStatus;
3100 : }
3101 : #endif // HAVE_GEOS
3102 :
3103 : /************************************************************************/
3104 : /* GetMetadataDomainList() */
3105 : /************************************************************************/
3106 :
3107 1 : char **GDALTileIndexBand::GetMetadataDomainList()
3108 : {
3109 1 : return CSLAddString(GDALRasterBand::GetMetadataDomainList(),
3110 1 : "LocationInfo");
3111 : }
3112 :
3113 : /************************************************************************/
3114 : /* GetMetadataItem() */
3115 : /************************************************************************/
3116 :
3117 44 : const char *GDALTileIndexBand::GetMetadataItem(const char *pszName,
3118 : const char *pszDomain)
3119 :
3120 : {
3121 : /* ==================================================================== */
3122 : /* LocationInfo handling. */
3123 : /* ==================================================================== */
3124 44 : if (pszDomain != nullptr && EQUAL(pszDomain, "LocationInfo") &&
3125 19 : (STARTS_WITH_CI(pszName, "Pixel_") ||
3126 6 : STARTS_WITH_CI(pszName, "GeoPixel_")))
3127 : {
3128 : // What pixel are we aiming at?
3129 18 : int iPixel = 0;
3130 18 : int iLine = 0;
3131 :
3132 18 : if (STARTS_WITH_CI(pszName, "Pixel_"))
3133 : {
3134 13 : pszName += strlen("Pixel_");
3135 13 : iPixel = atoi(pszName);
3136 13 : const char *const pszUnderscore = strchr(pszName, '_');
3137 13 : if (!pszUnderscore)
3138 2 : return nullptr;
3139 11 : iLine = atoi(pszUnderscore + 1);
3140 : }
3141 5 : else if (STARTS_WITH_CI(pszName, "GeoPixel_"))
3142 : {
3143 5 : pszName += strlen("GeoPixel_");
3144 5 : const double dfGeoX = CPLAtof(pszName);
3145 5 : const char *const pszUnderscore = strchr(pszName, '_');
3146 5 : if (!pszUnderscore)
3147 2 : return nullptr;
3148 3 : const double dfGeoY = CPLAtof(pszUnderscore + 1);
3149 :
3150 3 : double adfInvGeoTransform[6] = {0.0};
3151 3 : if (!GDALInvGeoTransform(m_poDS->m_gt.data(), adfInvGeoTransform))
3152 0 : return nullptr;
3153 :
3154 3 : iPixel = static_cast<int>(floor(adfInvGeoTransform[0] +
3155 3 : adfInvGeoTransform[1] * dfGeoX +
3156 3 : adfInvGeoTransform[2] * dfGeoY));
3157 3 : iLine = static_cast<int>(floor(adfInvGeoTransform[3] +
3158 3 : adfInvGeoTransform[4] * dfGeoX +
3159 3 : adfInvGeoTransform[5] * dfGeoY));
3160 : }
3161 : else
3162 : {
3163 0 : return nullptr;
3164 : }
3165 :
3166 23 : if (iPixel < 0 || iLine < 0 || iPixel >= GetXSize() ||
3167 9 : iLine >= GetYSize())
3168 6 : return nullptr;
3169 :
3170 8 : if (!m_poDS->CollectSources(iPixel, iLine, 1, 1,
3171 : /* bMultiThreadAllowed = */ false))
3172 0 : return nullptr;
3173 :
3174 : // Format into XML.
3175 8 : m_osLastLocationInfo = "<LocationInfo>";
3176 :
3177 8 : if (!m_poDS->m_aoSourceDesc.empty())
3178 : {
3179 : const auto AddSource =
3180 6 : [&](const GDALTileIndexDataset::SourceDesc &oSourceDesc)
3181 : {
3182 6 : m_osLastLocationInfo += "<File>";
3183 : char *const pszXMLEscaped =
3184 6 : CPLEscapeString(oSourceDesc.osName.c_str(), -1, CPLES_XML);
3185 6 : m_osLastLocationInfo += pszXMLEscaped;
3186 6 : CPLFree(pszXMLEscaped);
3187 6 : m_osLastLocationInfo += "</File>";
3188 11 : };
3189 :
3190 5 : const int anBand[] = {nBand};
3191 5 : if (!m_poDS->NeedInitBuffer(1, anBand))
3192 : {
3193 4 : AddSource(m_poDS->m_aoSourceDesc.back());
3194 : }
3195 : else
3196 : {
3197 3 : for (const auto &oSourceDesc : m_poDS->m_aoSourceDesc)
3198 : {
3199 2 : if (oSourceDesc.poDS)
3200 2 : AddSource(oSourceDesc);
3201 : }
3202 : }
3203 : }
3204 :
3205 8 : m_osLastLocationInfo += "</LocationInfo>";
3206 :
3207 8 : return m_osLastLocationInfo.c_str();
3208 : }
3209 :
3210 26 : return GDALPamRasterBand::GetMetadataItem(pszName, pszDomain);
3211 : }
3212 :
3213 : /************************************************************************/
3214 : /* SetMetadataItem() */
3215 : /************************************************************************/
3216 :
3217 13 : CPLErr GDALTileIndexBand::SetMetadataItem(const char *pszName,
3218 : const char *pszValue,
3219 : const char *pszDomain)
3220 : {
3221 13 : if (nBand > 0 && m_poDS->m_bXMLUpdatable)
3222 : {
3223 1 : m_poDS->m_bXMLModified = true;
3224 1 : return GDALRasterBand::SetMetadataItem(pszName, pszValue, pszDomain);
3225 : }
3226 12 : else if (nBand > 0 && m_poDS->TileIndexSupportsEditingLayerMetadata())
3227 : {
3228 6 : m_poDS->m_poLayer->SetMetadataItem(
3229 6 : CPLSPrintf("BAND_%d_%s", nBand, pszName), pszValue, pszDomain);
3230 6 : return GDALRasterBand::SetMetadataItem(pszName, pszValue, pszDomain);
3231 : }
3232 : else
3233 : {
3234 6 : return GDALPamRasterBand::SetMetadataItem(pszName, pszValue, pszDomain);
3235 : }
3236 : }
3237 :
3238 : /************************************************************************/
3239 : /* SetMetadata() */
3240 : /************************************************************************/
3241 :
3242 2 : CPLErr GDALTileIndexBand::SetMetadata(char **papszMD, const char *pszDomain)
3243 : {
3244 2 : if (nBand > 0 && m_poDS->m_bXMLUpdatable)
3245 : {
3246 1 : m_poDS->m_bXMLModified = true;
3247 1 : return GDALRasterBand::SetMetadata(papszMD, pszDomain);
3248 : }
3249 1 : else if (nBand > 0 && m_poDS->TileIndexSupportsEditingLayerMetadata())
3250 : {
3251 2 : CPLStringList aosMD;
3252 :
3253 1 : if (!pszDomain || pszDomain[0] == 0)
3254 : {
3255 : // Reinject dataset metadata
3256 1 : char **papszLayerMD = m_poDS->m_poLayer->GetMetadata(pszDomain);
3257 14 : for (const char *const *papszIter = papszLayerMD;
3258 14 : papszIter && *papszIter; ++papszIter)
3259 : {
3260 13 : if (!STARTS_WITH(*papszIter, "BAND_") ||
3261 12 : STARTS_WITH(*papszIter, MD_BAND_COUNT))
3262 1 : aosMD.AddString(*papszIter);
3263 : }
3264 : }
3265 :
3266 8 : for (int i = 0; papszMD && papszMD[i]; ++i)
3267 : {
3268 7 : aosMD.AddString(CPLSPrintf("BAND_%d_%s", nBand, papszMD[i]));
3269 : }
3270 :
3271 1 : if (!pszDomain || pszDomain[0] == 0)
3272 : {
3273 4 : for (const char *pszItem : apszReservedBandItems)
3274 : {
3275 3 : const char *pszKey = CPLSPrintf("BAND_%d_%s", nBand, pszItem);
3276 3 : if (!aosMD.FetchNameValue(pszKey))
3277 : {
3278 3 : if (const char *pszVal =
3279 3 : m_poDS->m_poLayer->GetMetadataItem(pszKey))
3280 : {
3281 3 : aosMD.SetNameValue(pszKey, pszVal);
3282 : }
3283 : }
3284 : }
3285 : }
3286 :
3287 1 : m_poDS->m_poLayer->SetMetadata(aosMD.List(), pszDomain);
3288 1 : return GDALRasterBand::SetMetadata(papszMD, pszDomain);
3289 : }
3290 : else
3291 : {
3292 0 : return GDALPamRasterBand::SetMetadata(papszMD, pszDomain);
3293 : }
3294 : }
3295 :
3296 : /************************************************************************/
3297 : /* GetSrcDstWin() */
3298 : /************************************************************************/
3299 :
3300 358 : static bool GetSrcDstWin(const GDALGeoTransform &tileGT, int nTileXSize,
3301 : int nTileYSize, const GDALGeoTransform &vrtGT,
3302 : int nVRTXSize, int nVRTYSize, double *pdfSrcXOff,
3303 : double *pdfSrcYOff, double *pdfSrcXSize,
3304 : double *pdfSrcYSize, double *pdfDstXOff,
3305 : double *pdfDstYOff, double *pdfDstXSize,
3306 : double *pdfDstYSize)
3307 : {
3308 358 : const double minX = vrtGT[GT_TOPLEFT_X];
3309 358 : const double we_res = vrtGT[GT_WE_RES];
3310 358 : const double maxX = minX + nVRTXSize * we_res;
3311 358 : const double maxY = vrtGT[GT_TOPLEFT_Y];
3312 358 : const double ns_res = vrtGT[GT_NS_RES];
3313 358 : const double minY = maxY + nVRTYSize * ns_res;
3314 :
3315 : /* Check that the destination bounding box intersects the source bounding
3316 : * box */
3317 358 : if (tileGT[GT_TOPLEFT_X] + nTileXSize * tileGT[GT_WE_RES] <= minX)
3318 0 : return false;
3319 358 : if (tileGT[GT_TOPLEFT_X] >= maxX)
3320 1 : return false;
3321 357 : if (tileGT[GT_TOPLEFT_Y] + nTileYSize * tileGT[GT_NS_RES] >= maxY)
3322 0 : return false;
3323 357 : if (tileGT[GT_TOPLEFT_Y] <= minY)
3324 0 : return false;
3325 :
3326 357 : if (tileGT[GT_TOPLEFT_X] < minX)
3327 : {
3328 1 : *pdfSrcXOff = (minX - tileGT[GT_TOPLEFT_X]) / tileGT[GT_WE_RES];
3329 1 : *pdfDstXOff = 0.0;
3330 : }
3331 : else
3332 : {
3333 356 : *pdfSrcXOff = 0.0;
3334 356 : *pdfDstXOff = ((tileGT[GT_TOPLEFT_X] - minX) / we_res);
3335 : }
3336 357 : if (maxY < tileGT[GT_TOPLEFT_Y])
3337 : {
3338 1 : *pdfSrcYOff = (tileGT[GT_TOPLEFT_Y] - maxY) / -tileGT[GT_NS_RES];
3339 1 : *pdfDstYOff = 0.0;
3340 : }
3341 : else
3342 : {
3343 356 : *pdfSrcYOff = 0.0;
3344 356 : *pdfDstYOff = ((maxY - tileGT[GT_TOPLEFT_Y]) / -ns_res);
3345 : }
3346 :
3347 357 : *pdfSrcXSize = nTileXSize;
3348 357 : *pdfSrcYSize = nTileYSize;
3349 357 : if (*pdfSrcXOff > 0)
3350 1 : *pdfSrcXSize -= *pdfSrcXOff;
3351 357 : if (*pdfSrcYOff > 0)
3352 1 : *pdfSrcYSize -= *pdfSrcYOff;
3353 :
3354 357 : const double dfSrcToDstXSize = tileGT[GT_WE_RES] / we_res;
3355 357 : *pdfDstXSize = *pdfSrcXSize * dfSrcToDstXSize;
3356 357 : const double dfSrcToDstYSize = tileGT[GT_NS_RES] / ns_res;
3357 357 : *pdfDstYSize = *pdfSrcYSize * dfSrcToDstYSize;
3358 :
3359 357 : if (*pdfDstXOff + *pdfDstXSize > nVRTXSize)
3360 : {
3361 3 : *pdfDstXSize = nVRTXSize - *pdfDstXOff;
3362 3 : *pdfSrcXSize = *pdfDstXSize / dfSrcToDstXSize;
3363 : }
3364 :
3365 357 : if (*pdfDstYOff + *pdfDstYSize > nVRTYSize)
3366 : {
3367 1 : *pdfDstYSize = nVRTYSize - *pdfDstYOff;
3368 1 : *pdfSrcYSize = *pdfDstYSize / dfSrcToDstYSize;
3369 : }
3370 :
3371 714 : return *pdfSrcXSize > 0 && *pdfDstXSize > 0 && *pdfSrcYSize > 0 &&
3372 714 : *pdfDstYSize > 0;
3373 : }
3374 :
3375 : /************************************************************************/
3376 : /* GDALDatasetCastToGTIDataset() */
3377 : /************************************************************************/
3378 :
3379 3 : GDALTileIndexDataset *GDALDatasetCastToGTIDataset(GDALDataset *poDS)
3380 : {
3381 3 : return dynamic_cast<GDALTileIndexDataset *>(poDS);
3382 : }
3383 :
3384 : /************************************************************************/
3385 : /* GTIGetSourcesMoreRecentThan() */
3386 : /************************************************************************/
3387 :
3388 : std::vector<GTISourceDesc>
3389 2 : GTIGetSourcesMoreRecentThan(GDALTileIndexDataset *poDS, int64_t mTime)
3390 : {
3391 2 : return poDS->GetSourcesMoreRecentThan(mTime);
3392 : }
3393 :
3394 : /************************************************************************/
3395 : /* GetSourcesMoreRecentThan() */
3396 : /************************************************************************/
3397 :
3398 : std::vector<GTISourceDesc>
3399 2 : GDALTileIndexDataset::GetSourcesMoreRecentThan(int64_t mTime)
3400 : {
3401 2 : std::vector<GTISourceDesc> oRes;
3402 :
3403 2 : m_poLayer->SetSpatialFilter(nullptr);
3404 6 : for (auto &&poFeature : m_poLayer)
3405 : {
3406 4 : if (!poFeature->IsFieldSetAndNotNull(m_nLocationFieldIndex))
3407 : {
3408 2 : continue;
3409 : }
3410 :
3411 4 : auto poGeom = poFeature->GetGeometryRef();
3412 4 : if (!poGeom || poGeom->IsEmpty())
3413 0 : continue;
3414 :
3415 4 : OGREnvelope sEnvelope;
3416 4 : poGeom->getEnvelope(&sEnvelope);
3417 :
3418 4 : double dfXOff = (sEnvelope.MinX - m_gt[GT_TOPLEFT_X]) / m_gt[GT_WE_RES];
3419 4 : if (dfXOff >= nRasterXSize)
3420 0 : continue;
3421 :
3422 4 : double dfYOff = (sEnvelope.MaxY - m_gt[GT_TOPLEFT_Y]) / m_gt[GT_NS_RES];
3423 4 : if (dfYOff >= nRasterYSize)
3424 0 : continue;
3425 :
3426 4 : double dfXSize = (sEnvelope.MaxX - sEnvelope.MinX) / m_gt[GT_WE_RES];
3427 4 : if (dfXOff < 0)
3428 : {
3429 0 : dfXSize += dfXOff;
3430 0 : dfXOff = 0;
3431 0 : if (dfXSize <= 0)
3432 0 : continue;
3433 : }
3434 :
3435 : double dfYSize =
3436 4 : (sEnvelope.MaxY - sEnvelope.MinY) / std::fabs(m_gt[GT_NS_RES]);
3437 4 : if (dfYOff < 0)
3438 : {
3439 0 : dfYSize += dfYOff;
3440 0 : dfYOff = 0;
3441 0 : if (dfYSize <= 0)
3442 0 : continue;
3443 : }
3444 :
3445 : const char *pszTileName =
3446 4 : poFeature->GetFieldAsString(m_nLocationFieldIndex);
3447 : std::string osTileName(
3448 4 : GetAbsoluteFileName(pszTileName, GetDescription()));
3449 : VSIStatBufL sStatSource;
3450 8 : if (VSIStatL(osTileName.c_str(), &sStatSource) != 0 ||
3451 4 : sStatSource.st_mtime <= mTime)
3452 : {
3453 2 : continue;
3454 : }
3455 :
3456 2 : constexpr double EPS = 1e-8;
3457 4 : GTISourceDesc oSourceDesc;
3458 2 : oSourceDesc.osFilename = std::move(osTileName);
3459 2 : oSourceDesc.nDstXOff = static_cast<int>(dfXOff + EPS);
3460 2 : oSourceDesc.nDstYOff = static_cast<int>(dfYOff + EPS);
3461 2 : oSourceDesc.nDstXSize = static_cast<int>(dfXSize + 0.5);
3462 2 : oSourceDesc.nDstYSize = static_cast<int>(dfYSize + 0.5);
3463 2 : oRes.emplace_back(std::move(oSourceDesc));
3464 : }
3465 :
3466 2 : return oRes;
3467 : }
3468 :
3469 : /************************************************************************/
3470 : /* GetSourceDesc() */
3471 : /************************************************************************/
3472 :
3473 361 : bool GDALTileIndexDataset::GetSourceDesc(const std::string &osTileName,
3474 : SourceDesc &oSourceDesc,
3475 : std::mutex *pMutex)
3476 : {
3477 361 : std::shared_ptr<GDALDataset> poTileDS;
3478 :
3479 361 : if (pMutex)
3480 138 : pMutex->lock();
3481 361 : const bool bTileKnown = m_oMapSharedSources.tryGet(osTileName, poTileDS);
3482 361 : if (pMutex)
3483 138 : pMutex->unlock();
3484 :
3485 361 : if (!bTileKnown)
3486 : {
3487 470 : poTileDS = std::shared_ptr<GDALDataset>(
3488 : GDALProxyPoolDataset::Create(
3489 : osTileName.c_str(), nullptr, GA_ReadOnly,
3490 : /* bShared = */ true, m_osUniqueHandle.c_str()),
3491 235 : GDALDatasetUniquePtrReleaser());
3492 235 : if (!poTileDS)
3493 : {
3494 3 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot open source %s",
3495 : osTileName.c_str());
3496 3 : return false;
3497 : }
3498 232 : if (poTileDS->GetRasterCount() == 0)
3499 : {
3500 0 : CPLError(CE_Failure, CPLE_AppDefined,
3501 : "Source %s has no raster bands", osTileName.c_str());
3502 0 : return false;
3503 : }
3504 :
3505 : // do palette -> RGB(A) expansion if needed
3506 232 : if (!GTIDoPaletteExpansionIfNeeded(poTileDS, nBands))
3507 0 : return false;
3508 :
3509 232 : bool bWarpVRT = false;
3510 232 : bool bExportSRS = false;
3511 232 : bool bAddAlphaToVRT = false;
3512 232 : const OGRSpatialReference *poTileSRS = poTileDS->GetSpatialRef();
3513 232 : GDALGeoTransform tileGT;
3514 402 : if (!m_oSRS.IsEmpty() && poTileSRS != nullptr &&
3515 171 : !m_oSRS.IsSame(poTileSRS))
3516 : {
3517 2 : CPLDebug("VRT",
3518 : "Tile %s has not the same SRS as the VRT. "
3519 : "Proceed to on-the-fly warping",
3520 : osTileName.c_str());
3521 2 : bWarpVRT = true;
3522 2 : bExportSRS = true;
3523 2 : bAddAlphaToVRT = true;
3524 : }
3525 229 : else if (poTileDS->GetGeoTransform(tileGT) == CE_None &&
3526 230 : tileGT[GT_NS_RES] > 0 &&
3527 1 : ((m_oSRS.IsEmpty() && poTileSRS == nullptr) ||
3528 0 : (!m_oSRS.IsEmpty() && poTileSRS && m_oSRS.IsSame(poTileSRS))))
3529 :
3530 : {
3531 1 : CPLDebug("VRT",
3532 : "Tile %s is south-up oriented. "
3533 : "Proceed to on-the-fly warping",
3534 : osTileName.c_str());
3535 1 : bWarpVRT = true;
3536 : }
3537 :
3538 230 : if (bWarpVRT)
3539 : {
3540 3 : CPLStringList aosOptions;
3541 3 : aosOptions.AddString("-of");
3542 3 : aosOptions.AddString("VRT");
3543 :
3544 3 : if ((poTileDS->GetRasterBand(1)->GetColorTable() == nullptr &&
3545 3 : poTileDS->GetRasterBand(1)->GetCategoryNames() == nullptr) ||
3546 0 : m_eResampling == GRIORA_Mode)
3547 : {
3548 3 : aosOptions.AddString("-r");
3549 3 : aosOptions.AddString(m_osResampling.c_str());
3550 : }
3551 :
3552 3 : if (bExportSRS)
3553 : {
3554 2 : if (m_osWKT.empty())
3555 : {
3556 0 : char *pszWKT = nullptr;
3557 0 : const char *const apszWKTOptions[] = {"FORMAT=WKT2_2019",
3558 : nullptr};
3559 0 : m_oSRS.exportToWkt(&pszWKT, apszWKTOptions);
3560 0 : if (pszWKT)
3561 0 : m_osWKT = pszWKT;
3562 0 : CPLFree(pszWKT);
3563 :
3564 0 : if (m_osWKT.empty())
3565 : {
3566 0 : CPLError(CE_Failure, CPLE_AppDefined,
3567 : "Cannot export VRT SRS to WKT2");
3568 0 : return false;
3569 : }
3570 : }
3571 :
3572 2 : aosOptions.AddString("-t_srs");
3573 2 : aosOptions.AddString(m_osWKT.c_str());
3574 : }
3575 :
3576 : // First pass to get the extent of the tile in the
3577 : // target VRT SRS
3578 : GDALWarpAppOptions *psWarpOptions =
3579 3 : GDALWarpAppOptionsNew(aosOptions.List(), nullptr);
3580 3 : GDALDatasetH ahSrcDS[] = {GDALDataset::ToHandle(poTileDS.get())};
3581 3 : int bUsageError = false;
3582 : auto poWarpDS =
3583 : std::unique_ptr<GDALDataset>(GDALDataset::FromHandle(GDALWarp(
3584 3 : "", nullptr, 1, ahSrcDS, psWarpOptions, &bUsageError)));
3585 3 : GDALWarpAppOptionsFree(psWarpOptions);
3586 3 : if (!poWarpDS)
3587 : {
3588 0 : return false;
3589 : }
3590 :
3591 : // Second pass to create a warped source VRT whose
3592 : // extent is aligned on the one of the target VRT
3593 3 : GDALGeoTransform warpDSGT;
3594 3 : const auto eErr = poWarpDS->GetGeoTransform(warpDSGT);
3595 3 : CPL_IGNORE_RET_VAL(eErr);
3596 3 : CPLAssert(eErr == CE_None);
3597 3 : const double dfVRTMinX = m_gt[GT_TOPLEFT_X];
3598 3 : const double dfVRTResX = m_gt[GT_WE_RES];
3599 3 : const double dfVRTMaxY = m_gt[GT_TOPLEFT_Y];
3600 3 : const double dfVRTResYAbs = -m_gt[GT_NS_RES];
3601 : const double dfWarpMinX =
3602 3 : std::floor((warpDSGT[GT_TOPLEFT_X] - dfVRTMinX) / dfVRTResX) *
3603 : dfVRTResX +
3604 3 : dfVRTMinX;
3605 : const double dfWarpMaxX =
3606 3 : std::ceil((warpDSGT[GT_TOPLEFT_X] +
3607 3 : warpDSGT[GT_WE_RES] * poWarpDS->GetRasterXSize() -
3608 : dfVRTMinX) /
3609 3 : dfVRTResX) *
3610 : dfVRTResX +
3611 3 : dfVRTMinX;
3612 : const double dfWarpMaxY =
3613 3 : dfVRTMaxY - std::floor((dfVRTMaxY - warpDSGT[GT_TOPLEFT_Y]) /
3614 3 : dfVRTResYAbs) *
3615 3 : dfVRTResYAbs;
3616 : const double dfWarpMinY =
3617 : dfVRTMaxY -
3618 3 : std::ceil((dfVRTMaxY -
3619 3 : (warpDSGT[GT_TOPLEFT_Y] +
3620 3 : warpDSGT[GT_NS_RES] * poWarpDS->GetRasterYSize())) /
3621 3 : dfVRTResYAbs) *
3622 3 : dfVRTResYAbs;
3623 :
3624 3 : aosOptions.AddString("-te");
3625 3 : aosOptions.AddString(CPLSPrintf("%.17g", dfWarpMinX));
3626 3 : aosOptions.AddString(CPLSPrintf("%.17g", dfWarpMinY));
3627 3 : aosOptions.AddString(CPLSPrintf("%.17g", dfWarpMaxX));
3628 3 : aosOptions.AddString(CPLSPrintf("%.17g", dfWarpMaxY));
3629 :
3630 3 : aosOptions.AddString("-tr");
3631 3 : aosOptions.AddString(CPLSPrintf("%.17g", dfVRTResX));
3632 3 : aosOptions.AddString(CPLSPrintf("%.17g", dfVRTResYAbs));
3633 :
3634 3 : if (bAddAlphaToVRT)
3635 2 : aosOptions.AddString("-dstalpha");
3636 :
3637 3 : psWarpOptions = GDALWarpAppOptionsNew(aosOptions.List(), nullptr);
3638 3 : poWarpDS.reset(GDALDataset::FromHandle(GDALWarp(
3639 : "", nullptr, 1, ahSrcDS, psWarpOptions, &bUsageError)));
3640 3 : GDALWarpAppOptionsFree(psWarpOptions);
3641 3 : if (!poWarpDS)
3642 : {
3643 0 : return false;
3644 : }
3645 :
3646 3 : poTileDS.reset(poWarpDS.release());
3647 : }
3648 :
3649 230 : if (pMutex)
3650 68 : pMutex->lock();
3651 232 : m_oMapSharedSources.insert(osTileName, poTileDS);
3652 232 : if (pMutex)
3653 70 : pMutex->unlock();
3654 : }
3655 :
3656 358 : GDALGeoTransform gtTile;
3657 358 : if (poTileDS->GetGeoTransform(gtTile) != CE_None)
3658 : {
3659 0 : CPLError(CE_Failure, CPLE_AppDefined, "%s lacks geotransform",
3660 : osTileName.c_str());
3661 0 : return false;
3662 : }
3663 :
3664 358 : bool bHasNoData = false;
3665 358 : bool bSameNoData = true;
3666 358 : double dfNoDataValue = 0;
3667 358 : GDALRasterBand *poMaskBand = nullptr;
3668 358 : const int nBandCount = poTileDS->GetRasterCount();
3669 1233 : for (int iBand = 0; iBand < nBandCount; ++iBand)
3670 : {
3671 875 : auto poTileBand = poTileDS->GetRasterBand(iBand + 1);
3672 875 : int bThisBandHasNoData = false;
3673 : const double dfThisBandNoDataValue =
3674 875 : poTileBand->GetNoDataValue(&bThisBandHasNoData);
3675 875 : if (bThisBandHasNoData)
3676 : {
3677 22 : bHasNoData = true;
3678 22 : dfNoDataValue = dfThisBandNoDataValue;
3679 : }
3680 1392 : if (iBand > 0 &&
3681 517 : (static_cast<int>(bThisBandHasNoData) !=
3682 517 : static_cast<int>(bHasNoData) ||
3683 12 : (bHasNoData &&
3684 12 : !IsSameNaNAware(dfNoDataValue, dfThisBandNoDataValue))))
3685 : {
3686 0 : bSameNoData = false;
3687 : }
3688 :
3689 875 : if (poTileBand->GetMaskFlags() == GMF_PER_DATASET)
3690 2 : poMaskBand = poTileBand->GetMaskBand();
3691 873 : else if (poTileBand->GetColorInterpretation() == GCI_AlphaBand)
3692 31 : poMaskBand = poTileBand;
3693 : }
3694 :
3695 0 : std::unique_ptr<VRTSimpleSource> poSource;
3696 358 : if (!bHasNoData)
3697 : {
3698 348 : poSource = std::make_unique<VRTSimpleSource>();
3699 : }
3700 : else
3701 : {
3702 20 : auto poComplexSource = std::make_unique<VRTComplexSource>();
3703 10 : poComplexSource->SetNoDataValue(dfNoDataValue);
3704 10 : poSource = std::move(poComplexSource);
3705 : }
3706 :
3707 716 : GetSrcDstWin(gtTile, poTileDS->GetRasterXSize(), poTileDS->GetRasterYSize(),
3708 358 : m_gt, GetRasterXSize(), GetRasterYSize(),
3709 358 : &poSource->m_dfSrcXOff, &poSource->m_dfSrcYOff,
3710 358 : &poSource->m_dfSrcXSize, &poSource->m_dfSrcYSize,
3711 358 : &poSource->m_dfDstXOff, &poSource->m_dfDstYOff,
3712 358 : &poSource->m_dfDstXSize, &poSource->m_dfDstYSize);
3713 :
3714 358 : oSourceDesc.osName = osTileName;
3715 358 : oSourceDesc.poDS = std::move(poTileDS);
3716 358 : oSourceDesc.poSource = std::move(poSource);
3717 358 : oSourceDesc.bHasNoData = bHasNoData;
3718 358 : oSourceDesc.bSameNoData = bSameNoData;
3719 358 : if (bSameNoData)
3720 358 : oSourceDesc.dfSameNoData = dfNoDataValue;
3721 358 : oSourceDesc.poMaskBand = poMaskBand;
3722 358 : return true;
3723 : }
3724 :
3725 : /************************************************************************/
3726 : /* GetNumThreads() */
3727 : /************************************************************************/
3728 :
3729 8 : int GDALTileIndexDataset::GetNumThreads() const
3730 : {
3731 : const char *pszNumThreads =
3732 8 : CSLFetchNameValueDef(GetOpenOptions(), "NUM_THREADS", nullptr);
3733 8 : if (!pszNumThreads)
3734 8 : pszNumThreads = CPLGetConfigOption("GTI_NUM_THREADS", nullptr);
3735 8 : if (!pszNumThreads)
3736 6 : pszNumThreads = CPLGetConfigOption("GDAL_NUM_THREADS", "ALL_CPUS");
3737 8 : if (EQUAL(pszNumThreads, "0") || EQUAL(pszNumThreads, "1"))
3738 3 : return atoi(pszNumThreads);
3739 5 : const int nMaxPoolSize = GDALGetMaxDatasetPoolSize();
3740 5 : const int nLimit = std::min(CPLGetNumCPUs(), nMaxPoolSize);
3741 5 : if (EQUAL(pszNumThreads, "ALL_CPUS"))
3742 5 : return nLimit;
3743 0 : return std::min(atoi(pszNumThreads), nLimit);
3744 : }
3745 :
3746 : /************************************************************************/
3747 : /* CollectSources() */
3748 : /************************************************************************/
3749 :
3750 189 : bool GDALTileIndexDataset::CollectSources(double dfXOff, double dfYOff,
3751 : double dfXSize, double dfYSize,
3752 : bool bMultiThreadAllowed)
3753 : {
3754 189 : const double dfMinX = m_gt[GT_TOPLEFT_X] + dfXOff * m_gt[GT_WE_RES];
3755 189 : const double dfMaxX = dfMinX + dfXSize * m_gt[GT_WE_RES];
3756 189 : const double dfMaxY = m_gt[GT_TOPLEFT_Y] + dfYOff * m_gt[GT_NS_RES];
3757 189 : const double dfMinY = dfMaxY + dfYSize * m_gt[GT_NS_RES];
3758 :
3759 189 : if (dfMinX == m_dfLastMinXFilter && dfMinY == m_dfLastMinYFilter &&
3760 57 : dfMaxX == m_dfLastMaxXFilter && dfMaxY == m_dfLastMaxYFilter)
3761 : {
3762 53 : return true;
3763 : }
3764 :
3765 136 : m_dfLastMinXFilter = dfMinX;
3766 136 : m_dfLastMinYFilter = dfMinY;
3767 136 : m_dfLastMaxXFilter = dfMaxX;
3768 136 : m_dfLastMaxYFilter = dfMaxY;
3769 136 : m_bLastMustUseMultiThreading = false;
3770 :
3771 136 : OGRLayer *poSQLLayer = nullptr;
3772 136 : if (!m_osSpatialSQL.empty())
3773 : {
3774 : const std::string osSQL =
3775 3 : CPLString(m_osSpatialSQL)
3776 6 : .replaceAll("{XMIN}", CPLSPrintf("%.17g", dfMinX))
3777 6 : .replaceAll("{YMIN}", CPLSPrintf("%.17g", dfMinY))
3778 6 : .replaceAll("{XMAX}", CPLSPrintf("%.17g", dfMaxX))
3779 6 : .replaceAll("{YMAX}", CPLSPrintf("%.17g", dfMaxY));
3780 3 : poSQLLayer = m_poVectorDS->ExecuteSQL(osSQL.c_str(), nullptr, nullptr);
3781 3 : if (!poSQLLayer)
3782 1 : return 0;
3783 : }
3784 : else
3785 : {
3786 133 : m_poLayer->SetSpatialFilterRect(dfMinX, dfMinY, dfMaxX, dfMaxY);
3787 133 : m_poLayer->ResetReading();
3788 : }
3789 :
3790 135 : OGRLayer *const poLayer = poSQLLayer ? poSQLLayer : m_poLayer;
3791 :
3792 135 : m_aoSourceDesc.clear();
3793 : while (true)
3794 : {
3795 463 : auto poFeature = std::unique_ptr<OGRFeature>(poLayer->GetNextFeature());
3796 463 : if (!poFeature)
3797 135 : break;
3798 328 : if (!poFeature->IsFieldSetAndNotNull(m_nLocationFieldIndex))
3799 : {
3800 1 : continue;
3801 : }
3802 :
3803 327 : SourceDesc oSourceDesc;
3804 327 : oSourceDesc.poFeature = std::move(poFeature);
3805 327 : m_aoSourceDesc.emplace_back(std::move(oSourceDesc));
3806 :
3807 327 : if (m_aoSourceDesc.size() > 10 * 1000 * 1000)
3808 : {
3809 : // Safety belt...
3810 0 : CPLError(CE_Failure, CPLE_AppDefined,
3811 : "More than 10 million contributing sources to a "
3812 : "single RasterIO() request is not supported");
3813 0 : return false;
3814 : }
3815 328 : }
3816 :
3817 135 : if (poSQLLayer)
3818 2 : ReleaseResultSet(poSQLLayer);
3819 :
3820 135 : constexpr int MINIMUM_PIXEL_COUNT_FOR_THREADED_IO = 1000 * 1000;
3821 204 : if (bMultiThreadAllowed && m_aoSourceDesc.size() > 1 &&
3822 69 : dfXSize * dfYSize > MINIMUM_PIXEL_COUNT_FOR_THREADED_IO)
3823 : {
3824 8 : if (m_nNumThreads < 0)
3825 8 : m_nNumThreads = GetNumThreads();
3826 8 : bMultiThreadAllowed = m_nNumThreads > 1;
3827 : }
3828 : else
3829 : {
3830 127 : bMultiThreadAllowed = false;
3831 : }
3832 :
3833 135 : if (bMultiThreadAllowed)
3834 : {
3835 : CPLRectObj sGlobalBounds;
3836 5 : sGlobalBounds.minx = dfXOff;
3837 5 : sGlobalBounds.miny = dfYOff;
3838 5 : sGlobalBounds.maxx = dfXOff + dfXSize;
3839 5 : sGlobalBounds.maxy = dfYOff + dfYSize;
3840 5 : CPLQuadTree *hQuadTree = CPLQuadTreeCreate(&sGlobalBounds, nullptr);
3841 :
3842 5 : bool bCompatibleOfMultiThread = true;
3843 5 : std::set<std::string> oSetTileNames;
3844 77 : for (const auto &oSourceDesc : m_aoSourceDesc)
3845 : {
3846 : const char *pszTileName =
3847 73 : oSourceDesc.poFeature->GetFieldAsString(m_nLocationFieldIndex);
3848 73 : if (oSetTileNames.find(pszTileName) != oSetTileNames.end())
3849 : {
3850 0 : bCompatibleOfMultiThread = false;
3851 1 : break;
3852 : }
3853 73 : oSetTileNames.insert(pszTileName);
3854 :
3855 73 : const auto poGeom = oSourceDesc.poFeature->GetGeometryRef();
3856 73 : if (!poGeom || poGeom->IsEmpty())
3857 0 : continue;
3858 :
3859 73 : OGREnvelope sEnvelope;
3860 73 : poGeom->getEnvelope(&sEnvelope);
3861 :
3862 : CPLRectObj sSourceBounds;
3863 73 : sSourceBounds.minx =
3864 73 : (sEnvelope.MinX - m_gt[GT_TOPLEFT_X]) / m_gt[GT_WE_RES];
3865 73 : sSourceBounds.maxx =
3866 73 : (sEnvelope.MaxX - m_gt[GT_TOPLEFT_X]) / m_gt[GT_WE_RES];
3867 : // Yes use of MaxY to compute miny is intended given that MaxY is
3868 : // in georeferenced space whereas miny is in pixel space.
3869 73 : sSourceBounds.miny =
3870 73 : (sEnvelope.MaxY - m_gt[GT_TOPLEFT_Y]) / m_gt[GT_NS_RES];
3871 : // Same here for maxy vs Miny
3872 73 : sSourceBounds.maxy =
3873 73 : (sEnvelope.MinY - m_gt[GT_TOPLEFT_Y]) / m_gt[GT_NS_RES];
3874 :
3875 : // Clamp to global bounds and some epsilon to avoid adjacent tiles
3876 : // to be considered as overlapping
3877 73 : constexpr double EPSILON = 0.1;
3878 73 : sSourceBounds.minx =
3879 73 : std::max(sGlobalBounds.minx, sSourceBounds.minx) + EPSILON;
3880 73 : sSourceBounds.maxx =
3881 73 : std::min(sGlobalBounds.maxx, sSourceBounds.maxx) - EPSILON;
3882 73 : sSourceBounds.miny =
3883 73 : std::max(sGlobalBounds.miny, sSourceBounds.miny) + EPSILON;
3884 73 : sSourceBounds.maxy =
3885 73 : std::min(sGlobalBounds.maxy, sSourceBounds.maxy) - EPSILON;
3886 :
3887 : // Check that the new source doesn't overlap an existing one.
3888 73 : if (CPLQuadTreeHasMatch(hQuadTree, &sSourceBounds))
3889 : {
3890 1 : bCompatibleOfMultiThread = false;
3891 1 : break;
3892 : }
3893 :
3894 72 : CPLQuadTreeInsertWithBounds(
3895 : hQuadTree,
3896 : const_cast<void *>(static_cast<const void *>(&oSourceDesc)),
3897 : &sSourceBounds);
3898 : }
3899 :
3900 5 : CPLQuadTreeDestroy(hQuadTree);
3901 :
3902 5 : if (bCompatibleOfMultiThread)
3903 : {
3904 4 : m_bLastMustUseMultiThreading = true;
3905 4 : return true;
3906 : }
3907 : }
3908 :
3909 131 : if (m_aoSourceDesc.size() > 1)
3910 : {
3911 66 : SortSourceDesc();
3912 : }
3913 :
3914 : // Try to find the last (most prioritary) fully opaque source covering
3915 : // the whole AOI. We only need to start rendering from it.
3916 131 : size_t i = m_aoSourceDesc.size();
3917 266 : while (i > 0)
3918 : {
3919 223 : --i;
3920 223 : auto &poFeature = m_aoSourceDesc[i].poFeature;
3921 : const char *pszTileName =
3922 223 : poFeature->GetFieldAsString(m_nLocationFieldIndex);
3923 : const std::string osTileName(
3924 223 : GetAbsoluteFileName(pszTileName, GetDescription()));
3925 :
3926 223 : SourceDesc oSourceDesc;
3927 223 : if (!GetSourceDesc(osTileName, oSourceDesc, nullptr))
3928 2 : return false;
3929 :
3930 : // Check consistency of bounding box in tile index vs actual
3931 : // extent of the tile.
3932 221 : GDALGeoTransform tileGT;
3933 221 : if (oSourceDesc.poDS->GetGeoTransform(tileGT) == CE_None &&
3934 221 : tileGT[GT_ROTATION_PARAM1] == 0 && tileGT[GT_ROTATION_PARAM2] == 0)
3935 : {
3936 221 : OGREnvelope sActualTileExtent;
3937 221 : sActualTileExtent.MinX = tileGT[GT_TOPLEFT_X];
3938 221 : sActualTileExtent.MaxX =
3939 442 : sActualTileExtent.MinX +
3940 221 : oSourceDesc.poDS->GetRasterXSize() * tileGT[GT_WE_RES];
3941 221 : sActualTileExtent.MaxY = tileGT[GT_TOPLEFT_Y];
3942 221 : sActualTileExtent.MinY =
3943 442 : sActualTileExtent.MaxY +
3944 221 : oSourceDesc.poDS->GetRasterYSize() * tileGT[GT_NS_RES];
3945 221 : const auto poGeom = poFeature->GetGeometryRef();
3946 221 : if (poGeom && !poGeom->IsEmpty())
3947 : {
3948 221 : OGREnvelope sGeomTileExtent;
3949 221 : poGeom->getEnvelope(&sGeomTileExtent);
3950 221 : sGeomTileExtent.MinX -= m_gt[GT_WE_RES];
3951 221 : sGeomTileExtent.MaxX += m_gt[GT_WE_RES];
3952 221 : sGeomTileExtent.MinY -= std::fabs(m_gt[GT_NS_RES]);
3953 221 : sGeomTileExtent.MaxY += std::fabs(m_gt[GT_NS_RES]);
3954 221 : if (!sGeomTileExtent.Contains(sActualTileExtent))
3955 : {
3956 2 : if (!sGeomTileExtent.Intersects(sActualTileExtent))
3957 : {
3958 1 : CPLError(CE_Warning, CPLE_AppDefined,
3959 : "Tile index is out of sync with actual "
3960 : "extent of %s. Bounding box from tile index "
3961 : "is (%g, %g, %g, %g) does not intersect at "
3962 : "all bounding box from tile (%g, %g, %g, %g)",
3963 : osTileName.c_str(), sGeomTileExtent.MinX,
3964 : sGeomTileExtent.MinY, sGeomTileExtent.MaxX,
3965 : sGeomTileExtent.MaxY, sActualTileExtent.MinX,
3966 : sActualTileExtent.MinY, sActualTileExtent.MaxX,
3967 : sActualTileExtent.MaxY);
3968 1 : continue;
3969 : }
3970 1 : CPLError(CE_Warning, CPLE_AppDefined,
3971 : "Tile index is out of sync with actual extent "
3972 : "of %s. Bounding box from tile index is (%g, %g, "
3973 : "%g, %g) does not fully contain bounding box from "
3974 : "tile (%g, %g, %g, %g)",
3975 : osTileName.c_str(), sGeomTileExtent.MinX,
3976 : sGeomTileExtent.MinY, sGeomTileExtent.MaxX,
3977 : sGeomTileExtent.MaxY, sActualTileExtent.MinX,
3978 : sActualTileExtent.MinY, sActualTileExtent.MaxX,
3979 : sActualTileExtent.MaxY);
3980 : }
3981 : }
3982 : }
3983 :
3984 220 : const auto &poSource = oSourceDesc.poSource;
3985 220 : if (dfXOff >= poSource->m_dfDstXOff + poSource->m_dfDstXSize ||
3986 220 : dfYOff >= poSource->m_dfDstYOff + poSource->m_dfDstYSize ||
3987 657 : poSource->m_dfDstXOff >= dfXOff + dfXSize ||
3988 217 : poSource->m_dfDstYOff >= dfYOff + dfYSize)
3989 : {
3990 : // Can happen as some spatial filters select slightly more features
3991 : // than strictly needed.
3992 3 : continue;
3993 : }
3994 :
3995 : const bool bCoversWholeAOI =
3996 217 : (poSource->m_dfDstXOff <= dfXOff &&
3997 140 : poSource->m_dfDstYOff <= dfYOff &&
3998 139 : poSource->m_dfDstXOff + poSource->m_dfDstXSize >=
3999 483 : dfXOff + dfXSize &&
4000 126 : poSource->m_dfDstYOff + poSource->m_dfDstYSize >=
4001 126 : dfYOff + dfYSize);
4002 217 : oSourceDesc.bCoversWholeAOI = bCoversWholeAOI;
4003 :
4004 217 : m_aoSourceDesc[i] = std::move(oSourceDesc);
4005 :
4006 217 : if (m_aoSourceDesc[i].bCoversWholeAOI &&
4007 217 : !m_aoSourceDesc[i].bHasNoData && !m_aoSourceDesc[i].poMaskBand)
4008 : {
4009 86 : break;
4010 : }
4011 : }
4012 :
4013 129 : if (i > 0)
4014 : {
4015 : // Remove sources that will not be rendered
4016 32 : m_aoSourceDesc.erase(m_aoSourceDesc.begin(),
4017 64 : m_aoSourceDesc.begin() + i);
4018 : }
4019 :
4020 : // Remove elements that have no dataset
4021 0 : m_aoSourceDesc.erase(std::remove_if(m_aoSourceDesc.begin(),
4022 : m_aoSourceDesc.end(),
4023 221 : [](const SourceDesc &desc)
4024 350 : { return desc.poDS == nullptr; }),
4025 258 : m_aoSourceDesc.end());
4026 :
4027 129 : return true;
4028 : }
4029 :
4030 : /************************************************************************/
4031 : /* SortSourceDesc() */
4032 : /************************************************************************/
4033 :
4034 66 : void GDALTileIndexDataset::SortSourceDesc()
4035 : {
4036 66 : const auto eFieldType = m_nSortFieldIndex >= 0
4037 66 : ? m_poLayer->GetLayerDefn()
4038 47 : ->GetFieldDefn(m_nSortFieldIndex)
4039 47 : ->GetType()
4040 66 : : OFTMaxType;
4041 66 : std::sort(
4042 : m_aoSourceDesc.begin(), m_aoSourceDesc.end(),
4043 1828 : [this, eFieldType](const SourceDesc &a, const SourceDesc &b)
4044 : {
4045 419 : const auto &poFeatureA = (m_bSortFieldAsc ? a : b).poFeature;
4046 419 : const auto &poFeatureB = (m_bSortFieldAsc ? b : a).poFeature;
4047 918 : if (m_nSortFieldIndex >= 0 &&
4048 499 : poFeatureA->IsFieldSetAndNotNull(m_nSortFieldIndex) &&
4049 80 : poFeatureB->IsFieldSetAndNotNull(m_nSortFieldIndex))
4050 : {
4051 80 : if (eFieldType == OFTString)
4052 : {
4053 : const int nCmp =
4054 5 : strcmp(poFeatureA->GetFieldAsString(m_nSortFieldIndex),
4055 : poFeatureB->GetFieldAsString(m_nSortFieldIndex));
4056 5 : if (nCmp < 0)
4057 1 : return true;
4058 4 : if (nCmp > 0)
4059 2 : return false;
4060 : }
4061 75 : else if (eFieldType == OFTInteger || eFieldType == OFTInteger64)
4062 : {
4063 : const auto nA =
4064 45 : poFeatureA->GetFieldAsInteger64(m_nSortFieldIndex);
4065 : const auto nB =
4066 45 : poFeatureB->GetFieldAsInteger64(m_nSortFieldIndex);
4067 45 : if (nA < nB)
4068 3 : return true;
4069 42 : if (nA > nB)
4070 42 : return false;
4071 : }
4072 30 : else if (eFieldType == OFTReal)
4073 : {
4074 : const auto dfA =
4075 3 : poFeatureA->GetFieldAsDouble(m_nSortFieldIndex);
4076 : const auto dfB =
4077 3 : poFeatureB->GetFieldAsDouble(m_nSortFieldIndex);
4078 3 : if (dfA < dfB)
4079 1 : return true;
4080 2 : if (dfA > dfB)
4081 2 : return false;
4082 : }
4083 27 : else if (eFieldType == OFTDate || eFieldType == OFTDateTime)
4084 : {
4085 : const auto poFieldA =
4086 27 : poFeatureA->GetRawFieldRef(m_nSortFieldIndex);
4087 : const auto poFieldB =
4088 27 : poFeatureB->GetRawFieldRef(m_nSortFieldIndex);
4089 :
4090 : #define COMPARE_DATE_COMPONENT(comp) \
4091 : do \
4092 : { \
4093 : if (poFieldA->Date.comp < poFieldB->Date.comp) \
4094 : return true; \
4095 : if (poFieldA->Date.comp > poFieldB->Date.comp) \
4096 : return false; \
4097 : } while (0)
4098 :
4099 27 : COMPARE_DATE_COMPONENT(Year);
4100 21 : COMPARE_DATE_COMPONENT(Month);
4101 15 : COMPARE_DATE_COMPONENT(Day);
4102 9 : COMPARE_DATE_COMPONENT(Hour);
4103 8 : COMPARE_DATE_COMPONENT(Minute);
4104 7 : COMPARE_DATE_COMPONENT(Second);
4105 : }
4106 : else
4107 : {
4108 0 : CPLAssert(false);
4109 : }
4110 : }
4111 347 : return poFeatureA->GetFID() < poFeatureB->GetFID();
4112 : });
4113 66 : }
4114 :
4115 : /************************************************************************/
4116 : /* CompositeSrcWithMaskIntoDest() */
4117 : /************************************************************************/
4118 :
4119 : static void
4120 66 : CompositeSrcWithMaskIntoDest(const int nOutXSize, const int nOutYSize,
4121 : const GDALDataType eBufType,
4122 : const int nBufTypeSize, const GSpacing nPixelSpace,
4123 : const GSpacing nLineSpace, const GByte *pabySrc,
4124 : const GByte *const pabyMask, GByte *const pabyDest)
4125 : {
4126 66 : size_t iMaskIdx = 0;
4127 66 : if (eBufType == GDT_Byte)
4128 : {
4129 : // Optimization for byte case
4130 136 : for (int iY = 0; iY < nOutYSize; iY++)
4131 : {
4132 86 : GByte *pabyDestLine =
4133 86 : pabyDest + static_cast<GPtrDiff_t>(iY * nLineSpace);
4134 86 : int iX = 0;
4135 : #ifdef USE_SSE2_OPTIM
4136 86 : if (nPixelSpace == 1)
4137 : {
4138 : // SSE2 version up to 6 times faster than portable version
4139 86 : const auto xmm_zero = _mm_setzero_si128();
4140 86 : constexpr int SIZEOF_REG = static_cast<int>(sizeof(xmm_zero));
4141 110 : for (; iX + SIZEOF_REG <= nOutXSize; iX += SIZEOF_REG)
4142 : {
4143 48 : auto xmm_mask = _mm_loadu_si128(
4144 : reinterpret_cast<__m128i const *>(pabyMask + iMaskIdx));
4145 24 : const auto xmm_src = _mm_loadu_si128(
4146 : reinterpret_cast<__m128i const *>(pabySrc));
4147 24 : auto xmm_dst = _mm_loadu_si128(
4148 : reinterpret_cast<__m128i const *>(pabyDestLine));
4149 : #ifdef USE_SSE41_OPTIM
4150 : xmm_dst = _mm_blendv_epi8(xmm_dst, xmm_src, xmm_mask);
4151 : #else
4152 : // mask[i] = 0 becomes 255, and mask[i] != 0 becomes 0
4153 24 : xmm_mask = _mm_cmpeq_epi8(xmm_mask, xmm_zero);
4154 : // dst_data[i] = (mask[i] & dst_data[i]) |
4155 : // (~mask[i] & src_data[i])
4156 : // That is:
4157 : // dst_data[i] = dst_data[i] when mask[i] = 255
4158 : // dst_data[i] = src_data[i] when mask[i] = 0
4159 72 : xmm_dst = _mm_or_si128(_mm_and_si128(xmm_mask, xmm_dst),
4160 : _mm_andnot_si128(xmm_mask, xmm_src));
4161 : #endif
4162 : _mm_storeu_si128(reinterpret_cast<__m128i *>(pabyDestLine),
4163 : xmm_dst);
4164 24 : pabyDestLine += SIZEOF_REG;
4165 24 : pabySrc += SIZEOF_REG;
4166 24 : iMaskIdx += SIZEOF_REG;
4167 : }
4168 : }
4169 : #endif
4170 342 : for (; iX < nOutXSize; iX++)
4171 : {
4172 256 : if (pabyMask[iMaskIdx])
4173 : {
4174 218 : *pabyDestLine = *pabySrc;
4175 : }
4176 256 : pabyDestLine += static_cast<GPtrDiff_t>(nPixelSpace);
4177 256 : pabySrc++;
4178 256 : iMaskIdx++;
4179 : }
4180 : }
4181 : }
4182 : else
4183 : {
4184 38 : for (int iY = 0; iY < nOutYSize; iY++)
4185 : {
4186 22 : GByte *pabyDestLine =
4187 22 : pabyDest + static_cast<GPtrDiff_t>(iY * nLineSpace);
4188 54 : for (int iX = 0; iX < nOutXSize; iX++)
4189 : {
4190 32 : if (pabyMask[iMaskIdx])
4191 : {
4192 16 : memcpy(pabyDestLine, pabySrc, nBufTypeSize);
4193 : }
4194 32 : pabyDestLine += static_cast<GPtrDiff_t>(nPixelSpace);
4195 32 : pabySrc += nBufTypeSize;
4196 32 : iMaskIdx++;
4197 : }
4198 : }
4199 : }
4200 66 : }
4201 :
4202 : /************************************************************************/
4203 : /* NeedInitBuffer() */
4204 : /************************************************************************/
4205 :
4206 : // Must be called after CollectSources()
4207 177 : bool GDALTileIndexDataset::NeedInitBuffer(int nBandCount,
4208 : const int *panBandMap) const
4209 : {
4210 177 : bool bNeedInitBuffer = true;
4211 : // If the last source (that is the most prioritary one) covers at least
4212 : // the window of interest and is fully opaque, then we don't need to
4213 : // initialize the buffer, and can directly render that source.
4214 177 : int bHasNoData = false;
4215 351 : if (!m_aoSourceDesc.empty() && m_aoSourceDesc.back().bCoversWholeAOI &&
4216 162 : (!m_aoSourceDesc.back().bHasNoData ||
4217 : // Also, if there's a single source and that the VRT bands and the
4218 : // source bands have the same nodata value, we can skip initialization.
4219 12 : (m_aoSourceDesc.size() == 1 && m_aoSourceDesc.back().bSameNoData &&
4220 10 : m_bSameNoData && m_bSameDataType &&
4221 5 : IsSameNaNAware(papoBands[0]->GetNoDataValue(&bHasNoData),
4222 5 : m_aoSourceDesc.back().dfSameNoData) &&
4223 356 : bHasNoData)) &&
4224 189 : (!m_aoSourceDesc.back().poMaskBand ||
4225 : // Also, if there's a single source that has a mask band, and the VRT
4226 : // bands have no-nodata or a 0-nodata value, we can skip
4227 : // initialization.
4228 43 : (m_aoSourceDesc.size() == 1 && m_bSameDataType &&
4229 7 : !(nBandCount == 1 && panBandMap[0] == 0) && m_bSameNoData &&
4230 7 : papoBands[0]->GetNoDataValue(&bHasNoData) == 0)))
4231 : {
4232 124 : bNeedInitBuffer = false;
4233 : }
4234 177 : return bNeedInitBuffer;
4235 : }
4236 :
4237 : /************************************************************************/
4238 : /* InitBuffer() */
4239 : /************************************************************************/
4240 :
4241 58 : void GDALTileIndexDataset::InitBuffer(void *pData, int nBufXSize, int nBufYSize,
4242 : GDALDataType eBufType, int nBandCount,
4243 : const int *panBandMap,
4244 : GSpacing nPixelSpace, GSpacing nLineSpace,
4245 : GSpacing nBandSpace) const
4246 : {
4247 58 : const int nBufTypeSize = GDALGetDataTypeSizeBytes(eBufType);
4248 58 : if (m_bSameNoData && nBandCount > 1 &&
4249 18 : ((nPixelSpace == nBufTypeSize &&
4250 18 : nLineSpace == nBufXSize * nPixelSpace &&
4251 18 : nBandSpace == nBufYSize * nLineSpace) ||
4252 0 : (nBandSpace == nBufTypeSize &&
4253 0 : nPixelSpace == nBandCount * nBandSpace &&
4254 0 : nLineSpace == nBufXSize * nPixelSpace)))
4255 : {
4256 18 : const int nBandNr = panBandMap[0];
4257 : auto poVRTBand =
4258 : nBandNr == 0
4259 18 : ? m_poMaskBand.get()
4260 18 : : cpl::down_cast<GDALTileIndexBand *>(papoBands[nBandNr - 1]);
4261 18 : CPLAssert(poVRTBand);
4262 18 : const double dfNoData = poVRTBand->m_dfNoDataValue;
4263 18 : if (dfNoData == 0.0)
4264 : {
4265 16 : memset(pData, 0,
4266 16 : static_cast<size_t>(nBufXSize) * nBufYSize * nBandCount *
4267 16 : nBufTypeSize);
4268 : }
4269 : else
4270 : {
4271 2 : GDALCopyWords64(
4272 : &dfNoData, GDT_Float64, 0, pData, eBufType, nBufTypeSize,
4273 2 : static_cast<size_t>(nBufXSize) * nBufYSize * nBandCount);
4274 18 : }
4275 : }
4276 : else
4277 : {
4278 81 : for (int i = 0; i < nBandCount; ++i)
4279 : {
4280 41 : const int nBandNr = panBandMap[i];
4281 41 : auto poVRTBand = nBandNr == 0 ? m_poMaskBand.get()
4282 39 : : cpl::down_cast<GDALTileIndexBand *>(
4283 39 : papoBands[nBandNr - 1]);
4284 41 : GByte *pabyBandData = static_cast<GByte *>(pData) + i * nBandSpace;
4285 41 : if (nPixelSpace == nBufTypeSize &&
4286 41 : poVRTBand->m_dfNoDataValue == 0.0)
4287 : {
4288 37 : if (nLineSpace == nBufXSize * nPixelSpace)
4289 : {
4290 37 : memset(pabyBandData, 0,
4291 37 : static_cast<size_t>(nBufYSize * nLineSpace));
4292 : }
4293 : else
4294 : {
4295 0 : for (int iLine = 0; iLine < nBufYSize; iLine++)
4296 : {
4297 0 : memset(static_cast<GByte *>(pabyBandData) +
4298 0 : static_cast<GIntBig>(iLine) * nLineSpace,
4299 0 : 0, static_cast<size_t>(nBufXSize * nPixelSpace));
4300 : }
4301 37 : }
4302 : }
4303 : else
4304 : {
4305 4 : double dfWriteValue = poVRTBand->m_dfNoDataValue;
4306 :
4307 12 : for (int iLine = 0; iLine < nBufYSize; iLine++)
4308 : {
4309 8 : GDALCopyWords(&dfWriteValue, GDT_Float64, 0,
4310 8 : static_cast<GByte *>(pabyBandData) +
4311 8 : static_cast<GIntBig>(nLineSpace) * iLine,
4312 : eBufType, static_cast<int>(nPixelSpace),
4313 : nBufXSize);
4314 : }
4315 : }
4316 : }
4317 : }
4318 58 : }
4319 :
4320 : /************************************************************************/
4321 : /* RenderSource() */
4322 : /************************************************************************/
4323 :
4324 480 : CPLErr GDALTileIndexDataset::RenderSource(
4325 : const SourceDesc &oSourceDesc, bool bNeedInitBuffer, int nBandNrMax,
4326 : int nXOff, int nYOff, int nXSize, int nYSize, double dfXOff, double dfYOff,
4327 : double dfXSize, double dfYSize, int nBufXSize, int nBufYSize, void *pData,
4328 : GDALDataType eBufType, int nBandCount, BANDMAP_TYPE panBandMap,
4329 : GSpacing nPixelSpace, GSpacing nLineSpace, GSpacing nBandSpace,
4330 : GDALRasterIOExtraArg *psExtraArg,
4331 : VRTSource::WorkingState &oWorkingState) const
4332 : {
4333 480 : auto &poTileDS = oSourceDesc.poDS;
4334 480 : auto &poSource = oSourceDesc.poSource;
4335 480 : auto poComplexSource = dynamic_cast<VRTComplexSource *>(poSource.get());
4336 480 : CPLErr eErr = CE_None;
4337 :
4338 480 : if (poTileDS->GetRasterCount() + 1 == nBandNrMax &&
4339 484 : papoBands[nBandNrMax - 1]->GetColorInterpretation() == GCI_AlphaBand &&
4340 4 : papoBands[nBandNrMax - 1]->GetRasterDataType() == GDT_Byte)
4341 : {
4342 : // Special case when there's typically a mix of RGB and RGBA source
4343 : // datasets and we read a RGB one.
4344 14 : for (int iBand = 0; iBand < nBandCount && eErr == CE_None; ++iBand)
4345 : {
4346 10 : const int nBandNr = panBandMap[iBand];
4347 10 : if (nBandNr == nBandNrMax)
4348 : {
4349 : // The window we will actually request from the source raster band.
4350 4 : double dfReqXOff = 0.0;
4351 4 : double dfReqYOff = 0.0;
4352 4 : double dfReqXSize = 0.0;
4353 4 : double dfReqYSize = 0.0;
4354 4 : int nReqXOff = 0;
4355 4 : int nReqYOff = 0;
4356 4 : int nReqXSize = 0;
4357 4 : int nReqYSize = 0;
4358 :
4359 : // The window we will actual set _within_ the pData buffer.
4360 4 : int nOutXOff = 0;
4361 4 : int nOutYOff = 0;
4362 4 : int nOutXSize = 0;
4363 4 : int nOutYSize = 0;
4364 :
4365 4 : bool bError = false;
4366 :
4367 4 : auto poTileBand = poTileDS->GetRasterBand(1);
4368 4 : poSource->SetRasterBand(poTileBand, false);
4369 4 : if (poSource->GetSrcDstWindow(
4370 : dfXOff, dfYOff, dfXSize, dfYSize, nBufXSize, nBufYSize,
4371 : &dfReqXOff, &dfReqYOff, &dfReqXSize, &dfReqYSize,
4372 : &nReqXOff, &nReqYOff, &nReqXSize, &nReqYSize, &nOutXOff,
4373 4 : &nOutYOff, &nOutXSize, &nOutYSize, bError))
4374 : {
4375 4 : GByte *pabyOut =
4376 : static_cast<GByte *>(pData) +
4377 4 : static_cast<GPtrDiff_t>(iBand * nBandSpace +
4378 4 : nOutXOff * nPixelSpace +
4379 4 : nOutYOff * nLineSpace);
4380 :
4381 4 : constexpr GByte n255 = 255;
4382 8 : for (int iY = 0; iY < nOutYSize; iY++)
4383 : {
4384 4 : GDALCopyWords(
4385 : &n255, GDT_Byte, 0,
4386 4 : pabyOut + static_cast<GPtrDiff_t>(iY * nLineSpace),
4387 : eBufType, static_cast<int>(nPixelSpace), nOutXSize);
4388 : }
4389 : }
4390 : }
4391 : else
4392 : {
4393 6 : auto poTileBand = poTileDS->GetRasterBand(nBandNr);
4394 6 : if (poComplexSource)
4395 : {
4396 0 : int bHasNoData = false;
4397 : const double dfNoDataValue =
4398 0 : poTileBand->GetNoDataValue(&bHasNoData);
4399 0 : poComplexSource->SetNoDataValue(
4400 0 : bHasNoData ? dfNoDataValue : VRT_NODATA_UNSET);
4401 : }
4402 6 : poSource->SetRasterBand(poTileBand, false);
4403 :
4404 : GDALRasterIOExtraArg sExtraArg;
4405 6 : INIT_RASTERIO_EXTRA_ARG(sExtraArg);
4406 6 : if (psExtraArg->eResampleAlg != GRIORA_NearestNeighbour)
4407 : {
4408 : // cppcheck-suppress redundantAssignment
4409 0 : sExtraArg.eResampleAlg = psExtraArg->eResampleAlg;
4410 : }
4411 : else
4412 : {
4413 : // cppcheck-suppress redundantAssignment
4414 6 : sExtraArg.eResampleAlg = m_eResampling;
4415 : }
4416 :
4417 6 : GByte *pabyBandData =
4418 6 : static_cast<GByte *>(pData) + iBand * nBandSpace;
4419 12 : eErr = poSource->RasterIO(
4420 : poTileBand->GetRasterDataType(), nXOff, nYOff, nXSize,
4421 : nYSize, pabyBandData, nBufXSize, nBufYSize, eBufType,
4422 6 : nPixelSpace, nLineSpace, &sExtraArg, oWorkingState);
4423 : }
4424 : }
4425 4 : return eErr;
4426 : }
4427 476 : else if (poTileDS->GetRasterCount() < nBandNrMax)
4428 : {
4429 2 : CPLError(CE_Failure, CPLE_AppDefined, "%s has not enough bands.",
4430 : oSourceDesc.osName.c_str());
4431 2 : return CE_Failure;
4432 : }
4433 :
4434 474 : if ((oSourceDesc.poMaskBand && bNeedInitBuffer) || nBandNrMax == 0)
4435 : {
4436 : // The window we will actually request from the source raster band.
4437 55 : double dfReqXOff = 0.0;
4438 55 : double dfReqYOff = 0.0;
4439 55 : double dfReqXSize = 0.0;
4440 55 : double dfReqYSize = 0.0;
4441 55 : int nReqXOff = 0;
4442 55 : int nReqYOff = 0;
4443 55 : int nReqXSize = 0;
4444 55 : int nReqYSize = 0;
4445 :
4446 : // The window we will actual set _within_ the pData buffer.
4447 55 : int nOutXOff = 0;
4448 55 : int nOutYOff = 0;
4449 55 : int nOutXSize = 0;
4450 55 : int nOutYSize = 0;
4451 :
4452 55 : bool bError = false;
4453 :
4454 55 : auto poFirstTileBand = poTileDS->GetRasterBand(1);
4455 55 : poSource->SetRasterBand(poFirstTileBand, false);
4456 55 : if (poSource->GetSrcDstWindow(
4457 : dfXOff, dfYOff, dfXSize, dfYSize, nBufXSize, nBufYSize,
4458 : &dfReqXOff, &dfReqYOff, &dfReqXSize, &dfReqYSize, &nReqXOff,
4459 : &nReqYOff, &nReqXSize, &nReqYSize, &nOutXOff, &nOutYOff,
4460 55 : &nOutXSize, &nOutYSize, bError))
4461 : {
4462 55 : int iMaskBandIdx = -1;
4463 55 : if (eBufType == GDT_Byte && nBandNrMax == 0)
4464 : {
4465 : // when called from m_poMaskBand
4466 4 : iMaskBandIdx = 0;
4467 : }
4468 51 : else if (oSourceDesc.poMaskBand)
4469 : {
4470 : // If we request a Byte buffer and the mask band is actually
4471 : // one of the queried bands of this request, we can save
4472 : // requesting it separately.
4473 51 : const int nMaskBandNr = oSourceDesc.poMaskBand->GetBand();
4474 39 : if (eBufType == GDT_Byte && nMaskBandNr >= 1 &&
4475 129 : nMaskBandNr <= poTileDS->GetRasterCount() &&
4476 39 : poTileDS->GetRasterBand(nMaskBandNr) ==
4477 39 : oSourceDesc.poMaskBand)
4478 : {
4479 61 : for (int iBand = 0; iBand < nBandCount; ++iBand)
4480 : {
4481 44 : if (panBandMap[iBand] == nMaskBandNr)
4482 : {
4483 20 : iMaskBandIdx = iBand;
4484 20 : break;
4485 : }
4486 : }
4487 : }
4488 : }
4489 :
4490 : GDALRasterIOExtraArg sExtraArg;
4491 55 : INIT_RASTERIO_EXTRA_ARG(sExtraArg);
4492 55 : if (psExtraArg->eResampleAlg != GRIORA_NearestNeighbour)
4493 : {
4494 : // cppcheck-suppress redundantAssignment
4495 0 : sExtraArg.eResampleAlg = psExtraArg->eResampleAlg;
4496 : }
4497 : else
4498 : {
4499 : // cppcheck-suppress redundantAssignment
4500 55 : sExtraArg.eResampleAlg = m_eResampling;
4501 : }
4502 55 : sExtraArg.bFloatingPointWindowValidity = TRUE;
4503 55 : sExtraArg.dfXOff = dfReqXOff;
4504 55 : sExtraArg.dfYOff = dfReqYOff;
4505 55 : sExtraArg.dfXSize = dfReqXSize;
4506 55 : sExtraArg.dfYSize = dfReqYSize;
4507 :
4508 76 : if (iMaskBandIdx < 0 && oSourceDesc.abyMask.empty() &&
4509 21 : oSourceDesc.poMaskBand)
4510 : {
4511 : // Fetch the mask band
4512 : try
4513 : {
4514 21 : oSourceDesc.abyMask.resize(static_cast<size_t>(nOutXSize) *
4515 21 : nOutYSize);
4516 : }
4517 0 : catch (const std::bad_alloc &)
4518 : {
4519 0 : CPLError(CE_Failure, CPLE_OutOfMemory,
4520 : "Cannot allocate working buffer for mask");
4521 0 : return CE_Failure;
4522 : }
4523 :
4524 21 : if (oSourceDesc.poMaskBand->RasterIO(
4525 : GF_Read, nReqXOff, nReqYOff, nReqXSize, nReqYSize,
4526 21 : oSourceDesc.abyMask.data(), nOutXSize, nOutYSize,
4527 21 : GDT_Byte, 0, 0, &sExtraArg) != CE_None)
4528 : {
4529 0 : oSourceDesc.abyMask.clear();
4530 0 : return CE_Failure;
4531 : }
4532 : }
4533 :
4534 : // Allocate a temporary contiguous buffer to receive pixel data
4535 55 : const int nBufTypeSize = GDALGetDataTypeSizeBytes(eBufType);
4536 55 : const size_t nWorkBufferBandSize =
4537 55 : static_cast<size_t>(nOutXSize) * nOutYSize * nBufTypeSize;
4538 55 : std::vector<GByte> abyWorkBuffer;
4539 : try
4540 : {
4541 55 : abyWorkBuffer.resize(nBandCount * nWorkBufferBandSize);
4542 : }
4543 0 : catch (const std::bad_alloc &)
4544 : {
4545 0 : CPLError(CE_Failure, CPLE_OutOfMemory,
4546 : "Cannot allocate working buffer");
4547 0 : return CE_Failure;
4548 : }
4549 :
4550 : const GByte *const pabyMask =
4551 : iMaskBandIdx >= 0
4552 24 : ? abyWorkBuffer.data() + iMaskBandIdx * nWorkBufferBandSize
4553 79 : : oSourceDesc.abyMask.data();
4554 :
4555 55 : if (nBandNrMax == 0)
4556 : {
4557 : // Special case when called from m_poMaskBand
4558 12 : if (poTileDS->GetRasterBand(1)->GetMaskBand()->RasterIO(
4559 : GF_Read, nReqXOff, nReqYOff, nReqXSize, nReqYSize,
4560 6 : abyWorkBuffer.data(), nOutXSize, nOutYSize, eBufType, 0,
4561 6 : 0, &sExtraArg) != CE_None)
4562 : {
4563 0 : return CE_Failure;
4564 : }
4565 : }
4566 98 : else if (poTileDS->RasterIO(GF_Read, nReqXOff, nReqYOff, nReqXSize,
4567 49 : nReqYSize, abyWorkBuffer.data(),
4568 : nOutXSize, nOutYSize, eBufType,
4569 : nBandCount, panBandMap, 0, 0, 0,
4570 49 : &sExtraArg) != CE_None)
4571 : {
4572 0 : return CE_Failure;
4573 : }
4574 :
4575 : // Compose the temporary contiguous buffer into the target
4576 : // buffer, taking into account the mask
4577 55 : GByte *pabyOut = static_cast<GByte *>(pData) +
4578 55 : static_cast<GPtrDiff_t>(nOutXOff * nPixelSpace +
4579 55 : nOutYOff * nLineSpace);
4580 :
4581 121 : for (int iBand = 0; iBand < nBandCount && eErr == CE_None; ++iBand)
4582 : {
4583 66 : GByte *pabyDestBand =
4584 66 : pabyOut + static_cast<GPtrDiff_t>(iBand * nBandSpace);
4585 : const GByte *pabySrc =
4586 66 : abyWorkBuffer.data() + iBand * nWorkBufferBandSize;
4587 :
4588 66 : CompositeSrcWithMaskIntoDest(
4589 : nOutXSize, nOutYSize, eBufType, nBufTypeSize, nPixelSpace,
4590 : nLineSpace, pabySrc, pabyMask, pabyDestBand);
4591 : }
4592 55 : }
4593 : }
4594 419 : else if (m_bSameDataType && !bNeedInitBuffer && oSourceDesc.bHasNoData)
4595 : {
4596 : // We create a non-VRTComplexSource SimpleSource copy of poSource
4597 : // to be able to call DatasetRasterIO()
4598 4 : VRTSimpleSource oSimpleSource(poSource.get(), 1.0, 1.0);
4599 :
4600 : GDALRasterIOExtraArg sExtraArg;
4601 4 : INIT_RASTERIO_EXTRA_ARG(sExtraArg);
4602 4 : if (psExtraArg->eResampleAlg != GRIORA_NearestNeighbour)
4603 : {
4604 : // cppcheck-suppress redundantAssignment
4605 0 : sExtraArg.eResampleAlg = psExtraArg->eResampleAlg;
4606 : }
4607 : else
4608 : {
4609 : // cppcheck-suppress redundantAssignment
4610 4 : sExtraArg.eResampleAlg = m_eResampling;
4611 : }
4612 :
4613 4 : auto poTileBand = poTileDS->GetRasterBand(panBandMap[0]);
4614 4 : oSimpleSource.SetRasterBand(poTileBand, false);
4615 4 : eErr = oSimpleSource.DatasetRasterIO(
4616 4 : papoBands[0]->GetRasterDataType(), nXOff, nYOff, nXSize, nYSize,
4617 : pData, nBufXSize, nBufYSize, eBufType, nBandCount, panBandMap,
4618 4 : nPixelSpace, nLineSpace, nBandSpace, &sExtraArg);
4619 : }
4620 415 : else if (m_bSameDataType && !poComplexSource)
4621 : {
4622 407 : auto poTileBand = poTileDS->GetRasterBand(panBandMap[0]);
4623 407 : poSource->SetRasterBand(poTileBand, false);
4624 :
4625 : GDALRasterIOExtraArg sExtraArg;
4626 407 : INIT_RASTERIO_EXTRA_ARG(sExtraArg);
4627 407 : if (poTileBand->GetColorTable())
4628 : {
4629 : // cppcheck-suppress redundantAssignment
4630 0 : sExtraArg.eResampleAlg = GRIORA_NearestNeighbour;
4631 : }
4632 407 : else if (psExtraArg->eResampleAlg != GRIORA_NearestNeighbour)
4633 : {
4634 : // cppcheck-suppress redundantAssignment
4635 0 : sExtraArg.eResampleAlg = psExtraArg->eResampleAlg;
4636 : }
4637 : else
4638 : {
4639 : // cppcheck-suppress redundantAssignment
4640 407 : sExtraArg.eResampleAlg = m_eResampling;
4641 : }
4642 :
4643 814 : eErr = poSource->DatasetRasterIO(
4644 407 : papoBands[0]->GetRasterDataType(), nXOff, nYOff, nXSize, nYSize,
4645 : pData, nBufXSize, nBufYSize, eBufType, nBandCount, panBandMap,
4646 407 : nPixelSpace, nLineSpace, nBandSpace, &sExtraArg);
4647 : }
4648 : else
4649 : {
4650 16 : for (int i = 0; i < nBandCount && eErr == CE_None; ++i)
4651 : {
4652 8 : const int nBandNr = panBandMap[i];
4653 8 : GByte *pabyBandData = static_cast<GByte *>(pData) + i * nBandSpace;
4654 8 : auto poTileBand = poTileDS->GetRasterBand(nBandNr);
4655 8 : if (poComplexSource)
4656 : {
4657 8 : int bHasNoData = false;
4658 : const double dfNoDataValue =
4659 8 : poTileBand->GetNoDataValue(&bHasNoData);
4660 8 : poComplexSource->SetNoDataValue(bHasNoData ? dfNoDataValue
4661 8 : : VRT_NODATA_UNSET);
4662 : }
4663 8 : poSource->SetRasterBand(poTileBand, false);
4664 :
4665 : GDALRasterIOExtraArg sExtraArg;
4666 8 : INIT_RASTERIO_EXTRA_ARG(sExtraArg);
4667 8 : if (poTileBand->GetColorTable())
4668 : {
4669 : // cppcheck-suppress redundantAssignment
4670 0 : sExtraArg.eResampleAlg = GRIORA_NearestNeighbour;
4671 : }
4672 8 : else if (psExtraArg->eResampleAlg != GRIORA_NearestNeighbour)
4673 : {
4674 : // cppcheck-suppress redundantAssignment
4675 0 : sExtraArg.eResampleAlg = psExtraArg->eResampleAlg;
4676 : }
4677 : else
4678 : {
4679 : // cppcheck-suppress redundantAssignment
4680 8 : sExtraArg.eResampleAlg = m_eResampling;
4681 : }
4682 :
4683 16 : eErr = poSource->RasterIO(
4684 8 : papoBands[nBandNr - 1]->GetRasterDataType(), nXOff, nYOff,
4685 : nXSize, nYSize, pabyBandData, nBufXSize, nBufYSize, eBufType,
4686 8 : nPixelSpace, nLineSpace, &sExtraArg, oWorkingState);
4687 : }
4688 : }
4689 474 : return eErr;
4690 : }
4691 :
4692 : /************************************************************************/
4693 : /* IRasterIO() */
4694 : /************************************************************************/
4695 :
4696 183 : CPLErr GDALTileIndexDataset::IRasterIO(
4697 : GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize,
4698 : void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType,
4699 : int nBandCount, BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
4700 : GSpacing nLineSpace, GSpacing nBandSpace, GDALRasterIOExtraArg *psExtraArg)
4701 : {
4702 183 : if (eRWFlag != GF_Read)
4703 0 : return CE_Failure;
4704 :
4705 183 : if (nBufXSize < nXSize && nBufYSize < nYSize && AreOverviewsEnabled())
4706 : {
4707 2 : int bTried = FALSE;
4708 2 : const CPLErr eErr = TryOverviewRasterIO(
4709 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
4710 : eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace,
4711 : nBandSpace, psExtraArg, &bTried);
4712 2 : if (bTried)
4713 2 : return eErr;
4714 : }
4715 :
4716 181 : double dfXOff = nXOff;
4717 181 : double dfYOff = nYOff;
4718 181 : double dfXSize = nXSize;
4719 181 : double dfYSize = nYSize;
4720 181 : if (psExtraArg->bFloatingPointWindowValidity)
4721 : {
4722 6 : dfXOff = psExtraArg->dfXOff;
4723 6 : dfYOff = psExtraArg->dfYOff;
4724 6 : dfXSize = psExtraArg->dfXSize;
4725 6 : dfYSize = psExtraArg->dfYSize;
4726 : }
4727 :
4728 181 : if (!CollectSources(dfXOff, dfYOff, dfXSize, dfYSize,
4729 : /* bMultiThreadAllowed = */ true))
4730 : {
4731 3 : return CE_Failure;
4732 : }
4733 :
4734 : // We might be called with nBandCount == 1 && panBandMap[0] == 0
4735 : // to mean m_poMaskBand
4736 178 : int nBandNrMax = 0;
4737 405 : for (int i = 0; i < nBandCount; ++i)
4738 : {
4739 227 : const int nBandNr = panBandMap[i];
4740 227 : nBandNrMax = std::max(nBandNrMax, nBandNr);
4741 : }
4742 :
4743 : const bool bNeedInitBuffer =
4744 178 : m_bLastMustUseMultiThreading || NeedInitBuffer(nBandCount, panBandMap);
4745 :
4746 178 : if (!bNeedInitBuffer)
4747 : {
4748 120 : return RenderSource(
4749 120 : m_aoSourceDesc.back(), bNeedInitBuffer, nBandNrMax, nXOff, nYOff,
4750 : nXSize, nYSize, dfXOff, dfYOff, dfXSize, dfYSize, nBufXSize,
4751 : nBufYSize, pData, eBufType, nBandCount, panBandMap, nPixelSpace,
4752 240 : nLineSpace, nBandSpace, psExtraArg, m_oWorkingState);
4753 : }
4754 : else
4755 : {
4756 58 : InitBuffer(pData, nBufXSize, nBufYSize, eBufType, nBandCount,
4757 : panBandMap, nPixelSpace, nLineSpace, nBandSpace);
4758 :
4759 58 : if (m_bLastMustUseMultiThreading)
4760 : {
4761 12 : CPLErrorAccumulator oErrorAccumulator;
4762 6 : std::atomic<bool> bSuccess = true;
4763 : const int nContributingSources =
4764 6 : static_cast<int>(m_aoSourceDesc.size());
4765 6 : CPLWorkerThreadPool *psThreadPool = GDALGetGlobalThreadPool(
4766 6 : std::min(nContributingSources, m_nNumThreads));
4767 : const int nThreads =
4768 6 : std::min(nContributingSources, psThreadPool->GetThreadCount());
4769 6 : CPLDebugOnly("GTI",
4770 : "IRasterIO(): use optimized "
4771 : "multi-threaded code path. "
4772 : "Using %d threads",
4773 : nThreads);
4774 :
4775 : {
4776 12 : std::lock_guard oLock(m_oQueueWorkingStates.oMutex);
4777 6 : if (m_oQueueWorkingStates.oStates.size() <
4778 6 : static_cast<size_t>(nThreads))
4779 : {
4780 4 : m_oQueueWorkingStates.oStates.resize(nThreads);
4781 : }
4782 22 : for (int i = 0; i < nThreads; ++i)
4783 : {
4784 16 : if (!m_oQueueWorkingStates.oStates[i])
4785 10 : m_oQueueWorkingStates.oStates[i] =
4786 20 : std::make_unique<VRTSource::WorkingState>();
4787 : }
4788 : }
4789 :
4790 6 : auto oQueue = psThreadPool->CreateJobQueue();
4791 6 : std::atomic<int> nCompletedJobs = 0;
4792 144 : for (auto &oSourceDesc : m_aoSourceDesc)
4793 : {
4794 138 : auto psJob = new RasterIOJob();
4795 138 : psJob->poDS = this;
4796 138 : psJob->pbSuccess = &bSuccess;
4797 138 : psJob->poErrorAccumulator = &oErrorAccumulator;
4798 138 : psJob->pnCompletedJobs = &nCompletedJobs;
4799 138 : psJob->poQueueWorkingStates = &m_oQueueWorkingStates;
4800 138 : psJob->nBandNrMax = nBandNrMax;
4801 138 : psJob->nXOff = nXOff;
4802 138 : psJob->nYOff = nYOff;
4803 138 : psJob->nXSize = nXSize;
4804 138 : psJob->nYSize = nYSize;
4805 138 : psJob->pData = pData;
4806 138 : psJob->nBufXSize = nBufXSize;
4807 138 : psJob->nBufYSize = nBufYSize;
4808 138 : psJob->eBufType = eBufType;
4809 138 : psJob->nBandCount = nBandCount;
4810 138 : psJob->panBandMap = panBandMap;
4811 138 : psJob->nPixelSpace = nPixelSpace;
4812 138 : psJob->nLineSpace = nLineSpace;
4813 138 : psJob->nBandSpace = nBandSpace;
4814 138 : psJob->psExtraArg = psExtraArg;
4815 :
4816 : psJob->osTileName = oSourceDesc.poFeature->GetFieldAsString(
4817 138 : m_nLocationFieldIndex);
4818 :
4819 138 : if (!oQueue->SubmitJob(RasterIOJob::Func, psJob))
4820 : {
4821 0 : delete psJob;
4822 0 : bSuccess = false;
4823 0 : break;
4824 : }
4825 : }
4826 :
4827 54 : while (oQueue->WaitEvent())
4828 : {
4829 : // Quite rough progress callback. We could do better by counting
4830 : // the number of contributing pixels.
4831 48 : if (psExtraArg->pfnProgress)
4832 : {
4833 94 : psExtraArg->pfnProgress(double(nCompletedJobs.load()) /
4834 : nContributingSources,
4835 : "", psExtraArg->pProgressData);
4836 : }
4837 : }
4838 :
4839 6 : oErrorAccumulator.ReplayErrors();
4840 :
4841 6 : if (bSuccess && psExtraArg->pfnProgress)
4842 : {
4843 4 : psExtraArg->pfnProgress(1.0, "", psExtraArg->pProgressData);
4844 : }
4845 :
4846 6 : return bSuccess ? CE_None : CE_Failure;
4847 : }
4848 : else
4849 : {
4850 : // Now render from bottom of the stack to top.
4851 275 : for (auto &oSourceDesc : m_aoSourceDesc)
4852 : {
4853 446 : if (oSourceDesc.poDS &&
4854 223 : RenderSource(oSourceDesc, bNeedInitBuffer, nBandNrMax,
4855 : nXOff, nYOff, nXSize, nYSize, dfXOff, dfYOff,
4856 : dfXSize, dfYSize, nBufXSize, nBufYSize, pData,
4857 : eBufType, nBandCount, panBandMap, nPixelSpace,
4858 : nLineSpace, nBandSpace, psExtraArg,
4859 446 : m_oWorkingState) != CE_None)
4860 0 : return CE_Failure;
4861 : }
4862 :
4863 52 : if (psExtraArg->pfnProgress)
4864 : {
4865 4 : psExtraArg->pfnProgress(1.0, "", psExtraArg->pProgressData);
4866 : }
4867 :
4868 52 : return CE_None;
4869 : }
4870 : }
4871 : }
4872 :
4873 : /************************************************************************/
4874 : /* GDALTileIndexDataset::RasterIOJob::Func() */
4875 : /************************************************************************/
4876 :
4877 138 : void GDALTileIndexDataset::RasterIOJob::Func(void *pData)
4878 : {
4879 : auto psJob =
4880 276 : std::unique_ptr<RasterIOJob>(static_cast<RasterIOJob *>(pData));
4881 138 : if (*psJob->pbSuccess)
4882 : {
4883 : const std::string osTileName(GetAbsoluteFileName(
4884 276 : psJob->osTileName.c_str(), psJob->poDS->GetDescription()));
4885 :
4886 276 : SourceDesc oSourceDesc;
4887 :
4888 276 : auto oAccumulator = psJob->poErrorAccumulator->InstallForCurrentScope();
4889 138 : CPL_IGNORE_RET_VAL(oAccumulator);
4890 :
4891 : const bool bCanOpenSource =
4892 138 : psJob->poDS->GetSourceDesc(osTileName, oSourceDesc,
4893 275 : &psJob->poQueueWorkingStates->oMutex) &&
4894 137 : oSourceDesc.poDS;
4895 :
4896 138 : if (!bCanOpenSource)
4897 : {
4898 1 : *psJob->pbSuccess = false;
4899 : }
4900 : else
4901 : {
4902 137 : GDALRasterIOExtraArg sArg = *(psJob->psExtraArg);
4903 137 : sArg.pfnProgress = nullptr;
4904 137 : sArg.pProgressData = nullptr;
4905 :
4906 137 : std::unique_ptr<VRTSource::WorkingState> poWorkingState;
4907 : {
4908 274 : std::lock_guard oLock(psJob->poQueueWorkingStates->oMutex);
4909 : poWorkingState =
4910 137 : std::move(psJob->poQueueWorkingStates->oStates.back());
4911 137 : psJob->poQueueWorkingStates->oStates.pop_back();
4912 137 : CPLAssert(poWorkingState.get());
4913 : }
4914 :
4915 137 : double dfXOff = psJob->nXOff;
4916 137 : double dfYOff = psJob->nYOff;
4917 137 : double dfXSize = psJob->nXSize;
4918 137 : double dfYSize = psJob->nYSize;
4919 137 : if (psJob->psExtraArg->bFloatingPointWindowValidity)
4920 : {
4921 0 : dfXOff = psJob->psExtraArg->dfXOff;
4922 0 : dfYOff = psJob->psExtraArg->dfYOff;
4923 0 : dfXSize = psJob->psExtraArg->dfXSize;
4924 0 : dfYSize = psJob->psExtraArg->dfYSize;
4925 : }
4926 :
4927 : const bool bRenderOK =
4928 274 : psJob->poDS->RenderSource(
4929 137 : oSourceDesc, /*bNeedInitBuffer = */ true, psJob->nBandNrMax,
4930 137 : psJob->nXOff, psJob->nYOff, psJob->nXSize, psJob->nYSize,
4931 137 : dfXOff, dfYOff, dfXSize, dfYSize, psJob->nBufXSize,
4932 137 : psJob->nBufYSize, psJob->pData, psJob->eBufType,
4933 137 : psJob->nBandCount, psJob->panBandMap, psJob->nPixelSpace,
4934 137 : psJob->nLineSpace, psJob->nBandSpace, &sArg,
4935 137 : *(poWorkingState.get())) == CE_None;
4936 :
4937 137 : if (!bRenderOK)
4938 : {
4939 1 : *psJob->pbSuccess = false;
4940 : }
4941 :
4942 : {
4943 274 : std::lock_guard oLock(psJob->poQueueWorkingStates->oMutex);
4944 274 : psJob->poQueueWorkingStates->oStates.push_back(
4945 137 : std::move(poWorkingState));
4946 : }
4947 : }
4948 : }
4949 :
4950 138 : ++(*psJob->pnCompletedJobs);
4951 138 : }
4952 :
4953 : #ifdef GDAL_ENABLE_ALGORITHMS
4954 :
4955 : /************************************************************************/
4956 : /* GDALGTICreateAlgorithm */
4957 : /************************************************************************/
4958 :
4959 : class GDALGTICreateAlgorithm final : public GDALRasterIndexAlgorithm
4960 : {
4961 : public:
4962 : static constexpr const char *NAME = "create";
4963 : static constexpr const char *DESCRIPTION =
4964 : "Create an index of raster datasets compatible of the GDAL Tile Index "
4965 : "(GTI) driver.";
4966 : static constexpr const char *HELP_URL =
4967 : "/programs/gdal_driver_gti_create.html";
4968 :
4969 : GDALGTICreateAlgorithm();
4970 :
4971 : protected:
4972 : bool AddExtraOptions(CPLStringList &aosOptions) override;
4973 :
4974 : private:
4975 : std::string m_xmlFilename{};
4976 : std::vector<double> m_resolution{};
4977 : std::vector<double> m_bbox{};
4978 : std::string m_dataType{};
4979 : int m_bandCount = 0;
4980 : std::vector<double> m_nodata{};
4981 : std::vector<std::string> m_colorInterpretation{};
4982 : bool m_mask = false;
4983 : std::vector<std::string> m_fetchedMetadata{};
4984 : };
4985 :
4986 : /************************************************************************/
4987 : /* GDALGTICreateAlgorithm::GDALGTICreateAlgorithm() */
4988 : /************************************************************************/
4989 :
4990 31 : GDALGTICreateAlgorithm::GDALGTICreateAlgorithm()
4991 31 : : GDALRasterIndexAlgorithm(NAME, DESCRIPTION, HELP_URL)
4992 : {
4993 31 : AddProgressArg();
4994 31 : AddInputDatasetArg(&m_inputDatasets, GDAL_OF_RASTER)
4995 31 : .SetAutoOpenDataset(false);
4996 31 : GDALVectorOutputAbstractAlgorithm::AddAllOutputArgs();
4997 :
4998 31 : AddCommonOptions();
4999 :
5000 : AddArg("xml-filename", 0,
5001 : _("Filename of the XML Virtual Tile Index file to generate, that "
5002 : "can be used as an input for the GDAL GTI / Virtual Raster Tile "
5003 : "Index driver"),
5004 62 : &m_xmlFilename)
5005 31 : .SetMinCharCount(1);
5006 :
5007 : AddArg("resolution", 0,
5008 : _("Resolution (in destination CRS units) of the virtual mosaic"),
5009 62 : &m_resolution)
5010 31 : .SetMinCount(2)
5011 31 : .SetMaxCount(2)
5012 31 : .SetMinValueExcluded(0)
5013 31 : .SetRepeatedArgAllowed(false)
5014 31 : .SetDisplayHintAboutRepetition(false)
5015 31 : .SetMetaVar("<xres>,<yres>");
5016 :
5017 : AddBBOXArg(
5018 : &m_bbox,
5019 31 : _("Bounding box (in destination CRS units) of the virtual mosaic"));
5020 31 : AddOutputDataTypeArg(&m_dataType, _("Datatype of the virtual mosaic"));
5021 : AddArg("band-count", 0, _("Number of bands of the virtual mosaic"),
5022 62 : &m_bandCount)
5023 31 : .SetMinValueIncluded(1);
5024 : AddArg("nodata", 0, _("Nodata value(s) of the bands of the virtual mosaic"),
5025 31 : &m_nodata);
5026 : AddArg("color-interpretation", 0,
5027 : _("Color interpretation(s) of the bands of the virtual mosaic"),
5028 62 : &m_colorInterpretation)
5029 31 : .SetChoices("red", "green", "blue", "alpha", "gray", "undefined");
5030 : AddArg("mask", 0, _("Defines that the virtual mosaic has a mask band"),
5031 31 : &m_mask);
5032 : AddArg("fetch-metadata", 0,
5033 : _("Fetch a metadata item from source rasters and write it as a "
5034 : "field in the index."),
5035 62 : &m_fetchedMetadata)
5036 62 : .SetMetaVar("<gdal-metadata-name>,<field-name>,<field-type>")
5037 31 : .SetPackedValuesAllowed(false)
5038 : .AddValidationAction(
5039 6 : [this]()
5040 : {
5041 6 : for (const std::string &s : m_fetchedMetadata)
5042 : {
5043 : const CPLStringList aosTokens(
5044 4 : CSLTokenizeString2(s.c_str(), ",", 0));
5045 4 : if (aosTokens.size() != 3)
5046 : {
5047 1 : ReportError(
5048 : CE_Failure, CPLE_IllegalArg,
5049 : "'%s' is not of the form "
5050 : "<gdal-metadata-name>,<field-name>,<field-type>",
5051 : s.c_str());
5052 1 : return false;
5053 : }
5054 3 : bool ok = false;
5055 18 : for (const char *type : {"String", "Integer", "Integer64",
5056 21 : "Real", "Date", "DateTime"})
5057 : {
5058 18 : if (EQUAL(aosTokens[2], type))
5059 2 : ok = true;
5060 : }
5061 3 : if (!ok)
5062 : {
5063 1 : ReportError(CE_Failure, CPLE_IllegalArg,
5064 : "'%s' has an invalid field type '%s'. It "
5065 : "should be one of 'String', 'Integer', "
5066 : "'Integer64', 'Real', 'Date', 'DateTime'.",
5067 : s.c_str(), aosTokens[2]);
5068 1 : return false;
5069 : }
5070 : }
5071 2 : return true;
5072 31 : });
5073 31 : }
5074 :
5075 : /************************************************************************/
5076 : /* GDALGTICreateAlgorithm::AddExtraOptions() */
5077 : /************************************************************************/
5078 :
5079 4 : bool GDALGTICreateAlgorithm::AddExtraOptions(CPLStringList &aosOptions)
5080 : {
5081 4 : if (!m_xmlFilename.empty())
5082 : {
5083 1 : aosOptions.push_back("-gti_filename");
5084 1 : aosOptions.push_back(m_xmlFilename);
5085 : }
5086 4 : if (!m_resolution.empty())
5087 : {
5088 1 : aosOptions.push_back("-tr");
5089 1 : aosOptions.push_back(CPLSPrintf("%.17g", m_resolution[0]));
5090 1 : aosOptions.push_back(CPLSPrintf("%.17g", m_resolution[1]));
5091 : }
5092 4 : if (!m_bbox.empty())
5093 : {
5094 1 : aosOptions.push_back("-te");
5095 1 : aosOptions.push_back(CPLSPrintf("%.17g", m_bbox[0]));
5096 1 : aosOptions.push_back(CPLSPrintf("%.17g", m_bbox[1]));
5097 1 : aosOptions.push_back(CPLSPrintf("%.17g", m_bbox[2]));
5098 1 : aosOptions.push_back(CPLSPrintf("%.17g", m_bbox[3]));
5099 : }
5100 4 : if (!m_dataType.empty())
5101 : {
5102 1 : aosOptions.push_back("-ot");
5103 1 : aosOptions.push_back(m_dataType);
5104 : }
5105 4 : if (m_bandCount > 0)
5106 : {
5107 3 : aosOptions.push_back("-bandcount");
5108 3 : aosOptions.push_back(CPLSPrintf("%d", m_bandCount));
5109 :
5110 5 : if (!m_nodata.empty() && m_nodata.size() != 1 &&
5111 2 : static_cast<int>(m_nodata.size()) != m_bandCount)
5112 : {
5113 1 : ReportError(CE_Failure, CPLE_IllegalArg,
5114 : "%d nodata values whereas one or %d were expected",
5115 1 : static_cast<int>(m_nodata.size()), m_bandCount);
5116 1 : return false;
5117 : }
5118 :
5119 4 : if (!m_colorInterpretation.empty() &&
5120 4 : m_colorInterpretation.size() != 1 &&
5121 2 : static_cast<int>(m_colorInterpretation.size()) != m_bandCount)
5122 : {
5123 1 : ReportError(
5124 : CE_Failure, CPLE_IllegalArg,
5125 : "%d color interpretations whereas one or %d were expected",
5126 1 : static_cast<int>(m_colorInterpretation.size()), m_bandCount);
5127 1 : return false;
5128 : }
5129 : }
5130 2 : if (!m_nodata.empty())
5131 : {
5132 2 : std::string val;
5133 3 : for (double v : m_nodata)
5134 : {
5135 2 : if (!val.empty())
5136 1 : val += ',';
5137 2 : val += CPLSPrintf("%.17g", v);
5138 : }
5139 1 : aosOptions.push_back("-nodata");
5140 1 : aosOptions.push_back(val);
5141 : }
5142 2 : if (!m_colorInterpretation.empty())
5143 : {
5144 2 : std::string val;
5145 3 : for (const std::string &s : m_colorInterpretation)
5146 : {
5147 2 : if (!val.empty())
5148 1 : val += ',';
5149 2 : val += s;
5150 : }
5151 1 : aosOptions.push_back("-colorinterp");
5152 1 : aosOptions.push_back(val);
5153 : }
5154 2 : if (m_mask)
5155 1 : aosOptions.push_back("-mask");
5156 3 : for (const std::string &s : m_fetchedMetadata)
5157 : {
5158 1 : aosOptions.push_back("-fetch_md");
5159 2 : const CPLStringList aosTokens(CSLTokenizeString2(s.c_str(), ",", 0));
5160 4 : for (const char *token : aosTokens)
5161 : {
5162 3 : aosOptions.push_back(token);
5163 : }
5164 : }
5165 2 : return true;
5166 : }
5167 :
5168 : /************************************************************************/
5169 : /* GDALTileIndexInstantiateAlgorithm() */
5170 : /************************************************************************/
5171 :
5172 : static GDALAlgorithm *
5173 31 : GDALTileIndexInstantiateAlgorithm(const std::vector<std::string> &aosPath)
5174 : {
5175 31 : if (aosPath.size() == 1 && aosPath[0] == "create")
5176 : {
5177 31 : return std::make_unique<GDALGTICreateAlgorithm>().release();
5178 : }
5179 : else
5180 : {
5181 0 : return nullptr;
5182 : }
5183 : }
5184 :
5185 : #endif
5186 :
5187 : /************************************************************************/
5188 : /* GDALRegister_GTI() */
5189 : /************************************************************************/
5190 :
5191 2054 : void GDALRegister_GTI()
5192 : {
5193 2054 : if (GDALGetDriverByName("GTI") != nullptr)
5194 283 : return;
5195 :
5196 3542 : auto poDriver = std::make_unique<GDALDriver>();
5197 :
5198 1771 : poDriver->SetDescription("GTI");
5199 1771 : poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
5200 1771 : poDriver->SetMetadataItem(GDAL_DMD_LONGNAME, "GDAL Raster Tile Index");
5201 1771 : poDriver->SetMetadataItem(GDAL_DMD_EXTENSIONS, "gti.gpkg gti.fgb gti");
5202 1771 : poDriver->SetMetadataItem(GDAL_DMD_CONNECTION_PREFIX, GTI_PREFIX);
5203 1771 : poDriver->SetMetadataItem(GDAL_DMD_HELPTOPIC, "drivers/raster/gti.html");
5204 :
5205 1771 : poDriver->pfnOpen = GDALTileIndexDatasetOpen;
5206 1771 : poDriver->pfnIdentify = GDALTileIndexDatasetIdentify;
5207 :
5208 1771 : poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
5209 :
5210 1771 : poDriver->SetMetadataItem(
5211 : GDAL_DMD_OPENOPTIONLIST,
5212 : "<OpenOptionList>"
5213 : " <Option name='LAYER' type='string'/>"
5214 : " <Option name='SQL' type='string'/>"
5215 : " <Option name='SPATIAL_SQL' type='string'/>"
5216 : " <Option name='LOCATION_FIELD' type='string'/>"
5217 : " <Option name='SORT_FIELD' type='string'/>"
5218 : " <Option name='SORT_FIELD_ASC' type='boolean'/>"
5219 : " <Option name='FILTER' type='string'/>"
5220 : " <Option name='SRS' type='string'/>"
5221 : " <Option name='RESX' type='float'/>"
5222 : " <Option name='RESY' type='float'/>"
5223 : " <Option name='MINX' type='float'/>"
5224 : " <Option name='MINY' type='float'/>"
5225 : " <Option name='MAXX' type='float'/>"
5226 : " <Option name='MAXY' type='float'/>"
5227 : "<Option name='NUM_THREADS' type='string' description="
5228 : "'Number of worker threads for reading. Can be set to ALL_CPUS' "
5229 : "default='ALL_CPUS'/>"
5230 1771 : "</OpenOptionList>");
5231 :
5232 : #ifdef GDAL_ENABLE_ALGORITHMS
5233 3542 : poDriver->DeclareAlgorithm({"create"});
5234 1771 : poDriver->pfnInstantiateAlgorithm = GDALTileIndexInstantiateAlgorithm;
5235 : #endif
5236 :
5237 : #ifdef BUILT_AS_PLUGIN
5238 : // Used by gdaladdo and test_gdaladdo.py
5239 : poDriver->SetMetadataItem("IS_PLUGIN", "YES");
5240 : #endif
5241 :
5242 1771 : GetGDALDriverManager()->RegisterDriver(poDriver.release());
5243 : }
|