Coverage Report

Created: 2025-11-16 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/frmts/vrt/vrtderivedrasterband.cpp
Line
Count
Source
1
/******************************************************************************
2
 *
3
 * Project:  Virtual GDAL Datasets
4
 * Purpose:  Implementation of a sourced raster band that derives its raster
5
 *           by applying an algorithm (GDALDerivedPixelFunc) to the sources.
6
 * Author:   Pete Nagy
7
 *
8
 ******************************************************************************
9
 * Copyright (c) 2005 Vexcel Corp.
10
 * Copyright (c) 2008-2011, Even Rouault <even dot rouault at spatialys.com>
11
 *
12
 * SPDX-License-Identifier: MIT
13
 *****************************************************************************/
14
15
#include "cpl_minixml.h"
16
#include "cpl_string.h"
17
#include "gdal_priv.h"
18
#include "vrtdataset.h"
19
#include "cpl_multiproc.h"
20
#include "gdalpython.h"
21
#include "gdalantirecursion.h"
22
23
#include <algorithm>
24
#include <array>
25
#include <map>
26
#include <vector>
27
#include <utility>
28
29
/*! @cond Doxygen_Suppress */
30
31
using namespace GDALPy;
32
33
// #define GDAL_VRT_DISABLE_PYTHON
34
35
#ifndef GDAL_VRT_ENABLE_PYTHON_DEFAULT
36
// Can be YES, NO or TRUSTED_MODULES
37
0
#define GDAL_VRT_ENABLE_PYTHON_DEFAULT "TRUSTED_MODULES"
38
#endif
39
40
/* Flags for getting buffers */
41
0
#define PyBUF_WRITABLE 0x0001
42
0
#define PyBUF_FORMAT 0x0004
43
0
#define PyBUF_ND 0x0008
44
0
#define PyBUF_STRIDES (0x0010 | PyBUF_ND)
45
0
#define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES)
46
0
#define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_WRITABLE | PyBUF_FORMAT)
47
48
/************************************************************************/
49
/*                        GDALCreateNumpyArray()                        */
50
/************************************************************************/
51
52
static PyObject *GDALCreateNumpyArray(PyObject *pCreateArray, void *pBuffer,
53
                                      GDALDataType eType, int nHeight,
54
                                      int nWidth)
55
0
{
56
0
    PyObject *poPyBuffer;
57
0
    const size_t nSize =
58
0
        static_cast<size_t>(nHeight) * nWidth * GDALGetDataTypeSizeBytes(eType);
59
0
    Py_buffer pybuffer;
60
0
    if (PyBuffer_FillInfo(&pybuffer, nullptr, static_cast<char *>(pBuffer),
61
0
                          nSize, 0, PyBUF_FULL) != 0)
62
0
    {
63
0
        return nullptr;
64
0
    }
65
0
    poPyBuffer = PyMemoryView_FromBuffer(&pybuffer);
66
0
    PyObject *pArgsCreateArray = PyTuple_New(4);
67
0
    PyTuple_SetItem(pArgsCreateArray, 0, poPyBuffer);
68
0
    const char *pszDataType = nullptr;
69
0
    switch (eType)
70
0
    {
71
0
        case GDT_Byte:
72
0
            pszDataType = "uint8";
73
0
            break;
74
0
        case GDT_Int8:
75
0
            pszDataType = "int8";
76
0
            break;
77
0
        case GDT_UInt16:
78
0
            pszDataType = "uint16";
79
0
            break;
80
0
        case GDT_Int16:
81
0
            pszDataType = "int16";
82
0
            break;
83
0
        case GDT_UInt32:
84
0
            pszDataType = "uint32";
85
0
            break;
86
0
        case GDT_Int32:
87
0
            pszDataType = "int32";
88
0
            break;
89
0
        case GDT_Int64:
90
0
            pszDataType = "int64";
91
0
            break;
92
0
        case GDT_UInt64:
93
0
            pszDataType = "uint64";
94
0
            break;
95
0
        case GDT_Float16:
96
0
            pszDataType = "float16";
97
0
            break;
98
0
        case GDT_Float32:
99
0
            pszDataType = "float32";
100
0
            break;
101
0
        case GDT_Float64:
102
0
            pszDataType = "float64";
103
0
            break;
104
0
        case GDT_CInt16:
105
0
        case GDT_CInt32:
106
0
            CPLAssert(FALSE);
107
0
            break;
108
0
        case GDT_CFloat16:
109
0
            CPLAssert(FALSE);
110
0
            break;
111
0
        case GDT_CFloat32:
112
0
            pszDataType = "complex64";
113
0
            break;
114
0
        case GDT_CFloat64:
115
0
            pszDataType = "complex128";
116
0
            break;
117
0
        case GDT_Unknown:
118
0
        case GDT_TypeCount:
119
0
            CPLAssert(FALSE);
120
0
            break;
121
0
    }
122
0
    PyTuple_SetItem(
123
0
        pArgsCreateArray, 1,
124
0
        PyBytes_FromStringAndSize(pszDataType, strlen(pszDataType)));
125
0
    PyTuple_SetItem(pArgsCreateArray, 2, PyLong_FromLong(nHeight));
126
0
    PyTuple_SetItem(pArgsCreateArray, 3, PyLong_FromLong(nWidth));
127
0
    PyObject *poNumpyArray =
128
0
        PyObject_Call(pCreateArray, pArgsCreateArray, nullptr);
129
0
    Py_DecRef(pArgsCreateArray);
130
0
    if (PyErr_Occurred())
131
0
        PyErr_Print();
132
0
    return poNumpyArray;
133
0
}
134
135
/************************************************************************/
136
/* ==================================================================== */
137
/*                     VRTDerivedRasterBandPrivateData                  */
138
/* ==================================================================== */
139
/************************************************************************/
140
141
class VRTDerivedRasterBandPrivateData
142
{
143
    VRTDerivedRasterBandPrivateData(const VRTDerivedRasterBandPrivateData &) =
144
        delete;
145
    VRTDerivedRasterBandPrivateData &
146
    operator=(const VRTDerivedRasterBandPrivateData &) = delete;
147
148
  public:
149
    CPLString m_osCode{};
150
    CPLString m_osLanguage = "C";
151
    int m_nBufferRadius = 0;
152
    PyObject *m_poGDALCreateNumpyArray = nullptr;
153
    PyObject *m_poUserFunction = nullptr;
154
    bool m_bPythonInitializationDone = false;
155
    bool m_bPythonInitializationSuccess = false;
156
    bool m_bExclusiveLock = false;
157
    bool m_bFirstTime = true;
158
    std::vector<std::pair<CPLString, CPLString>> m_oFunctionArgs{};
159
    bool m_bSkipNonContributingSourcesSpecified = false;
160
    bool m_bSkipNonContributingSources = false;
161
    GIntBig m_nAllowedRAMUsage = 0;
162
163
    VRTDerivedRasterBandPrivateData()
164
0
        : m_nAllowedRAMUsage(CPLGetUsablePhysicalRAM() / 10 * 4)
165
0
    {
166
        // Use only up to 40% of RAM to acquire source bands and generate the
167
        // output buffer.
168
        // Only for tests now
169
0
        const char *pszMAX_RAM = "VRT_DERIVED_DATASET_ALLOWED_RAM_USAGE";
170
0
        if (const char *pszVal = CPLGetConfigOption(pszMAX_RAM, nullptr))
171
0
        {
172
0
            CPL_IGNORE_RET_VAL(
173
0
                CPLParseMemorySize(pszVal, &m_nAllowedRAMUsage, nullptr));
174
0
        }
175
0
    }
176
177
    ~VRTDerivedRasterBandPrivateData();
178
};
179
180
VRTDerivedRasterBandPrivateData::~VRTDerivedRasterBandPrivateData()
181
0
{
182
0
    if (m_poGDALCreateNumpyArray)
183
0
        Py_DecRef(m_poGDALCreateNumpyArray);
184
0
    if (m_poUserFunction)
185
0
        Py_DecRef(m_poUserFunction);
186
0
}
187
188
/************************************************************************/
189
/* ==================================================================== */
190
/*                          VRTDerivedRasterBand                        */
191
/* ==================================================================== */
192
/************************************************************************/
193
194
/************************************************************************/
195
/*                        VRTDerivedRasterBand()                        */
196
/************************************************************************/
197
198
VRTDerivedRasterBand::VRTDerivedRasterBand(GDALDataset *poDSIn, int nBandIn)
199
0
    : VRTSourcedRasterBand(poDSIn, nBandIn), m_poPrivate(nullptr),
200
0
      eSourceTransferType(GDT_Unknown)
201
0
{
202
0
    m_poPrivate = new VRTDerivedRasterBandPrivateData;
203
0
}
204
205
/************************************************************************/
206
/*                        VRTDerivedRasterBand()                        */
207
/************************************************************************/
208
209
VRTDerivedRasterBand::VRTDerivedRasterBand(GDALDataset *poDSIn, int nBandIn,
210
                                           GDALDataType eType, int nXSize,
211
                                           int nYSize, int nBlockXSizeIn,
212
                                           int nBlockYSizeIn)
213
0
    : VRTSourcedRasterBand(poDSIn, nBandIn, eType, nXSize, nYSize,
214
0
                           nBlockXSizeIn, nBlockYSizeIn),
215
0
      m_poPrivate(nullptr), eSourceTransferType(GDT_Unknown)
216
0
{
217
0
    m_poPrivate = new VRTDerivedRasterBandPrivateData;
218
0
}
219
220
/************************************************************************/
221
/*                       ~VRTDerivedRasterBand()                        */
222
/************************************************************************/
223
224
VRTDerivedRasterBand::~VRTDerivedRasterBand()
225
226
0
{
227
0
    delete m_poPrivate;
228
0
}
229
230
/************************************************************************/
231
/*                               Cleanup()                              */
232
/************************************************************************/
233
234
void VRTDerivedRasterBand::Cleanup()
235
0
{
236
0
}
237
238
/************************************************************************/
239
/*                      GetGlobalMapPixelFunction()                     */
240
/************************************************************************/
241
242
static std::map<std::string,
243
                std::pair<VRTDerivedRasterBand::PixelFunc, std::string>> &
244
GetGlobalMapPixelFunction()
245
0
{
246
0
    static std::map<std::string,
247
0
                    std::pair<VRTDerivedRasterBand::PixelFunc, std::string>>
248
0
        gosMapPixelFunction;
249
0
    return gosMapPixelFunction;
250
0
}
251
252
/************************************************************************/
253
/*                           AddPixelFunction()                         */
254
/************************************************************************/
255
256
/*! @endcond */
257
258
/**
259
 * This adds a pixel function to the global list of available pixel
260
 * functions for derived bands.  Pixel functions must be registered
261
 * in this way before a derived band tries to access data.
262
 *
263
 * Derived bands are stored with only the name of the pixel function
264
 * that it will apply, and if a pixel function matching the name is not
265
 * found the IRasterIO() call will do nothing.
266
 *
267
 * @param pszName Name used to access pixel function
268
 * @param pfnNewFunction Pixel function associated with name.  An
269
 *  existing pixel function registered with the same name will be
270
 *  replaced with the new one.
271
 *
272
 * @return CE_None, invalid (NULL) parameters are currently ignored.
273
 */
274
CPLErr CPL_STDCALL GDALAddDerivedBandPixelFunc(
275
    const char *pszName, GDALDerivedPixelFunc pfnNewFunction)
276
0
{
277
0
    if (pszName == nullptr || pszName[0] == '\0' || pfnNewFunction == nullptr)
278
0
    {
279
0
        return CE_None;
280
0
    }
281
282
0
    GetGlobalMapPixelFunction()[pszName] = {
283
0
        [pfnNewFunction](void **papoSources, int nSources, void *pData,
284
0
                         int nBufXSize, int nBufYSize, GDALDataType eSrcType,
285
0
                         GDALDataType eBufType, int nPixelSpace, int nLineSpace,
286
0
                         CSLConstList papszFunctionArgs)
287
0
        {
288
0
            (void)papszFunctionArgs;
289
0
            return pfnNewFunction(papoSources, nSources, pData, nBufXSize,
290
0
                                  nBufYSize, eSrcType, eBufType, nPixelSpace,
291
0
                                  nLineSpace);
292
0
        },
293
0
        ""};
294
295
0
    return CE_None;
296
0
}
297
298
/**
299
 * This adds a pixel function to the global list of available pixel
300
 * functions for derived bands.  Pixel functions must be registered
301
 * in this way before a derived band tries to access data.
302
 *
303
 * Derived bands are stored with only the name of the pixel function
304
 * that it will apply, and if a pixel function matching the name is not
305
 * found the IRasterIO() call will do nothing.
306
 *
307
 * @param pszName Name used to access pixel function
308
 * @param pfnNewFunction Pixel function associated with name.  An
309
 *  existing pixel function registered with the same name will be
310
 *  replaced with the new one.
311
 * @param pszMetadata Pixel function metadata (not currently implemented)
312
 *
313
 * @return CE_None, invalid (NULL) parameters are currently ignored.
314
 * @since GDAL 3.4
315
 */
316
CPLErr CPL_STDCALL GDALAddDerivedBandPixelFuncWithArgs(
317
    const char *pszName, GDALDerivedPixelFuncWithArgs pfnNewFunction,
318
    const char *pszMetadata)
319
0
{
320
0
    if (!pszName || pszName[0] == '\0' || !pfnNewFunction)
321
0
    {
322
0
        return CE_None;
323
0
    }
324
325
0
    GetGlobalMapPixelFunction()[pszName] = {pfnNewFunction,
326
0
                                            pszMetadata ? pszMetadata : ""};
327
328
0
    return CE_None;
329
0
}
330
331
/*! @cond Doxygen_Suppress */
332
333
/**
334
 * This adds a pixel function to the global list of available pixel
335
 * functions for derived bands.
336
 *
337
 * This is the same as the C function GDALAddDerivedBandPixelFunc()
338
 *
339
 * @param pszFuncNameIn Name used to access pixel function
340
 * @param pfnNewFunction Pixel function associated with name.  An
341
 *  existing pixel function registered with the same name will be
342
 *  replaced with the new one.
343
 *
344
 * @return CE_None, invalid (NULL) parameters are currently ignored.
345
 */
346
CPLErr
347
VRTDerivedRasterBand::AddPixelFunction(const char *pszFuncNameIn,
348
                                       GDALDerivedPixelFunc pfnNewFunction)
349
0
{
350
0
    return GDALAddDerivedBandPixelFunc(pszFuncNameIn, pfnNewFunction);
351
0
}
352
353
CPLErr VRTDerivedRasterBand::AddPixelFunction(
354
    const char *pszFuncNameIn, GDALDerivedPixelFuncWithArgs pfnNewFunction,
355
    const char *pszMetadata)
356
0
{
357
0
    return GDALAddDerivedBandPixelFuncWithArgs(pszFuncNameIn, pfnNewFunction,
358
0
                                               pszMetadata);
359
0
}
360
361
/************************************************************************/
362
/*                           GetPixelFunction()                         */
363
/************************************************************************/
364
365
/**
366
 * Get a pixel function previously registered using the global
367
 * AddPixelFunction.
368
 *
369
 * @param pszFuncNameIn The name associated with the pixel function.
370
 *
371
 * @return A pointer to a std::pair whose first element is the pixel
372
 *         function pointer and second element is the pixel function
373
 *         metadata string. If no pixel function has been registered
374
 *         for pszFuncNameIn, nullptr will be returned.
375
 */
376
/* static */
377
const std::pair<VRTDerivedRasterBand::PixelFunc, std::string> *
378
VRTDerivedRasterBand::GetPixelFunction(const char *pszFuncNameIn)
379
0
{
380
0
    if (pszFuncNameIn == nullptr || pszFuncNameIn[0] == '\0')
381
0
    {
382
0
        return nullptr;
383
0
    }
384
385
0
    const auto &oMapPixelFunction = GetGlobalMapPixelFunction();
386
0
    const auto oIter = oMapPixelFunction.find(pszFuncNameIn);
387
388
0
    if (oIter == oMapPixelFunction.end())
389
0
        return nullptr;
390
391
0
    return &(oIter->second);
392
0
}
393
394
/************************************************************************/
395
/*                        GetPixelFunctionNames()                       */
396
/************************************************************************/
397
398
/**
399
 * Return the list of available pixel function names.
400
 */
401
/* static */
402
std::vector<std::string> VRTDerivedRasterBand::GetPixelFunctionNames()
403
0
{
404
0
    std::vector<std::string> res;
405
0
    for (const auto &iter : GetGlobalMapPixelFunction())
406
0
    {
407
0
        res.push_back(iter.first);
408
0
    }
409
0
    return res;
410
0
}
411
412
/************************************************************************/
413
/*                         SetPixelFunctionName()                       */
414
/************************************************************************/
415
416
/**
417
 * Set the pixel function name to be applied to this derived band.  The
418
 * name should match a pixel function registered using AddPixelFunction.
419
 *
420
 * @param pszFuncNameIn Name of pixel function to be applied to this derived
421
 * band.
422
 */
423
void VRTDerivedRasterBand::SetPixelFunctionName(const char *pszFuncNameIn)
424
0
{
425
0
    osFuncName = (pszFuncNameIn == nullptr) ? "" : pszFuncNameIn;
426
0
}
427
428
/************************************************************************/
429
/*                     AddPixelFunctionArgument()                       */
430
/************************************************************************/
431
432
/**
433
 *  Set a pixel function argument to a specified value.
434
 * @param pszArg the argument name
435
 * @param pszValue the argument value
436
 *
437
 * @since 3.12
438
 */
439
void VRTDerivedRasterBand::AddPixelFunctionArgument(const char *pszArg,
440
                                                    const char *pszValue)
441
0
{
442
0
    m_poPrivate->m_oFunctionArgs.emplace_back(pszArg, pszValue);
443
0
}
444
445
/************************************************************************/
446
/*                         SetPixelFunctionLanguage()                   */
447
/************************************************************************/
448
449
/**
450
 * Set the language of the pixel function.
451
 *
452
 * @param pszLanguage Language of the pixel function (only "C" and "Python"
453
 * are supported currently)
454
 * @since GDAL 2.3
455
 */
456
void VRTDerivedRasterBand::SetPixelFunctionLanguage(const char *pszLanguage)
457
0
{
458
0
    m_poPrivate->m_osLanguage = pszLanguage;
459
0
}
460
461
/************************************************************************/
462
/*                 SetSkipNonContributingSources()                      */
463
/************************************************************************/
464
465
/** Whether sources that do not intersect the VRTRasterBand RasterIO() requested
466
 * region should be omitted. By default, data for all sources, including ones
467
 * that do not intersect it, are passed to the pixel function. By setting this
468
 * parameter to true, only sources that intersect the requested region will be
469
 * passed.
470
 *
471
 * @param bSkip whether to skip non-contributing sources
472
 *
473
 * @since 3.12
474
 */
475
void VRTDerivedRasterBand::SetSkipNonContributingSources(bool bSkip)
476
0
{
477
0
    m_poPrivate->m_bSkipNonContributingSources = bSkip;
478
0
    m_poPrivate->m_bSkipNonContributingSourcesSpecified = true;
479
0
}
480
481
/************************************************************************/
482
/*                         SetSourceTransferType()                      */
483
/************************************************************************/
484
485
/**
486
 * Set the transfer type to be used to obtain pixel information from
487
 * all of the sources.  If unset, the transfer type used will be the
488
 * same as the derived band data type.  This makes it possible, for
489
 * example, to pass CFloat32 source pixels to the pixel function, even
490
 * if the pixel function generates a raster for a derived band that
491
 * is of type Byte.
492
 *
493
 * @param eDataTypeIn Data type to use to obtain pixel information from
494
 * the sources to be passed to the derived band pixel function.
495
 */
496
void VRTDerivedRasterBand::SetSourceTransferType(GDALDataType eDataTypeIn)
497
0
{
498
0
    eSourceTransferType = eDataTypeIn;
499
0
}
500
501
/************************************************************************/
502
/*                           InitializePython()                         */
503
/************************************************************************/
504
505
bool VRTDerivedRasterBand::InitializePython()
506
0
{
507
0
    if (m_poPrivate->m_bPythonInitializationDone)
508
0
        return m_poPrivate->m_bPythonInitializationSuccess;
509
510
0
    m_poPrivate->m_bPythonInitializationDone = true;
511
0
    m_poPrivate->m_bPythonInitializationSuccess = false;
512
513
0
    const size_t nIdxDot = osFuncName.rfind(".");
514
0
    CPLString osPythonModule;
515
0
    CPLString osPythonFunction;
516
0
    if (nIdxDot != std::string::npos)
517
0
    {
518
0
        osPythonModule = osFuncName.substr(0, nIdxDot);
519
0
        osPythonFunction = osFuncName.substr(nIdxDot + 1);
520
0
    }
521
0
    else
522
0
    {
523
0
        osPythonFunction = osFuncName;
524
0
    }
525
526
0
#ifndef GDAL_VRT_DISABLE_PYTHON
527
0
    const char *pszPythonEnabled =
528
0
        CPLGetConfigOption("GDAL_VRT_ENABLE_PYTHON", nullptr);
529
#else
530
    const char *pszPythonEnabled = "NO";
531
#endif
532
0
    const CPLString osPythonEnabled(
533
0
        pszPythonEnabled ? pszPythonEnabled : GDAL_VRT_ENABLE_PYTHON_DEFAULT);
534
535
0
    if (EQUAL(osPythonEnabled, "TRUSTED_MODULES"))
536
0
    {
537
0
        bool bIsTrustedModule = false;
538
0
        const CPLString osVRTTrustedModules(
539
0
            CPLGetConfigOption("GDAL_VRT_PYTHON_TRUSTED_MODULES", ""));
540
0
        if (!osPythonModule.empty())
541
0
        {
542
0
            char **papszTrustedModules =
543
0
                CSLTokenizeString2(osVRTTrustedModules, ",", 0);
544
0
            for (char **papszIter = papszTrustedModules;
545
0
                 !bIsTrustedModule && papszIter && *papszIter; ++papszIter)
546
0
            {
547
0
                const char *pszIterModule = *papszIter;
548
0
                size_t nIterModuleLen = strlen(pszIterModule);
549
0
                if (nIterModuleLen > 2 &&
550
0
                    strncmp(pszIterModule + nIterModuleLen - 2, ".*", 2) == 0)
551
0
                {
552
0
                    bIsTrustedModule =
553
0
                        (strncmp(osPythonModule, pszIterModule,
554
0
                                 nIterModuleLen - 2) == 0) &&
555
0
                        (osPythonModule.size() == nIterModuleLen - 2 ||
556
0
                         (osPythonModule.size() >= nIterModuleLen &&
557
0
                          osPythonModule[nIterModuleLen - 1] == '.'));
558
0
                }
559
0
                else if (nIterModuleLen >= 1 &&
560
0
                         pszIterModule[nIterModuleLen - 1] == '*')
561
0
                {
562
0
                    bIsTrustedModule = (strncmp(osPythonModule, pszIterModule,
563
0
                                                nIterModuleLen - 1) == 0);
564
0
                }
565
0
                else
566
0
                {
567
0
                    bIsTrustedModule =
568
0
                        (strcmp(osPythonModule, pszIterModule) == 0);
569
0
                }
570
0
            }
571
0
            CSLDestroy(papszTrustedModules);
572
0
        }
573
574
0
        if (!bIsTrustedModule)
575
0
        {
576
0
            if (osPythonModule.empty())
577
0
            {
578
0
                CPLError(
579
0
                    CE_Failure, CPLE_AppDefined,
580
0
                    "Python code needs to be executed, but it uses inline code "
581
0
                    "in the VRT whereas the current policy is to trust only "
582
0
                    "code from external trusted modules (defined in the "
583
0
                    "GDAL_VRT_PYTHON_TRUSTED_MODULES configuration option). "
584
0
                    "If you trust the code in %s, you can set the "
585
0
                    "GDAL_VRT_ENABLE_PYTHON configuration option to YES.",
586
0
                    GetDataset() ? GetDataset()->GetDescription()
587
0
                                 : "(unknown VRT)");
588
0
            }
589
0
            else if (osVRTTrustedModules.empty())
590
0
            {
591
0
                CPLError(
592
0
                    CE_Failure, CPLE_AppDefined,
593
0
                    "Python code needs to be executed, but it uses code "
594
0
                    "from module '%s', whereas the current policy is to "
595
0
                    "trust only code from modules defined in the "
596
0
                    "GDAL_VRT_PYTHON_TRUSTED_MODULES configuration option, "
597
0
                    "which is currently unset. "
598
0
                    "If you trust the code in '%s', you can add module '%s' "
599
0
                    "to GDAL_VRT_PYTHON_TRUSTED_MODULES (or set the "
600
0
                    "GDAL_VRT_ENABLE_PYTHON configuration option to YES).",
601
0
                    osPythonModule.c_str(),
602
0
                    GetDataset() ? GetDataset()->GetDescription()
603
0
                                 : "(unknown VRT)",
604
0
                    osPythonModule.c_str());
605
0
            }
606
0
            else
607
0
            {
608
0
                CPLError(
609
0
                    CE_Failure, CPLE_AppDefined,
610
0
                    "Python code needs to be executed, but it uses code "
611
0
                    "from module '%s', whereas the current policy is to "
612
0
                    "trust only code from modules '%s' (defined in the "
613
0
                    "GDAL_VRT_PYTHON_TRUSTED_MODULES configuration option). "
614
0
                    "If you trust the code in '%s', you can add module '%s' "
615
0
                    "to GDAL_VRT_PYTHON_TRUSTED_MODULES (or set the "
616
0
                    "GDAL_VRT_ENABLE_PYTHON configuration option to YES).",
617
0
                    osPythonModule.c_str(), osVRTTrustedModules.c_str(),
618
0
                    GetDataset() ? GetDataset()->GetDescription()
619
0
                                 : "(unknown VRT)",
620
0
                    osPythonModule.c_str());
621
0
            }
622
0
            return false;
623
0
        }
624
0
    }
625
626
#ifdef disabled_because_this_is_probably_broken_by_design
627
    // See https://lwn.net/Articles/574215/
628
    // and http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
629
    else if (EQUAL(osPythonEnabled, "IF_SAFE"))
630
    {
631
        bool bSafe = true;
632
        // If the function comes from another module, then we don't know
633
        if (!osPythonModule.empty())
634
        {
635
            CPLDebug("VRT", "Python function is from another module");
636
            bSafe = false;
637
        }
638
639
        CPLString osCode(m_poPrivate->m_osCode);
640
641
        // Reject all imports except a few trusted modules
642
        const char *const apszTrustedImports[] = {
643
            "import math",
644
            "from math import",
645
            "import numpy",  // caution: numpy has lots of I/O functions !
646
            "from numpy import",
647
            // TODO: not sure if importing arbitrary stuff from numba is OK
648
            // so let's just restrict to jit.
649
            "from numba import jit",
650
651
            // Not imports but still whitelisted, whereas other __ is banned
652
            "__init__",
653
            "__call__",
654
        };
655
        for (size_t i = 0; i < CPL_ARRAYSIZE(apszTrustedImports); ++i)
656
        {
657
            osCode.replaceAll(CPLString(apszTrustedImports[i]), "");
658
        }
659
660
        // Some dangerous built-in functions or numpy functions
661
        const char *const apszUntrusted[] = {
662
            "import",  // and __import__
663
            "eval",       "compile", "open",
664
            "load",        // reload, numpy.load
665
            "file",        // and exec_file, numpy.fromfile, numpy.tofile
666
            "input",       // and raw_input
667
            "save",        // numpy.save
668
            "memmap",      // numpy.memmap
669
            "DataSource",  // numpy.DataSource
670
            "genfromtxt",  // numpy.genfromtxt
671
            "getattr",
672
            "ctypeslib",  // numpy.ctypeslib
673
            "testing",    // numpy.testing
674
            "dump",       // numpy.ndarray.dump
675
            "fromregex",  // numpy.fromregex
676
            "__"};
677
        for (size_t i = 0; i < CPL_ARRAYSIZE(apszUntrusted); ++i)
678
        {
679
            if (osCode.find(apszUntrusted[i]) != std::string::npos)
680
            {
681
                CPLDebug("VRT", "Found '%s' word in Python code",
682
                         apszUntrusted[i]);
683
                bSafe = false;
684
            }
685
        }
686
687
        if (!bSafe)
688
        {
689
            CPLError(CE_Failure, CPLE_AppDefined,
690
                     "Python code needs to be executed, but we cannot verify "
691
                     "if it is safe, so this is disabled by default. "
692
                     "If you trust the code in %s, you can set the "
693
                     "GDAL_VRT_ENABLE_PYTHON configuration option to YES.",
694
                     GetDataset() ? GetDataset()->GetDescription()
695
                                  : "(unknown VRT)");
696
            return false;
697
        }
698
    }
699
#endif  // disabled_because_this_is_probably_broken_by_design
700
701
0
    else if (!EQUAL(osPythonEnabled, "YES") && !EQUAL(osPythonEnabled, "ON") &&
702
0
             !EQUAL(osPythonEnabled, "TRUE"))
703
0
    {
704
0
        if (pszPythonEnabled == nullptr)
705
0
        {
706
            // Note: this is dead code with our current default policy
707
            // GDAL_VRT_ENABLE_PYTHON == "TRUSTED_MODULES"
708
0
            CPLError(CE_Failure, CPLE_AppDefined,
709
0
                     "Python code needs to be executed, but this is "
710
0
                     "disabled by default. If you trust the code in %s, "
711
0
                     "you can set the GDAL_VRT_ENABLE_PYTHON configuration "
712
0
                     "option to YES.",
713
0
                     GetDataset() ? GetDataset()->GetDescription()
714
0
                                  : "(unknown VRT)");
715
0
        }
716
0
        else
717
0
        {
718
0
            CPLError(
719
0
                CE_Failure, CPLE_AppDefined,
720
0
                "Python code in %s needs to be executed, but this has been "
721
0
                "explicitly disabled.",
722
0
                GetDataset() ? GetDataset()->GetDescription()
723
0
                             : "(unknown VRT)");
724
0
        }
725
0
        return false;
726
0
    }
727
728
0
    if (!GDALPythonInitialize())
729
0
        return false;
730
731
    // Whether we should just use our own global mutex, in addition to Python
732
    // GIL locking.
733
0
    m_poPrivate->m_bExclusiveLock =
734
0
        CPLTestBool(CPLGetConfigOption("GDAL_VRT_PYTHON_EXCLUSIVE_LOCK", "NO"));
735
736
    // numba jit'ification doesn't seem to be thread-safe, so force use of
737
    // lock now and at first execution of function. Later executions seem to
738
    // be thread-safe. This problem doesn't seem to appear for code in
739
    // regular files
740
0
    const bool bUseExclusiveLock =
741
0
        m_poPrivate->m_bExclusiveLock ||
742
0
        m_poPrivate->m_osCode.find("@jit") != std::string::npos;
743
0
    GIL_Holder oHolder(bUseExclusiveLock);
744
745
    // As we don't want to depend on numpy C API/ABI, we use a trick to build
746
    // a numpy array object. We define a Python function to which we pass a
747
    // Python buffer object.
748
749
    // We need to build a unique module name, otherwise this will crash in
750
    // multithreaded use cases.
751
0
    CPLString osModuleName(CPLSPrintf("gdal_vrt_module_%p", this));
752
0
    PyObject *poCompiledString = Py_CompileString(
753
0
        ("import numpy\n"
754
0
         "def GDALCreateNumpyArray(buffer, dtype, height, width):\n"
755
0
         "    return numpy.frombuffer(buffer, str(dtype.decode('ascii')))."
756
0
         "reshape([height, width])\n"
757
0
         "\n" +
758
0
         m_poPrivate->m_osCode)
759
0
            .c_str(),
760
0
        osModuleName, Py_file_input);
761
0
    if (poCompiledString == nullptr || PyErr_Occurred())
762
0
    {
763
0
        CPLError(CE_Failure, CPLE_AppDefined, "Couldn't compile code:\n%s",
764
0
                 GetPyExceptionString().c_str());
765
0
        return false;
766
0
    }
767
0
    PyObject *poModule =
768
0
        PyImport_ExecCodeModule(osModuleName, poCompiledString);
769
0
    Py_DecRef(poCompiledString);
770
771
0
    if (poModule == nullptr || PyErr_Occurred())
772
0
    {
773
0
        CPLError(CE_Failure, CPLE_AppDefined, "%s",
774
0
                 GetPyExceptionString().c_str());
775
0
        return false;
776
0
    }
777
778
    // Fetch user computation function
779
0
    if (!osPythonModule.empty())
780
0
    {
781
0
        PyObject *poUserModule = PyImport_ImportModule(osPythonModule);
782
0
        if (poUserModule == nullptr || PyErr_Occurred())
783
0
        {
784
0
            CPLString osException = GetPyExceptionString();
785
0
            if (!osException.empty() && osException.back() == '\n')
786
0
            {
787
0
                osException.pop_back();
788
0
            }
789
0
            if (osException.find("ModuleNotFoundError") == 0)
790
0
            {
791
0
                osException += ". You may need to define PYTHONPATH";
792
0
            }
793
0
            CPLError(CE_Failure, CPLE_AppDefined, "%s", osException.c_str());
794
0
            Py_DecRef(poModule);
795
0
            return false;
796
0
        }
797
0
        m_poPrivate->m_poUserFunction =
798
0
            PyObject_GetAttrString(poUserModule, osPythonFunction);
799
0
        Py_DecRef(poUserModule);
800
0
    }
801
0
    else
802
0
    {
803
0
        m_poPrivate->m_poUserFunction =
804
0
            PyObject_GetAttrString(poModule, osPythonFunction);
805
0
    }
806
0
    if (m_poPrivate->m_poUserFunction == nullptr || PyErr_Occurred())
807
0
    {
808
0
        CPLError(CE_Failure, CPLE_AppDefined, "%s",
809
0
                 GetPyExceptionString().c_str());
810
0
        Py_DecRef(poModule);
811
0
        return false;
812
0
    }
813
0
    if (!PyCallable_Check(m_poPrivate->m_poUserFunction))
814
0
    {
815
0
        CPLError(CE_Failure, CPLE_AppDefined, "Object '%s' is not callable",
816
0
                 osPythonFunction.c_str());
817
0
        Py_DecRef(poModule);
818
0
        return false;
819
0
    }
820
821
    // Fetch our GDALCreateNumpyArray python function
822
0
    m_poPrivate->m_poGDALCreateNumpyArray =
823
0
        PyObject_GetAttrString(poModule, "GDALCreateNumpyArray");
824
0
    if (m_poPrivate->m_poGDALCreateNumpyArray == nullptr || PyErr_Occurred())
825
0
    {
826
        // Shouldn't happen normally...
827
0
        CPLError(CE_Failure, CPLE_AppDefined, "%s",
828
0
                 GetPyExceptionString().c_str());
829
0
        Py_DecRef(poModule);
830
0
        return false;
831
0
    }
832
0
    Py_DecRef(poModule);
833
834
0
    m_poPrivate->m_bPythonInitializationSuccess = true;
835
0
    return true;
836
0
}
837
838
CPLErr VRTDerivedRasterBand::GetPixelFunctionArguments(
839
    const CPLString &osMetadata,
840
    const std::vector<int> &anMapBufferIdxToSourceIdx, int nXOff, int nYOff,
841
    std::vector<std::pair<CPLString, CPLString>> &oAdditionalArgs)
842
0
{
843
844
0
    auto poArgs = CPLXMLTreeCloser(CPLParseXMLString(osMetadata));
845
0
    if (poArgs != nullptr && poArgs->eType == CXT_Element &&
846
0
        !strcmp(poArgs->pszValue, "PixelFunctionArgumentsList"))
847
0
    {
848
0
        for (CPLXMLNode *psIter = poArgs->psChild; psIter != nullptr;
849
0
             psIter = psIter->psNext)
850
0
        {
851
0
            if (psIter->eType == CXT_Element &&
852
0
                !strcmp(psIter->pszValue, "Argument"))
853
0
            {
854
0
                CPLString osName, osType, osValue;
855
0
                auto pszName = CPLGetXMLValue(psIter, "name", nullptr);
856
0
                if (pszName != nullptr)
857
0
                    osName = pszName;
858
0
                auto pszType = CPLGetXMLValue(psIter, "type", nullptr);
859
0
                if (pszType != nullptr)
860
0
                    osType = pszType;
861
0
                auto pszValue = CPLGetXMLValue(psIter, "value", nullptr);
862
0
                if (pszValue != nullptr)
863
0
                    osValue = pszValue;
864
0
                if (osType == "constant" && osValue != "" && osName != "")
865
0
                    oAdditionalArgs.push_back(
866
0
                        std::pair<CPLString, CPLString>(osName, osValue));
867
0
                if (osType == "builtin")
868
0
                {
869
0
                    const CPLString &osArgName = osValue;
870
0
                    CPLString osVal;
871
0
                    double dfVal = 0;
872
873
0
                    int success(FALSE);
874
0
                    if (osArgName == "NoData")
875
0
                        dfVal = this->GetNoDataValue(&success);
876
0
                    else if (osArgName == "scale")
877
0
                        dfVal = this->GetScale(&success);
878
0
                    else if (osArgName == "offset")
879
0
                        dfVal = this->GetOffset(&success);
880
0
                    else if (osArgName == "xoff")
881
0
                    {
882
0
                        dfVal = static_cast<double>(nXOff);
883
0
                        success = true;
884
0
                    }
885
0
                    else if (osArgName == "yoff")
886
0
                    {
887
0
                        dfVal = static_cast<double>(nYOff);
888
0
                        success = true;
889
0
                    }
890
0
                    else if (osArgName == "geotransform")
891
0
                    {
892
0
                        GDALGeoTransform gt;
893
0
                        if (GetDataset()->GetGeoTransform(gt) != CE_None)
894
0
                        {
895
                            // Do not fail here because the argument is most
896
                            // likely not needed by the pixel function. If it
897
                            // is needed, the pixel function can emit the error.
898
0
                            continue;
899
0
                        }
900
0
                        osVal = CPLSPrintf(
901
0
                            "%.17g,%.17g,%.17g,%.17g,%.17g,%.17g", gt[0], gt[1],
902
0
                            gt[2], gt[3], gt[4], gt[5]);
903
0
                        success = true;
904
0
                    }
905
0
                    else if (osArgName == "source_names")
906
0
                    {
907
0
                        for (size_t iBuffer = 0;
908
0
                             iBuffer < anMapBufferIdxToSourceIdx.size();
909
0
                             iBuffer++)
910
0
                        {
911
0
                            const int iSource =
912
0
                                anMapBufferIdxToSourceIdx[iBuffer];
913
0
                            const VRTSource *poSource =
914
0
                                m_papoSources[iSource].get();
915
916
0
                            if (iBuffer > 0)
917
0
                            {
918
0
                                osVal += "|";
919
0
                            }
920
921
0
                            const auto &osSourceName = poSource->GetName();
922
0
                            if (osSourceName.empty())
923
0
                            {
924
0
                                osVal += "B" + std::to_string(iBuffer + 1);
925
0
                            }
926
0
                            else
927
0
                            {
928
0
                                osVal += osSourceName;
929
0
                            }
930
0
                        }
931
932
0
                        success = true;
933
0
                    }
934
0
                    else
935
0
                    {
936
0
                        CPLError(
937
0
                            CE_Failure, CPLE_NotSupported,
938
0
                            "PixelFunction builtin argument %s not supported",
939
0
                            osArgName.c_str());
940
0
                        return CE_Failure;
941
0
                    }
942
0
                    if (!success)
943
0
                    {
944
0
                        if (CPLTestBool(
945
0
                                CPLGetXMLValue(psIter, "optional", "false")))
946
0
                            continue;
947
948
0
                        CPLError(CE_Failure, CPLE_AppDefined,
949
0
                                 "Raster has no %s", osValue.c_str());
950
0
                        return CE_Failure;
951
0
                    }
952
953
0
                    if (osVal.empty())
954
0
                    {
955
0
                        osVal = CPLSPrintf("%.17g", dfVal);
956
0
                    }
957
958
0
                    oAdditionalArgs.push_back(
959
0
                        std::pair<CPLString, CPLString>(osArgName, osVal));
960
0
                    CPLDebug("VRT",
961
0
                             "Added builtin pixel function argument %s = %s",
962
0
                             osArgName.c_str(), osVal.c_str());
963
0
                }
964
0
            }
965
0
        }
966
0
    }
967
968
0
    return CE_None;
969
0
}
970
971
/************************************************************************/
972
/*                             IRasterIO()                              */
973
/************************************************************************/
974
975
/**
976
 * Read/write a region of image data for this band.
977
 *
978
 * Each of the sources for this derived band will be read and passed to
979
 * the derived band pixel function.  The pixel function is responsible
980
 * for applying whatever algorithm is necessary to generate this band's
981
 * pixels from the sources.
982
 *
983
 * The sources will be read using the transfer type specified for sources
984
 * using SetSourceTransferType().  If no transfer type has been set for
985
 * this derived band, the band's data type will be used as the transfer type.
986
 *
987
 * @see gdalrasterband
988
 *
989
 * @param eRWFlag Either GF_Read to read a region of data, or GT_Write to
990
 * write a region of data.
991
 *
992
 * @param nXOff The pixel offset to the top left corner of the region
993
 * of the band to be accessed.  This would be zero to start from the left side.
994
 *
995
 * @param nYOff The line offset to the top left corner of the region
996
 * of the band to be accessed.  This would be zero to start from the top.
997
 *
998
 * @param nXSize The width of the region of the band to be accessed in pixels.
999
 *
1000
 * @param nYSize The height of the region of the band to be accessed in lines.
1001
 *
1002
 * @param pData The buffer into which the data should be read, or from which
1003
 * it should be written.  This buffer must contain at least nBufXSize *
1004
 * nBufYSize words of type eBufType.  It is organized in left to right,
1005
 * top to bottom pixel order.  Spacing is controlled by the nPixelSpace,
1006
 * and nLineSpace parameters.
1007
 *
1008
 * @param nBufXSize The width of the buffer image into which the desired
1009
 * region is to be read, or from which it is to be written.
1010
 *
1011
 * @param nBufYSize The height of the buffer image into which the desired
1012
 * region is to be read, or from which it is to be written.
1013
 *
1014
 * @param eBufType The type of the pixel values in the pData data buffer.  The
1015
 * pixel values will automatically be translated to/from the GDALRasterBand
1016
 * data type as needed.
1017
 *
1018
 * @param nPixelSpace The byte offset from the start of one pixel value in
1019
 * pData to the start of the next pixel value within a scanline.  If defaulted
1020
 * (0) the size of the datatype eBufType is used.
1021
 *
1022
 * @param nLineSpace The byte offset from the start of one scanline in
1023
 * pData to the start of the next.  If defaulted the size of the datatype
1024
 * eBufType * nBufXSize is used.
1025
 *
1026
 * @return CE_Failure if the access fails, otherwise CE_None.
1027
 */
1028
CPLErr VRTDerivedRasterBand::IRasterIO(
1029
    GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize,
1030
    void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType,
1031
    GSpacing nPixelSpace, GSpacing nLineSpace, GDALRasterIOExtraArg *psExtraArg)
1032
0
{
1033
0
    if (eRWFlag == GF_Write)
1034
0
    {
1035
0
        CPLError(CE_Failure, CPLE_AppDefined,
1036
0
                 "Writing through VRTSourcedRasterBand is not supported.");
1037
0
        return CE_Failure;
1038
0
    }
1039
1040
0
    const std::string osFctId("VRTDerivedRasterBand::IRasterIO");
1041
0
    GDALAntiRecursionGuard oGuard(osFctId);
1042
0
    if (oGuard.GetCallDepth() >= 32)
1043
0
    {
1044
0
        CPLError(
1045
0
            CE_Failure, CPLE_AppDefined,
1046
0
            "VRTDerivedRasterBand::IRasterIO(): Recursion detected (case 1)");
1047
0
        return CE_Failure;
1048
0
    }
1049
1050
0
    GDALAntiRecursionGuard oGuard2(oGuard, poDS->GetDescription());
1051
    // Allow multiple recursion depths on the same dataset in case the split strategy is applied
1052
0
    if (oGuard2.GetCallDepth() > 15)
1053
0
    {
1054
0
        CPLError(
1055
0
            CE_Failure, CPLE_AppDefined,
1056
0
            "VRTDerivedRasterBand::IRasterIO(): Recursion detected (case 2)");
1057
0
        return CE_Failure;
1058
0
    }
1059
1060
    if constexpr (sizeof(GSpacing) > sizeof(int))
1061
0
    {
1062
0
        if (nLineSpace > INT_MAX)
1063
0
        {
1064
0
            if (nBufYSize == 1)
1065
0
            {
1066
0
                nLineSpace = 0;
1067
0
            }
1068
0
            else
1069
0
            {
1070
0
                CPLError(CE_Failure, CPLE_NotSupported,
1071
0
                         "VRTDerivedRasterBand::IRasterIO(): nLineSpace > "
1072
0
                         "INT_MAX not supported");
1073
0
                return CE_Failure;
1074
0
            }
1075
0
        }
1076
0
    }
1077
1078
    /* -------------------------------------------------------------------- */
1079
    /*      Do we have overviews that would be appropriate to satisfy       */
1080
    /*      this request?                                                   */
1081
    /* -------------------------------------------------------------------- */
1082
0
    auto l_poDS = dynamic_cast<VRTDataset *>(poDS);
1083
0
    if (l_poDS &&
1084
0
        l_poDS->m_apoOverviews.empty() &&  // do not use virtual overviews
1085
0
        (nBufXSize < nXSize || nBufYSize < nYSize) && GetOverviewCount() > 0)
1086
0
    {
1087
0
        if (OverviewRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize, pData,
1088
0
                             nBufXSize, nBufYSize, eBufType, nPixelSpace,
1089
0
                             nLineSpace, psExtraArg) == CE_None)
1090
0
            return CE_None;
1091
0
    }
1092
1093
0
    const int nBufTypeSize = GDALGetDataTypeSizeBytes(eBufType);
1094
0
    GDALDataType eSrcType = eSourceTransferType;
1095
0
    if (eSrcType == GDT_Unknown || eSrcType >= GDT_TypeCount)
1096
0
    {
1097
        // Check the largest data type for all sources
1098
0
        GDALDataType eAllSrcType = GDT_Unknown;
1099
0
        for (auto &poSource : m_papoSources)
1100
0
        {
1101
0
            if (poSource->GetType() == VRTSimpleSource::GetTypeStatic())
1102
0
            {
1103
0
                const auto poSS =
1104
0
                    static_cast<VRTSimpleSource *>(poSource.get());
1105
0
                auto l_poBand = poSS->GetRasterBand();
1106
0
                if (l_poBand)
1107
0
                {
1108
0
                    eAllSrcType = GDALDataTypeUnion(
1109
0
                        eAllSrcType, l_poBand->GetRasterDataType());
1110
0
                }
1111
0
                else
1112
0
                {
1113
0
                    eAllSrcType = GDT_Unknown;
1114
0
                    break;
1115
0
                }
1116
0
            }
1117
0
            else
1118
0
            {
1119
0
                eAllSrcType = GDT_Unknown;
1120
0
                break;
1121
0
            }
1122
0
        }
1123
1124
0
        if (eAllSrcType != GDT_Unknown)
1125
0
            eSrcType = eAllSrcType;
1126
0
        else
1127
0
            eSrcType = eBufType;
1128
0
    }
1129
0
    const int nSrcTypeSize = GDALGetDataTypeSizeBytes(eSrcType);
1130
1131
    // If acquiring the region of interest in a single time is going
1132
    // to consume too much RAM, split in halves, and that recursively
1133
    // until we get below m_nAllowedRAMUsage.
1134
0
    if (m_poPrivate->m_nAllowedRAMUsage > 0 && !m_papoSources.empty() &&
1135
0
        nSrcTypeSize > 0 && nBufXSize == nXSize && nBufYSize == nYSize &&
1136
0
        static_cast<GIntBig>(nBufXSize) * nBufYSize >
1137
0
            m_poPrivate->m_nAllowedRAMUsage /
1138
0
                (static_cast<int>(m_papoSources.size()) * nSrcTypeSize))
1139
0
    {
1140
0
        CPLErr eErr = SplitRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
1141
0
                                    pData, nBufXSize, nBufYSize, eBufType,
1142
0
                                    nPixelSpace, nLineSpace, psExtraArg);
1143
0
        if (eErr != CE_Warning)
1144
0
            return eErr;
1145
0
    }
1146
1147
    /* ---- Get pixel function for band ---- */
1148
0
    const std::pair<PixelFunc, std::string> *poPixelFunc = nullptr;
1149
0
    std::vector<std::pair<CPLString, CPLString>> oAdditionalArgs;
1150
1151
0
    if (EQUAL(m_poPrivate->m_osLanguage, "C"))
1152
0
    {
1153
0
        poPixelFunc =
1154
0
            VRTDerivedRasterBand::GetPixelFunction(osFuncName.c_str());
1155
0
        if (poPixelFunc == nullptr)
1156
0
        {
1157
0
            CPLError(CE_Failure, CPLE_IllegalArg,
1158
0
                     "VRTDerivedRasterBand::IRasterIO:"
1159
0
                     "Derived band pixel function '%s' not registered.",
1160
0
                     osFuncName.c_str());
1161
0
            return CE_Failure;
1162
0
        }
1163
0
    }
1164
1165
    /* TODO: It would be nice to use a MallocBlock function for each
1166
       individual buffer that would recycle blocks of memory from a
1167
       cache by reassigning blocks that are nearly the same size.
1168
       A corresponding FreeBlock might only truly free if the total size
1169
       of freed blocks gets to be too great of a percentage of the size
1170
       of the allocated blocks. */
1171
1172
    // Get buffers for each source.
1173
0
    const int nBufferRadius = m_poPrivate->m_nBufferRadius;
1174
0
    if (nBufferRadius > (INT_MAX - nBufXSize) / 2 ||
1175
0
        nBufferRadius > (INT_MAX - nBufYSize) / 2)
1176
0
    {
1177
0
        CPLError(CE_Failure, CPLE_AppDefined,
1178
0
                 "Integer overflow: "
1179
0
                 "nBufferRadius > (INT_MAX - nBufXSize) / 2 || "
1180
0
                 "nBufferRadius > (INT_MAX - nBufYSize) / 2)");
1181
0
        return CE_Failure;
1182
0
    }
1183
0
    const int nExtBufXSize = nBufXSize + 2 * nBufferRadius;
1184
0
    const int nExtBufYSize = nBufYSize + 2 * nBufferRadius;
1185
0
    int nBufferCount = 0;
1186
1187
0
    std::vector<std::unique_ptr<void, VSIFreeReleaser>> apBuffers(
1188
0
        m_papoSources.size());
1189
0
    std::vector<int> anMapBufferIdxToSourceIdx(m_papoSources.size());
1190
0
    bool bSkipOutputBufferInitialization = !m_papoSources.empty();
1191
0
    for (int iSource = 0; iSource < static_cast<int>(m_papoSources.size());
1192
0
         iSource++)
1193
0
    {
1194
0
        if (m_poPrivate->m_bSkipNonContributingSources &&
1195
0
            m_papoSources[iSource]->IsSimpleSource())
1196
0
        {
1197
0
            bool bError = false;
1198
0
            double dfReqXOff, dfReqYOff, dfReqXSize, dfReqYSize;
1199
0
            int nReqXOff, nReqYOff, nReqXSize, nReqYSize;
1200
0
            int nOutXOff, nOutYOff, nOutXSize, nOutYSize;
1201
0
            auto poSource =
1202
0
                static_cast<VRTSimpleSource *>(m_papoSources[iSource].get());
1203
0
            if (!poSource->GetSrcDstWindow(
1204
0
                    nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize,
1205
0
                    &dfReqXOff, &dfReqYOff, &dfReqXSize, &dfReqYSize, &nReqXOff,
1206
0
                    &nReqYOff, &nReqXSize, &nReqYSize, &nOutXOff, &nOutYOff,
1207
0
                    &nOutXSize, &nOutYSize, bError))
1208
0
            {
1209
0
                if (bError)
1210
0
                {
1211
0
                    return CE_Failure;
1212
0
                }
1213
1214
                // Skip non contributing source
1215
0
                bSkipOutputBufferInitialization = false;
1216
0
                continue;
1217
0
            }
1218
0
        }
1219
1220
0
        anMapBufferIdxToSourceIdx[nBufferCount] = iSource;
1221
0
        apBuffers[nBufferCount].reset(
1222
0
            VSI_MALLOC3_VERBOSE(nSrcTypeSize, nExtBufXSize, nExtBufYSize));
1223
0
        if (apBuffers[nBufferCount] == nullptr)
1224
0
        {
1225
0
            return CE_Failure;
1226
0
        }
1227
1228
0
        bool bBufferInit = true;
1229
0
        if (m_papoSources[iSource]->IsSimpleSource())
1230
0
        {
1231
0
            const auto poSS =
1232
0
                static_cast<VRTSimpleSource *>(m_papoSources[iSource].get());
1233
0
            auto l_poBand = poSS->GetRasterBand();
1234
0
            if (l_poBand != nullptr && poSS->m_dfSrcXOff == 0.0 &&
1235
0
                poSS->m_dfSrcYOff == 0.0 &&
1236
0
                poSS->m_dfSrcXOff + poSS->m_dfSrcXSize ==
1237
0
                    l_poBand->GetXSize() &&
1238
0
                poSS->m_dfSrcYOff + poSS->m_dfSrcYSize ==
1239
0
                    l_poBand->GetYSize() &&
1240
0
                poSS->m_dfDstXOff == 0.0 && poSS->m_dfDstYOff == 0.0 &&
1241
0
                poSS->m_dfDstXOff + poSS->m_dfDstXSize == nRasterXSize &&
1242
0
                poSS->m_dfDstYOff + poSS->m_dfDstYSize == nRasterYSize)
1243
0
            {
1244
0
                if (m_papoSources[iSource]->GetType() ==
1245
0
                    VRTSimpleSource::GetTypeStatic())
1246
0
                    bBufferInit = false;
1247
0
            }
1248
0
            else
1249
0
            {
1250
0
                bSkipOutputBufferInitialization = false;
1251
0
            }
1252
0
        }
1253
0
        else
1254
0
        {
1255
0
            bSkipOutputBufferInitialization = false;
1256
0
        }
1257
0
        if (bBufferInit)
1258
0
        {
1259
            /* ------------------------------------------------------------ */
1260
            /* #4045: Initialize the newly allocated buffers before handing */
1261
            /* them off to the sources. These buffers are packed, so we     */
1262
            /* don't need any special line-by-line handling when a nonzero  */
1263
            /* nodata value is set.                                         */
1264
            /* ------------------------------------------------------------ */
1265
0
            if (!m_bNoDataValueSet || m_dfNoDataValue == 0)
1266
0
            {
1267
0
                memset(apBuffers[nBufferCount].get(), 0,
1268
0
                       static_cast<size_t>(nSrcTypeSize) * nExtBufXSize *
1269
0
                           nExtBufYSize);
1270
0
            }
1271
0
            else
1272
0
            {
1273
0
                GDALCopyWords64(
1274
0
                    &m_dfNoDataValue, GDT_Float64, 0,
1275
0
                    static_cast<GByte *>(apBuffers[nBufferCount].get()),
1276
0
                    eSrcType, nSrcTypeSize,
1277
0
                    static_cast<GPtrDiff_t>(nExtBufXSize) * nExtBufYSize);
1278
0
            }
1279
0
        }
1280
1281
0
        ++nBufferCount;
1282
0
    }
1283
1284
    /* -------------------------------------------------------------------- */
1285
    /*      Initialize the buffer to some background value. Use the         */
1286
    /*      nodata value if available.                                      */
1287
    /* -------------------------------------------------------------------- */
1288
0
    if (bSkipOutputBufferInitialization)
1289
0
    {
1290
        // Do nothing
1291
0
    }
1292
0
    else if (nPixelSpace == nBufTypeSize &&
1293
0
             (!m_bNoDataValueSet || m_dfNoDataValue == 0))
1294
0
    {
1295
0
        memset(pData, 0,
1296
0
               static_cast<size_t>(nBufXSize) * nBufYSize * nBufTypeSize);
1297
0
    }
1298
0
    else if (m_bNoDataValueSet)
1299
0
    {
1300
0
        double dfWriteValue = m_dfNoDataValue;
1301
1302
0
        for (int iLine = 0; iLine < nBufYSize; iLine++)
1303
0
        {
1304
0
            GDALCopyWords64(&dfWriteValue, GDT_Float64, 0,
1305
0
                            static_cast<GByte *>(pData) + nLineSpace * iLine,
1306
0
                            eBufType, static_cast<int>(nPixelSpace), nBufXSize);
1307
0
        }
1308
0
    }
1309
1310
    // No contributing sources and SkipNonContributingSources mode ?
1311
    // Do not call the pixel function and just return the 0/nodata initialized
1312
    // output buffer.
1313
0
    if (nBufferCount == 0 && m_poPrivate->m_bSkipNonContributingSources)
1314
0
    {
1315
0
        return CE_None;
1316
0
    }
1317
1318
0
    GDALRasterIOExtraArg sExtraArg;
1319
0
    GDALCopyRasterIOExtraArg(&sExtraArg, psExtraArg);
1320
1321
0
    int nXShiftInBuffer = 0;
1322
0
    int nYShiftInBuffer = 0;
1323
0
    int nExtBufXSizeReq = nExtBufXSize;
1324
0
    int nExtBufYSizeReq = nExtBufYSize;
1325
1326
0
    int nXOffExt = nXOff;
1327
0
    int nYOffExt = nYOff;
1328
0
    int nXSizeExt = nXSize;
1329
0
    int nYSizeExt = nYSize;
1330
1331
0
    if (nBufferRadius)
1332
0
    {
1333
0
        double dfXRatio = static_cast<double>(nXSize) / nBufXSize;
1334
0
        double dfYRatio = static_cast<double>(nYSize) / nBufYSize;
1335
1336
0
        if (!sExtraArg.bFloatingPointWindowValidity)
1337
0
        {
1338
0
            sExtraArg.dfXOff = nXOff;
1339
0
            sExtraArg.dfYOff = nYOff;
1340
0
            sExtraArg.dfXSize = nXSize;
1341
0
            sExtraArg.dfYSize = nYSize;
1342
0
        }
1343
1344
0
        sExtraArg.dfXOff -= dfXRatio * nBufferRadius;
1345
0
        sExtraArg.dfYOff -= dfYRatio * nBufferRadius;
1346
0
        sExtraArg.dfXSize += 2 * dfXRatio * nBufferRadius;
1347
0
        sExtraArg.dfYSize += 2 * dfYRatio * nBufferRadius;
1348
0
        if (sExtraArg.dfXOff < 0)
1349
0
        {
1350
0
            nXShiftInBuffer = -static_cast<int>(sExtraArg.dfXOff / dfXRatio);
1351
0
            nExtBufXSizeReq -= nXShiftInBuffer;
1352
0
            sExtraArg.dfXSize += sExtraArg.dfXOff;
1353
0
            sExtraArg.dfXOff = 0;
1354
0
        }
1355
0
        if (sExtraArg.dfYOff < 0)
1356
0
        {
1357
0
            nYShiftInBuffer = -static_cast<int>(sExtraArg.dfYOff / dfYRatio);
1358
0
            nExtBufYSizeReq -= nYShiftInBuffer;
1359
0
            sExtraArg.dfYSize += sExtraArg.dfYOff;
1360
0
            sExtraArg.dfYOff = 0;
1361
0
        }
1362
0
        if (sExtraArg.dfXOff + sExtraArg.dfXSize > nRasterXSize)
1363
0
        {
1364
0
            nExtBufXSizeReq -= static_cast<int>(
1365
0
                (sExtraArg.dfXOff + sExtraArg.dfXSize - nRasterXSize) /
1366
0
                dfXRatio);
1367
0
            sExtraArg.dfXSize = nRasterXSize - sExtraArg.dfXOff;
1368
0
        }
1369
0
        if (sExtraArg.dfYOff + sExtraArg.dfYSize > nRasterYSize)
1370
0
        {
1371
0
            nExtBufYSizeReq -= static_cast<int>(
1372
0
                (sExtraArg.dfYOff + sExtraArg.dfYSize - nRasterYSize) /
1373
0
                dfYRatio);
1374
0
            sExtraArg.dfYSize = nRasterYSize - sExtraArg.dfYOff;
1375
0
        }
1376
1377
0
        nXOffExt = static_cast<int>(sExtraArg.dfXOff);
1378
0
        nYOffExt = static_cast<int>(sExtraArg.dfYOff);
1379
0
        nXSizeExt = std::min(static_cast<int>(sExtraArg.dfXSize + 0.5),
1380
0
                             nRasterXSize - nXOffExt);
1381
0
        nYSizeExt = std::min(static_cast<int>(sExtraArg.dfYSize + 0.5),
1382
0
                             nRasterYSize - nYOffExt);
1383
0
    }
1384
1385
    // Load values for sources into packed buffers.
1386
0
    CPLErr eErr = CE_None;
1387
0
    VRTSource::WorkingState oWorkingState;
1388
0
    for (int iBuffer = 0; iBuffer < nBufferCount && eErr == CE_None; iBuffer++)
1389
0
    {
1390
0
        const int iSource = anMapBufferIdxToSourceIdx[iBuffer];
1391
0
        GByte *pabyBuffer = static_cast<GByte *>(apBuffers[iBuffer].get());
1392
0
        eErr = static_cast<VRTSource *>(m_papoSources[iSource].get())
1393
0
                   ->RasterIO(
1394
0
                       eSrcType, nXOffExt, nYOffExt, nXSizeExt, nYSizeExt,
1395
0
                       pabyBuffer + (static_cast<size_t>(nYShiftInBuffer) *
1396
0
                                         nExtBufXSize +
1397
0
                                     nXShiftInBuffer) *
1398
0
                                        nSrcTypeSize,
1399
0
                       nExtBufXSizeReq, nExtBufYSizeReq, eSrcType, nSrcTypeSize,
1400
0
                       static_cast<GSpacing>(nSrcTypeSize) * nExtBufXSize,
1401
0
                       &sExtraArg, oWorkingState);
1402
1403
        // Extend first lines
1404
0
        for (int iY = 0; iY < nYShiftInBuffer; iY++)
1405
0
        {
1406
0
            memcpy(pabyBuffer +
1407
0
                       static_cast<size_t>(iY) * nExtBufXSize * nSrcTypeSize,
1408
0
                   pabyBuffer + static_cast<size_t>(nYShiftInBuffer) *
1409
0
                                    nExtBufXSize * nSrcTypeSize,
1410
0
                   static_cast<size_t>(nExtBufXSize) * nSrcTypeSize);
1411
0
        }
1412
        // Extend last lines
1413
0
        for (int iY = nYShiftInBuffer + nExtBufYSizeReq; iY < nExtBufYSize;
1414
0
             iY++)
1415
0
        {
1416
0
            memcpy(pabyBuffer +
1417
0
                       static_cast<size_t>(iY) * nExtBufXSize * nSrcTypeSize,
1418
0
                   pabyBuffer + static_cast<size_t>(nYShiftInBuffer +
1419
0
                                                    nExtBufYSizeReq - 1) *
1420
0
                                    nExtBufXSize * nSrcTypeSize,
1421
0
                   static_cast<size_t>(nExtBufXSize) * nSrcTypeSize);
1422
0
        }
1423
        // Extend first cols
1424
0
        if (nXShiftInBuffer)
1425
0
        {
1426
0
            for (int iY = 0; iY < nExtBufYSize; iY++)
1427
0
            {
1428
0
                for (int iX = 0; iX < nXShiftInBuffer; iX++)
1429
0
                {
1430
0
                    memcpy(pabyBuffer +
1431
0
                               static_cast<size_t>(iY * nExtBufXSize + iX) *
1432
0
                                   nSrcTypeSize,
1433
0
                           pabyBuffer +
1434
0
                               (static_cast<size_t>(iY) * nExtBufXSize +
1435
0
                                nXShiftInBuffer) *
1436
0
                                   nSrcTypeSize,
1437
0
                           nSrcTypeSize);
1438
0
                }
1439
0
            }
1440
0
        }
1441
        // Extent last cols
1442
0
        if (nXShiftInBuffer + nExtBufXSizeReq < nExtBufXSize)
1443
0
        {
1444
0
            for (int iY = 0; iY < nExtBufYSize; iY++)
1445
0
            {
1446
0
                for (int iX = nXShiftInBuffer + nExtBufXSizeReq;
1447
0
                     iX < nExtBufXSize; iX++)
1448
0
                {
1449
0
                    memcpy(pabyBuffer +
1450
0
                               (static_cast<size_t>(iY) * nExtBufXSize + iX) *
1451
0
                                   nSrcTypeSize,
1452
0
                           pabyBuffer +
1453
0
                               (static_cast<size_t>(iY) * nExtBufXSize +
1454
0
                                nXShiftInBuffer + nExtBufXSizeReq - 1) *
1455
0
                                   nSrcTypeSize,
1456
0
                           nSrcTypeSize);
1457
0
                }
1458
0
            }
1459
0
        }
1460
0
    }
1461
1462
    // Collect any pixel function arguments
1463
0
    if (poPixelFunc != nullptr && !poPixelFunc->second.empty())
1464
0
    {
1465
0
        if (GetPixelFunctionArguments(poPixelFunc->second,
1466
0
                                      anMapBufferIdxToSourceIdx, nXOff, nYOff,
1467
0
                                      oAdditionalArgs) != CE_None)
1468
0
        {
1469
0
            eErr = CE_Failure;
1470
0
        }
1471
0
    }
1472
1473
    // Apply pixel function.
1474
0
    if (eErr == CE_None && EQUAL(m_poPrivate->m_osLanguage, "Python"))
1475
0
    {
1476
        // numpy doesn't have native cint16/cint32/cfloat16
1477
0
        if (eSrcType == GDT_CInt16 || eSrcType == GDT_CInt32 ||
1478
0
            eSrcType == GDT_CFloat16)
1479
0
        {
1480
0
            CPLError(CE_Failure, CPLE_AppDefined,
1481
0
                     "CInt16/CInt32/CFloat16 data type not supported for "
1482
0
                     "SourceTransferType");
1483
0
            return CE_Failure;
1484
0
        }
1485
0
        if (eDataType == GDT_CInt16 || eDataType == GDT_CInt32 ||
1486
0
            eDataType == GDT_CFloat16)
1487
0
        {
1488
0
            CPLError(
1489
0
                CE_Failure, CPLE_AppDefined,
1490
0
                "CInt16/CInt32/CFloat16 data type not supported for data type");
1491
0
            return CE_Failure;
1492
0
        }
1493
1494
0
        if (!InitializePython())
1495
0
            return CE_Failure;
1496
1497
0
        std::unique_ptr<GByte, VSIFreeReleaser> pabyTmpBuffer;
1498
        // Do we need a temporary buffer or can we use directly the output
1499
        // buffer ?
1500
0
        if (nBufferRadius != 0 || eDataType != eBufType ||
1501
0
            nPixelSpace != nBufTypeSize ||
1502
0
            nLineSpace != static_cast<GSpacing>(nBufTypeSize) * nBufXSize)
1503
0
        {
1504
0
            pabyTmpBuffer.reset(static_cast<GByte *>(VSI_CALLOC_VERBOSE(
1505
0
                static_cast<size_t>(nExtBufXSize) * nExtBufYSize,
1506
0
                GDALGetDataTypeSizeBytes(eDataType))));
1507
0
            if (!pabyTmpBuffer)
1508
0
                return CE_Failure;
1509
0
        }
1510
1511
0
        {
1512
0
            const bool bUseExclusiveLock =
1513
0
                m_poPrivate->m_bExclusiveLock ||
1514
0
                (m_poPrivate->m_bFirstTime &&
1515
0
                 m_poPrivate->m_osCode.find("@jit") != std::string::npos);
1516
0
            m_poPrivate->m_bFirstTime = false;
1517
0
            GIL_Holder oHolder(bUseExclusiveLock);
1518
1519
            // Prepare target numpy array
1520
0
            PyObject *poPyDstArray = GDALCreateNumpyArray(
1521
0
                m_poPrivate->m_poGDALCreateNumpyArray,
1522
0
                pabyTmpBuffer ? pabyTmpBuffer.get() : pData, eDataType,
1523
0
                nExtBufYSize, nExtBufXSize);
1524
0
            if (!poPyDstArray)
1525
0
            {
1526
0
                return CE_Failure;
1527
0
            }
1528
1529
            // Wrap source buffers as input numpy arrays
1530
0
            PyObject *pyArgInputArray = PyTuple_New(nBufferCount);
1531
0
            for (int i = 0; i < nBufferCount; i++)
1532
0
            {
1533
0
                GByte *pabyBuffer = static_cast<GByte *>(apBuffers[i].get());
1534
0
                PyObject *poPySrcArray = GDALCreateNumpyArray(
1535
0
                    m_poPrivate->m_poGDALCreateNumpyArray, pabyBuffer, eSrcType,
1536
0
                    nExtBufYSize, nExtBufXSize);
1537
0
                CPLAssert(poPySrcArray);
1538
0
                PyTuple_SetItem(pyArgInputArray, i, poPySrcArray);
1539
0
            }
1540
1541
            // Create arguments
1542
0
            PyObject *pyArgs = PyTuple_New(10);
1543
0
            PyTuple_SetItem(pyArgs, 0, pyArgInputArray);
1544
0
            PyTuple_SetItem(pyArgs, 1, poPyDstArray);
1545
0
            PyTuple_SetItem(pyArgs, 2, PyLong_FromLong(nXOff));
1546
0
            PyTuple_SetItem(pyArgs, 3, PyLong_FromLong(nYOff));
1547
0
            PyTuple_SetItem(pyArgs, 4, PyLong_FromLong(nXSize));
1548
0
            PyTuple_SetItem(pyArgs, 5, PyLong_FromLong(nYSize));
1549
0
            PyTuple_SetItem(pyArgs, 6, PyLong_FromLong(nRasterXSize));
1550
0
            PyTuple_SetItem(pyArgs, 7, PyLong_FromLong(nRasterYSize));
1551
0
            PyTuple_SetItem(pyArgs, 8, PyLong_FromLong(nBufferRadius));
1552
1553
0
            GDALGeoTransform gt;
1554
0
            if (GetDataset())
1555
0
                GetDataset()->GetGeoTransform(gt);
1556
0
            PyObject *pyGT = PyTuple_New(6);
1557
0
            for (int i = 0; i < 6; i++)
1558
0
                PyTuple_SetItem(pyGT, i, PyFloat_FromDouble(gt[i]));
1559
0
            PyTuple_SetItem(pyArgs, 9, pyGT);
1560
1561
            // Prepare kwargs
1562
0
            PyObject *pyKwargs = PyDict_New();
1563
0
            for (size_t i = 0; i < m_poPrivate->m_oFunctionArgs.size(); ++i)
1564
0
            {
1565
0
                const char *pszKey =
1566
0
                    m_poPrivate->m_oFunctionArgs[i].first.c_str();
1567
0
                const char *pszValue =
1568
0
                    m_poPrivate->m_oFunctionArgs[i].second.c_str();
1569
0
                PyDict_SetItemString(
1570
0
                    pyKwargs, pszKey,
1571
0
                    PyBytes_FromStringAndSize(pszValue, strlen(pszValue)));
1572
0
            }
1573
1574
            // Call user function
1575
0
            PyObject *pRetValue =
1576
0
                PyObject_Call(m_poPrivate->m_poUserFunction, pyArgs, pyKwargs);
1577
1578
0
            Py_DecRef(pyArgs);
1579
0
            Py_DecRef(pyKwargs);
1580
1581
0
            if (ErrOccurredEmitCPLError())
1582
0
            {
1583
0
                eErr = CE_Failure;
1584
0
            }
1585
0
            if (pRetValue)
1586
0
                Py_DecRef(pRetValue);
1587
0
        }  // End of GIL section
1588
1589
0
        if (pabyTmpBuffer)
1590
0
        {
1591
            // Copy numpy destination array to user buffer
1592
0
            for (int iY = 0; iY < nBufYSize; iY++)
1593
0
            {
1594
0
                size_t nSrcOffset =
1595
0
                    (static_cast<size_t>(iY + nBufferRadius) * nExtBufXSize +
1596
0
                     nBufferRadius) *
1597
0
                    GDALGetDataTypeSizeBytes(eDataType);
1598
0
                GDALCopyWords64(pabyTmpBuffer.get() + nSrcOffset, eDataType,
1599
0
                                GDALGetDataTypeSizeBytes(eDataType),
1600
0
                                static_cast<GByte *>(pData) + iY * nLineSpace,
1601
0
                                eBufType, static_cast<int>(nPixelSpace),
1602
0
                                nBufXSize);
1603
0
            }
1604
0
        }
1605
0
    }
1606
0
    else if (eErr == CE_None && poPixelFunc != nullptr)
1607
0
    {
1608
0
        CPLStringList aosArgs;
1609
1610
0
        oAdditionalArgs.insert(oAdditionalArgs.end(),
1611
0
                               m_poPrivate->m_oFunctionArgs.begin(),
1612
0
                               m_poPrivate->m_oFunctionArgs.end());
1613
0
        for (const auto &oArg : oAdditionalArgs)
1614
0
        {
1615
0
            const char *pszKey = oArg.first.c_str();
1616
0
            const char *pszValue = oArg.second.c_str();
1617
0
            aosArgs.SetNameValue(pszKey, pszValue);
1618
0
        }
1619
1620
0
        static_assert(sizeof(apBuffers[0]) == sizeof(void *));
1621
0
        eErr = (poPixelFunc->first)(
1622
            // We cast vector<unique_ptr<void>>.data() as void**. This is OK
1623
            // given above static_assert
1624
0
            reinterpret_cast<void **>(apBuffers.data()), nBufferCount, pData,
1625
0
            nBufXSize, nBufYSize, eSrcType, eBufType,
1626
0
            static_cast<int>(nPixelSpace), static_cast<int>(nLineSpace),
1627
0
            aosArgs.List());
1628
0
    }
1629
1630
0
    return eErr;
1631
0
}
1632
1633
/************************************************************************/
1634
/*                         IGetDataCoverageStatus()                     */
1635
/************************************************************************/
1636
1637
int VRTDerivedRasterBand::IGetDataCoverageStatus(
1638
    int /* nXOff */, int /* nYOff */, int /* nXSize */, int /* nYSize */,
1639
    int /* nMaskFlagStop */, double *pdfDataPct)
1640
0
{
1641
0
    if (pdfDataPct != nullptr)
1642
0
        *pdfDataPct = -1.0;
1643
0
    return GDAL_DATA_COVERAGE_STATUS_UNIMPLEMENTED |
1644
0
           GDAL_DATA_COVERAGE_STATUS_DATA;
1645
0
}
1646
1647
/************************************************************************/
1648
/*                              XMLInit()                               */
1649
/************************************************************************/
1650
1651
CPLErr VRTDerivedRasterBand::XMLInit(const CPLXMLNode *psTree,
1652
                                     const char *pszVRTPath,
1653
                                     VRTMapSharedResources &oMapSharedSources)
1654
1655
0
{
1656
0
    const CPLErr eErr =
1657
0
        VRTSourcedRasterBand::XMLInit(psTree, pszVRTPath, oMapSharedSources);
1658
0
    if (eErr != CE_None)
1659
0
        return eErr;
1660
1661
    // Read derived pixel function type.
1662
0
    SetPixelFunctionName(CPLGetXMLValue(psTree, "PixelFunctionType", nullptr));
1663
0
    if (osFuncName.empty())
1664
0
    {
1665
0
        CPLError(CE_Failure, CPLE_AppDefined, "PixelFunctionType missing");
1666
0
        return CE_Failure;
1667
0
    }
1668
1669
0
    m_poPrivate->m_osLanguage =
1670
0
        CPLGetXMLValue(psTree, "PixelFunctionLanguage", "C");
1671
0
    if (!EQUAL(m_poPrivate->m_osLanguage, "C") &&
1672
0
        !EQUAL(m_poPrivate->m_osLanguage, "Python"))
1673
0
    {
1674
0
        CPLError(CE_Failure, CPLE_NotSupported,
1675
0
                 "Unsupported PixelFunctionLanguage");
1676
0
        return CE_Failure;
1677
0
    }
1678
1679
0
    m_poPrivate->m_osCode = CPLGetXMLValue(psTree, "PixelFunctionCode", "");
1680
0
    if (!m_poPrivate->m_osCode.empty() &&
1681
0
        !EQUAL(m_poPrivate->m_osLanguage, "Python"))
1682
0
    {
1683
0
        CPLError(CE_Failure, CPLE_NotSupported,
1684
0
                 "PixelFunctionCode can only be used with Python");
1685
0
        return CE_Failure;
1686
0
    }
1687
1688
0
    m_poPrivate->m_nBufferRadius =
1689
0
        atoi(CPLGetXMLValue(psTree, "BufferRadius", "0"));
1690
0
    if (m_poPrivate->m_nBufferRadius < 0 || m_poPrivate->m_nBufferRadius > 1024)
1691
0
    {
1692
0
        CPLError(CE_Failure, CPLE_AppDefined, "Invalid value for BufferRadius");
1693
0
        return CE_Failure;
1694
0
    }
1695
0
    if (m_poPrivate->m_nBufferRadius != 0 &&
1696
0
        !EQUAL(m_poPrivate->m_osLanguage, "Python"))
1697
0
    {
1698
0
        CPLError(CE_Failure, CPLE_NotSupported,
1699
0
                 "BufferRadius can only be used with Python");
1700
0
        return CE_Failure;
1701
0
    }
1702
1703
0
    const CPLXMLNode *const psArgs =
1704
0
        CPLGetXMLNode(psTree, "PixelFunctionArguments");
1705
0
    if (psArgs != nullptr)
1706
0
    {
1707
0
        for (const CPLXMLNode *psIter = psArgs->psChild; psIter;
1708
0
             psIter = psIter->psNext)
1709
0
        {
1710
0
            if (psIter->eType == CXT_Attribute)
1711
0
            {
1712
0
                AddPixelFunctionArgument(psIter->pszValue,
1713
0
                                         psIter->psChild->pszValue);
1714
0
            }
1715
0
        }
1716
0
    }
1717
1718
    // Read optional source transfer data type.
1719
0
    const char *pszTypeName =
1720
0
        CPLGetXMLValue(psTree, "SourceTransferType", nullptr);
1721
0
    if (pszTypeName != nullptr)
1722
0
    {
1723
0
        eSourceTransferType = GDALGetDataTypeByName(pszTypeName);
1724
0
    }
1725
1726
    // Whether to skip non contributing sources
1727
0
    const char *pszSkipNonContributingSources =
1728
0
        CPLGetXMLValue(psTree, "SkipNonContributingSources", nullptr);
1729
0
    if (pszSkipNonContributingSources)
1730
0
    {
1731
0
        SetSkipNonContributingSources(
1732
0
            CPLTestBool(pszSkipNonContributingSources));
1733
0
    }
1734
1735
0
    return CE_None;
1736
0
}
1737
1738
/************************************************************************/
1739
/*                           SerializeToXML()                           */
1740
/************************************************************************/
1741
1742
CPLXMLNode *VRTDerivedRasterBand::SerializeToXML(const char *pszVRTPath,
1743
                                                 bool &bHasWarnedAboutRAMUsage,
1744
                                                 size_t &nAccRAMUsage)
1745
0
{
1746
0
    CPLXMLNode *psTree = VRTSourcedRasterBand::SerializeToXML(
1747
0
        pszVRTPath, bHasWarnedAboutRAMUsage, nAccRAMUsage);
1748
1749
    /* -------------------------------------------------------------------- */
1750
    /*      Set subclass.                                                   */
1751
    /* -------------------------------------------------------------------- */
1752
0
    CPLCreateXMLNode(CPLCreateXMLNode(psTree, CXT_Attribute, "subClass"),
1753
0
                     CXT_Text, "VRTDerivedRasterBand");
1754
1755
    /* ---- Encode DerivedBand-specific fields ---- */
1756
0
    if (!EQUAL(m_poPrivate->m_osLanguage, "C"))
1757
0
    {
1758
0
        CPLSetXMLValue(psTree, "PixelFunctionLanguage",
1759
0
                       m_poPrivate->m_osLanguage);
1760
0
    }
1761
0
    if (!osFuncName.empty())
1762
0
        CPLSetXMLValue(psTree, "PixelFunctionType", osFuncName.c_str());
1763
0
    if (!m_poPrivate->m_oFunctionArgs.empty())
1764
0
    {
1765
0
        CPLXMLNode *psArgs =
1766
0
            CPLCreateXMLNode(psTree, CXT_Element, "PixelFunctionArguments");
1767
0
        for (size_t i = 0; i < m_poPrivate->m_oFunctionArgs.size(); ++i)
1768
0
        {
1769
0
            const char *pszKey = m_poPrivate->m_oFunctionArgs[i].first.c_str();
1770
0
            const char *pszValue =
1771
0
                m_poPrivate->m_oFunctionArgs[i].second.c_str();
1772
0
            CPLCreateXMLNode(CPLCreateXMLNode(psArgs, CXT_Attribute, pszKey),
1773
0
                             CXT_Text, pszValue);
1774
0
        }
1775
0
    }
1776
0
    if (!m_poPrivate->m_osCode.empty())
1777
0
    {
1778
0
        if (m_poPrivate->m_osCode.find("<![CDATA[") == std::string::npos)
1779
0
        {
1780
0
            CPLCreateXMLNode(
1781
0
                CPLCreateXMLNode(psTree, CXT_Element, "PixelFunctionCode"),
1782
0
                CXT_Literal,
1783
0
                ("<![CDATA[" + m_poPrivate->m_osCode + "]]>").c_str());
1784
0
        }
1785
0
        else
1786
0
        {
1787
0
            CPLSetXMLValue(psTree, "PixelFunctionCode", m_poPrivate->m_osCode);
1788
0
        }
1789
0
    }
1790
0
    if (m_poPrivate->m_nBufferRadius != 0)
1791
0
        CPLSetXMLValue(psTree, "BufferRadius",
1792
0
                       CPLSPrintf("%d", m_poPrivate->m_nBufferRadius));
1793
0
    if (this->eSourceTransferType != GDT_Unknown)
1794
0
        CPLSetXMLValue(psTree, "SourceTransferType",
1795
0
                       GDALGetDataTypeName(eSourceTransferType));
1796
1797
0
    if (m_poPrivate->m_bSkipNonContributingSourcesSpecified)
1798
0
    {
1799
0
        CPLSetXMLValue(psTree, "SkipNonContributingSources",
1800
0
                       m_poPrivate->m_bSkipNonContributingSources ? "true"
1801
0
                                                                  : "false");
1802
0
    }
1803
1804
0
    return psTree;
1805
0
}
1806
1807
/************************************************************************/
1808
/*                             GetMinimum()                             */
1809
/************************************************************************/
1810
1811
double VRTDerivedRasterBand::GetMinimum(int *pbSuccess)
1812
0
{
1813
0
    return GDALRasterBand::GetMinimum(pbSuccess);
1814
0
}
1815
1816
/************************************************************************/
1817
/*                             GetMaximum()                             */
1818
/************************************************************************/
1819
1820
double VRTDerivedRasterBand::GetMaximum(int *pbSuccess)
1821
0
{
1822
0
    return GDALRasterBand::GetMaximum(pbSuccess);
1823
0
}
1824
1825
/************************************************************************/
1826
/*                       ComputeRasterMinMax()                          */
1827
/************************************************************************/
1828
1829
CPLErr VRTDerivedRasterBand::ComputeRasterMinMax(int bApproxOK,
1830
                                                 double *adfMinMax)
1831
0
{
1832
0
    return GDALRasterBand::ComputeRasterMinMax(bApproxOK, adfMinMax);
1833
0
}
1834
1835
/************************************************************************/
1836
/*                         ComputeStatistics()                          */
1837
/************************************************************************/
1838
1839
CPLErr VRTDerivedRasterBand::ComputeStatistics(int bApproxOK, double *pdfMin,
1840
                                               double *pdfMax, double *pdfMean,
1841
                                               double *pdfStdDev,
1842
                                               GDALProgressFunc pfnProgress,
1843
                                               void *pProgressData)
1844
1845
0
{
1846
0
    return GDALRasterBand::ComputeStatistics(bApproxOK, pdfMin, pdfMax, pdfMean,
1847
0
                                             pdfStdDev, pfnProgress,
1848
0
                                             pProgressData);
1849
0
}
1850
1851
/************************************************************************/
1852
/*                            GetHistogram()                            */
1853
/************************************************************************/
1854
1855
CPLErr VRTDerivedRasterBand::GetHistogram(double dfMin, double dfMax,
1856
                                          int nBuckets, GUIntBig *panHistogram,
1857
                                          int bIncludeOutOfRange, int bApproxOK,
1858
                                          GDALProgressFunc pfnProgress,
1859
                                          void *pProgressData)
1860
1861
0
{
1862
0
    return VRTRasterBand::GetHistogram(dfMin, dfMax, nBuckets, panHistogram,
1863
0
                                       bIncludeOutOfRange, bApproxOK,
1864
0
                                       pfnProgress, pProgressData);
1865
0
}
1866
1867
/*! @endcond */