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