Coverage Report

Created: 2025-08-28 06:57

/src/gdal/gcore/gdalpamdataset.cpp
Line
Count
Source (jump to first uncovered line)
1
/******************************************************************************
2
 *
3
 * Project:  GDAL Core
4
 * Purpose:  Implementation of GDALPamDataset, a dataset base class that
5
 *           knows how to persist auxiliary metadata into a support XML file.
6
 * Author:   Frank Warmerdam, warmerdam@pobox.com
7
 *
8
 ******************************************************************************
9
 * Copyright (c) 2005, Frank Warmerdam <warmerdam@pobox.com>
10
 * Copyright (c) 2007-2013, Even Rouault <even dot rouault at spatialys.com>
11
 *
12
 * SPDX-License-Identifier: MIT
13
 ****************************************************************************/
14
15
#include "cpl_port.h"
16
#include "gdal_pam.h"
17
18
#include <cstddef>
19
#include <cstdlib>
20
#include <cstring>
21
#include <string>
22
23
#include "cpl_conv.h"
24
#include "cpl_error.h"
25
#include "cpl_minixml.h"
26
#include "cpl_progress.h"
27
#include "cpl_string.h"
28
#include "cpl_vsi.h"
29
#include "gdal.h"
30
#include "gdal_priv.h"
31
#include "ogr_core.h"
32
#include "ogr_spatialref.h"
33
34
/************************************************************************/
35
/*                           GDALPamDataset()                           */
36
/************************************************************************/
37
38
/**
39
 * \class GDALPamDataset "gdal_pam.h"
40
 *
41
 * A subclass of GDALDataset which introduces the ability to save and
42
 * restore auxiliary information (coordinate system, gcps, metadata,
43
 * etc) not supported by a file format via an "auxiliary metadata" file
44
 * with the .aux.xml extension.
45
 *
46
 * <h3>Enabling PAM</h3>
47
 *
48
 * PAM support can be enabled (resp. disabled) in GDAL by setting the
49
 * GDAL_PAM_ENABLED configuration option (via CPLSetConfigOption(), or the
50
 * environment) to the value of YES (resp. NO). Note: The default value is
51
 * build dependent and defaults to YES in Windows and Unix builds. Warning:
52
 * For GDAL < 3.5, setting this option to OFF may have unwanted side-effects on
53
 * drivers that rely on PAM functionality.
54
 *
55
 * <h3>PAM Proxy Files</h3>
56
 *
57
 * In order to be able to record auxiliary information about files on
58
 * read-only media such as CDROMs or in directories where the user does not
59
 * have write permissions, it is possible to enable the "PAM Proxy Database".
60
 * When enabled the .aux.xml files are kept in a different directory, writable
61
 * by the user. Overviews will also be stored in the PAM proxy directory.
62
 *
63
 * To enable this, set the GDAL_PAM_PROXY_DIR configuration option to be
64
 * the name of the directory where the proxies should be kept. The configuration
65
 * option must be set *before* the first access to PAM, because its value is
66
 * cached for later access.
67
 *
68
 * <h3>Adding PAM to Drivers</h3>
69
 *
70
 * Drivers for physical file formats that wish to support persistent auxiliary
71
 * metadata in addition to that for the format itself should derive their
72
 * dataset class from GDALPamDataset instead of directly from GDALDataset.
73
 * The raster band classes should also be derived from GDALPamRasterBand.
74
 *
75
 * They should also call something like this near the end of the Open()
76
 * method:
77
 *
78
 * \code
79
 *      poDS->SetDescription( poOpenInfo->pszFilename );
80
 *      poDS->TryLoadXML();
81
 * \endcode
82
 *
83
 * The SetDescription() is necessary so that the dataset will have a valid
84
 * filename set as the description before TryLoadXML() is called.  TryLoadXML()
85
 * will look for an .aux.xml file with the same basename as the dataset and
86
 * in the same directory.  If found the contents will be loaded and kept
87
 * track of in the GDALPamDataset and GDALPamRasterBand objects.  When a
88
 * call like GetProjectionRef() is not implemented by the format specific
89
 * class, it will fall through to the PAM implementation which will return
90
 * information if it was in the .aux.xml file.
91
 *
92
 * Drivers should also try to call the GDALPamDataset/GDALPamRasterBand
93
 * methods as a fallback if their implementation does not find information.
94
 * This allows using the .aux.xml for variations that can't be stored in
95
 * the format.  For instance, the GeoTIFF driver GetProjectionRef() looks
96
 * like this:
97
 *
98
 * \code
99
 *      if( EQUAL(pszProjection,"") )
100
 *          return GDALPamDataset::GetProjectionRef();
101
 *      else
102
 *          return( pszProjection );
103
 * \endcode
104
 *
105
 * So if the geotiff header is missing, the .aux.xml file will be
106
 * consulted.
107
 *
108
 * Similarly, if SetProjection() were called with a coordinate system
109
 * not supported by GeoTIFF, the SetProjection() method should pass it on
110
 * to the GDALPamDataset::SetProjection() method after issuing a warning
111
 * that the information can't be represented within the file itself.
112
 *
113
 * Drivers for subdataset based formats will also need to declare the
114
 * name of the physical file they are related to, and the name of their
115
 * subdataset before calling TryLoadXML().
116
 *
117
 * \code
118
 *      poDS->SetDescription( poOpenInfo->pszFilename );
119
 *      poDS->SetPhysicalFilename( poDS->pszFilename );
120
 *      poDS->SetSubdatasetName( osSubdatasetName );
121
 *
122
 *      poDS->TryLoadXML();
123
 * \endcode
124
 *
125
 * In some situations where a derived dataset (e.g. used by
126
 * GDALMDArray::AsClassicDataset()) is linked to a physical file, the name of
127
 * the derived dataset is set with the SetDerivedSubdatasetName() method.
128
 *
129
 * \code
130
 *      poDS->SetDescription( poOpenInfo->pszFilename );
131
 *      poDS->SetPhysicalFilename( poDS->pszFilename );
132
 *      poDS->SetDerivedDatasetName( osDerivedDatasetName );
133
 *
134
 *      poDS->TryLoadXML();
135
 * \endcode
136
 */
137
class GDALPamDataset;
138
139
GDALPamDataset::GDALPamDataset()
140
0
{
141
0
    SetMOFlags(GetMOFlags() | GMO_PAM_CLASS);
142
0
}
143
144
/************************************************************************/
145
/*                          ~GDALPamDataset()                           */
146
/************************************************************************/
147
148
GDALPamDataset::~GDALPamDataset()
149
150
0
{
151
0
    if (IsMarkedSuppressOnClose())
152
0
    {
153
0
        if (psPam && psPam->pszPamFilename != nullptr)
154
0
            VSIUnlink(psPam->pszPamFilename);
155
0
    }
156
0
    else if (nPamFlags & GPF_DIRTY)
157
0
    {
158
0
        CPLDebug("GDALPamDataset", "In destructor with dirty metadata.");
159
0
        GDALPamDataset::TrySaveXML();
160
0
    }
161
162
0
    PamClear();
163
0
}
164
165
/************************************************************************/
166
/*                             FlushCache()                             */
167
/************************************************************************/
168
169
CPLErr GDALPamDataset::FlushCache(bool bAtClosing)
170
171
0
{
172
0
    CPLErr eErr = GDALDataset::FlushCache(bAtClosing);
173
0
    if (nPamFlags & GPF_DIRTY)
174
0
    {
175
0
        if (TrySaveXML() != CE_None)
176
0
            eErr = CE_Failure;
177
0
    }
178
0
    return eErr;
179
0
}
180
181
/************************************************************************/
182
/*                            MarkPamDirty()                            */
183
/************************************************************************/
184
185
//! @cond Doxygen_Suppress
186
void GDALPamDataset::MarkPamDirty()
187
0
{
188
0
    if ((nPamFlags & GPF_DIRTY) == 0 &&
189
0
        CPLTestBool(CPLGetConfigOption("GDAL_PAM_ENABLE_MARK_DIRTY", "YES")))
190
0
    {
191
0
        nPamFlags |= GPF_DIRTY;
192
0
    }
193
0
}
194
195
// @endcond
196
197
/************************************************************************/
198
/*                           SerializeToXML()                           */
199
/************************************************************************/
200
201
//! @cond Doxygen_Suppress
202
CPLXMLNode *GDALPamDataset::SerializeToXML(const char *pszUnused)
203
204
0
{
205
0
    if (psPam == nullptr)
206
0
        return nullptr;
207
208
    /* -------------------------------------------------------------------- */
209
    /*      Setup root node and attributes.                                 */
210
    /* -------------------------------------------------------------------- */
211
0
    CPLXMLNode *psDSTree = CPLCreateXMLNode(nullptr, CXT_Element, "PAMDataset");
212
213
    /* -------------------------------------------------------------------- */
214
    /*      SRS                                                             */
215
    /* -------------------------------------------------------------------- */
216
0
    if (psPam->poSRS && !psPam->poSRS->IsEmpty())
217
0
    {
218
0
        char *pszWKT = nullptr;
219
0
        {
220
0
            CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
221
0
            if (psPam->poSRS->exportToWkt(&pszWKT) != OGRERR_NONE)
222
0
            {
223
0
                CPLFree(pszWKT);
224
0
                pszWKT = nullptr;
225
0
                const char *const apszOptions[] = {"FORMAT=WKT2", nullptr};
226
0
                psPam->poSRS->exportToWkt(&pszWKT, apszOptions);
227
0
            }
228
0
        }
229
0
        CPLXMLNode *psSRSNode =
230
0
            CPLCreateXMLElementAndValue(psDSTree, "SRS", pszWKT);
231
0
        CPLFree(pszWKT);
232
0
        const auto &mapping = psPam->poSRS->GetDataAxisToSRSAxisMapping();
233
0
        CPLString osMapping;
234
0
        for (size_t i = 0; i < mapping.size(); ++i)
235
0
        {
236
0
            if (!osMapping.empty())
237
0
                osMapping += ",";
238
0
            osMapping += CPLSPrintf("%d", mapping[i]);
239
0
        }
240
0
        CPLAddXMLAttributeAndValue(psSRSNode, "dataAxisToSRSAxisMapping",
241
0
                                   osMapping.c_str());
242
243
0
        const double dfCoordinateEpoch = psPam->poSRS->GetCoordinateEpoch();
244
0
        if (dfCoordinateEpoch > 0)
245
0
        {
246
0
            std::string osCoordinateEpoch = CPLSPrintf("%f", dfCoordinateEpoch);
247
0
            if (osCoordinateEpoch.find('.') != std::string::npos)
248
0
            {
249
0
                while (osCoordinateEpoch.back() == '0')
250
0
                    osCoordinateEpoch.resize(osCoordinateEpoch.size() - 1);
251
0
            }
252
0
            CPLAddXMLAttributeAndValue(psSRSNode, "coordinateEpoch",
253
0
                                       osCoordinateEpoch.c_str());
254
0
        }
255
0
    }
256
257
    /* -------------------------------------------------------------------- */
258
    /*      GeoTransform.                                                   */
259
    /* -------------------------------------------------------------------- */
260
0
    if (psPam->bHaveGeoTransform)
261
0
    {
262
0
        CPLString oFmt;
263
0
        oFmt.Printf("%24.16e,%24.16e,%24.16e,%24.16e,%24.16e,%24.16e",
264
0
                    psPam->gt[0], psPam->gt[1], psPam->gt[2], psPam->gt[3],
265
0
                    psPam->gt[4], psPam->gt[5]);
266
0
        CPLSetXMLValue(psDSTree, "GeoTransform", oFmt);
267
0
    }
268
269
    /* -------------------------------------------------------------------- */
270
    /*      Metadata.                                                       */
271
    /* -------------------------------------------------------------------- */
272
0
    if (psPam->bHasMetadata)
273
0
    {
274
0
        CPLXMLNode *psMD = oMDMD.Serialize();
275
0
        if (psMD != nullptr)
276
0
        {
277
0
            CPLAddXMLChild(psDSTree, psMD);
278
0
        }
279
0
    }
280
281
    /* -------------------------------------------------------------------- */
282
    /*      GCPs                                                            */
283
    /* -------------------------------------------------------------------- */
284
0
    if (!psPam->asGCPs.empty())
285
0
    {
286
0
        GDALSerializeGCPListToXML(psDSTree, psPam->asGCPs, psPam->poGCP_SRS);
287
0
    }
288
289
    /* -------------------------------------------------------------------- */
290
    /*      Process bands.                                                  */
291
    /* -------------------------------------------------------------------- */
292
293
    // Find last child
294
0
    CPLXMLNode *psLastChild = psDSTree->psChild;
295
0
    for (; psLastChild != nullptr && psLastChild->psNext;
296
0
         psLastChild = psLastChild->psNext)
297
0
    {
298
0
    }
299
300
0
    for (int iBand = 0; iBand < GetRasterCount(); iBand++)
301
0
    {
302
0
        GDALRasterBand *const poBand = GetRasterBand(iBand + 1);
303
304
0
        if (poBand == nullptr || !(poBand->GetMOFlags() & GMO_PAM_CLASS))
305
0
            continue;
306
307
0
        CPLXMLNode *const psBandTree =
308
0
            cpl::down_cast<GDALPamRasterBand *>(poBand)->SerializeToXML(
309
0
                pszUnused);
310
311
0
        if (psBandTree != nullptr)
312
0
        {
313
0
            if (psLastChild == nullptr)
314
0
            {
315
0
                CPLAddXMLChild(psDSTree, psBandTree);
316
0
            }
317
0
            else
318
0
            {
319
0
                psLastChild->psNext = psBandTree;
320
0
            }
321
0
            psLastChild = psBandTree;
322
0
        }
323
0
    }
324
325
    /* -------------------------------------------------------------------- */
326
    /*      We don't want to return anything if we had no metadata to       */
327
    /*      attach.                                                         */
328
    /* -------------------------------------------------------------------- */
329
0
    if (psDSTree->psChild == nullptr)
330
0
    {
331
0
        CPLDestroyXMLNode(psDSTree);
332
0
        psDSTree = nullptr;
333
0
    }
334
335
0
    return psDSTree;
336
0
}
337
338
/************************************************************************/
339
/*                           PamInitialize()                            */
340
/************************************************************************/
341
342
void GDALPamDataset::PamInitialize()
343
344
0
{
345
0
#ifdef PAM_ENABLED
346
0
    const char *const pszPamDefault = "YES";
347
#else
348
    const char *const pszPamDefault = "NO";
349
#endif
350
351
0
    if (psPam)
352
0
        return;
353
354
0
    if (!CPLTestBool(CPLGetConfigOption("GDAL_PAM_ENABLED", pszPamDefault)))
355
0
    {
356
0
        CPLDebugOnce("GDAL", "PAM is disabled");
357
0
        nPamFlags |= GPF_DISABLED;
358
0
    }
359
360
    /* ERO 2011/04/13 : GPF_AUXMODE seems to be unimplemented */
361
0
    if (EQUAL(CPLGetConfigOption("GDAL_PAM_MODE", "PAM"), "AUX"))
362
0
        nPamFlags |= GPF_AUXMODE;
363
364
0
    psPam = new GDALDatasetPamInfo;
365
0
    for (int iBand = 0; iBand < GetRasterCount(); iBand++)
366
0
    {
367
0
        GDALRasterBand *poBand = GetRasterBand(iBand + 1);
368
369
0
        if (poBand == nullptr || !(poBand->GetMOFlags() & GMO_PAM_CLASS))
370
0
            continue;
371
372
0
        cpl::down_cast<GDALPamRasterBand *>(poBand)->PamInitialize();
373
0
    }
374
0
}
375
376
/************************************************************************/
377
/*                              PamClear()                              */
378
/************************************************************************/
379
380
void GDALPamDataset::PamClear()
381
382
0
{
383
0
    if (psPam)
384
0
    {
385
0
        CPLFree(psPam->pszPamFilename);
386
0
        if (psPam->poSRS)
387
0
            psPam->poSRS->Release();
388
0
        if (psPam->poGCP_SRS)
389
0
            psPam->poGCP_SRS->Release();
390
391
0
        delete psPam;
392
0
        psPam = nullptr;
393
0
    }
394
0
}
395
396
/************************************************************************/
397
/*                              XMLInit()                               */
398
/************************************************************************/
399
400
CPLErr GDALPamDataset::XMLInit(const CPLXMLNode *psTree, const char *pszUnused)
401
402
0
{
403
    /* -------------------------------------------------------------------- */
404
    /*      Check for an SRS node.                                          */
405
    /* -------------------------------------------------------------------- */
406
0
    if (const CPLXMLNode *psSRSNode = CPLGetXMLNode(psTree, "SRS"))
407
0
    {
408
0
        if (psPam->poSRS)
409
0
            psPam->poSRS->Release();
410
0
        psPam->poSRS = new OGRSpatialReference();
411
0
        psPam->poSRS->SetFromUserInput(
412
0
            CPLGetXMLValue(psSRSNode, nullptr, ""),
413
0
            OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS);
414
0
        const char *pszMapping =
415
0
            CPLGetXMLValue(psSRSNode, "dataAxisToSRSAxisMapping", nullptr);
416
0
        if (pszMapping)
417
0
        {
418
0
            char **papszTokens =
419
0
                CSLTokenizeStringComplex(pszMapping, ",", FALSE, FALSE);
420
0
            std::vector<int> anMapping;
421
0
            for (int i = 0; papszTokens && papszTokens[i]; i++)
422
0
            {
423
0
                anMapping.push_back(atoi(papszTokens[i]));
424
0
            }
425
0
            CSLDestroy(papszTokens);
426
0
            psPam->poSRS->SetDataAxisToSRSAxisMapping(anMapping);
427
0
        }
428
0
        else
429
0
        {
430
0
            psPam->poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
431
0
        }
432
433
0
        const char *pszCoordinateEpoch =
434
0
            CPLGetXMLValue(psSRSNode, "coordinateEpoch", nullptr);
435
0
        if (pszCoordinateEpoch)
436
0
            psPam->poSRS->SetCoordinateEpoch(CPLAtof(pszCoordinateEpoch));
437
0
    }
438
439
    /* -------------------------------------------------------------------- */
440
    /*      Check for a GeoTransform node.                                  */
441
    /* -------------------------------------------------------------------- */
442
0
    const char *pszGT = CPLGetXMLValue(psTree, "GeoTransform", "");
443
0
    if (strlen(pszGT) > 0)
444
0
    {
445
0
        const CPLStringList aosTokens(
446
0
            CSLTokenizeStringComplex(pszGT, ",", FALSE, FALSE));
447
0
        if (aosTokens.size() != 6)
448
0
        {
449
0
            CPLError(CE_Warning, CPLE_AppDefined,
450
0
                     "GeoTransform node does not have expected six values.");
451
0
        }
452
0
        else
453
0
        {
454
0
            for (int iTA = 0; iTA < 6; iTA++)
455
0
                psPam->gt[iTA] = CPLAtof(aosTokens[iTA]);
456
0
            psPam->bHaveGeoTransform = TRUE;
457
0
        }
458
0
    }
459
460
    /* -------------------------------------------------------------------- */
461
    /*      Check for GCPs.                                                 */
462
    /* -------------------------------------------------------------------- */
463
0
    if (const CPLXMLNode *psGCPList = CPLGetXMLNode(psTree, "GCPList"))
464
0
    {
465
0
        if (psPam->poGCP_SRS)
466
0
            psPam->poGCP_SRS->Release();
467
0
        psPam->poGCP_SRS = nullptr;
468
469
        // Make sure any previous GCPs, perhaps from an .aux file, are cleared
470
        // if we have new ones.
471
0
        psPam->asGCPs.clear();
472
0
        GDALDeserializeGCPListFromXML(psGCPList, psPam->asGCPs,
473
0
                                      &(psPam->poGCP_SRS));
474
0
    }
475
476
    /* -------------------------------------------------------------------- */
477
    /*      Apply any dataset level metadata.                               */
478
    /* -------------------------------------------------------------------- */
479
0
    if (oMDMD.XMLInit(psTree, TRUE))
480
0
    {
481
0
        psPam->bHasMetadata = TRUE;
482
0
    }
483
484
    /* -------------------------------------------------------------------- */
485
    /*      Try loading ESRI xml encoded GeodataXform.                      */
486
    /* -------------------------------------------------------------------- */
487
0
    {
488
        // previously we only tried to load GeodataXform if we didn't already
489
        // encounter a valid SRS at this stage. But in some cases a PAMDataset
490
        // may have both a SRS child element AND a GeodataXform with a SpatialReference
491
        // child element. In this case we should prioritize the GeodataXform
492
        // over the root PAMDataset SRS node.
493
494
        // ArcGIS 9.3: GeodataXform as a root element
495
0
        const CPLXMLNode *psGeodataXform =
496
0
            CPLGetXMLNode(psTree, "=GeodataXform");
497
0
        CPLXMLTreeCloser oTreeValueAsXML(nullptr);
498
0
        if (psGeodataXform != nullptr)
499
0
        {
500
0
            char *apszMD[2];
501
0
            apszMD[0] = CPLSerializeXMLTree(psGeodataXform);
502
0
            apszMD[1] = nullptr;
503
0
            oMDMD.SetMetadata(apszMD, "xml:ESRI");
504
0
            CPLFree(apszMD[0]);
505
0
        }
506
0
        else
507
0
        {
508
            // ArcGIS 10: GeodataXform as content of xml:ESRI metadata domain.
509
0
            char **papszXML = oMDMD.GetMetadata("xml:ESRI");
510
0
            if (CSLCount(papszXML) == 1)
511
0
            {
512
0
                oTreeValueAsXML.reset(CPLParseXMLString(papszXML[0]));
513
0
                if (oTreeValueAsXML)
514
0
                    psGeodataXform =
515
0
                        CPLGetXMLNode(oTreeValueAsXML.get(), "=GeodataXform");
516
0
            }
517
0
        }
518
519
0
        if (psGeodataXform)
520
0
        {
521
0
            const char *pszESRI_WKT =
522
0
                CPLGetXMLValue(psGeodataXform, "SpatialReference.WKT", nullptr);
523
0
            if (pszESRI_WKT)
524
0
            {
525
0
                auto poSRS = std::make_unique<OGRSpatialReference>();
526
0
                poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
527
0
                if (poSRS->importFromWkt(pszESRI_WKT) != OGRERR_NONE)
528
0
                {
529
0
                    poSRS.reset();
530
0
                }
531
0
                delete psPam->poSRS;
532
0
                psPam->poSRS = poSRS.release();
533
0
            }
534
535
            // Parse GCPs
536
0
            const CPLXMLNode *psSourceGCPS =
537
0
                CPLGetXMLNode(psGeodataXform, "SourceGCPs");
538
0
            const CPLXMLNode *psTargetGCPs =
539
0
                CPLGetXMLNode(psGeodataXform, "TargetGCPs");
540
0
            const CPLXMLNode *psCoeffX =
541
0
                CPLGetXMLNode(psGeodataXform, "CoeffX");
542
0
            const CPLXMLNode *psCoeffY =
543
0
                CPLGetXMLNode(psGeodataXform, "CoeffY");
544
0
            if (psSourceGCPS && psTargetGCPs && !psPam->bHaveGeoTransform)
545
0
            {
546
0
                std::vector<double> adfSource;
547
0
                std::vector<double> adfTarget;
548
0
                bool ySourceAllNegative = true;
549
0
                for (auto psIter = psSourceGCPS->psChild; psIter;
550
0
                     psIter = psIter->psNext)
551
0
                {
552
0
                    if (psIter->eType == CXT_Element &&
553
0
                        strcmp(psIter->pszValue, "Double") == 0)
554
0
                    {
555
0
                        adfSource.push_back(
556
0
                            CPLAtof(CPLGetXMLValue(psIter, nullptr, "0")));
557
0
                        if ((adfSource.size() % 2) == 0 && adfSource.back() > 0)
558
0
                            ySourceAllNegative = false;
559
0
                    }
560
0
                }
561
0
                for (auto psIter = psTargetGCPs->psChild; psIter;
562
0
                     psIter = psIter->psNext)
563
0
                {
564
0
                    if (psIter->eType == CXT_Element &&
565
0
                        strcmp(psIter->pszValue, "Double") == 0)
566
0
                    {
567
0
                        adfTarget.push_back(
568
0
                            CPLAtof(CPLGetXMLValue(psIter, nullptr, "0")));
569
0
                    }
570
0
                }
571
0
                if (!adfSource.empty() &&
572
0
                    adfSource.size() == adfTarget.size() &&
573
0
                    (adfSource.size() % 2) == 0)
574
0
                {
575
0
                    std::vector<gdal::GCP> asGCPs;
576
0
                    for (size_t i = 0; i + 1 < adfSource.size(); i += 2)
577
0
                    {
578
0
                        asGCPs.emplace_back("", "",
579
0
                                            /* pixel = */ adfSource[i],
580
                                            /* line = */
581
0
                                            ySourceAllNegative
582
0
                                                ? -adfSource[i + 1]
583
0
                                                : adfSource[i + 1],
584
0
                                            /* X = */ adfTarget[i],
585
0
                                            /* Y = */ adfTarget[i + 1]);
586
0
                    }
587
0
                    GDALPamDataset::SetGCPs(static_cast<int>(asGCPs.size()),
588
0
                                            gdal::GCP::c_ptr(asGCPs),
589
0
                                            psPam->poSRS);
590
0
                    delete psPam->poSRS;
591
0
                    psPam->poSRS = nullptr;
592
0
                }
593
0
            }
594
0
            else if (psCoeffX && psCoeffY && !psPam->bHaveGeoTransform &&
595
0
                     EQUAL(
596
0
                         CPLGetXMLValue(psGeodataXform, "PolynomialOrder", ""),
597
0
                         "1"))
598
0
            {
599
0
                std::vector<double> adfCoeffX;
600
0
                std::vector<double> adfCoeffY;
601
0
                for (auto psIter = psCoeffX->psChild; psIter;
602
0
                     psIter = psIter->psNext)
603
0
                {
604
0
                    if (psIter->eType == CXT_Element &&
605
0
                        strcmp(psIter->pszValue, "Double") == 0)
606
0
                    {
607
0
                        adfCoeffX.push_back(
608
0
                            CPLAtof(CPLGetXMLValue(psIter, nullptr, "0")));
609
0
                    }
610
0
                }
611
0
                for (auto psIter = psCoeffY->psChild; psIter;
612
0
                     psIter = psIter->psNext)
613
0
                {
614
0
                    if (psIter->eType == CXT_Element &&
615
0
                        strcmp(psIter->pszValue, "Double") == 0)
616
0
                    {
617
0
                        adfCoeffY.push_back(
618
0
                            CPLAtof(CPLGetXMLValue(psIter, nullptr, "0")));
619
0
                    }
620
0
                }
621
0
                if (adfCoeffX.size() == 3 && adfCoeffY.size() == 3)
622
0
                {
623
0
                    psPam->gt[0] = adfCoeffX[0];
624
0
                    psPam->gt[1] = adfCoeffX[1];
625
                    // Looking at the example of https://github.com/qgis/QGIS/issues/53125#issuecomment-1567650082
626
                    // when comparing the .pgwx world file and .png.aux.xml file,
627
                    // it appears that the sign of the coefficients for the line
628
                    // terms must be negated (which is a bit in line with the
629
                    // negation of dfGCPLine in the above GCP case)
630
0
                    psPam->gt[2] = -adfCoeffX[2];
631
0
                    psPam->gt[3] = adfCoeffY[0];
632
0
                    psPam->gt[4] = adfCoeffY[1];
633
0
                    psPam->gt[5] = -adfCoeffY[2];
634
635
                    // Looking at the example of https://github.com/qgis/QGIS/issues/53125#issuecomment-1567650082
636
                    // when comparing the .pgwx world file and .png.aux.xml file,
637
                    // one can see that they have the same origin, so knowing
638
                    // that world file uses a center-of-pixel convention,
639
                    // correct from center of pixel to top left of pixel
640
0
                    psPam->gt[0] -= 0.5 * psPam->gt[1];
641
0
                    psPam->gt[0] -= 0.5 * psPam->gt[2];
642
0
                    psPam->gt[3] -= 0.5 * psPam->gt[4];
643
0
                    psPam->gt[3] -= 0.5 * psPam->gt[5];
644
645
0
                    psPam->bHaveGeoTransform = TRUE;
646
0
                }
647
0
            }
648
0
        }
649
0
    }
650
651
    /* -------------------------------------------------------------------- */
652
    /*      Process bands.                                                  */
653
    /* -------------------------------------------------------------------- */
654
0
    for (const CPLXMLNode *psBandTree = psTree->psChild; psBandTree;
655
0
         psBandTree = psBandTree->psNext)
656
0
    {
657
0
        if (psBandTree->eType != CXT_Element ||
658
0
            !EQUAL(psBandTree->pszValue, "PAMRasterBand"))
659
0
            continue;
660
661
0
        const int nBand = atoi(CPLGetXMLValue(psBandTree, "band", "0"));
662
663
0
        if (nBand < 1 || nBand > GetRasterCount())
664
0
            continue;
665
666
0
        GDALRasterBand *poBand = GetRasterBand(nBand);
667
668
0
        if (poBand == nullptr || !(poBand->GetMOFlags() & GMO_PAM_CLASS))
669
0
            continue;
670
671
0
        GDALPamRasterBand *poPamBand =
672
0
            cpl::down_cast<GDALPamRasterBand *>(GetRasterBand(nBand));
673
674
0
        poPamBand->XMLInit(psBandTree, pszUnused);
675
0
    }
676
677
    /* -------------------------------------------------------------------- */
678
    /*      Preserve Array information.                                     */
679
    /* -------------------------------------------------------------------- */
680
0
    for (const CPLXMLNode *psIter = psTree->psChild; psIter;
681
0
         psIter = psIter->psNext)
682
0
    {
683
0
        if (psIter->eType == CXT_Element &&
684
0
            (strcmp(psIter->pszValue, "Array") == 0 ||
685
0
             (psPam->osDerivedDatasetName.empty() &&
686
0
              strcmp(psIter->pszValue, "DerivedDataset") == 0)))
687
0
        {
688
0
            CPLXMLNode sArrayTmp = *psIter;
689
0
            sArrayTmp.psNext = nullptr;
690
0
            psPam->m_apoOtherNodes.emplace_back(
691
0
                CPLXMLTreeCloser(CPLCloneXMLTree(&sArrayTmp)));
692
0
        }
693
0
    }
694
695
    /* -------------------------------------------------------------------- */
696
    /*      Clear dirty flag.                                               */
697
    /* -------------------------------------------------------------------- */
698
0
    nPamFlags &= ~GPF_DIRTY;
699
700
0
    return CE_None;
701
0
}
702
703
/************************************************************************/
704
/*                        SetPhysicalFilename()                         */
705
/************************************************************************/
706
707
void GDALPamDataset::SetPhysicalFilename(const char *pszFilename)
708
709
0
{
710
0
    PamInitialize();
711
712
0
    if (psPam)
713
0
        psPam->osPhysicalFilename = pszFilename;
714
0
}
715
716
/************************************************************************/
717
/*                        GetPhysicalFilename()                         */
718
/************************************************************************/
719
720
const char *GDALPamDataset::GetPhysicalFilename()
721
722
0
{
723
0
    PamInitialize();
724
725
0
    if (psPam)
726
0
        return psPam->osPhysicalFilename;
727
728
0
    return "";
729
0
}
730
731
/************************************************************************/
732
/*                         SetSubdatasetName()                          */
733
/************************************************************************/
734
735
/* Mutually exclusive with SetDerivedDatasetName() */
736
void GDALPamDataset::SetSubdatasetName(const char *pszSubdataset)
737
738
0
{
739
0
    PamInitialize();
740
741
0
    if (psPam)
742
0
        psPam->osSubdatasetName = pszSubdataset;
743
0
}
744
745
/************************************************************************/
746
/*                        SetDerivedDatasetName()                        */
747
/************************************************************************/
748
749
/* Mutually exclusive with SetSubdatasetName() */
750
void GDALPamDataset::SetDerivedDatasetName(const char *pszDerivedDataset)
751
752
0
{
753
0
    PamInitialize();
754
755
0
    if (psPam)
756
0
        psPam->osDerivedDatasetName = pszDerivedDataset;
757
0
}
758
759
/************************************************************************/
760
/*                         GetSubdatasetName()                          */
761
/************************************************************************/
762
763
const char *GDALPamDataset::GetSubdatasetName()
764
765
0
{
766
0
    PamInitialize();
767
768
0
    if (psPam)
769
0
        return psPam->osSubdatasetName;
770
771
0
    return "";
772
0
}
773
774
/************************************************************************/
775
/*                          BuildPamFilename()                          */
776
/************************************************************************/
777
778
const char *GDALPamDataset::BuildPamFilename()
779
780
0
{
781
0
    if (psPam == nullptr)
782
0
        return nullptr;
783
784
    /* -------------------------------------------------------------------- */
785
    /*      What is the name of the physical file we are referencing?       */
786
    /*      We allow an override via the psPam->pszPhysicalFile item.       */
787
    /* -------------------------------------------------------------------- */
788
0
    if (psPam->pszPamFilename != nullptr)
789
0
        return psPam->pszPamFilename;
790
791
0
    const char *pszPhysicalFile = psPam->osPhysicalFilename;
792
793
0
    if (strlen(pszPhysicalFile) == 0 && GetDescription() != nullptr)
794
0
        pszPhysicalFile = GetDescription();
795
796
0
    if (strlen(pszPhysicalFile) == 0)
797
0
        return nullptr;
798
799
    /* -------------------------------------------------------------------- */
800
    /*      Try a proxy lookup, otherwise just add .aux.xml.                */
801
    /* -------------------------------------------------------------------- */
802
0
    const char *pszProxyPam = PamGetProxy(pszPhysicalFile);
803
0
    if (pszProxyPam != nullptr)
804
0
        psPam->pszPamFilename = CPLStrdup(pszProxyPam);
805
0
    else
806
0
    {
807
0
        if (!GDALCanFileAcceptSidecarFile(pszPhysicalFile))
808
0
            return nullptr;
809
0
        psPam->pszPamFilename =
810
0
            static_cast<char *>(CPLMalloc(strlen(pszPhysicalFile) + 10));
811
0
        strcpy(psPam->pszPamFilename, pszPhysicalFile);
812
0
        strcat(psPam->pszPamFilename, ".aux.xml");
813
0
    }
814
815
0
    return psPam->pszPamFilename;
816
0
}
817
818
/************************************************************************/
819
/*                   IsPamFilenameAPotentialSiblingFile()               */
820
/************************************************************************/
821
822
int GDALPamDataset::IsPamFilenameAPotentialSiblingFile()
823
0
{
824
0
    if (psPam == nullptr)
825
0
        return FALSE;
826
827
    /* -------------------------------------------------------------------- */
828
    /*      Determine if the PAM filename is a .aux.xml file next to the    */
829
    /*      physical file, or if it comes from the ProxyDB                  */
830
    /* -------------------------------------------------------------------- */
831
0
    const char *pszPhysicalFile = psPam->osPhysicalFilename;
832
833
0
    if (strlen(pszPhysicalFile) == 0 && GetDescription() != nullptr)
834
0
        pszPhysicalFile = GetDescription();
835
836
0
    size_t nLenPhysicalFile = strlen(pszPhysicalFile);
837
0
    int bIsSiblingPamFile =
838
0
        strncmp(psPam->pszPamFilename, pszPhysicalFile, nLenPhysicalFile) ==
839
0
            0 &&
840
0
        strcmp(psPam->pszPamFilename + nLenPhysicalFile, ".aux.xml") == 0;
841
842
0
    return bIsSiblingPamFile;
843
0
}
844
845
/************************************************************************/
846
/*                             TryLoadXML()                             */
847
/************************************************************************/
848
849
CPLErr GDALPamDataset::TryLoadXML(CSLConstList papszSiblingFiles)
850
851
0
{
852
0
    PamInitialize();
853
854
0
    if (psPam == nullptr || (nPamFlags & GPF_DISABLED) != 0)
855
0
        return CE_None;
856
857
    /* -------------------------------------------------------------------- */
858
    /*      Clear dirty flag.  Generally when we get to this point is       */
859
    /*      from a call at the end of the Open() method, and some calls     */
860
    /*      may have already marked the PAM info as dirty (for instance     */
861
    /*      setting metadata), but really everything to this point is       */
862
    /*      reproducible, and so the PAM info should not really be          */
863
    /*      thought of as dirty.                                            */
864
    /* -------------------------------------------------------------------- */
865
0
    nPamFlags &= ~GPF_DIRTY;
866
867
    /* -------------------------------------------------------------------- */
868
    /*      Try reading the file.                                           */
869
    /* -------------------------------------------------------------------- */
870
0
    if (!BuildPamFilename())
871
0
        return CE_None;
872
873
    /* -------------------------------------------------------------------- */
874
    /*      In case the PAM filename is a .aux.xml file next to the         */
875
    /*      physical file and we have a siblings list, then we can skip     */
876
    /*      stat'ing the filesystem.                                        */
877
    /* -------------------------------------------------------------------- */
878
0
    VSIStatBufL sStatBuf;
879
0
    CPLXMLNode *psTree = nullptr;
880
881
0
    if (papszSiblingFiles != nullptr && IsPamFilenameAPotentialSiblingFile() &&
882
0
        GDALCanReliablyUseSiblingFileList(psPam->pszPamFilename))
883
0
    {
884
0
        const int iSibling = CSLFindString(
885
0
            papszSiblingFiles, CPLGetFilename(psPam->pszPamFilename));
886
0
        if (iSibling >= 0)
887
0
        {
888
0
            CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
889
0
            psTree = CPLParseXMLFile(psPam->pszPamFilename);
890
0
        }
891
0
    }
892
0
    else if (VSIStatExL(psPam->pszPamFilename, &sStatBuf,
893
0
                        VSI_STAT_EXISTS_FLAG | VSI_STAT_NATURE_FLAG) == 0 &&
894
0
             VSI_ISREG(sStatBuf.st_mode))
895
0
    {
896
0
        CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
897
0
        psTree = CPLParseXMLFile(psPam->pszPamFilename);
898
0
    }
899
900
    /* -------------------------------------------------------------------- */
901
    /*      If we are looking for a subdataset, search for its subtree now. */
902
    /* -------------------------------------------------------------------- */
903
0
    if (psTree)
904
0
    {
905
0
        std::string osSubNode;
906
0
        std::string osSubNodeValue;
907
0
        if (!psPam->osSubdatasetName.empty())
908
0
        {
909
0
            osSubNode = "Subdataset";
910
0
            osSubNodeValue = psPam->osSubdatasetName;
911
0
        }
912
0
        else if (!psPam->osDerivedDatasetName.empty())
913
0
        {
914
0
            osSubNode = "DerivedDataset";
915
0
            osSubNodeValue = psPam->osDerivedDatasetName;
916
0
        }
917
0
        if (!osSubNode.empty())
918
0
        {
919
0
            CPLXMLNode *psSubTree = psTree->psChild;
920
921
0
            for (; psSubTree != nullptr; psSubTree = psSubTree->psNext)
922
0
            {
923
0
                if (psSubTree->eType != CXT_Element ||
924
0
                    !EQUAL(psSubTree->pszValue, osSubNode.c_str()))
925
0
                    continue;
926
927
0
                if (!EQUAL(CPLGetXMLValue(psSubTree, "name", ""),
928
0
                           osSubNodeValue.c_str()))
929
0
                    continue;
930
931
0
                psSubTree = CPLGetXMLNode(psSubTree, "PAMDataset");
932
0
                break;
933
0
            }
934
935
0
            if (psSubTree != nullptr)
936
0
                psSubTree = CPLCloneXMLTree(psSubTree);
937
938
0
            CPLDestroyXMLNode(psTree);
939
0
            psTree = psSubTree;
940
0
        }
941
0
    }
942
943
    /* -------------------------------------------------------------------- */
944
    /*      If we fail, try .aux.                                           */
945
    /* -------------------------------------------------------------------- */
946
0
    if (psTree == nullptr)
947
0
        return TryLoadAux(papszSiblingFiles);
948
949
    /* -------------------------------------------------------------------- */
950
    /*      Initialize ourselves from this XML tree.                        */
951
    /* -------------------------------------------------------------------- */
952
953
0
    CPLString osVRTPath(CPLGetPathSafe(psPam->pszPamFilename));
954
0
    const CPLErr eErr = XMLInit(psTree, osVRTPath);
955
956
0
    CPLDestroyXMLNode(psTree);
957
958
0
    if (eErr != CE_None)
959
0
        PamClear();
960
961
0
    return eErr;
962
0
}
963
964
/************************************************************************/
965
/*                             TrySaveXML()                             */
966
/************************************************************************/
967
968
CPLErr GDALPamDataset::TrySaveXML()
969
970
0
{
971
0
    nPamFlags &= ~GPF_DIRTY;
972
973
0
    if (psPam == nullptr || (nPamFlags & GPF_NOSAVE) != 0 ||
974
0
        (nPamFlags & GPF_DISABLED) != 0)
975
0
        return CE_None;
976
977
    /* -------------------------------------------------------------------- */
978
    /*      Make sure we know the filename we want to store in.             */
979
    /* -------------------------------------------------------------------- */
980
0
    if (!BuildPamFilename())
981
0
        return CE_None;
982
983
    /* -------------------------------------------------------------------- */
984
    /*      Build the XML representation of the auxiliary metadata.          */
985
    /* -------------------------------------------------------------------- */
986
0
    CPLXMLNode *psTree = SerializeToXML(nullptr);
987
988
0
    if (psTree == nullptr)
989
0
    {
990
        /* If we have unset all metadata, we have to delete the PAM file */
991
0
        CPLPushErrorHandler(CPLQuietErrorHandler);
992
0
        VSIUnlink(psPam->pszPamFilename);
993
0
        CPLPopErrorHandler();
994
0
        return CE_None;
995
0
    }
996
997
    /* -------------------------------------------------------------------- */
998
    /*      If we are working with a subdataset, we need to integrate       */
999
    /*      the subdataset tree within the whole existing pam tree,         */
1000
    /*      after removing any old version of the same subdataset.          */
1001
    /* -------------------------------------------------------------------- */
1002
0
    std::string osSubNode;
1003
0
    std::string osSubNodeValue;
1004
0
    if (!psPam->osSubdatasetName.empty())
1005
0
    {
1006
0
        osSubNode = "Subdataset";
1007
0
        osSubNodeValue = psPam->osSubdatasetName;
1008
0
    }
1009
0
    else if (!psPam->osDerivedDatasetName.empty())
1010
0
    {
1011
0
        osSubNode = "DerivedDataset";
1012
0
        osSubNodeValue = psPam->osDerivedDatasetName;
1013
0
    }
1014
0
    if (!osSubNode.empty())
1015
0
    {
1016
0
        CPLXMLNode *psOldTree = nullptr;
1017
1018
0
        VSIStatBufL sStatBuf;
1019
0
        if (VSIStatExL(psPam->pszPamFilename, &sStatBuf,
1020
0
                       VSI_STAT_EXISTS_FLAG | VSI_STAT_NATURE_FLAG) == 0 &&
1021
0
            VSI_ISREG(sStatBuf.st_mode))
1022
0
        {
1023
0
            CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
1024
0
            psOldTree = CPLParseXMLFile(psPam->pszPamFilename);
1025
0
        }
1026
1027
0
        if (psOldTree == nullptr)
1028
0
            psOldTree = CPLCreateXMLNode(nullptr, CXT_Element, "PAMDataset");
1029
1030
0
        CPLXMLNode *psSubTree = psOldTree->psChild;
1031
0
        for (/* initialized above */; psSubTree != nullptr;
1032
0
             psSubTree = psSubTree->psNext)
1033
0
        {
1034
0
            if (psSubTree->eType != CXT_Element ||
1035
0
                !EQUAL(psSubTree->pszValue, osSubNode.c_str()))
1036
0
                continue;
1037
1038
0
            if (!EQUAL(CPLGetXMLValue(psSubTree, "name", ""),
1039
0
                       osSubNodeValue.c_str()))
1040
0
                continue;
1041
1042
0
            break;
1043
0
        }
1044
1045
0
        if (psSubTree == nullptr)
1046
0
        {
1047
0
            psSubTree =
1048
0
                CPLCreateXMLNode(psOldTree, CXT_Element, osSubNode.c_str());
1049
0
            CPLCreateXMLNode(CPLCreateXMLNode(psSubTree, CXT_Attribute, "name"),
1050
0
                             CXT_Text, osSubNodeValue.c_str());
1051
0
        }
1052
1053
0
        CPLXMLNode *psOldPamDataset = CPLGetXMLNode(psSubTree, "PAMDataset");
1054
0
        if (psOldPamDataset != nullptr)
1055
0
        {
1056
0
            CPLRemoveXMLChild(psSubTree, psOldPamDataset);
1057
0
            CPLDestroyXMLNode(psOldPamDataset);
1058
0
        }
1059
1060
0
        CPLAddXMLChild(psSubTree, psTree);
1061
0
        psTree = psOldTree;
1062
0
    }
1063
1064
    /* -------------------------------------------------------------------- */
1065
    /*      Preserve other information.                                     */
1066
    /* -------------------------------------------------------------------- */
1067
0
    for (const auto &poOtherNode : psPam->m_apoOtherNodes)
1068
0
    {
1069
0
        CPLAddXMLChild(psTree, CPLCloneXMLTree(poOtherNode.get()));
1070
0
    }
1071
1072
    /* -------------------------------------------------------------------- */
1073
    /*      Try saving the auxiliary metadata.                               */
1074
    /* -------------------------------------------------------------------- */
1075
1076
0
    CPLPushErrorHandler(CPLQuietErrorHandler);
1077
0
    const int bSaved = CPLSerializeXMLTreeToFile(psTree, psPam->pszPamFilename);
1078
0
    CPLPopErrorHandler();
1079
1080
    /* -------------------------------------------------------------------- */
1081
    /*      If it fails, check if we have a proxy directory for auxiliary    */
1082
    /*      metadata to be stored in, and try to save there.                */
1083
    /* -------------------------------------------------------------------- */
1084
0
    CPLErr eErr = CE_None;
1085
1086
0
    if (bSaved)
1087
0
        eErr = CE_None;
1088
0
    else
1089
0
    {
1090
0
        const char *pszBasename = GetDescription();
1091
1092
0
        if (psPam->osPhysicalFilename.length() > 0)
1093
0
            pszBasename = psPam->osPhysicalFilename;
1094
1095
0
        const char *pszNewPam = nullptr;
1096
0
        if (PamGetProxy(pszBasename) == nullptr &&
1097
0
            ((pszNewPam = PamAllocateProxy(pszBasename)) != nullptr))
1098
0
        {
1099
0
            CPLErrorReset();
1100
0
            CPLFree(psPam->pszPamFilename);
1101
0
            psPam->pszPamFilename = CPLStrdup(pszNewPam);
1102
0
            eErr = TrySaveXML();
1103
0
        }
1104
        /* No way we can save into a /vsicurl resource */
1105
0
        else if (!STARTS_WITH(psPam->pszPamFilename, "/vsicurl"))
1106
0
        {
1107
0
            CPLError(CE_Warning, CPLE_AppDefined,
1108
0
                     "Unable to save auxiliary information in %s.",
1109
0
                     psPam->pszPamFilename);
1110
0
            eErr = CE_Warning;
1111
0
        }
1112
0
    }
1113
1114
    /* -------------------------------------------------------------------- */
1115
    /*      Cleanup                                                         */
1116
    /* -------------------------------------------------------------------- */
1117
0
    CPLDestroyXMLNode(psTree);
1118
1119
0
    return eErr;
1120
0
}
1121
1122
/************************************************************************/
1123
/*                             CloneInfo()                              */
1124
/************************************************************************/
1125
1126
CPLErr GDALPamDataset::CloneInfo(GDALDataset *poSrcDS, int nCloneFlags)
1127
1128
0
{
1129
0
    const int bOnlyIfMissing = nCloneFlags & GCIF_ONLY_IF_MISSING;
1130
0
    const int nSavedMOFlags = GetMOFlags();
1131
1132
0
    PamInitialize();
1133
1134
    /* -------------------------------------------------------------------- */
1135
    /*      Suppress NotImplemented error messages - mainly needed if PAM   */
1136
    /*      disabled.                                                       */
1137
    /* -------------------------------------------------------------------- */
1138
0
    SetMOFlags(nSavedMOFlags | GMO_IGNORE_UNIMPLEMENTED);
1139
1140
    /* -------------------------------------------------------------------- */
1141
    /*      GeoTransform                                                    */
1142
    /* -------------------------------------------------------------------- */
1143
0
    if (nCloneFlags & GCIF_GEOTRANSFORM)
1144
0
    {
1145
0
        GDALGeoTransform gt;
1146
1147
0
        if (poSrcDS->GetGeoTransform(gt) == CE_None)
1148
0
        {
1149
0
            GDALGeoTransform oldGT;
1150
1151
0
            if (!bOnlyIfMissing || GetGeoTransform(oldGT) != CE_None)
1152
0
                SetGeoTransform(gt);
1153
0
        }
1154
0
    }
1155
1156
    /* -------------------------------------------------------------------- */
1157
    /*      Projection                                                      */
1158
    /* -------------------------------------------------------------------- */
1159
0
    if (nCloneFlags & GCIF_PROJECTION)
1160
0
    {
1161
0
        const auto poSRS = poSrcDS->GetSpatialRef();
1162
1163
0
        if (poSRS != nullptr)
1164
0
        {
1165
0
            if (!bOnlyIfMissing || GetSpatialRef() == nullptr)
1166
0
                SetSpatialRef(poSRS);
1167
0
        }
1168
0
    }
1169
1170
    /* -------------------------------------------------------------------- */
1171
    /*      GCPs                                                            */
1172
    /* -------------------------------------------------------------------- */
1173
0
    if (nCloneFlags & GCIF_GCPS)
1174
0
    {
1175
0
        if (poSrcDS->GetGCPCount() > 0)
1176
0
        {
1177
0
            if (!bOnlyIfMissing || GetGCPCount() == 0)
1178
0
            {
1179
0
                SetGCPs(poSrcDS->GetGCPCount(), poSrcDS->GetGCPs(),
1180
0
                        poSrcDS->GetGCPSpatialRef());
1181
0
            }
1182
0
        }
1183
0
    }
1184
1185
    /* -------------------------------------------------------------------- */
1186
    /*      Metadata                                                        */
1187
    /* -------------------------------------------------------------------- */
1188
0
    if (nCloneFlags & GCIF_METADATA)
1189
0
    {
1190
0
        for (const char *pszMDD : {"", "RPC", "json:ISIS3", "json:VICAR"})
1191
0
        {
1192
0
            auto papszSrcMD = poSrcDS->GetMetadata(pszMDD);
1193
0
            if (papszSrcMD != nullptr)
1194
0
            {
1195
0
                if (!bOnlyIfMissing ||
1196
0
                    CSLCount(GetMetadata(pszMDD)) != CSLCount(papszSrcMD))
1197
0
                {
1198
0
                    SetMetadata(papszSrcMD, pszMDD);
1199
0
                }
1200
0
            }
1201
0
        }
1202
0
    }
1203
1204
    /* -------------------------------------------------------------------- */
1205
    /*      Process bands.                                                  */
1206
    /* -------------------------------------------------------------------- */
1207
0
    if (nCloneFlags & GCIF_PROCESS_BANDS)
1208
0
    {
1209
0
        for (int iBand = 0; iBand < GetRasterCount(); iBand++)
1210
0
        {
1211
0
            GDALRasterBand *poBand = GetRasterBand(iBand + 1);
1212
1213
0
            if (poBand == nullptr || !(poBand->GetMOFlags() & GMO_PAM_CLASS))
1214
0
                continue;
1215
1216
0
            if (poSrcDS->GetRasterCount() >= iBand + 1)
1217
0
            {
1218
0
                cpl::down_cast<GDALPamRasterBand *>(poBand)->CloneInfo(
1219
0
                    poSrcDS->GetRasterBand(iBand + 1), nCloneFlags);
1220
0
            }
1221
0
            else
1222
0
                CPLDebug("GDALPamDataset",
1223
0
                         "Skipping CloneInfo for band not in source, "
1224
0
                         "this is a bit unusual!");
1225
0
        }
1226
0
    }
1227
1228
    /* -------------------------------------------------------------------- */
1229
    /*      Copy masks.  These are really copied at a lower level using     */
1230
    /*      GDALDefaultOverviews, for formats with no native mask           */
1231
    /*      support but this is a convenient central point to put this      */
1232
    /*      for most drivers.                                               */
1233
    /* -------------------------------------------------------------------- */
1234
0
    if (nCloneFlags & GCIF_MASK)
1235
0
    {
1236
0
        GDALDriver::DefaultCopyMasks(poSrcDS, this, FALSE);
1237
0
    }
1238
1239
    /* -------------------------------------------------------------------- */
1240
    /*      Restore MO flags.                                               */
1241
    /* -------------------------------------------------------------------- */
1242
0
    SetMOFlags(nSavedMOFlags);
1243
1244
0
    return CE_None;
1245
0
}
1246
1247
//! @endcond
1248
1249
/************************************************************************/
1250
/*                            GetFileList()                             */
1251
/*                                                                      */
1252
/*      Add .aux.xml or .aux file into file list as appropriate.        */
1253
/************************************************************************/
1254
1255
char **GDALPamDataset::GetFileList()
1256
1257
0
{
1258
0
    char **papszFileList = GDALDataset::GetFileList();
1259
1260
0
    if (psPam && !psPam->osPhysicalFilename.empty() &&
1261
0
        GDALCanReliablyUseSiblingFileList(psPam->osPhysicalFilename.c_str()) &&
1262
0
        CSLFindString(papszFileList, psPam->osPhysicalFilename) == -1)
1263
0
    {
1264
0
        papszFileList =
1265
0
            CSLInsertString(papszFileList, 0, psPam->osPhysicalFilename);
1266
0
    }
1267
1268
0
    if (psPam && psPam->pszPamFilename)
1269
0
    {
1270
0
        int bAddPamFile = nPamFlags & GPF_DIRTY;
1271
0
        if (!bAddPamFile)
1272
0
        {
1273
0
            VSIStatBufL sStatBuf;
1274
0
            if (oOvManager.GetSiblingFiles() != nullptr &&
1275
0
                IsPamFilenameAPotentialSiblingFile() &&
1276
0
                GDALCanReliablyUseSiblingFileList(psPam->pszPamFilename))
1277
0
            {
1278
0
                bAddPamFile =
1279
0
                    CSLFindString(oOvManager.GetSiblingFiles(),
1280
0
                                  CPLGetFilename(psPam->pszPamFilename)) >= 0;
1281
0
            }
1282
0
            else
1283
0
            {
1284
0
                bAddPamFile = VSIStatExL(psPam->pszPamFilename, &sStatBuf,
1285
0
                                         VSI_STAT_EXISTS_FLAG) == 0;
1286
0
            }
1287
0
        }
1288
0
        if (bAddPamFile)
1289
0
        {
1290
0
            papszFileList = CSLAddString(papszFileList, psPam->pszPamFilename);
1291
0
        }
1292
0
    }
1293
1294
0
    if (psPam && !psPam->osAuxFilename.empty() &&
1295
0
        GDALCanReliablyUseSiblingFileList(psPam->osAuxFilename.c_str()) &&
1296
0
        CSLFindString(papszFileList, psPam->osAuxFilename) == -1)
1297
0
    {
1298
0
        papszFileList = CSLAddString(papszFileList, psPam->osAuxFilename);
1299
0
    }
1300
0
    return papszFileList;
1301
0
}
1302
1303
/************************************************************************/
1304
/*                          IBuildOverviews()                           */
1305
/************************************************************************/
1306
1307
//! @cond Doxygen_Suppress
1308
CPLErr GDALPamDataset::IBuildOverviews(
1309
    const char *pszResampling, int nOverviews, const int *panOverviewList,
1310
    int nListBands, const int *panBandList, GDALProgressFunc pfnProgress,
1311
    void *pProgressData, CSLConstList papszOptions)
1312
1313
0
{
1314
    /* -------------------------------------------------------------------- */
1315
    /*      Initialize PAM.                                                 */
1316
    /* -------------------------------------------------------------------- */
1317
0
    PamInitialize();
1318
0
    if (psPam == nullptr)
1319
0
        return GDALDataset::IBuildOverviews(
1320
0
            pszResampling, nOverviews, panOverviewList, nListBands, panBandList,
1321
0
            pfnProgress, pProgressData, papszOptions);
1322
1323
    /* -------------------------------------------------------------------- */
1324
    /*      If we appear to have subdatasets and to have a physical         */
1325
    /*      filename, use that physical filename to derive a name for a     */
1326
    /*      new overview file.                                              */
1327
    /* -------------------------------------------------------------------- */
1328
0
    if (oOvManager.IsInitialized() && psPam->osPhysicalFilename.length() != 0)
1329
0
    {
1330
0
        return oOvManager.BuildOverviewsSubDataset(
1331
0
            psPam->osPhysicalFilename, pszResampling, nOverviews,
1332
0
            panOverviewList, nListBands, panBandList, pfnProgress,
1333
0
            pProgressData, papszOptions);
1334
0
    }
1335
1336
0
    return GDALDataset::IBuildOverviews(
1337
0
        pszResampling, nOverviews, panOverviewList, nListBands, panBandList,
1338
0
        pfnProgress, pProgressData, papszOptions);
1339
0
}
1340
1341
//! @endcond
1342
1343
/************************************************************************/
1344
/*                           GetSpatialRef()                            */
1345
/************************************************************************/
1346
1347
const OGRSpatialReference *GDALPamDataset::GetSpatialRef() const
1348
1349
0
{
1350
0
    if (psPam && psPam->poSRS)
1351
0
        return psPam->poSRS;
1352
1353
0
    return GDALDataset::GetSpatialRef();
1354
0
}
1355
1356
/************************************************************************/
1357
/*                           SetSpatialRef()                            */
1358
/************************************************************************/
1359
1360
CPLErr GDALPamDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
1361
1362
0
{
1363
0
    PamInitialize();
1364
1365
0
    if (psPam == nullptr)
1366
0
        return GDALDataset::SetSpatialRef(poSRS);
1367
1368
0
    if (psPam->poSRS)
1369
0
        psPam->poSRS->Release();
1370
0
    psPam->poSRS = poSRS ? poSRS->Clone() : nullptr;
1371
0
    MarkPamDirty();
1372
1373
0
    return CE_None;
1374
0
}
1375
1376
/************************************************************************/
1377
/*                          GetGeoTransform()                           */
1378
/************************************************************************/
1379
1380
CPLErr GDALPamDataset::GetGeoTransform(GDALGeoTransform &gt) const
1381
1382
0
{
1383
0
    if (psPam && psPam->bHaveGeoTransform)
1384
0
    {
1385
0
        gt = psPam->gt;
1386
0
        return CE_None;
1387
0
    }
1388
1389
0
    return GDALDataset::GetGeoTransform(gt);
1390
0
}
1391
1392
/************************************************************************/
1393
/*                          SetGeoTransform()                           */
1394
/************************************************************************/
1395
1396
CPLErr GDALPamDataset::SetGeoTransform(const GDALGeoTransform &gt)
1397
1398
0
{
1399
0
    PamInitialize();
1400
1401
0
    if (psPam)
1402
0
    {
1403
0
        MarkPamDirty();
1404
0
        psPam->bHaveGeoTransform = true;
1405
0
        psPam->gt = gt;
1406
0
        return (CE_None);
1407
0
    }
1408
1409
0
    return GDALDataset::SetGeoTransform(gt);
1410
0
}
1411
1412
/************************************************************************/
1413
/*                        DeleteGeoTransform()                          */
1414
/************************************************************************/
1415
1416
/** Remove geotransform from PAM.
1417
 *
1418
 * @since GDAL 3.4.1
1419
 */
1420
void GDALPamDataset::DeleteGeoTransform()
1421
1422
0
{
1423
0
    PamInitialize();
1424
1425
0
    if (psPam && psPam->bHaveGeoTransform)
1426
0
    {
1427
0
        MarkPamDirty();
1428
0
        psPam->bHaveGeoTransform = FALSE;
1429
0
    }
1430
0
}
1431
1432
/************************************************************************/
1433
/*                            GetGCPCount()                             */
1434
/************************************************************************/
1435
1436
int GDALPamDataset::GetGCPCount()
1437
1438
0
{
1439
0
    if (psPam && !psPam->asGCPs.empty())
1440
0
        return static_cast<int>(psPam->asGCPs.size());
1441
1442
0
    return GDALDataset::GetGCPCount();
1443
0
}
1444
1445
/************************************************************************/
1446
/*                          GetGCPSpatialRef()                          */
1447
/************************************************************************/
1448
1449
const OGRSpatialReference *GDALPamDataset::GetGCPSpatialRef() const
1450
1451
0
{
1452
0
    if (psPam && psPam->poGCP_SRS != nullptr)
1453
0
        return psPam->poGCP_SRS;
1454
1455
0
    return GDALDataset::GetGCPSpatialRef();
1456
0
}
1457
1458
/************************************************************************/
1459
/*                               GetGCPs()                              */
1460
/************************************************************************/
1461
1462
const GDAL_GCP *GDALPamDataset::GetGCPs()
1463
1464
0
{
1465
0
    if (psPam && !psPam->asGCPs.empty())
1466
0
        return gdal::GCP::c_ptr(psPam->asGCPs);
1467
1468
0
    return GDALDataset::GetGCPs();
1469
0
}
1470
1471
/************************************************************************/
1472
/*                              SetGCPs()                               */
1473
/************************************************************************/
1474
1475
CPLErr GDALPamDataset::SetGCPs(int nGCPCount, const GDAL_GCP *pasGCPList,
1476
                               const OGRSpatialReference *poGCP_SRS)
1477
1478
0
{
1479
0
    PamInitialize();
1480
1481
0
    if (psPam)
1482
0
    {
1483
0
        if (psPam->poGCP_SRS)
1484
0
            psPam->poGCP_SRS->Release();
1485
0
        psPam->poGCP_SRS = poGCP_SRS ? poGCP_SRS->Clone() : nullptr;
1486
0
        psPam->asGCPs = gdal::GCP::fromC(pasGCPList, nGCPCount);
1487
0
        MarkPamDirty();
1488
1489
0
        return CE_None;
1490
0
    }
1491
1492
0
    return GDALDataset::SetGCPs(nGCPCount, pasGCPList, poGCP_SRS);
1493
0
}
1494
1495
/************************************************************************/
1496
/*                            SetMetadata()                             */
1497
/************************************************************************/
1498
1499
CPLErr GDALPamDataset::SetMetadata(char **papszMetadata, const char *pszDomain)
1500
1501
0
{
1502
0
    PamInitialize();
1503
1504
0
    if (psPam)
1505
0
    {
1506
0
        psPam->bHasMetadata = TRUE;
1507
0
        MarkPamDirty();
1508
0
    }
1509
1510
0
    return GDALDataset::SetMetadata(papszMetadata, pszDomain);
1511
0
}
1512
1513
/************************************************************************/
1514
/*                          SetMetadataItem()                           */
1515
/************************************************************************/
1516
1517
CPLErr GDALPamDataset::SetMetadataItem(const char *pszName,
1518
                                       const char *pszValue,
1519
                                       const char *pszDomain)
1520
1521
0
{
1522
0
    PamInitialize();
1523
1524
0
    if (psPam)
1525
0
    {
1526
0
        psPam->bHasMetadata = TRUE;
1527
0
        MarkPamDirty();
1528
0
    }
1529
1530
0
    return GDALDataset::SetMetadataItem(pszName, pszValue, pszDomain);
1531
0
}
1532
1533
/************************************************************************/
1534
/*                          GetMetadataItem()                           */
1535
/************************************************************************/
1536
1537
const char *GDALPamDataset::GetMetadataItem(const char *pszName,
1538
                                            const char *pszDomain)
1539
1540
0
{
1541
    /* -------------------------------------------------------------------- */
1542
    /*      A request against the ProxyOverviewRequest is a special         */
1543
    /*      mechanism to request an overview filename be allocated in       */
1544
    /*      the proxy pool location.  The allocated name is saved as        */
1545
    /*      metadata as well as being returned.                             */
1546
    /* -------------------------------------------------------------------- */
1547
0
    if (pszDomain != nullptr && EQUAL(pszDomain, "ProxyOverviewRequest"))
1548
0
    {
1549
0
        CPLString osPrelimOvr = GetDescription();
1550
0
        osPrelimOvr += ":::OVR";
1551
1552
0
        const char *pszProxyOvrFilename = PamAllocateProxy(osPrelimOvr);
1553
0
        if (pszProxyOvrFilename == nullptr)
1554
0
            return nullptr;
1555
1556
0
        SetMetadataItem("OVERVIEW_FILE", pszProxyOvrFilename, "OVERVIEWS");
1557
1558
0
        return pszProxyOvrFilename;
1559
0
    }
1560
1561
    /* -------------------------------------------------------------------- */
1562
    /*      If the OVERVIEW_FILE metadata is requested, we intercept the    */
1563
    /*      request in order to replace ":::BASE:::" with the path to       */
1564
    /*      the physical file - if available.  This is primarily for the    */
1565
    /*      purpose of managing subdataset overview filenames as being      */
1566
    /*      relative to the physical file the subdataset comes              */
1567
    /*      from. (#3287).                                                  */
1568
    /* -------------------------------------------------------------------- */
1569
0
    else if (pszDomain != nullptr && EQUAL(pszDomain, "OVERVIEWS") &&
1570
0
             EQUAL(pszName, "OVERVIEW_FILE"))
1571
0
    {
1572
0
        if (m_osOverviewFile.empty())
1573
0
        {
1574
0
            const char *pszOverviewFile =
1575
0
                GDALDataset::GetMetadataItem(pszName, pszDomain);
1576
1577
0
            if (pszOverviewFile == nullptr ||
1578
0
                !STARTS_WITH_CI(pszOverviewFile, ":::BASE:::"))
1579
0
                return pszOverviewFile;
1580
1581
0
            std::string osPath;
1582
1583
0
            if (strlen(GetPhysicalFilename()) > 0)
1584
0
                osPath = CPLGetPathSafe(GetPhysicalFilename());
1585
0
            else
1586
0
                osPath = CPLGetPathSafe(GetDescription());
1587
1588
0
            m_osOverviewFile = CPLFormFilenameSafe(
1589
0
                osPath.c_str(), pszOverviewFile + 10, nullptr);
1590
0
        }
1591
0
        return m_osOverviewFile.c_str();
1592
0
    }
1593
1594
    /* -------------------------------------------------------------------- */
1595
    /*      Everything else is a pass through.                              */
1596
    /* -------------------------------------------------------------------- */
1597
1598
0
    return GDALDataset::GetMetadataItem(pszName, pszDomain);
1599
0
}
1600
1601
/************************************************************************/
1602
/*                            GetMetadata()                             */
1603
/************************************************************************/
1604
1605
char **GDALPamDataset::GetMetadata(const char *pszDomain)
1606
1607
0
{
1608
    // if( pszDomain == nullptr || !EQUAL(pszDomain,"ProxyOverviewRequest") )
1609
0
    return GDALDataset::GetMetadata(pszDomain);
1610
0
}
1611
1612
/************************************************************************/
1613
/*                             TryLoadAux()                             */
1614
/************************************************************************/
1615
1616
//! @cond Doxygen_Suppress
1617
CPLErr GDALPamDataset::TryLoadAux(CSLConstList papszSiblingFiles)
1618
1619
0
{
1620
    /* -------------------------------------------------------------------- */
1621
    /*      Initialize PAM.                                                 */
1622
    /* -------------------------------------------------------------------- */
1623
0
    PamInitialize();
1624
1625
0
    if (psPam == nullptr || (nPamFlags & GPF_DISABLED) != 0)
1626
0
        return CE_None;
1627
1628
    /* -------------------------------------------------------------------- */
1629
    /*      What is the name of the physical file we are referencing?       */
1630
    /*      We allow an override via the psPam->pszPhysicalFile item.       */
1631
    /* -------------------------------------------------------------------- */
1632
0
    const char *pszPhysicalFile = psPam->osPhysicalFilename;
1633
1634
0
    if (strlen(pszPhysicalFile) == 0 && GetDescription() != nullptr)
1635
0
        pszPhysicalFile = GetDescription();
1636
1637
0
    if (strlen(pszPhysicalFile) == 0)
1638
0
        return CE_None;
1639
1640
0
    if (papszSiblingFiles && GDALCanReliablyUseSiblingFileList(pszPhysicalFile))
1641
0
    {
1642
0
        CPLString osAuxFilename = CPLResetExtensionSafe(pszPhysicalFile, "aux");
1643
0
        int iSibling =
1644
0
            CSLFindString(papszSiblingFiles, CPLGetFilename(osAuxFilename));
1645
0
        if (iSibling < 0)
1646
0
        {
1647
0
            osAuxFilename = pszPhysicalFile;
1648
0
            osAuxFilename += ".aux";
1649
0
            iSibling =
1650
0
                CSLFindString(papszSiblingFiles, CPLGetFilename(osAuxFilename));
1651
0
            if (iSibling < 0)
1652
0
                return CE_None;
1653
0
        }
1654
0
    }
1655
1656
    /* -------------------------------------------------------------------- */
1657
    /*      Try to open .aux file.                                          */
1658
    /* -------------------------------------------------------------------- */
1659
0
    GDALDataset *poAuxDS =
1660
0
        GDALFindAssociatedAuxFile(pszPhysicalFile, GA_ReadOnly, this);
1661
1662
0
    if (poAuxDS == nullptr)
1663
0
        return CE_None;
1664
1665
0
    psPam->osAuxFilename = poAuxDS->GetDescription();
1666
1667
    /* -------------------------------------------------------------------- */
1668
    /*      Do we have an SRS on the aux file?                              */
1669
    /* -------------------------------------------------------------------- */
1670
0
    if (strlen(poAuxDS->GetProjectionRef()) > 0)
1671
0
        GDALPamDataset::SetProjection(poAuxDS->GetProjectionRef());
1672
1673
    /* -------------------------------------------------------------------- */
1674
    /*      Geotransform.                                                   */
1675
    /* -------------------------------------------------------------------- */
1676
0
    if (poAuxDS->GetGeoTransform(psPam->gt) == CE_None)
1677
0
        psPam->bHaveGeoTransform = TRUE;
1678
1679
    /* -------------------------------------------------------------------- */
1680
    /*      GCPs                                                            */
1681
    /* -------------------------------------------------------------------- */
1682
0
    if (poAuxDS->GetGCPCount() > 0)
1683
0
    {
1684
0
        psPam->asGCPs =
1685
0
            gdal::GCP::fromC(poAuxDS->GetGCPs(), poAuxDS->GetGCPCount());
1686
0
    }
1687
1688
    /* -------------------------------------------------------------------- */
1689
    /*      Apply metadata. We likely ought to be merging this in rather    */
1690
    /*      than overwriting everything that was there.                     */
1691
    /* -------------------------------------------------------------------- */
1692
0
    char **papszMD = poAuxDS->GetMetadata();
1693
0
    if (CSLCount(papszMD) > 0)
1694
0
    {
1695
0
        char **papszMerged = CSLMerge(CSLDuplicate(GetMetadata()), papszMD);
1696
0
        GDALPamDataset::SetMetadata(papszMerged);
1697
0
        CSLDestroy(papszMerged);
1698
0
    }
1699
1700
0
    papszMD = poAuxDS->GetMetadata("XFORMS");
1701
0
    if (CSLCount(papszMD) > 0)
1702
0
    {
1703
0
        char **papszMerged =
1704
0
            CSLMerge(CSLDuplicate(GetMetadata("XFORMS")), papszMD);
1705
0
        GDALPamDataset::SetMetadata(papszMerged, "XFORMS");
1706
0
        CSLDestroy(papszMerged);
1707
0
    }
1708
1709
    /* ==================================================================== */
1710
    /*      Process bands.                                                  */
1711
    /* ==================================================================== */
1712
0
    for (int iBand = 0; iBand < poAuxDS->GetRasterCount(); iBand++)
1713
0
    {
1714
0
        if (iBand >= GetRasterCount())
1715
0
            break;
1716
1717
0
        GDALRasterBand *const poAuxBand = poAuxDS->GetRasterBand(iBand + 1);
1718
0
        GDALRasterBand *const poBand = GetRasterBand(iBand + 1);
1719
1720
0
        papszMD = poAuxBand->GetMetadata();
1721
0
        if (CSLCount(papszMD) > 0)
1722
0
        {
1723
0
            char **papszMerged =
1724
0
                CSLMerge(CSLDuplicate(poBand->GetMetadata()), papszMD);
1725
0
            poBand->SetMetadata(papszMerged);
1726
0
            CSLDestroy(papszMerged);
1727
0
        }
1728
1729
0
        if (strlen(poAuxBand->GetDescription()) > 0)
1730
0
            poBand->SetDescription(poAuxBand->GetDescription());
1731
1732
0
        if (poAuxBand->GetCategoryNames() != nullptr)
1733
0
            poBand->SetCategoryNames(poAuxBand->GetCategoryNames());
1734
1735
0
        if (poAuxBand->GetColorTable() != nullptr &&
1736
0
            poBand->GetColorTable() == nullptr)
1737
0
            poBand->SetColorTable(poAuxBand->GetColorTable());
1738
1739
        // histograms?
1740
0
        double dfMin = 0.0;
1741
0
        double dfMax = 0.0;
1742
0
        int nBuckets = 0;
1743
0
        GUIntBig *panHistogram = nullptr;
1744
1745
0
        if (poAuxBand->GetDefaultHistogram(&dfMin, &dfMax, &nBuckets,
1746
0
                                           &panHistogram, FALSE, nullptr,
1747
0
                                           nullptr) == CE_None)
1748
0
        {
1749
0
            poBand->SetDefaultHistogram(dfMin, dfMax, nBuckets, panHistogram);
1750
0
            CPLFree(panHistogram);
1751
0
        }
1752
1753
        // RAT
1754
0
        if (poAuxBand->GetDefaultRAT() != nullptr)
1755
0
            poBand->SetDefaultRAT(poAuxBand->GetDefaultRAT());
1756
1757
        // NoData
1758
0
        int bSuccess = FALSE;
1759
0
        const double dfNoDataValue = poAuxBand->GetNoDataValue(&bSuccess);
1760
0
        if (bSuccess)
1761
0
            poBand->SetNoDataValue(dfNoDataValue);
1762
0
    }
1763
1764
0
    GDALClose(poAuxDS);
1765
1766
    /* -------------------------------------------------------------------- */
1767
    /*      Mark PAM info as clean.                                         */
1768
    /* -------------------------------------------------------------------- */
1769
0
    nPamFlags &= ~GPF_DIRTY;
1770
1771
0
    return CE_Failure;
1772
0
}
1773
1774
//! @endcond
1775
1776
/************************************************************************/
1777
/*                          ClearStatistics()                           */
1778
/************************************************************************/
1779
1780
void GDALPamDataset::ClearStatistics()
1781
0
{
1782
0
    PamInitialize();
1783
0
    if (!psPam)
1784
0
        return;
1785
0
    for (int i = 1; i <= nBands; ++i)
1786
0
    {
1787
0
        bool bChanged = false;
1788
0
        GDALRasterBand *poBand = GetRasterBand(i);
1789
0
        CPLStringList aosNewMD;
1790
0
        for (const char *pszStr :
1791
0
             cpl::Iterate(static_cast<CSLConstList>(poBand->GetMetadata())))
1792
0
        {
1793
0
            if (STARTS_WITH_CI(pszStr, "STATISTICS_"))
1794
0
            {
1795
0
                MarkPamDirty();
1796
0
                bChanged = true;
1797
0
            }
1798
0
            else
1799
0
            {
1800
0
                aosNewMD.AddString(pszStr);
1801
0
            }
1802
0
        }
1803
0
        if (bChanged)
1804
0
        {
1805
0
            poBand->SetMetadata(aosNewMD.List());
1806
0
        }
1807
0
    }
1808
1809
0
    GDALDataset::ClearStatistics();
1810
0
}