Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: Virtual GDAL Datasets
4 : * Purpose: Implementation of VRTPansharpenedRasterBand and
5 : *VRTPansharpenedDataset. Author: Even Rouault <even.rouault at spatialys.com>
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 2015, Even Rouault <even.rouault at spatialys.com>
9 : *
10 : * SPDX-License-Identifier: MIT
11 : ****************************************************************************/
12 :
13 : #include "cpl_port.h"
14 : #include "gdal_vrt.h"
15 : #include "vrtdataset.h"
16 :
17 : #include <cassert>
18 : #include <cmath>
19 : #include <cstddef>
20 : #include <cstdlib>
21 : #include <cstring>
22 :
23 : #include <algorithm>
24 : #include <limits>
25 : #include <map>
26 : #include <set>
27 : #include <string>
28 : #include <utility>
29 : #include <vector>
30 :
31 : #include "cpl_conv.h"
32 : #include "cpl_error.h"
33 : #include "cpl_minixml.h"
34 : #include "cpl_string.h"
35 : #include "cpl_vsi.h"
36 : #include "gdal.h"
37 : #include "gdal_priv.h"
38 : #include "gdalpansharpen.h"
39 : #include "ogr_core.h"
40 : #include "ogr_spatialref.h"
41 :
42 : /************************************************************************/
43 : /* GDALCreatePansharpenedVRT() */
44 : /************************************************************************/
45 :
46 : /**
47 : * Create a virtual pansharpened dataset.
48 : *
49 : * This function will create a virtual pansharpened dataset.
50 : *
51 : * Starting with GDAL 3.12, a reference will be taken on the dataset owing
52 : * each input bands.
53 : * Before 3.12, no reference were taken on the passed bands. Consequently,
54 : * they or their dataset to which they belong had to be kept open until
55 : * this virtual pansharpened dataset is closed.
56 : *
57 : * The returned dataset will have no associated filename for itself. If you
58 : * want to write the virtual dataset description to a file, use the
59 : * GDALSetDescription() function (or SetDescription() method) on the dataset
60 : * to assign a filename before it is closed.
61 : *
62 : * @param pszXML Pansharpened VRT XML where <SpectralBand> elements have
63 : * no explicit SourceFilename and SourceBand. The spectral bands in the XML will
64 : * be assigned the successive values of the pahInputSpectralBands array. Must
65 : * not be NULL.
66 : *
67 : * @param hPanchroBand Panchromatic band. Must not be NULL.
68 : *
69 : * @param nInputSpectralBands Number of input spectral bands. Must be greater
70 : * than zero.
71 : *
72 : * @param pahInputSpectralBands Array of nInputSpectralBands spectral bands.
73 : *
74 : * @return NULL on failure, or a new virtual dataset handle on success to be
75 : * closed with GDALClose().
76 : *
77 : * @since GDAL 2.1
78 : */
79 :
80 18 : GDALDatasetH GDALCreatePansharpenedVRT(const char *pszXML,
81 : GDALRasterBandH hPanchroBand,
82 : int nInputSpectralBands,
83 : GDALRasterBandH *pahInputSpectralBands)
84 : {
85 18 : VALIDATE_POINTER1(pszXML, "GDALCreatePansharpenedVRT", nullptr);
86 18 : VALIDATE_POINTER1(hPanchroBand, "GDALCreatePansharpenedVRT", nullptr);
87 18 : VALIDATE_POINTER1(pahInputSpectralBands, "GDALCreatePansharpenedVRT",
88 : nullptr);
89 :
90 18 : CPLXMLNode *psTree = CPLParseXMLString(pszXML);
91 18 : if (psTree == nullptr)
92 1 : return nullptr;
93 17 : VRTPansharpenedDataset *poDS = new VRTPansharpenedDataset(0, 0);
94 17 : CPLErr eErr = poDS->XMLInit(psTree, nullptr, hPanchroBand,
95 : nInputSpectralBands, pahInputSpectralBands);
96 17 : CPLDestroyXMLNode(psTree);
97 17 : if (eErr != CE_None)
98 : {
99 4 : delete poDS;
100 4 : return nullptr;
101 : }
102 13 : return GDALDataset::ToHandle(poDS);
103 : }
104 :
105 : /*! @cond Doxygen_Suppress */
106 :
107 : /************************************************************************/
108 : /* ==================================================================== */
109 : /* VRTPansharpenedDataset */
110 : /* ==================================================================== */
111 : /************************************************************************/
112 :
113 : /************************************************************************/
114 : /* VRTPansharpenedDataset() */
115 : /************************************************************************/
116 :
117 171 : VRTPansharpenedDataset::VRTPansharpenedDataset(int nXSize, int nYSize,
118 171 : int nBlockXSize, int nBlockYSize)
119 : : VRTDataset(nXSize, nYSize,
120 171 : nBlockXSize > 0 ? nBlockXSize : std::min(nXSize, 512),
121 171 : nBlockYSize > 0 ? nBlockYSize : std::min(nYSize, 512)),
122 : m_poMainDataset(nullptr), m_bLoadingOtherBands(FALSE),
123 : m_pabyLastBufferBandRasterIO(nullptr), m_nLastBandRasterIOXOff(0),
124 : m_nLastBandRasterIOYOff(0), m_nLastBandRasterIOXSize(0),
125 : m_nLastBandRasterIOYSize(0), m_eLastBandRasterIODataType(GDT_Unknown),
126 513 : m_eGTAdjustment(GTAdjust_Union), m_bNoDataDisabled(FALSE)
127 : {
128 171 : eAccess = GA_Update;
129 171 : m_poMainDataset = this;
130 171 : }
131 :
132 : /************************************************************************/
133 : /* ~VRTPansharpenedDataset() */
134 : /************************************************************************/
135 :
136 342 : VRTPansharpenedDataset::~VRTPansharpenedDataset()
137 :
138 : {
139 171 : VRTPansharpenedDataset::FlushCache(true);
140 171 : VRTPansharpenedDataset::CloseDependentDatasets();
141 171 : CPLFree(m_pabyLastBufferBandRasterIO);
142 342 : }
143 :
144 : /************************************************************************/
145 : /* CloseDependentDatasets() */
146 : /************************************************************************/
147 :
148 171 : int VRTPansharpenedDataset::CloseDependentDatasets()
149 : {
150 171 : int bHasDroppedRef = VRTDataset::CloseDependentDatasets();
151 :
152 : /* -------------------------------------------------------------------- */
153 : /* Destroy the raster bands if they exist. */
154 : /* -------------------------------------------------------------------- */
155 492 : for (int iBand = 0; iBand < nBands; iBand++)
156 : {
157 321 : delete papoBands[iBand];
158 : }
159 171 : nBands = 0;
160 :
161 : // Destroy the overviews before m_poPansharpener as they might reference
162 : // files that are in m_apoDatasetsToReleaseRef.
163 171 : bHasDroppedRef |= !m_apoOverviewDatasets.empty();
164 171 : m_apoOverviewDatasets.clear();
165 :
166 171 : if (m_poPansharpener != nullptr)
167 : {
168 : // Delete the pansharper object before closing the dataset
169 : // because it may have warped the bands into an intermediate VRT
170 146 : m_poPansharpener.reset();
171 :
172 : // Close in reverse order (VRT firsts and real datasets after)
173 633 : for (int i = static_cast<int>(m_apoDatasetsToReleaseRef.size()) - 1;
174 633 : i >= 0; i--)
175 : {
176 487 : bHasDroppedRef = TRUE;
177 487 : m_apoDatasetsToReleaseRef[i].reset();
178 : }
179 146 : m_apoDatasetsToReleaseRef.clear();
180 : }
181 :
182 171 : return bHasDroppedRef;
183 : }
184 :
185 : /************************************************************************/
186 : /* GetFileList() */
187 : /************************************************************************/
188 :
189 2 : char **VRTPansharpenedDataset::GetFileList()
190 : {
191 2 : char **papszFileList = GDALDataset::GetFileList();
192 :
193 2 : if (m_poPansharpener != nullptr)
194 : {
195 2 : const GDALPansharpenOptions *psOptions = m_poPansharpener->GetOptions();
196 2 : if (psOptions != nullptr)
197 : {
198 4 : std::set<CPLString> oSetNames;
199 2 : if (psOptions->hPanchroBand != nullptr)
200 : {
201 2 : GDALDataset *poDS = GDALDataset::FromHandle(
202 2 : GDALGetBandDataset(psOptions->hPanchroBand));
203 2 : if (poDS != nullptr)
204 : {
205 : const char *pszName =
206 2 : poDS->GetMetadataItem("UNDERLYING_DATASET");
207 2 : if (!pszName)
208 1 : pszName = poDS->GetDescription();
209 2 : papszFileList = CSLAddString(papszFileList, pszName);
210 2 : oSetNames.insert(pszName);
211 : }
212 : }
213 6 : for (int i = 0; i < psOptions->nInputSpectralBands; i++)
214 : {
215 4 : if (psOptions->pahInputSpectralBands[i] != nullptr)
216 : {
217 : GDALDataset *poDS =
218 4 : GDALDataset::FromHandle(GDALGetBandDataset(
219 4 : psOptions->pahInputSpectralBands[i]));
220 4 : if (poDS != nullptr)
221 : {
222 : const char *pszName =
223 4 : poDS->GetMetadataItem("UNDERLYING_DATASET");
224 4 : if (!pszName)
225 3 : pszName = poDS->GetDescription();
226 4 : if (!cpl::contains(oSetNames, pszName))
227 : {
228 : papszFileList =
229 2 : CSLAddString(papszFileList, pszName);
230 2 : oSetNames.insert(pszName);
231 : }
232 : }
233 : }
234 : }
235 : }
236 : }
237 :
238 2 : return papszFileList;
239 : }
240 :
241 : /************************************************************************/
242 : /* XMLInit() */
243 : /************************************************************************/
244 :
245 151 : CPLErr VRTPansharpenedDataset::XMLInit(const CPLXMLNode *psTree,
246 : const char *pszVRTPathIn)
247 :
248 : {
249 151 : return XMLInit(psTree, pszVRTPathIn, nullptr, 0, nullptr);
250 : }
251 :
252 168 : CPLErr VRTPansharpenedDataset::XMLInit(const CPLXMLNode *psTree,
253 : const char *pszVRTPathIn,
254 : GDALRasterBandH hPanchroBandIn,
255 : int nInputSpectralBandsIn,
256 : GDALRasterBandH *pahInputSpectralBandsIn)
257 : {
258 : CPLErr eErr;
259 : std::unique_ptr<GDALPansharpenOptions,
260 : decltype(&GDALDestroyPansharpenOptions)>
261 336 : psPanOptions(nullptr, GDALDestroyPansharpenOptions);
262 :
263 : /* -------------------------------------------------------------------- */
264 : /* Initialize blocksize before calling sub-init so that the */
265 : /* band initializers can get it from the dataset object when */
266 : /* they are created. */
267 : /* -------------------------------------------------------------------- */
268 168 : m_nBlockXSize = atoi(CPLGetXMLValue(psTree, "BlockXSize", "512"));
269 168 : m_nBlockYSize = atoi(CPLGetXMLValue(psTree, "BlockYSize", "512"));
270 :
271 : /* -------------------------------------------------------------------- */
272 : /* Parse PansharpeningOptions */
273 : /* -------------------------------------------------------------------- */
274 :
275 168 : const CPLXMLNode *psOptions = CPLGetXMLNode(psTree, "PansharpeningOptions");
276 168 : if (psOptions == nullptr)
277 : {
278 1 : CPLError(CE_Failure, CPLE_AppDefined, "Missing PansharpeningOptions");
279 1 : return CE_Failure;
280 : }
281 :
282 334 : if (CPLGetXMLValue(psOptions, "MSShiftX", nullptr) != nullptr ||
283 167 : CPLGetXMLValue(psOptions, "MSShiftY", nullptr) != nullptr)
284 : {
285 0 : CPLError(CE_Failure, CPLE_AppDefined,
286 : "Options MSShiftX and MSShiftY are no longer supported. "
287 : "Spatial adjustment between panchromatic and multispectral "
288 : "bands is done through their geotransform.");
289 0 : return CE_Failure;
290 : }
291 :
292 334 : CPLString osSourceFilename;
293 167 : GDALDataset *poPanDataset = nullptr;
294 167 : GDALRasterBand *poPanBand = nullptr;
295 334 : std::map<CPLString, GDALDataset *> oMapNamesToDataset;
296 : int nPanBand;
297 :
298 167 : if (hPanchroBandIn == nullptr)
299 : {
300 : const CPLXMLNode *psPanchroBand =
301 150 : CPLGetXMLNode(psOptions, "PanchroBand");
302 150 : if (psPanchroBand == nullptr)
303 : {
304 1 : CPLError(CE_Failure, CPLE_AppDefined, "PanchroBand missing");
305 18 : return CE_Failure;
306 : }
307 :
308 149 : osSourceFilename = CPLGetXMLValue(psPanchroBand, "SourceFilename", "");
309 149 : if (osSourceFilename.empty())
310 : {
311 1 : CPLError(CE_Failure, CPLE_AppDefined,
312 : "PanchroBand.SourceFilename missing");
313 1 : return CE_Failure;
314 : }
315 148 : const bool bRelativeToVRT = CPL_TO_BOOL(atoi(CPLGetXMLValue(
316 : psPanchroBand, "SourceFilename.relativetoVRT", "0")));
317 148 : if (bRelativeToVRT)
318 : {
319 : const std::string osAbs = CPLProjectRelativeFilenameSafe(
320 103 : pszVRTPathIn, osSourceFilename.c_str());
321 103 : m_oMapToRelativeFilenames[osAbs] = osSourceFilename;
322 103 : osSourceFilename = osAbs;
323 : }
324 :
325 : const CPLStringList aosOpenOptions(
326 148 : GDALDeserializeOpenOptionsFromXML(psPanchroBand));
327 :
328 148 : poPanDataset = GDALDataset::Open(osSourceFilename,
329 : GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR,
330 : nullptr, aosOpenOptions.List());
331 148 : if (poPanDataset == nullptr)
332 : {
333 16 : return CE_Failure;
334 : }
335 :
336 : const char *pszSourceBand =
337 132 : CPLGetXMLValue(psPanchroBand, "SourceBand", "1");
338 132 : nPanBand = atoi(pszSourceBand);
339 132 : poPanBand = poPanDataset->GetRasterBand(nPanBand);
340 132 : if (poPanBand == nullptr)
341 : {
342 0 : CPLError(CE_Failure, CPLE_AppDefined, "%s invalid band of %s",
343 : pszSourceBand, osSourceFilename.c_str());
344 0 : GDALClose(poPanDataset);
345 0 : return CE_Failure;
346 : }
347 132 : oMapNamesToDataset[osSourceFilename] = poPanDataset;
348 : }
349 : else
350 : {
351 17 : poPanBand = GDALRasterBand::FromHandle(hPanchroBandIn);
352 17 : nPanBand = poPanBand->GetBand();
353 17 : poPanDataset = poPanBand->GetDataset();
354 17 : if (poPanDataset == nullptr)
355 : {
356 0 : CPLError(
357 : CE_Failure, CPLE_AppDefined,
358 : "Cannot retrieve dataset associated with panchromatic band");
359 0 : return CE_Failure;
360 : }
361 17 : oMapNamesToDataset[CPLSPrintf("%p", poPanDataset)] = poPanDataset;
362 17 : poPanDataset->Reference();
363 : }
364 149 : m_apoDatasetsToReleaseRef.push_back(
365 298 : std::unique_ptr<GDALDataset, GDALDatasetUniquePtrReleaser>(
366 : poPanDataset));
367 149 : poPanDataset = m_apoDatasetsToReleaseRef.back().get();
368 : // Figure out which kind of adjustment we should do if the pan and spectral
369 : // bands do not share the same geotransform
370 : const char *pszGTAdjustment =
371 149 : CPLGetXMLValue(psOptions, "SpatialExtentAdjustment", "Union");
372 149 : if (EQUAL(pszGTAdjustment, "Union"))
373 68 : m_eGTAdjustment = GTAdjust_Union;
374 81 : else if (EQUAL(pszGTAdjustment, "Intersection"))
375 3 : m_eGTAdjustment = GTAdjust_Intersection;
376 78 : else if (EQUAL(pszGTAdjustment, "None"))
377 2 : m_eGTAdjustment = GTAdjust_None;
378 76 : else if (EQUAL(pszGTAdjustment, "NoneWithoutWarning"))
379 75 : m_eGTAdjustment = GTAdjust_NoneWithoutWarning;
380 : else
381 : {
382 1 : m_eGTAdjustment = GTAdjust_Union;
383 1 : CPLError(CE_Failure, CPLE_AppDefined,
384 : "Unsupported value for GeoTransformAdjustment. Defaulting to "
385 : "Union");
386 : }
387 :
388 : const char *pszNumThreads =
389 149 : CPLGetXMLValue(psOptions, "NumThreads", nullptr);
390 149 : int nThreads = 0;
391 149 : if (pszNumThreads != nullptr)
392 : {
393 101 : if (EQUAL(pszNumThreads, "ALL_CPUS"))
394 65 : nThreads = -1;
395 : else
396 36 : nThreads = atoi(pszNumThreads);
397 : }
398 :
399 : const char *pszAlgorithm =
400 149 : CPLGetXMLValue(psOptions, "Algorithm", "WeightedBrovey");
401 149 : if (!EQUAL(pszAlgorithm, "WeightedBrovey"))
402 : {
403 0 : CPLError(CE_Failure, CPLE_AppDefined, "Algorithm %s unsupported",
404 : pszAlgorithm);
405 0 : return CE_Failure;
406 : }
407 :
408 298 : std::vector<double> adfWeights;
409 149 : if (const CPLXMLNode *psAlgOptions =
410 149 : CPLGetXMLNode(psOptions, "AlgorithmOptions"))
411 : {
412 : const char *pszWeights =
413 25 : CPLGetXMLValue(psAlgOptions, "Weights", nullptr);
414 25 : if (pszWeights != nullptr)
415 : {
416 25 : char **papszTokens = CSLTokenizeString2(pszWeights, " ,", 0);
417 81 : for (int i = 0; papszTokens && papszTokens[i]; i++)
418 56 : adfWeights.push_back(CPLAtof(papszTokens[i]));
419 25 : CSLDestroy(papszTokens);
420 : }
421 : }
422 :
423 149 : GDALRIOResampleAlg eResampleAlg = GDALRasterIOGetResampleAlg(
424 : CPLGetXMLValue(psOptions, "Resampling", "Cubic"));
425 :
426 298 : std::vector<GDALRasterBand *> ahSpectralBands;
427 298 : std::map<int, int> aMapDstBandToSpectralBand;
428 149 : std::map<int, int>::iterator aMapDstBandToSpectralBandIter;
429 149 : int nBitDepth = 0;
430 149 : bool bFoundNonMatchingGT = false;
431 149 : GDALGeoTransform panGT;
432 : const bool bPanGeoTransformValid =
433 149 : (poPanDataset->GetGeoTransform(panGT) == CE_None);
434 149 : if (!bPanGeoTransformValid)
435 : {
436 1 : CPLError(CE_Failure, CPLE_AppDefined,
437 : "Panchromatic band has no associated geotransform");
438 1 : return CE_Failure;
439 : }
440 148 : int nPanXSize = poPanBand->GetXSize();
441 148 : int nPanYSize = poPanBand->GetYSize();
442 148 : int bHasNoData = FALSE;
443 148 : double dfNoData = poPanBand->GetNoDataValue(&bHasNoData);
444 148 : double dfLRPanX = panGT[0] + nPanXSize * panGT[1] + nPanYSize * panGT[2];
445 148 : double dfLRPanY = panGT[3] + nPanXSize * panGT[4] + nPanYSize * panGT[5];
446 148 : bool bFoundRotatingTerms = (panGT[2] != 0.0 || panGT[4] != 0.0);
447 148 : double dfMinX = panGT[0];
448 148 : double dfMaxX = dfLRPanX;
449 148 : double dfMaxY = panGT[3];
450 148 : double dfMinY = dfLRPanY;
451 148 : if (dfMinY > dfMaxY)
452 84 : std::swap(dfMinY, dfMaxY);
453 148 : const double dfPanMinY = dfMinY;
454 148 : const double dfPanMaxY = dfMaxY;
455 :
456 148 : const auto poPanSRS = poPanDataset->GetSpatialRef();
457 :
458 : /* -------------------------------------------------------------------- */
459 : /* First pass on spectral datasets to check their georeferencing. */
460 : /* -------------------------------------------------------------------- */
461 148 : int iSpectralBand = 0;
462 995 : for (const CPLXMLNode *psIter = psOptions->psChild; psIter;
463 847 : psIter = psIter->psNext)
464 : {
465 : GDALDataset *poDataset;
466 848 : if (psIter->eType != CXT_Element ||
467 848 : !EQUAL(psIter->pszValue, "SpectralBand"))
468 524 : continue;
469 :
470 324 : if (nInputSpectralBandsIn && pahInputSpectralBandsIn != nullptr)
471 : {
472 42 : if (iSpectralBand == nInputSpectralBandsIn)
473 : {
474 1 : CPLError(CE_Failure, CPLE_AppDefined,
475 : "More SpectralBand elements than in source array");
476 1 : goto error;
477 : }
478 : poDataset = GDALRasterBand::FromHandle(
479 41 : pahInputSpectralBandsIn[iSpectralBand])
480 41 : ->GetDataset();
481 41 : if (poDataset == nullptr)
482 : {
483 0 : CPLError(CE_Failure, CPLE_AppDefined,
484 : "SpectralBand has no associated dataset");
485 0 : goto error;
486 : }
487 41 : osSourceFilename = poDataset->GetDescription();
488 :
489 41 : oMapNamesToDataset[CPLSPrintf("%p", poDataset)] = poDataset;
490 41 : poDataset->Reference();
491 : }
492 : else
493 : {
494 282 : osSourceFilename = CPLGetXMLValue(psIter, "SourceFilename", "");
495 282 : if (osSourceFilename.empty())
496 : {
497 0 : CPLError(CE_Failure, CPLE_AppDefined,
498 : "SpectralBand.SourceFilename missing");
499 0 : goto error;
500 : }
501 282 : int bRelativeToVRT = atoi(
502 : CPLGetXMLValue(psIter, "SourceFilename.relativetoVRT", "0"));
503 282 : if (bRelativeToVRT)
504 : {
505 : const std::string osAbs = CPLProjectRelativeFilenameSafe(
506 211 : pszVRTPathIn, osSourceFilename.c_str());
507 211 : m_oMapToRelativeFilenames[osAbs] = osSourceFilename;
508 211 : osSourceFilename = osAbs;
509 : }
510 282 : poDataset = oMapNamesToDataset[osSourceFilename];
511 282 : if (poDataset == nullptr)
512 : {
513 : const CPLStringList aosOpenOptions(
514 134 : GDALDeserializeOpenOptionsFromXML(psIter));
515 :
516 134 : poDataset = GDALDataset::Open(
517 : osSourceFilename, GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR,
518 : nullptr, aosOpenOptions.List());
519 134 : if (poDataset == nullptr)
520 : {
521 0 : goto error;
522 : }
523 134 : oMapNamesToDataset[osSourceFilename] = poDataset;
524 : }
525 : else
526 : {
527 148 : poDataset->Reference();
528 : }
529 : }
530 323 : m_apoDatasetsToReleaseRef.push_back(
531 646 : std::unique_ptr<GDALDataset, GDALDatasetUniquePtrReleaser>(
532 : poDataset));
533 323 : poDataset = m_apoDatasetsToReleaseRef.back().get();
534 :
535 : // Check that the spectral band has a georeferencing consistent
536 : // of the pan band. Allow an error of at most the size of one pixel
537 : // of the spectral band.
538 323 : const auto poSpectralSRS = poDataset->GetSpatialRef();
539 323 : if (poPanSRS)
540 : {
541 135 : if (poSpectralSRS)
542 : {
543 135 : if (!poPanSRS->IsSame(poSpectralSRS))
544 : {
545 1 : CPLError(CE_Warning, CPLE_AppDefined,
546 : "Pan dataset and %s do not seem to "
547 : "have same projection. Results might "
548 : "be incorrect",
549 : osSourceFilename.c_str());
550 : }
551 : }
552 : else
553 : {
554 0 : CPLError(CE_Warning, CPLE_AppDefined,
555 : "Pan dataset has a projection, whereas %s "
556 : "not. Results might be incorrect",
557 : osSourceFilename.c_str());
558 : }
559 : }
560 188 : else if (poSpectralSRS)
561 : {
562 0 : CPLError(CE_Warning, CPLE_AppDefined,
563 : "Pan dataset has no projection, whereas %s has "
564 : "one. Results might be incorrect",
565 : osSourceFilename.c_str());
566 : }
567 :
568 323 : GDALGeoTransform spectralGT;
569 323 : if (poDataset->GetGeoTransform(spectralGT) != CE_None)
570 : {
571 0 : CPLError(CE_Failure, CPLE_AppDefined,
572 : "Spectral band has no associated geotransform");
573 0 : goto error;
574 : }
575 323 : if (spectralGT[5] * panGT[5] < 0)
576 : {
577 0 : CPLError(CE_Failure, CPLE_NotSupported,
578 : "Spectral band vertical orientation is "
579 : "different from pan one");
580 0 : goto error;
581 : }
582 :
583 323 : int bIsThisOneNonMatching = FALSE;
584 323 : double dfPixelSize = std::max(spectralGT[1], std::abs(spectralGT[5]));
585 585 : if (std::abs(panGT[0] - spectralGT[0]) > dfPixelSize ||
586 262 : std::abs(panGT[3] - spectralGT[3]) > dfPixelSize)
587 : {
588 61 : bIsThisOneNonMatching = TRUE;
589 61 : if (m_eGTAdjustment == GTAdjust_None)
590 : {
591 2 : CPLError(CE_Warning, CPLE_AppDefined,
592 : "Georeferencing of top-left corner of pan "
593 : "dataset and %s do not match",
594 : osSourceFilename.c_str());
595 : }
596 : }
597 646 : bFoundRotatingTerms = bFoundRotatingTerms ||
598 323 : (spectralGT[2] != 0.0 || spectralGT[4] != 0.0);
599 323 : double dfLRSpectralX = spectralGT[0] +
600 323 : poDataset->GetRasterXSize() * spectralGT[1] +
601 323 : poDataset->GetRasterYSize() * spectralGT[2];
602 323 : double dfLRSpectralY = spectralGT[3] +
603 323 : poDataset->GetRasterXSize() * spectralGT[4] +
604 323 : poDataset->GetRasterYSize() * spectralGT[5];
605 537 : if (std::abs(dfLRPanX - dfLRSpectralX) > dfPixelSize ||
606 214 : std::abs(dfLRPanY - dfLRSpectralY) > dfPixelSize)
607 : {
608 109 : bIsThisOneNonMatching = TRUE;
609 109 : if (m_eGTAdjustment == GTAdjust_None)
610 : {
611 2 : CPLError(CE_Warning, CPLE_AppDefined,
612 : "Georeferencing of bottom-right corner of "
613 : "pan dataset and %s do not match",
614 : osSourceFilename.c_str());
615 : }
616 : }
617 :
618 323 : double dfThisMinY = dfLRSpectralY;
619 323 : double dfThisMaxY = spectralGT[3];
620 323 : if (dfThisMinY > dfThisMaxY)
621 168 : std::swap(dfThisMinY, dfThisMaxY);
622 323 : if (bIsThisOneNonMatching && m_eGTAdjustment == GTAdjust_Union)
623 : {
624 24 : dfMinX = std::min(dfMinX, spectralGT[0]);
625 24 : dfMinY = std::min(dfMinY, dfThisMinY);
626 24 : dfMaxX = std::max(dfMaxX, dfLRSpectralX);
627 24 : dfMaxY = std::max(dfMaxY, dfThisMaxY);
628 : }
629 299 : else if (bIsThisOneNonMatching &&
630 85 : m_eGTAdjustment == GTAdjust_Intersection)
631 : {
632 2 : dfMinX = std::max(dfMinX, spectralGT[0]);
633 2 : dfMinY = std::max(dfMinY, dfThisMinY);
634 2 : dfMaxX = std::min(dfMaxX, dfLRSpectralX);
635 2 : dfMaxY = std::min(dfMaxY, dfThisMaxY);
636 : }
637 :
638 323 : bFoundNonMatchingGT = bFoundNonMatchingGT || bIsThisOneNonMatching;
639 :
640 323 : iSpectralBand++;
641 : }
642 :
643 147 : if (nInputSpectralBandsIn && iSpectralBand != nInputSpectralBandsIn)
644 : {
645 1 : CPLError(CE_Failure, CPLE_AppDefined,
646 : "Less SpectralBand elements than in source array");
647 1 : goto error;
648 : }
649 :
650 : /* -------------------------------------------------------------------- */
651 : /* On-the-fly spatial extent adjustment if needed and asked. */
652 : /* -------------------------------------------------------------------- */
653 :
654 146 : if (bFoundNonMatchingGT && (m_eGTAdjustment == GTAdjust_Union ||
655 45 : m_eGTAdjustment == GTAdjust_Intersection))
656 : {
657 13 : if (bFoundRotatingTerms)
658 : {
659 0 : CPLError(
660 : CE_Failure, CPLE_NotSupported,
661 : "One of the panchromatic or spectral datasets has rotating "
662 : "terms in their geotransform matrix. Adjustment not possible");
663 2 : goto error;
664 : }
665 13 : if (m_eGTAdjustment == GTAdjust_Intersection &&
666 2 : (dfMinX >= dfMaxX || dfMinY >= dfMaxY))
667 : {
668 1 : CPLError(
669 : CE_Failure, CPLE_NotSupported,
670 : "One of the panchromatic or spectral datasets has rotating "
671 : "terms in their geotransform matrix. Adjustment not possible");
672 1 : goto error;
673 : }
674 12 : if (m_eGTAdjustment == GTAdjust_Union)
675 11 : CPLDebug("VRT", "Do union of bounding box of panchromatic and "
676 : "spectral datasets");
677 : else
678 1 : CPLDebug("VRT", "Do intersection of bounding box of panchromatic "
679 : "and spectral datasets");
680 :
681 : // If the pandataset needs adjustments, make sure the coordinates of the
682 : // union/intersection properly align with the grid of the pandataset
683 : // to avoid annoying sub-pixel shifts on the panchro band.
684 12 : double dfPixelSize = std::max(panGT[1], std::abs(panGT[5]));
685 12 : if (std::abs(panGT[0] - dfMinX) > dfPixelSize ||
686 7 : std::abs(dfPanMaxY - dfMaxY) > dfPixelSize ||
687 21 : std::abs(dfLRPanX - dfMaxX) > dfPixelSize ||
688 2 : std::abs(dfPanMinY - dfMinY) > dfPixelSize)
689 : {
690 10 : dfMinX =
691 10 : panGT[0] +
692 10 : std::floor((dfMinX - panGT[0]) / panGT[1] + 0.5) * panGT[1];
693 10 : dfMaxX =
694 10 : dfLRPanX +
695 10 : std::floor((dfMaxX - dfLRPanX) / panGT[1] + 0.5) * panGT[1];
696 10 : if (panGT[5] > 0)
697 : {
698 0 : dfMinY = dfPanMinY +
699 0 : std::floor((dfMinY - dfPanMinY) / panGT[5] + 0.5) *
700 0 : panGT[5];
701 0 : dfMaxY = dfPanMinY +
702 0 : std::floor((dfMaxY - dfPanMinY) / panGT[5] + 0.5) *
703 0 : panGT[5];
704 : }
705 : else
706 : {
707 10 : dfMinY = dfPanMaxY +
708 10 : std::floor((dfMinY - dfPanMaxY) / panGT[5] + 0.5) *
709 10 : panGT[5];
710 10 : dfMaxY = dfPanMaxY +
711 20 : std::floor((dfMaxY - dfPanMaxY) / panGT[5] + 0.5) *
712 10 : panGT[5];
713 : }
714 : }
715 :
716 : std::map<CPLString, GDALDataset *>::iterator oIter =
717 12 : oMapNamesToDataset.begin();
718 34 : for (; oIter != oMapNamesToDataset.end(); ++oIter)
719 : {
720 23 : GDALDataset *poSrcDS = oIter->second;
721 23 : GDALGeoTransform gt;
722 23 : if (poSrcDS->GetGeoTransform(gt) != CE_None)
723 3 : continue;
724 :
725 : // Check if this dataset needs adjustments
726 23 : dfPixelSize = std::max(gt.xscale, std::abs(gt.yscale));
727 23 : dfPixelSize = std::max(panGT[1], dfPixelSize);
728 23 : dfPixelSize = std::max(std::abs(panGT[5]), dfPixelSize);
729 23 : double dfThisMinX = gt.xorig;
730 : double dfThisMaxX =
731 23 : gt.xorig + poSrcDS->GetRasterXSize() * gt.xscale;
732 23 : double dfThisMaxY = gt.yorig;
733 : double dfThisMinY =
734 23 : gt.yorig + poSrcDS->GetRasterYSize() * gt.yscale;
735 23 : if (dfThisMinY > dfThisMaxY)
736 2 : std::swap(dfThisMinY, dfThisMaxY);
737 23 : if (std::abs(dfThisMinX - dfMinX) <= dfPixelSize &&
738 11 : std::abs(dfThisMaxY - dfMaxY) <= dfPixelSize &&
739 37 : std::abs(dfThisMaxX - dfMaxX) <= dfPixelSize &&
740 3 : std::abs(dfThisMinY - dfMinY) <= dfPixelSize)
741 : {
742 3 : continue;
743 : }
744 :
745 20 : GDALGeoTransform adjustedGT;
746 20 : adjustedGT[0] = dfMinX;
747 20 : adjustedGT[1] = gt.xscale;
748 20 : adjustedGT[2] = 0;
749 20 : adjustedGT[3] = gt.yscale > 0 ? dfMinY : dfMaxY;
750 20 : adjustedGT[4] = 0;
751 20 : adjustedGT[5] = gt.yscale;
752 : const double dfAdjustedRasterXSize =
753 20 : 0.5 + (dfMaxX - dfMinX) / adjustedGT[1];
754 : const double dfAdjustedRasterYSize =
755 20 : 0.5 + (dfMaxY - dfMinY) / std::abs(adjustedGT[5]);
756 20 : if (!(dfAdjustedRasterXSize >= 1 &&
757 20 : dfAdjustedRasterXSize < INT_MAX &&
758 19 : dfAdjustedRasterYSize >= 1 &&
759 19 : dfAdjustedRasterYSize < INT_MAX))
760 : {
761 1 : CPLError(CE_Failure, CPLE_AppDefined,
762 : "Datasets are too disjoint");
763 1 : goto error;
764 : }
765 19 : const int nAdjustRasterXSize =
766 : static_cast<int>(dfAdjustedRasterXSize);
767 19 : const int nAdjustRasterYSize =
768 : static_cast<int>(dfAdjustedRasterYSize);
769 :
770 : VRTDataset *poVDS =
771 19 : new VRTDataset(nAdjustRasterXSize, nAdjustRasterYSize);
772 19 : poVDS->SetWritable(FALSE);
773 19 : poVDS->SetMetadataItem("UNDERLYING_DATASET",
774 19 : poSrcDS->GetDescription());
775 19 : poVDS->SetGeoTransform(adjustedGT);
776 19 : poVDS->SetProjection(poPanDataset->GetProjectionRef());
777 :
778 44 : for (int i = 0; i < poSrcDS->GetRasterCount(); i++)
779 : {
780 25 : GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand(i + 1);
781 25 : poVDS->AddBand(poSrcBand->GetRasterDataType(), nullptr);
782 : VRTSourcedRasterBand *poVRTBand =
783 : static_cast<VRTSourcedRasterBand *>(
784 25 : poVDS->GetRasterBand(i + 1));
785 :
786 50 : const char *pszNBITS = poSrcBand->GetMetadataItem(
787 25 : GDALMD_NBITS, GDAL_MDD_IMAGE_STRUCTURE);
788 25 : if (pszNBITS)
789 0 : poVRTBand->SetMetadataItem(GDALMD_NBITS, pszNBITS,
790 0 : GDAL_MDD_IMAGE_STRUCTURE);
791 :
792 25 : VRTSimpleSource *poSimpleSource = new VRTSimpleSource();
793 100 : poVRTBand->ConfigureSource(
794 : poSimpleSource, poSrcBand, FALSE,
795 25 : static_cast<int>(
796 25 : std::floor((dfMinX - gt.xorig) / gt.xscale + 0.001)),
797 25 : gt.yscale < 0
798 22 : ? static_cast<int>(std::floor(
799 22 : (dfMaxY - dfThisMaxY) / gt.yscale + 0.001))
800 3 : : static_cast<int>(std::floor(
801 3 : (dfMinY - dfThisMinY) / gt.yscale + 0.001)),
802 25 : static_cast<int>(0.5 + (dfMaxX - dfMinX) / gt.xscale),
803 25 : static_cast<int>(0.5 +
804 25 : (dfMaxY - dfMinY) / std::abs(gt.yscale)),
805 : 0, 0, nAdjustRasterXSize, nAdjustRasterYSize);
806 :
807 25 : poVRTBand->AddSource(poSimpleSource);
808 : }
809 :
810 19 : oIter->second = poVDS;
811 19 : if (poSrcDS == poPanDataset)
812 : {
813 9 : panGT = adjustedGT;
814 9 : poPanDataset = poVDS;
815 9 : poPanBand = poPanDataset->GetRasterBand(nPanBand);
816 9 : nPanXSize = poPanDataset->GetRasterXSize();
817 9 : nPanYSize = poPanDataset->GetRasterYSize();
818 : }
819 :
820 19 : m_apoDatasetsToReleaseRef.push_back(
821 38 : std::unique_ptr<GDALDataset, GDALDatasetUniquePtrReleaser>(
822 : poVDS));
823 : }
824 : }
825 :
826 144 : if (nRasterXSize == 0 && nRasterYSize == 0)
827 : {
828 131 : nRasterXSize = nPanXSize;
829 131 : nRasterYSize = nPanYSize;
830 : }
831 13 : else if (nRasterXSize != nPanXSize || nRasterYSize != nPanYSize)
832 : {
833 0 : CPLError(CE_Failure, CPLE_AppDefined,
834 : "Inconsistent declared VRT dimensions with panchro dataset");
835 0 : goto error;
836 : }
837 :
838 : /* -------------------------------------------------------------------- */
839 : /* Initialize all the general VRT stuff. This will even */
840 : /* create the VRTPansharpenedRasterBands and initialize them. */
841 : /* -------------------------------------------------------------------- */
842 144 : eErr = VRTDataset::XMLInit(psTree, pszVRTPathIn);
843 :
844 144 : if (eErr != CE_None)
845 : {
846 0 : goto error;
847 : }
848 :
849 : /* -------------------------------------------------------------------- */
850 : /* Inherit georeferencing info from panchro band if not defined */
851 : /* in VRT. */
852 : /* -------------------------------------------------------------------- */
853 :
854 : {
855 144 : GDALGeoTransform outGT;
856 276 : if (GetGeoTransform(outGT) != CE_None && GetGCPCount() == 0 &&
857 132 : GetSpatialRef() == nullptr)
858 : {
859 132 : if (bPanGeoTransformValid)
860 : {
861 132 : SetGeoTransform(panGT);
862 : }
863 132 : if (poPanSRS)
864 : {
865 38 : SetSpatialRef(poPanSRS);
866 : }
867 : }
868 : }
869 :
870 : /* -------------------------------------------------------------------- */
871 : /* Parse rest of PansharpeningOptions */
872 : /* -------------------------------------------------------------------- */
873 144 : iSpectralBand = 0;
874 979 : for (const CPLXMLNode *psIter = psOptions->psChild; psIter;
875 835 : psIter = psIter->psNext)
876 : {
877 835 : if (psIter->eType != CXT_Element ||
878 835 : !EQUAL(psIter->pszValue, "SpectralBand"))
879 519 : continue;
880 :
881 : GDALDataset *poDataset;
882 : GDALRasterBand *poBand;
883 :
884 316 : const char *pszDstBand = CPLGetXMLValue(psIter, "dstBand", nullptr);
885 316 : int nDstBand = -1;
886 316 : if (pszDstBand != nullptr)
887 : {
888 310 : nDstBand = atoi(pszDstBand);
889 310 : if (nDstBand <= 0)
890 : {
891 0 : CPLError(CE_Failure, CPLE_AppDefined,
892 : "SpectralBand.dstBand = '%s' invalid", pszDstBand);
893 0 : goto error;
894 : }
895 : }
896 :
897 316 : if (nInputSpectralBandsIn && pahInputSpectralBandsIn != nullptr)
898 : {
899 70 : poBand = GDALRasterBand::FromHandle(
900 35 : pahInputSpectralBandsIn[iSpectralBand]);
901 35 : poDataset = poBand->GetDataset();
902 35 : if (poDataset)
903 : {
904 35 : poDataset = oMapNamesToDataset[CPLSPrintf("%p", poDataset)];
905 35 : CPLAssert(poDataset);
906 35 : if (poDataset)
907 35 : poBand = poDataset->GetRasterBand(poBand->GetBand());
908 : }
909 : }
910 : else
911 : {
912 281 : osSourceFilename = CPLGetXMLValue(psIter, "SourceFilename", "");
913 281 : const bool bRelativeToVRT = CPL_TO_BOOL(atoi(
914 : CPLGetXMLValue(psIter, "SourceFilename.relativetoVRT", "0")));
915 281 : if (bRelativeToVRT)
916 422 : osSourceFilename = CPLProjectRelativeFilenameSafe(
917 211 : pszVRTPathIn, osSourceFilename.c_str());
918 281 : poDataset = oMapNamesToDataset[osSourceFilename];
919 281 : CPLAssert(poDataset);
920 : const char *pszSourceBand =
921 281 : CPLGetXMLValue(psIter, "SourceBand", "1");
922 281 : const int nBand = atoi(pszSourceBand);
923 281 : poBand = poDataset->GetRasterBand(nBand);
924 281 : if (poBand == nullptr)
925 : {
926 0 : CPLError(CE_Failure, CPLE_AppDefined, "%s invalid band of %s",
927 : pszSourceBand, osSourceFilename.c_str());
928 0 : goto error;
929 : }
930 : }
931 :
932 316 : if (bHasNoData)
933 : {
934 3 : double dfSpectralNoData = poPanBand->GetNoDataValue(&bHasNoData);
935 3 : if (bHasNoData && dfSpectralNoData != dfNoData)
936 0 : bHasNoData = FALSE;
937 : }
938 :
939 316 : ahSpectralBands.push_back(poBand);
940 316 : if (nDstBand >= 1)
941 : {
942 310 : if (aMapDstBandToSpectralBand.find(nDstBand - 1) !=
943 620 : aMapDstBandToSpectralBand.end())
944 : {
945 0 : CPLError(
946 : CE_Failure, CPLE_AppDefined,
947 : "Another spectral band is already mapped to output band %d",
948 : nDstBand);
949 0 : goto error;
950 : }
951 310 : aMapDstBandToSpectralBand[nDstBand - 1] =
952 310 : static_cast<int>(ahSpectralBands.size() - 1);
953 : }
954 :
955 316 : iSpectralBand++;
956 : }
957 :
958 144 : if (ahSpectralBands.empty())
959 : {
960 0 : CPLError(CE_Failure, CPLE_AppDefined, "No spectral band defined");
961 0 : goto error;
962 : }
963 :
964 : {
965 144 : const char *pszNoData = CPLGetXMLValue(psOptions, "NoData", nullptr);
966 144 : if (pszNoData)
967 : {
968 45 : if (EQUAL(pszNoData, "NONE"))
969 : {
970 2 : m_bNoDataDisabled = TRUE;
971 2 : bHasNoData = FALSE;
972 : }
973 : else
974 : {
975 43 : bHasNoData = TRUE;
976 43 : dfNoData = CPLAtof(pszNoData);
977 : }
978 : }
979 : }
980 :
981 : // Set nodata to 0 if not already set (explicitly or inherited)
982 144 : if ((m_eGTAdjustment == GTAdjust_None ||
983 142 : m_eGTAdjustment == GTAdjust_NoneWithoutWarning) &&
984 77 : !bHasNoData && !m_bNoDataDisabled)
985 : {
986 39 : bHasNoData = TRUE;
987 39 : dfNoData = 0;
988 : }
989 :
990 144 : if (GetRasterCount() == 0)
991 : {
992 372 : for (int i = 0; i < static_cast<int>(aMapDstBandToSpectralBand.size());
993 : i++)
994 : {
995 251 : if (aMapDstBandToSpectralBand.find(i) ==
996 502 : aMapDstBandToSpectralBand.end())
997 : {
998 0 : CPLError(CE_Failure, CPLE_AppDefined,
999 : "Hole in SpectralBand.dstBand numbering");
1000 0 : goto error;
1001 : }
1002 251 : GDALRasterBand *poInputBand = GDALRasterBand::FromHandle(
1003 251 : ahSpectralBands[aMapDstBandToSpectralBand[i]]);
1004 : GDALRasterBand *poBand = new VRTPansharpenedRasterBand(
1005 251 : this, i + 1, poInputBand->GetRasterDataType());
1006 251 : poBand->SetColorInterpretation(
1007 251 : poInputBand->GetColorInterpretation());
1008 251 : if (bHasNoData)
1009 160 : poBand->SetNoDataValue(dfNoData);
1010 251 : SetBand(i + 1, poBand);
1011 : }
1012 : }
1013 : else
1014 : {
1015 23 : int nIdxAsPansharpenedBand = 0;
1016 86 : for (int i = 0; i < nBands; i++)
1017 : {
1018 63 : if (static_cast<VRTRasterBand *>(GetRasterBand(i + 1))
1019 63 : ->IsPansharpenRasterBand())
1020 : {
1021 59 : if (aMapDstBandToSpectralBand.find(i) ==
1022 118 : aMapDstBandToSpectralBand.end())
1023 : {
1024 0 : CPLError(CE_Failure, CPLE_AppDefined,
1025 : "Band %d of type VRTPansharpenedRasterBand, but "
1026 : "no corresponding SpectralBand",
1027 : i + 1);
1028 0 : goto error;
1029 : }
1030 : else
1031 : {
1032 : static_cast<VRTPansharpenedRasterBand *>(
1033 59 : GetRasterBand(i + 1))
1034 59 : ->SetIndexAsPansharpenedBand(nIdxAsPansharpenedBand);
1035 59 : nIdxAsPansharpenedBand++;
1036 : }
1037 : }
1038 : }
1039 : }
1040 :
1041 : // Figure out bit depth
1042 : {
1043 : const char *pszBitDepth =
1044 144 : CPLGetXMLValue(psOptions, "BitDepth", nullptr);
1045 144 : if (pszBitDepth == nullptr)
1046 : pszBitDepth =
1047 133 : GDALRasterBand::FromHandle(ahSpectralBands[0])
1048 133 : ->GetMetadataItem(GDALMD_NBITS, GDAL_MDD_IMAGE_STRUCTURE);
1049 144 : if (pszBitDepth)
1050 13 : nBitDepth = atoi(pszBitDepth);
1051 144 : if (nBitDepth)
1052 : {
1053 37 : for (int i = 0; i < nBands; i++)
1054 : {
1055 24 : if (!static_cast<VRTRasterBand *>(GetRasterBand(i + 1))
1056 24 : ->IsPansharpenRasterBand())
1057 2 : continue;
1058 22 : if (GetRasterBand(i + 1)->GetMetadataItem(
1059 22 : GDALMD_NBITS, GDAL_MDD_IMAGE_STRUCTURE) == nullptr)
1060 : {
1061 22 : if (nBitDepth != 8 && nBitDepth != 16 && nBitDepth != 32)
1062 : {
1063 12 : GetRasterBand(i + 1)->SetMetadataItem(
1064 : GDALMD_NBITS, CPLSPrintf("%d", nBitDepth),
1065 6 : GDAL_MDD_IMAGE_STRUCTURE);
1066 : }
1067 : }
1068 0 : else if (nBitDepth == 8 || nBitDepth == 16 || nBitDepth == 32)
1069 : {
1070 0 : GetRasterBand(i + 1)->SetMetadataItem(
1071 0 : GDALMD_NBITS, nullptr, GDAL_MDD_IMAGE_STRUCTURE);
1072 : }
1073 : }
1074 : }
1075 : }
1076 :
1077 144 : if (GDALGetRasterBandXSize(ahSpectralBands[0]) >
1078 288 : GDALGetRasterBandXSize(poPanBand) ||
1079 144 : GDALGetRasterBandYSize(ahSpectralBands[0]) >
1080 144 : GDALGetRasterBandYSize(poPanBand))
1081 : {
1082 0 : CPLError(CE_Warning, CPLE_AppDefined,
1083 : "Dimensions of spectral band larger than panchro band");
1084 : }
1085 :
1086 144 : aMapDstBandToSpectralBandIter = aMapDstBandToSpectralBand.begin();
1087 454 : for (; aMapDstBandToSpectralBandIter != aMapDstBandToSpectralBand.end();
1088 310 : ++aMapDstBandToSpectralBandIter)
1089 : {
1090 310 : const int nDstBand = 1 + aMapDstBandToSpectralBandIter->first;
1091 620 : if (nDstBand > nBands ||
1092 310 : !static_cast<VRTRasterBand *>(GetRasterBand(nDstBand))
1093 310 : ->IsPansharpenRasterBand())
1094 : {
1095 0 : CPLError(CE_Failure, CPLE_AppDefined,
1096 : "SpectralBand.dstBand = '%d' invalid", nDstBand);
1097 0 : goto error;
1098 : }
1099 : }
1100 :
1101 144 : if (adfWeights.empty())
1102 : {
1103 379 : for (int i = 0; i < static_cast<int>(ahSpectralBands.size()); i++)
1104 : {
1105 260 : adfWeights.push_back(1.0 / ahSpectralBands.size());
1106 : }
1107 : }
1108 25 : else if (adfWeights.size() != ahSpectralBands.size())
1109 : {
1110 0 : CPLError(CE_Failure, CPLE_AppDefined,
1111 : "%d weights defined, but %d input spectral bands",
1112 0 : static_cast<int>(adfWeights.size()),
1113 0 : static_cast<int>(ahSpectralBands.size()));
1114 0 : goto error;
1115 : }
1116 :
1117 144 : if (aMapDstBandToSpectralBand.empty())
1118 : {
1119 1 : CPLError(CE_Warning, CPLE_AppDefined,
1120 : "No spectral band is mapped to an output band");
1121 : }
1122 :
1123 : /* -------------------------------------------------------------------- */
1124 : /* Instantiate poPansharpener */
1125 : /* -------------------------------------------------------------------- */
1126 144 : psPanOptions.reset(GDALCreatePansharpenOptions());
1127 144 : psPanOptions->ePansharpenAlg = GDAL_PSH_WEIGHTED_BROVEY;
1128 144 : psPanOptions->eResampleAlg = eResampleAlg;
1129 144 : psPanOptions->nBitDepth = nBitDepth;
1130 144 : psPanOptions->nWeightCount = static_cast<int>(adfWeights.size());
1131 288 : psPanOptions->padfWeights =
1132 144 : static_cast<double *>(CPLMalloc(sizeof(double) * adfWeights.size()));
1133 144 : memcpy(psPanOptions->padfWeights, &adfWeights[0],
1134 144 : sizeof(double) * adfWeights.size());
1135 144 : psPanOptions->hPanchroBand = poPanBand;
1136 144 : psPanOptions->nInputSpectralBands =
1137 144 : static_cast<int>(ahSpectralBands.size());
1138 288 : psPanOptions->pahInputSpectralBands = static_cast<GDALRasterBandH *>(
1139 144 : CPLMalloc(sizeof(GDALRasterBandH) * ahSpectralBands.size()));
1140 144 : memcpy(psPanOptions->pahInputSpectralBands, &ahSpectralBands[0],
1141 144 : sizeof(GDALRasterBandH) * ahSpectralBands.size());
1142 144 : psPanOptions->nOutPansharpenedBands =
1143 144 : static_cast<int>(aMapDstBandToSpectralBand.size());
1144 288 : psPanOptions->panOutPansharpenedBands = static_cast<int *>(
1145 144 : CPLMalloc(sizeof(int) * aMapDstBandToSpectralBand.size()));
1146 144 : aMapDstBandToSpectralBandIter = aMapDstBandToSpectralBand.begin();
1147 454 : for (int i = 0;
1148 454 : aMapDstBandToSpectralBandIter != aMapDstBandToSpectralBand.end();
1149 310 : ++aMapDstBandToSpectralBandIter, ++i)
1150 : {
1151 310 : psPanOptions->panOutPansharpenedBands[i] =
1152 310 : aMapDstBandToSpectralBandIter->second;
1153 : }
1154 144 : psPanOptions->bHasNoData = bHasNoData;
1155 144 : psPanOptions->dfNoData = dfNoData;
1156 144 : psPanOptions->nThreads = nThreads;
1157 144 : psPanOptions->bNoDataOutsideSpectralExtent =
1158 286 : (m_eGTAdjustment == GTAdjust_None ||
1159 142 : m_eGTAdjustment == GTAdjust_NoneWithoutWarning);
1160 :
1161 144 : if (nBands == psPanOptions->nOutPansharpenedBands)
1162 140 : SetMetadataItem(GDALMD_INTERLEAVE, "PIXEL", GDAL_MDD_IMAGE_STRUCTURE);
1163 :
1164 144 : m_poPansharpener = std::make_unique<GDALPansharpenOperation>();
1165 144 : eErr = m_poPansharpener->Initialize(psPanOptions.get());
1166 144 : if (eErr != CE_None)
1167 : {
1168 : // Delete the pansharper object before closing the dataset
1169 : // because it may have warped the bands into an intermediate VRT
1170 1 : m_poPansharpener.reset();
1171 :
1172 : // Close in reverse order (VRT firsts and real datasets after)
1173 3 : for (int i = static_cast<int>(m_apoDatasetsToReleaseRef.size()) - 1;
1174 3 : i >= 0; i--)
1175 : {
1176 2 : m_apoDatasetsToReleaseRef[i].reset();
1177 : }
1178 1 : m_apoDatasetsToReleaseRef.clear();
1179 : }
1180 :
1181 144 : return eErr;
1182 :
1183 4 : error:
1184 : // Close in reverse order (VRT firsts and real datasets after)
1185 15 : for (int i = static_cast<int>(m_apoDatasetsToReleaseRef.size()) - 1; i >= 0;
1186 : i--)
1187 : {
1188 11 : m_apoDatasetsToReleaseRef[i].reset();
1189 : }
1190 4 : m_apoDatasetsToReleaseRef.clear();
1191 4 : return CE_Failure;
1192 : }
1193 :
1194 : /************************************************************************/
1195 : /* SerializeToXML() */
1196 : /************************************************************************/
1197 :
1198 8 : CPLXMLNode *VRTPansharpenedDataset::SerializeToXML(const char *pszVRTPathIn)
1199 :
1200 : {
1201 8 : CPLXMLNode *psTree = VRTDataset::SerializeToXML(pszVRTPathIn);
1202 :
1203 8 : if (psTree == nullptr)
1204 0 : return psTree;
1205 :
1206 : /* -------------------------------------------------------------------- */
1207 : /* Set subclass. */
1208 : /* -------------------------------------------------------------------- */
1209 8 : CPLCreateXMLNode(CPLCreateXMLNode(psTree, CXT_Attribute, "subClass"),
1210 : CXT_Text, "VRTPansharpenedDataset");
1211 :
1212 : /* -------------------------------------------------------------------- */
1213 : /* Serialize the block size. */
1214 : /* -------------------------------------------------------------------- */
1215 8 : CPLCreateXMLElementAndValue(psTree, "BlockXSize",
1216 : CPLSPrintf("%d", m_nBlockXSize));
1217 8 : CPLCreateXMLElementAndValue(psTree, "BlockYSize",
1218 : CPLSPrintf("%d", m_nBlockYSize));
1219 :
1220 : /* -------------------------------------------------------------------- */
1221 : /* Serialize the options. */
1222 : /* -------------------------------------------------------------------- */
1223 8 : if (m_poPansharpener == nullptr)
1224 0 : return psTree;
1225 8 : const GDALPansharpenOptions *psOptions = m_poPansharpener->GetOptions();
1226 8 : if (psOptions == nullptr)
1227 0 : return psTree;
1228 :
1229 : CPLXMLNode *psOptionsNode =
1230 8 : CPLCreateXMLNode(psTree, CXT_Element, "PansharpeningOptions");
1231 :
1232 8 : if (psOptions->ePansharpenAlg == GDAL_PSH_WEIGHTED_BROVEY)
1233 : {
1234 8 : CPLCreateXMLElementAndValue(psOptionsNode, "Algorithm",
1235 : "WeightedBrovey");
1236 : }
1237 : else
1238 : {
1239 0 : CPLAssert(false);
1240 : }
1241 8 : if (psOptions->nWeightCount)
1242 : {
1243 16 : CPLString osWeights;
1244 29 : for (int i = 0; i < psOptions->nWeightCount; i++)
1245 : {
1246 21 : if (i)
1247 13 : osWeights += ",";
1248 21 : osWeights += CPLSPrintf("%.16g", psOptions->padfWeights[i]);
1249 : }
1250 8 : CPLCreateXMLElementAndValue(
1251 : CPLCreateXMLNode(psOptionsNode, CXT_Element, "AlgorithmOptions"),
1252 : "Weights", osWeights.c_str());
1253 : }
1254 8 : CPLCreateXMLElementAndValue(
1255 : psOptionsNode, "Resampling",
1256 8 : GDALRasterIOGetResampleAlg(psOptions->eResampleAlg));
1257 :
1258 8 : if (psOptions->nThreads == -1)
1259 : {
1260 7 : CPLCreateXMLElementAndValue(psOptionsNode, "NumThreads", "ALL_CPUS");
1261 : }
1262 1 : else if (psOptions->nThreads > 1)
1263 : {
1264 0 : CPLCreateXMLElementAndValue(psOptionsNode, "NumThreads",
1265 0 : CPLSPrintf("%d", psOptions->nThreads));
1266 : }
1267 :
1268 8 : if (psOptions->nBitDepth)
1269 0 : CPLCreateXMLElementAndValue(psOptionsNode, "BitDepth",
1270 0 : CPLSPrintf("%d", psOptions->nBitDepth));
1271 :
1272 8 : const char *pszAdjust = nullptr;
1273 8 : switch (m_eGTAdjustment)
1274 : {
1275 8 : case GTAdjust_Union:
1276 8 : pszAdjust = "Union";
1277 8 : break;
1278 0 : case GTAdjust_Intersection:
1279 0 : pszAdjust = "Intersection";
1280 0 : break;
1281 0 : case GTAdjust_None:
1282 0 : pszAdjust = "None";
1283 0 : break;
1284 0 : case GTAdjust_NoneWithoutWarning:
1285 0 : pszAdjust = "NoneWithoutWarning";
1286 0 : break;
1287 0 : default:
1288 0 : break;
1289 : }
1290 :
1291 8 : if (psOptions->bHasNoData)
1292 : {
1293 1 : CPLCreateXMLElementAndValue(psOptionsNode, "NoData",
1294 1 : CPLSPrintf("%.16g", psOptions->dfNoData));
1295 : }
1296 7 : else if (m_bNoDataDisabled)
1297 : {
1298 0 : CPLCreateXMLElementAndValue(psOptionsNode, "NoData", "None");
1299 : }
1300 :
1301 8 : if (pszAdjust)
1302 8 : CPLCreateXMLElementAndValue(psOptionsNode, "SpatialExtentAdjustment",
1303 : pszAdjust);
1304 :
1305 8 : if (psOptions->hPanchroBand)
1306 : {
1307 : CPLXMLNode *psBand =
1308 8 : CPLCreateXMLNode(psOptionsNode, CXT_Element, "PanchroBand");
1309 : GDALRasterBand *poBand =
1310 8 : GDALRasterBand::FromHandle(psOptions->hPanchroBand);
1311 8 : if (poBand->GetDataset())
1312 : {
1313 8 : auto poPanchroDS = poBand->GetDataset();
1314 : std::map<CPLString, CPLString>::iterator oIter =
1315 8 : m_oMapToRelativeFilenames.find(poPanchroDS->GetDescription());
1316 8 : if (oIter == m_oMapToRelativeFilenames.end())
1317 : {
1318 : const char *pszUnderlyingDS =
1319 7 : poPanchroDS->GetMetadataItem("UNDERLYING_DATASET");
1320 7 : if (!pszUnderlyingDS)
1321 6 : pszUnderlyingDS = poPanchroDS->GetDescription();
1322 7 : CPLCreateXMLElementAndValue(psBand, "SourceFilename",
1323 : pszUnderlyingDS);
1324 : }
1325 : else
1326 : {
1327 1 : CPLXMLNode *psSourceFilename = CPLCreateXMLElementAndValue(
1328 1 : psBand, "SourceFilename", oIter->second);
1329 1 : CPLCreateXMLNode(CPLCreateXMLNode(psSourceFilename,
1330 : CXT_Attribute,
1331 : "relativeToVRT"),
1332 : CXT_Text, "1");
1333 : }
1334 :
1335 8 : GDALSerializeOpenOptionsToXML(psBand,
1336 8 : poPanchroDS->GetOpenOptions());
1337 :
1338 8 : CPLCreateXMLElementAndValue(psBand, "SourceBand",
1339 : CPLSPrintf("%d", poBand->GetBand()));
1340 : }
1341 : }
1342 29 : for (int i = 0; i < psOptions->nInputSpectralBands; i++)
1343 : {
1344 : CPLXMLNode *psBand =
1345 21 : CPLCreateXMLNode(psOptionsNode, CXT_Element, "SpectralBand");
1346 :
1347 40 : for (int j = 0; j < psOptions->nOutPansharpenedBands; j++)
1348 : {
1349 40 : if (psOptions->panOutPansharpenedBands[j] == i)
1350 : {
1351 41 : for (int k = 0; k < nBands; k++)
1352 : {
1353 41 : if (static_cast<VRTRasterBand *>(GetRasterBand(k + 1))
1354 41 : ->IsPansharpenRasterBand())
1355 : {
1356 40 : if (static_cast<VRTPansharpenedRasterBand *>(
1357 40 : GetRasterBand(k + 1))
1358 40 : ->GetIndexAsPansharpenedBand() == j)
1359 : {
1360 21 : CPLCreateXMLNode(CPLCreateXMLNode(psBand,
1361 : CXT_Attribute,
1362 : "dstBand"),
1363 : CXT_Text, CPLSPrintf("%d", k + 1));
1364 21 : break;
1365 : }
1366 : }
1367 : }
1368 21 : break;
1369 : }
1370 : }
1371 :
1372 : GDALRasterBand *poBand =
1373 21 : GDALRasterBand::FromHandle(psOptions->pahInputSpectralBands[i]);
1374 21 : if (poBand->GetDataset())
1375 : {
1376 21 : auto poSpectralDS = poBand->GetDataset();
1377 : std::map<CPLString, CPLString>::iterator oIter =
1378 21 : m_oMapToRelativeFilenames.find(poSpectralDS->GetDescription());
1379 21 : if (oIter == m_oMapToRelativeFilenames.end())
1380 : {
1381 : const char *pszUnderlyingDS =
1382 21 : poSpectralDS->GetMetadataItem("UNDERLYING_DATASET");
1383 21 : if (!pszUnderlyingDS)
1384 20 : pszUnderlyingDS = poSpectralDS->GetDescription();
1385 21 : CPLCreateXMLElementAndValue(psBand, "SourceFilename",
1386 : pszUnderlyingDS);
1387 : }
1388 : else
1389 : {
1390 0 : CPLXMLNode *psSourceFilename = CPLCreateXMLElementAndValue(
1391 0 : psBand, "SourceFilename", oIter->second);
1392 0 : CPLCreateXMLNode(CPLCreateXMLNode(psSourceFilename,
1393 : CXT_Attribute,
1394 : "relativeToVRT"),
1395 : CXT_Text, "1");
1396 : }
1397 :
1398 21 : GDALSerializeOpenOptionsToXML(psBand,
1399 21 : poSpectralDS->GetOpenOptions());
1400 :
1401 21 : CPLCreateXMLElementAndValue(psBand, "SourceBand",
1402 : CPLSPrintf("%d", poBand->GetBand()));
1403 : }
1404 : }
1405 :
1406 8 : return psTree;
1407 : }
1408 :
1409 : /************************************************************************/
1410 : /* GetBlockSize() */
1411 : /************************************************************************/
1412 :
1413 317 : void VRTPansharpenedDataset::GetBlockSize(int *pnBlockXSize,
1414 : int *pnBlockYSize) const
1415 :
1416 : {
1417 317 : assert(nullptr != pnBlockXSize);
1418 317 : assert(nullptr != pnBlockYSize);
1419 :
1420 317 : *pnBlockXSize = m_nBlockXSize;
1421 317 : *pnBlockYSize = m_nBlockYSize;
1422 317 : }
1423 :
1424 : /************************************************************************/
1425 : /* AddBand() */
1426 : /************************************************************************/
1427 :
1428 1 : CPLErr VRTPansharpenedDataset::AddBand(CPL_UNUSED GDALDataType eType,
1429 : CPL_UNUSED CSLConstList papszOptions)
1430 :
1431 : {
1432 1 : CPLError(CE_Failure, CPLE_NotSupported, "AddBand() not supported");
1433 :
1434 1 : return CE_Failure;
1435 : }
1436 :
1437 : /************************************************************************/
1438 : /* IRasterIO() */
1439 : /************************************************************************/
1440 :
1441 1174 : CPLErr VRTPansharpenedDataset::IRasterIO(
1442 : GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize,
1443 : void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType,
1444 : int nBandCount, BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
1445 : GSpacing nLineSpace, GSpacing nBandSpace, GDALRasterIOExtraArg *psExtraArg)
1446 : {
1447 1174 : if (eRWFlag == GF_Write)
1448 0 : return CE_Failure;
1449 :
1450 : /* Try to pass the request to the most appropriate overview dataset */
1451 1174 : if (nBufXSize < nXSize && nBufYSize < nYSize)
1452 : {
1453 : int bTried;
1454 1 : CPLErr eErr = TryOverviewRasterIO(
1455 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
1456 : eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace,
1457 : nBandSpace, psExtraArg, &bTried);
1458 1 : if (bTried)
1459 0 : return eErr;
1460 : }
1461 :
1462 1174 : const int nDataTypeSize = GDALGetDataTypeSizeBytes(eBufType);
1463 1174 : if (nXSize == nBufXSize && nYSize == nBufYSize &&
1464 1173 : nDataTypeSize == nPixelSpace && nLineSpace == nPixelSpace * nBufXSize &&
1465 1173 : nBandSpace == nLineSpace * nBufYSize && nBandCount == nBands)
1466 : {
1467 3538 : for (int i = 0; i < nBands; i++)
1468 : {
1469 4732 : if (panBandMap[i] != i + 1 ||
1470 2366 : !static_cast<VRTRasterBand *>(GetRasterBand(i + 1))
1471 2366 : ->IsPansharpenRasterBand())
1472 : {
1473 0 : goto default_path;
1474 : }
1475 : }
1476 :
1477 : //{static int bDone = 0; if (!bDone) printf("(2)\n"); bDone = 1; }
1478 1172 : return m_poPansharpener->ProcessRegion(nXOff, nYOff, nXSize, nYSize,
1479 1172 : pData, eBufType);
1480 : }
1481 :
1482 2 : default_path:
1483 : //{static int bDone = 0; if (!bDone) printf("(3)\n"); bDone = 1; }
1484 2 : return VRTDataset::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize, pData,
1485 : nBufXSize, nBufYSize, eBufType, nBandCount,
1486 : panBandMap, nPixelSpace, nLineSpace,
1487 2 : nBandSpace, psExtraArg);
1488 : }
1489 :
1490 : /************************************************************************/
1491 : /* ==================================================================== */
1492 : /* VRTPansharpenedRasterBand */
1493 : /* ==================================================================== */
1494 : /************************************************************************/
1495 :
1496 : /************************************************************************/
1497 : /* VRTPansharpenedRasterBand() */
1498 : /************************************************************************/
1499 :
1500 317 : VRTPansharpenedRasterBand::VRTPansharpenedRasterBand(GDALDataset *poDSIn,
1501 : int nBandIn,
1502 317 : GDALDataType eDataTypeIn)
1503 317 : : m_nIndexAsPansharpenedBand(nBandIn - 1)
1504 : {
1505 317 : Initialize(poDSIn->GetRasterXSize(), poDSIn->GetRasterYSize());
1506 :
1507 317 : poDS = poDSIn;
1508 317 : nBand = nBandIn;
1509 317 : eAccess = GA_Update;
1510 317 : eDataType = eDataTypeIn;
1511 :
1512 317 : static_cast<VRTPansharpenedDataset *>(poDS)->GetBlockSize(&nBlockXSize,
1513 : &nBlockYSize);
1514 317 : }
1515 :
1516 : /************************************************************************/
1517 : /* ~VRTPansharpenedRasterBand() */
1518 : /************************************************************************/
1519 :
1520 634 : VRTPansharpenedRasterBand::~VRTPansharpenedRasterBand()
1521 :
1522 : {
1523 317 : FlushCache(true);
1524 634 : }
1525 :
1526 : /************************************************************************/
1527 : /* IReadBlock() */
1528 : /************************************************************************/
1529 :
1530 26 : CPLErr VRTPansharpenedRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff,
1531 : void *pImage)
1532 :
1533 : {
1534 26 : const int nReqXOff = nBlockXOff * nBlockXSize;
1535 26 : const int nReqYOff = nBlockYOff * nBlockYSize;
1536 26 : const int nReqXSize = std::min(nBlockXSize, nRasterXSize - nReqXOff);
1537 26 : const int nReqYSize = std::min(nBlockYSize, nRasterYSize - nReqYOff);
1538 :
1539 : //{static int bDone = 0; if (!bDone) printf("(4)\n"); bDone = 1; }
1540 26 : const int nDataTypeSize = GDALGetDataTypeSizeBytes(eDataType);
1541 : GDALRasterIOExtraArg sExtraArg;
1542 26 : INIT_RASTERIO_EXTRA_ARG(sExtraArg);
1543 52 : if (IRasterIO(GF_Read, nReqXOff, nReqYOff, nReqXSize, nReqYSize, pImage,
1544 : nReqXSize, nReqYSize, eDataType, nDataTypeSize,
1545 26 : static_cast<GSpacing>(nDataTypeSize) * nReqXSize,
1546 26 : &sExtraArg) != CE_None)
1547 : {
1548 0 : return CE_Failure;
1549 : }
1550 :
1551 26 : if (nReqXSize < nBlockXSize)
1552 : {
1553 5613 : for (int j = nReqYSize - 1; j >= 0; j--)
1554 : {
1555 5600 : memmove(static_cast<GByte *>(pImage) +
1556 5600 : static_cast<size_t>(j) * nDataTypeSize * nBlockXSize,
1557 5600 : static_cast<GByte *>(pImage) +
1558 5600 : static_cast<size_t>(j) * nDataTypeSize * nReqXSize,
1559 5600 : static_cast<size_t>(nReqXSize) * nDataTypeSize);
1560 5600 : memset(static_cast<GByte *>(pImage) +
1561 5600 : (static_cast<size_t>(j) * nBlockXSize + nReqXSize) *
1562 5600 : nDataTypeSize,
1563 : 0,
1564 5600 : static_cast<size_t>(nBlockXSize - nReqXSize) *
1565 5600 : nDataTypeSize);
1566 : }
1567 : }
1568 26 : if (nReqYSize < nBlockYSize)
1569 : {
1570 22 : memset(static_cast<GByte *>(pImage) +
1571 22 : static_cast<size_t>(nReqYSize) * nBlockXSize * nDataTypeSize,
1572 : 0,
1573 22 : static_cast<size_t>(nBlockYSize - nReqYSize) * nBlockXSize *
1574 22 : nDataTypeSize);
1575 : }
1576 :
1577 : // Cache other bands
1578 26 : CPLErr eErr = CE_None;
1579 26 : VRTPansharpenedDataset *poGDS = static_cast<VRTPansharpenedDataset *>(poDS);
1580 26 : if (poGDS->nBands != 1 && !poGDS->m_bLoadingOtherBands)
1581 : {
1582 10 : poGDS->m_bLoadingOtherBands = TRUE;
1583 :
1584 36 : for (int iOtherBand = 1; iOtherBand <= poGDS->nBands; iOtherBand++)
1585 : {
1586 26 : if (iOtherBand == nBand)
1587 10 : continue;
1588 :
1589 : GDALRasterBlock *poBlock =
1590 16 : poGDS->GetRasterBand(iOtherBand)
1591 16 : ->GetLockedBlockRef(nBlockXOff, nBlockYOff);
1592 16 : if (poBlock == nullptr)
1593 : {
1594 0 : eErr = CE_Failure;
1595 0 : break;
1596 : }
1597 16 : poBlock->DropLock();
1598 : }
1599 :
1600 10 : poGDS->m_bLoadingOtherBands = FALSE;
1601 : }
1602 :
1603 26 : return eErr;
1604 : }
1605 :
1606 : /************************************************************************/
1607 : /* IRasterIO() */
1608 : /************************************************************************/
1609 :
1610 128 : CPLErr VRTPansharpenedRasterBand::IRasterIO(
1611 : GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize,
1612 : void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType,
1613 : GSpacing nPixelSpace, GSpacing nLineSpace, GDALRasterIOExtraArg *psExtraArg)
1614 : {
1615 128 : if (eRWFlag == GF_Write)
1616 0 : return CE_Failure;
1617 :
1618 128 : VRTPansharpenedDataset *poGDS = static_cast<VRTPansharpenedDataset *>(poDS);
1619 :
1620 : /* Try to pass the request to the most appropriate overview dataset */
1621 128 : if (nBufXSize < nXSize && nBufYSize < nYSize)
1622 : {
1623 : int bTried;
1624 3 : CPLErr eErr = TryOverviewRasterIO(
1625 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
1626 : eBufType, nPixelSpace, nLineSpace, psExtraArg, &bTried);
1627 3 : if (bTried)
1628 0 : return eErr;
1629 : }
1630 :
1631 128 : const int nDataTypeSize = GDALGetDataTypeSizeBytes(eBufType);
1632 128 : if (nDataTypeSize > 0 && nXSize == nBufXSize && nYSize == nBufYSize &&
1633 125 : nDataTypeSize == nPixelSpace && nLineSpace == nPixelSpace * nBufXSize)
1634 : {
1635 : const GDALPansharpenOptions *psOptions =
1636 125 : poGDS->m_poPansharpener->GetOptions();
1637 :
1638 : // Have we already done this request for another band ?
1639 : // If so use the cached result
1640 125 : const size_t nBufferSizePerBand =
1641 125 : static_cast<size_t>(nXSize) * nYSize * nDataTypeSize;
1642 125 : if (nXOff == poGDS->m_nLastBandRasterIOXOff &&
1643 118 : nYOff >= poGDS->m_nLastBandRasterIOYOff &&
1644 111 : nXSize == poGDS->m_nLastBandRasterIOXSize &&
1645 69 : nYOff + nYSize <= poGDS->m_nLastBandRasterIOYOff +
1646 69 : poGDS->m_nLastBandRasterIOYSize &&
1647 59 : eBufType == poGDS->m_eLastBandRasterIODataType)
1648 : {
1649 : //{static int bDone = 0; if (!bDone) printf("(6)\n"); bDone = 1; }
1650 53 : if (poGDS->m_pabyLastBufferBandRasterIO == nullptr)
1651 0 : return CE_Failure;
1652 53 : const size_t nBufferSizePerBandCached =
1653 53 : static_cast<size_t>(nXSize) * poGDS->m_nLastBandRasterIOYSize *
1654 53 : nDataTypeSize;
1655 53 : memcpy(pData,
1656 53 : poGDS->m_pabyLastBufferBandRasterIO +
1657 53 : nBufferSizePerBandCached * m_nIndexAsPansharpenedBand +
1658 53 : static_cast<size_t>(nYOff -
1659 53 : poGDS->m_nLastBandRasterIOYOff) *
1660 53 : nXSize * nDataTypeSize,
1661 : nBufferSizePerBand);
1662 53 : return CE_None;
1663 : }
1664 :
1665 72 : int nYSizeToCache = nYSize;
1666 72 : if (nYSize == 1 && nXSize == nRasterXSize)
1667 : {
1668 : //{static int bDone = 0; if (!bDone) printf("(7)\n"); bDone = 1; }
1669 : // For efficiency, try to cache at leak 256 K
1670 0 : nYSizeToCache = (256 * 1024) / nXSize / nDataTypeSize;
1671 0 : if (nYSizeToCache == 0)
1672 0 : nYSizeToCache = 1;
1673 0 : else if (nYOff + nYSizeToCache > nRasterYSize)
1674 0 : nYSizeToCache = nRasterYSize - nYOff;
1675 : }
1676 72 : const GUIntBig nBufferSize = static_cast<GUIntBig>(nXSize) *
1677 72 : nYSizeToCache * nDataTypeSize *
1678 72 : psOptions->nOutPansharpenedBands;
1679 : // Check the we don't overflow (for 32 bit platforms)
1680 72 : if (nBufferSize > std::numeric_limits<size_t>::max() / 2)
1681 : {
1682 0 : CPLError(CE_Failure, CPLE_OutOfMemory,
1683 : "Out of memory error while allocating working buffers");
1684 0 : return CE_Failure;
1685 : }
1686 : GByte *pabyTemp = static_cast<GByte *>(
1687 72 : VSI_REALLOC_VERBOSE(poGDS->m_pabyLastBufferBandRasterIO,
1688 : static_cast<size_t>(nBufferSize)));
1689 72 : if (pabyTemp == nullptr)
1690 : {
1691 0 : return CE_Failure;
1692 : }
1693 72 : poGDS->m_nLastBandRasterIOXOff = nXOff;
1694 72 : poGDS->m_nLastBandRasterIOYOff = nYOff;
1695 72 : poGDS->m_nLastBandRasterIOXSize = nXSize;
1696 72 : poGDS->m_nLastBandRasterIOYSize = nYSizeToCache;
1697 72 : poGDS->m_eLastBandRasterIODataType = eBufType;
1698 72 : poGDS->m_pabyLastBufferBandRasterIO = pabyTemp;
1699 :
1700 72 : CPLErr eErr = poGDS->m_poPansharpener->ProcessRegion(
1701 : nXOff, nYOff, nXSize, nYSizeToCache,
1702 72 : poGDS->m_pabyLastBufferBandRasterIO, eBufType);
1703 72 : if (eErr == CE_None)
1704 : {
1705 : //{static int bDone = 0; if (!bDone) printf("(8)\n"); bDone = 1; }
1706 72 : size_t nBufferSizePerBandCached = static_cast<size_t>(nXSize) *
1707 72 : poGDS->m_nLastBandRasterIOYSize *
1708 72 : nDataTypeSize;
1709 72 : memcpy(pData,
1710 72 : poGDS->m_pabyLastBufferBandRasterIO +
1711 72 : nBufferSizePerBandCached * m_nIndexAsPansharpenedBand,
1712 : nBufferSizePerBand);
1713 : }
1714 : else
1715 : {
1716 0 : VSIFree(poGDS->m_pabyLastBufferBandRasterIO);
1717 0 : poGDS->m_pabyLastBufferBandRasterIO = nullptr;
1718 : }
1719 72 : return eErr;
1720 : }
1721 :
1722 : //{static int bDone = 0; if (!bDone) printf("(9)\n"); bDone = 1; }
1723 3 : CPLErr eErr = VRTRasterBand::IRasterIO(
1724 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
1725 : eBufType, nPixelSpace, nLineSpace, psExtraArg);
1726 :
1727 3 : return eErr;
1728 : }
1729 :
1730 : /************************************************************************/
1731 : /* SerializeToXML() */
1732 : /************************************************************************/
1733 :
1734 : CPLXMLNode *
1735 21 : VRTPansharpenedRasterBand::SerializeToXML(const char *pszVRTPathIn,
1736 : bool &bHasWarnedAboutRAMUsage,
1737 : size_t &nAccRAMUsage)
1738 :
1739 : {
1740 21 : CPLXMLNode *psTree = VRTRasterBand::SerializeToXML(
1741 : pszVRTPathIn, bHasWarnedAboutRAMUsage, nAccRAMUsage);
1742 :
1743 : /* -------------------------------------------------------------------- */
1744 : /* Set subclass. */
1745 : /* -------------------------------------------------------------------- */
1746 21 : CPLCreateXMLNode(CPLCreateXMLNode(psTree, CXT_Attribute, "subClass"),
1747 : CXT_Text, "VRTPansharpenedRasterBand");
1748 :
1749 21 : return psTree;
1750 : }
1751 :
1752 : /************************************************************************/
1753 : /* GetOverviewCount() */
1754 : /************************************************************************/
1755 :
1756 25 : int VRTPansharpenedRasterBand::GetOverviewCount()
1757 : {
1758 25 : VRTPansharpenedDataset *poGDS = static_cast<VRTPansharpenedDataset *>(poDS);
1759 :
1760 : // Build on-the-fly overviews from overviews of pan and spectral bands
1761 50 : if (poGDS->m_poPansharpener != nullptr &&
1762 50 : poGDS->m_apoOverviewDatasets.empty() && poGDS->m_poMainDataset == poGDS)
1763 : {
1764 : const GDALPansharpenOptions *psOptions =
1765 20 : poGDS->m_poPansharpener->GetOptions();
1766 :
1767 : GDALRasterBand *poPanBand =
1768 20 : GDALRasterBand::FromHandle(psOptions->hPanchroBand);
1769 20 : int nOvrCount = poPanBand->GetOverviewCount();
1770 20 : if (nOvrCount > 0)
1771 : {
1772 14 : for (int i = 0; i < poGDS->GetRasterCount(); i++)
1773 : {
1774 10 : if (!static_cast<VRTRasterBand *>(poGDS->GetRasterBand(i + 1))
1775 10 : ->IsPansharpenRasterBand())
1776 : {
1777 0 : return 0;
1778 : }
1779 : }
1780 :
1781 : // Limit number of overviews of the VRTPansharpenedRasterBand to
1782 : // the minimum number of overviews of the pan and spectral source
1783 : // bands, and also make sure all spectral bands have overviews
1784 : // of the same dimension for a given level.
1785 4 : std::vector<std::pair<int, int>> sizeSpectralOverviews;
1786 14 : for (int i = 0; i < psOptions->nInputSpectralBands; i++)
1787 : {
1788 10 : auto poSpectralBand = GDALRasterBand::FromHandle(
1789 10 : psOptions->pahInputSpectralBands[i]);
1790 10 : nOvrCount =
1791 10 : std::min(nOvrCount, poSpectralBand->GetOverviewCount());
1792 10 : if (i == 0)
1793 : {
1794 7 : for (int iOvr = 0; iOvr < nOvrCount; ++iOvr)
1795 : {
1796 3 : auto poOvrBand = poSpectralBand->GetOverview(iOvr);
1797 : sizeSpectralOverviews.emplace_back(
1798 3 : poOvrBand->GetXSize(), poOvrBand->GetYSize());
1799 : }
1800 : }
1801 : else
1802 : {
1803 10 : for (int iOvr = 0; iOvr < nOvrCount; ++iOvr)
1804 : {
1805 4 : auto poOvrBand = poSpectralBand->GetOverview(iOvr);
1806 4 : if (sizeSpectralOverviews[iOvr].first !=
1807 8 : poOvrBand->GetXSize() ||
1808 4 : sizeSpectralOverviews[iOvr].second !=
1809 4 : poOvrBand->GetYSize())
1810 : {
1811 0 : nOvrCount = iOvr;
1812 0 : break;
1813 : }
1814 : }
1815 : }
1816 : }
1817 :
1818 4 : auto poPanBandDS = poPanBand->GetDataset();
1819 7 : for (int j = 0; j < nOvrCount; j++)
1820 : {
1821 : std::unique_ptr<GDALDataset, GDALDatasetUniquePtrReleaser>
1822 3 : poPanOvrDS(GDALCreateOverviewDataset(poPanBandDS, j, true));
1823 3 : if (!poPanOvrDS)
1824 : {
1825 0 : CPLError(CE_Warning, CPLE_AppDefined,
1826 : "GDALCreateOverviewDataset(poPanBandDS, %d, true) "
1827 : "failed",
1828 : j);
1829 0 : break;
1830 : }
1831 : GDALRasterBand *poPanOvrBand =
1832 3 : poPanOvrDS->GetRasterBand(poPanBand->GetBand());
1833 : auto poOvrDS = std::make_unique<VRTPansharpenedDataset>(
1834 3 : poPanOvrBand->GetXSize(), poPanOvrBand->GetYSize());
1835 6 : poOvrDS->m_apoDatasetsToReleaseRef.push_back(
1836 3 : std::move(poPanOvrDS));
1837 10 : for (int i = 0; i < poGDS->GetRasterCount(); i++)
1838 : {
1839 7 : GDALRasterBand *poSrcBand = poGDS->GetRasterBand(i + 1);
1840 : auto poBand = std::make_unique<VRTPansharpenedRasterBand>(
1841 7 : poOvrDS.get(), i + 1, poSrcBand->GetRasterDataType());
1842 14 : const char *pszNBITS = poSrcBand->GetMetadataItem(
1843 7 : GDALMD_NBITS, GDAL_MDD_IMAGE_STRUCTURE);
1844 7 : if (pszNBITS)
1845 0 : poBand->SetMetadataItem(GDALMD_NBITS, pszNBITS,
1846 0 : GDAL_MDD_IMAGE_STRUCTURE);
1847 7 : int bHasNoData = FALSE;
1848 : const double dfNoData =
1849 7 : poSrcBand->GetNoDataValue(&bHasNoData);
1850 7 : if (bHasNoData)
1851 1 : poBand->SetNoDataValue(dfNoData);
1852 14 : poBand->SetColorInterpretation(
1853 7 : poSrcBand->GetColorInterpretation());
1854 7 : poOvrDS->SetBand(i + 1, std::move(poBand));
1855 : }
1856 :
1857 : std::unique_ptr<GDALPansharpenOptions,
1858 : decltype(&GDALDestroyPansharpenOptions)>
1859 : psPanOvrOptions(GDALClonePansharpenOptions(psOptions),
1860 3 : GDALDestroyPansharpenOptions);
1861 3 : psPanOvrOptions->hPanchroBand = poPanOvrBand;
1862 10 : for (int i = 0; i < psOptions->nInputSpectralBands; i++)
1863 : {
1864 7 : auto poSpectralBand = GDALRasterBand::FromHandle(
1865 7 : psOptions->pahInputSpectralBands[i]);
1866 : std::unique_ptr<GDALDataset, GDALDatasetUniquePtrReleaser>
1867 : poSpectralOvrDS(GDALCreateOverviewDataset(
1868 7 : poSpectralBand->GetDataset(), j, true));
1869 7 : if (!poSpectralOvrDS)
1870 : {
1871 0 : CPLError(CE_Warning, CPLE_AppDefined,
1872 : "GDALCreateOverviewDataset(poSpectralBand->"
1873 : "GetDataset(), %d, true) failed",
1874 : j);
1875 0 : return 0;
1876 : }
1877 14 : psPanOvrOptions->pahInputSpectralBands[i] =
1878 7 : poSpectralOvrDS->GetRasterBand(
1879 : poSpectralBand->GetBand());
1880 14 : poOvrDS->m_apoDatasetsToReleaseRef.push_back(
1881 7 : std::move(poSpectralOvrDS));
1882 : }
1883 3 : poOvrDS->m_poPansharpener =
1884 6 : std::make_unique<GDALPansharpenOperation>();
1885 6 : if (poOvrDS->m_poPansharpener->Initialize(
1886 6 : psPanOvrOptions.get()) != CE_None)
1887 : {
1888 0 : CPLError(CE_Warning, CPLE_AppDefined,
1889 : "Unable to initialize pansharpener.");
1890 0 : return 0;
1891 : }
1892 :
1893 3 : poOvrDS->m_poMainDataset = poGDS;
1894 3 : poOvrDS->SetMetadataItem(GDALMD_INTERLEAVE, "PIXEL",
1895 3 : GDAL_MDD_IMAGE_STRUCTURE);
1896 :
1897 3 : poGDS->m_apoOverviewDatasets.push_back(std::move(poOvrDS));
1898 : }
1899 : }
1900 : }
1901 25 : return static_cast<int>(poGDS->m_apoOverviewDatasets.size());
1902 : }
1903 :
1904 : /************************************************************************/
1905 : /* GetOverview() */
1906 : /************************************************************************/
1907 :
1908 7 : GDALRasterBand *VRTPansharpenedRasterBand::GetOverview(int iOvr)
1909 : {
1910 7 : if (iOvr < 0 || iOvr >= GetOverviewCount())
1911 2 : return nullptr;
1912 :
1913 5 : VRTPansharpenedDataset *poGDS = static_cast<VRTPansharpenedDataset *>(poDS);
1914 :
1915 5 : return poGDS->m_apoOverviewDatasets[iOvr]->GetRasterBand(nBand);
1916 : }
1917 :
1918 : /*! @endcond */
|