Line data Source code
1 :
2 : /******************************************************************************
3 : *
4 : * Project: GDAL Core
5 : * Purpose: Helper code to implement overview support in different drivers.
6 : * Author: Frank Warmerdam, warmerdam@pobox.com
7 : *
8 : ******************************************************************************
9 : * Copyright (c) 2000, Frank Warmerdam
10 : * Copyright (c) 2007-2010, Even Rouault <even dot rouault at spatialys.com>
11 : *
12 : * SPDX-License-Identifier: MIT
13 : ****************************************************************************/
14 :
15 : #include "cpl_port.h"
16 : #include "gdal_priv.h"
17 :
18 : #include <cmath>
19 : #include <cstddef>
20 : #include <cstdlib>
21 :
22 : #include <algorithm>
23 : #include <complex>
24 : #include <condition_variable>
25 : #include <limits>
26 : #include <list>
27 : #include <memory>
28 : #include <mutex>
29 : #include <vector>
30 :
31 : #include "cpl_conv.h"
32 : #include "cpl_error.h"
33 : #include "cpl_float.h"
34 : #include "cpl_progress.h"
35 : #include "cpl_vsi.h"
36 : #include "cpl_worker_thread_pool.h"
37 : #include "gdal.h"
38 : #include "gdal_thread_pool.h"
39 : #include "gdalwarper.h"
40 : #include "gdal_vrt.h"
41 : #include "vrtdataset.h"
42 :
43 : #ifdef USE_NEON_OPTIMIZATIONS
44 : #include "include_sse2neon.h"
45 :
46 : #if (!defined(__aarch64__) && !defined(_M_ARM64))
47 : #define ARM_V7
48 : #endif
49 :
50 : #define USE_SSE2
51 :
52 : #include "gdalsse_priv.h"
53 :
54 : // Restrict to 64bit processors because they are guaranteed to have SSE2,
55 : // or if __AVX2__ is defined.
56 : #elif defined(__x86_64) || defined(_M_X64) || defined(__AVX2__)
57 : #define USE_SSE2
58 :
59 : #include "gdalsse_priv.h"
60 :
61 : #ifdef __SSE3__
62 : #include <pmmintrin.h>
63 : #endif
64 : #ifdef __SSSE3__
65 : #include <tmmintrin.h>
66 : #endif
67 : #ifdef __SSE4_1__
68 : #include <smmintrin.h>
69 : #endif
70 : #ifdef __AVX2__
71 : #include <immintrin.h>
72 : #endif
73 :
74 : #endif
75 :
76 : // To be included after above USE_SSE2 and include gdalsse_priv.h
77 : // to avoid build issue on Windows x86
78 : #include "gdal_priv_templates.hpp"
79 :
80 : /************************************************************************/
81 : /* GDALResampleChunk_Near() */
82 : /************************************************************************/
83 :
84 : template <class T>
85 1298 : static CPLErr GDALResampleChunk_NearT(const GDALOverviewResampleArgs &args,
86 : const T *pChunk, T **ppDstBuffer)
87 :
88 : {
89 1298 : const double dfXRatioDstToSrc = args.dfXRatioDstToSrc;
90 1298 : const double dfYRatioDstToSrc = args.dfYRatioDstToSrc;
91 1298 : const GDALDataType eWrkDataType = args.eWrkDataType;
92 1298 : const int nChunkXOff = args.nChunkXOff;
93 1298 : const int nChunkXSize = args.nChunkXSize;
94 1298 : const int nChunkYOff = args.nChunkYOff;
95 1298 : const int nDstXOff = args.nDstXOff;
96 1298 : const int nDstXOff2 = args.nDstXOff2;
97 1298 : const int nDstYOff = args.nDstYOff;
98 1298 : const int nDstYOff2 = args.nDstYOff2;
99 1298 : const int nDstXWidth = nDstXOff2 - nDstXOff;
100 :
101 : /* -------------------------------------------------------------------- */
102 : /* Allocate buffers. */
103 : /* -------------------------------------------------------------------- */
104 1298 : *ppDstBuffer = static_cast<T *>(
105 1298 : VSI_MALLOC3_VERBOSE(nDstXWidth, nDstYOff2 - nDstYOff,
106 : GDALGetDataTypeSizeBytes(eWrkDataType)));
107 1298 : if (*ppDstBuffer == nullptr)
108 : {
109 0 : return CE_Failure;
110 : }
111 1298 : T *const pDstBuffer = *ppDstBuffer;
112 :
113 : int *panSrcXOff =
114 1298 : static_cast<int *>(VSI_MALLOC2_VERBOSE(nDstXWidth, sizeof(int)));
115 :
116 1298 : if (panSrcXOff == nullptr)
117 : {
118 0 : return CE_Failure;
119 : }
120 :
121 : /* ==================================================================== */
122 : /* Precompute inner loop constants. */
123 : /* ==================================================================== */
124 840960 : for (int iDstPixel = nDstXOff; iDstPixel < nDstXOff2; ++iDstPixel)
125 : {
126 839662 : int nSrcXOff = static_cast<int>(0.5 + iDstPixel * dfXRatioDstToSrc);
127 839662 : if (nSrcXOff < nChunkXOff)
128 0 : nSrcXOff = nChunkXOff;
129 :
130 839662 : panSrcXOff[iDstPixel - nDstXOff] = nSrcXOff;
131 : }
132 :
133 : /* ==================================================================== */
134 : /* Loop over destination scanlines. */
135 : /* ==================================================================== */
136 142553 : for (int iDstLine = nDstYOff; iDstLine < nDstYOff2; ++iDstLine)
137 : {
138 141255 : int nSrcYOff = static_cast<int>(0.5 + iDstLine * dfYRatioDstToSrc);
139 141255 : if (nSrcYOff < nChunkYOff)
140 0 : nSrcYOff = nChunkYOff;
141 :
142 141255 : const T *const pSrcScanline =
143 : pChunk +
144 141255 : (static_cast<size_t>(nSrcYOff - nChunkYOff) * nChunkXSize) -
145 137798 : nChunkXOff;
146 :
147 : /* --------------------------------------------------------------------
148 : */
149 : /* Loop over destination pixels */
150 : /* --------------------------------------------------------------------
151 : */
152 141255 : T *pDstScanline =
153 141255 : pDstBuffer + static_cast<size_t>(iDstLine - nDstYOff) * nDstXWidth;
154 120247521 : for (int iDstPixel = 0; iDstPixel < nDstXWidth; ++iDstPixel)
155 : {
156 120106064 : pDstScanline[iDstPixel] = pSrcScanline[panSrcXOff[iDstPixel]];
157 : }
158 : }
159 :
160 1298 : CPLFree(panSrcXOff);
161 :
162 1298 : return CE_None;
163 : }
164 :
165 1298 : static CPLErr GDALResampleChunk_Near(const GDALOverviewResampleArgs &args,
166 : const void *pChunk, void **ppDstBuffer,
167 : GDALDataType *peDstBufferDataType)
168 : {
169 1298 : *peDstBufferDataType = args.eWrkDataType;
170 1298 : switch (args.eWrkDataType)
171 : {
172 : // For nearest resampling, as no computation is done, only the
173 : // size of the data type matters.
174 1098 : case GDT_UInt8:
175 : case GDT_Int8:
176 : {
177 1098 : CPLAssert(GDALGetDataTypeSizeBytes(args.eWrkDataType) == 1);
178 1098 : return GDALResampleChunk_NearT(
179 : args, static_cast<const uint8_t *>(pChunk),
180 1098 : reinterpret_cast<uint8_t **>(ppDstBuffer));
181 : }
182 :
183 84 : case GDT_Int16:
184 : case GDT_UInt16:
185 : case GDT_Float16:
186 : {
187 84 : CPLAssert(GDALGetDataTypeSizeBytes(args.eWrkDataType) == 2);
188 84 : return GDALResampleChunk_NearT(
189 : args, static_cast<const uint16_t *>(pChunk),
190 84 : reinterpret_cast<uint16_t **>(ppDstBuffer));
191 : }
192 :
193 68 : case GDT_CInt16:
194 : case GDT_CFloat16:
195 : case GDT_Int32:
196 : case GDT_UInt32:
197 : case GDT_Float32:
198 : {
199 68 : CPLAssert(GDALGetDataTypeSizeBytes(args.eWrkDataType) == 4);
200 68 : return GDALResampleChunk_NearT(
201 : args, static_cast<const uint32_t *>(pChunk),
202 68 : reinterpret_cast<uint32_t **>(ppDstBuffer));
203 : }
204 :
205 44 : case GDT_CInt32:
206 : case GDT_CFloat32:
207 : case GDT_Int64:
208 : case GDT_UInt64:
209 : case GDT_Float64:
210 : {
211 44 : CPLAssert(GDALGetDataTypeSizeBytes(args.eWrkDataType) == 8);
212 44 : return GDALResampleChunk_NearT(
213 : args, static_cast<const uint64_t *>(pChunk),
214 44 : reinterpret_cast<uint64_t **>(ppDstBuffer));
215 : }
216 :
217 4 : case GDT_CFloat64:
218 : {
219 4 : return GDALResampleChunk_NearT(
220 : args, static_cast<const std::complex<double> *>(pChunk),
221 4 : reinterpret_cast<std::complex<double> **>(ppDstBuffer));
222 : }
223 :
224 0 : case GDT_Unknown:
225 : case GDT_TypeCount:
226 0 : break;
227 : }
228 0 : CPLAssert(false);
229 : return CE_Failure;
230 : }
231 :
232 : namespace
233 : {
234 :
235 : // Find in the color table the entry whose RGB value is the closest
236 : // (using quadratic distance) to the test color, ignoring transparent entries.
237 3837 : int BestColorEntry(const std::vector<GDALColorEntry> &entries,
238 : const GDALColorEntry &test)
239 : {
240 3837 : int nMinDist = std::numeric_limits<int>::max();
241 3837 : size_t bestEntry = 0;
242 986109 : for (size_t i = 0; i < entries.size(); ++i)
243 : {
244 982272 : const GDALColorEntry &entry = entries[i];
245 : // Ignore transparent entries
246 982272 : if (entry.c4 == 0)
247 3237 : continue;
248 :
249 979035 : int nDist = ((test.c1 - entry.c1) * (test.c1 - entry.c1)) +
250 979035 : ((test.c2 - entry.c2) * (test.c2 - entry.c2)) +
251 979035 : ((test.c3 - entry.c3) * (test.c3 - entry.c3));
252 979035 : if (nDist < nMinDist)
253 : {
254 15847 : nMinDist = nDist;
255 15847 : bestEntry = i;
256 : }
257 : }
258 3837 : return static_cast<int>(bestEntry);
259 : }
260 :
261 7 : std::vector<GDALColorEntry> ReadColorTable(const GDALColorTable &table,
262 : int &transparentIdx)
263 : {
264 7 : std::vector<GDALColorEntry> entries(table.GetColorEntryCount());
265 :
266 7 : transparentIdx = -1;
267 7 : int i = 0;
268 1799 : for (auto &entry : entries)
269 : {
270 1792 : table.GetColorEntryAsRGB(i, &entry);
271 1792 : if (transparentIdx < 0 && entry.c4 == 0)
272 1 : transparentIdx = i;
273 1792 : ++i;
274 : }
275 7 : return entries;
276 : }
277 :
278 : } // unnamed namespace
279 :
280 : /************************************************************************/
281 : /* SQUARE() */
282 : /************************************************************************/
283 :
284 6427 : template <class T, class Tsquare = T> inline Tsquare SQUARE(T val)
285 : {
286 6427 : return static_cast<Tsquare>(val) * val;
287 : }
288 :
289 : /************************************************************************/
290 : /* ComputeIntegerRMS() */
291 : /************************************************************************/
292 : // Compute rms = sqrt(sumSquares / weight) in such a way that it is the
293 : // integer that minimizes abs(rms**2 - sumSquares / weight)
294 : template <class T, class Twork>
295 42 : inline T ComputeIntegerRMS(double sumSquares, double weight)
296 : {
297 42 : const double sumDivWeight = sumSquares / weight;
298 42 : T rms = static_cast<T>(sqrt(sumDivWeight));
299 :
300 : // Is rms**2 or (rms+1)**2 closest to sumSquares / weight ?
301 : // Naive version:
302 : // if( weight * (rms+1)**2 - sumSquares < sumSquares - weight * rms**2 )
303 42 : if (static_cast<double>(static_cast<Twork>(2) * rms * (rms + 1) + 1) <
304 42 : 2 * sumDivWeight)
305 6 : rms += 1;
306 42 : return rms;
307 : }
308 :
309 : template <class T, class Tsum> inline T ComputeIntegerRMS_4values(Tsum)
310 : {
311 : CPLAssert(false);
312 : return 0;
313 : }
314 :
315 28 : template <> inline GByte ComputeIntegerRMS_4values<GByte, int>(int sumSquares)
316 : {
317 : // It has been verified that given the correction on rms below, using
318 : // sqrt((float)((sumSquares + 1)/ 4)) or sqrt((float)sumSquares * 0.25f)
319 : // is equivalent, so use the former as it is used twice.
320 28 : const int sumSquaresPlusOneDiv4 = (sumSquares + 1) / 4;
321 28 : const float sumDivWeight = static_cast<float>(sumSquaresPlusOneDiv4);
322 28 : GByte rms = static_cast<GByte>(std::sqrt(sumDivWeight));
323 :
324 : // Is rms**2 or (rms+1)**2 closest to sumSquares / weight ?
325 : // Naive version:
326 : // if( weight * (rms+1)**2 - sumSquares < sumSquares - weight * rms**2 )
327 : // Optimized version for integer case and weight == 4
328 28 : if (static_cast<int>(rms) * (rms + 1) < sumSquaresPlusOneDiv4)
329 5 : rms += 1;
330 28 : return rms;
331 : }
332 :
333 : template <>
334 24 : inline GUInt16 ComputeIntegerRMS_4values<GUInt16, double>(double sumSquares)
335 : {
336 24 : const double sumDivWeight = sumSquares * 0.25;
337 24 : GUInt16 rms = static_cast<GUInt16>(std::sqrt(sumDivWeight));
338 :
339 : // Is rms**2 or (rms+1)**2 closest to sumSquares / weight ?
340 : // Naive version:
341 : // if( weight * (rms+1)**2 - sumSquares < sumSquares - weight * rms**2 )
342 : // Optimized version for integer case and weight == 4
343 24 : if (static_cast<GUInt32>(rms) * (rms + 1) <
344 24 : static_cast<GUInt32>(sumDivWeight + 0.25))
345 4 : rms += 1;
346 24 : return rms;
347 : }
348 :
349 : #ifdef USE_SSE2
350 :
351 : /************************************************************************/
352 : /* QuadraticMeanByteSSE2OrAVX2() */
353 : /************************************************************************/
354 :
355 : #if defined(__SSSE3__) || defined(USE_NEON_OPTIMIZATIONS)
356 : #define sse2_hadd_epi16 _mm_hadd_epi16
357 : #else
358 5064270 : inline __m128i sse2_hadd_epi16(__m128i a, __m128i b)
359 : {
360 : // Horizontal addition of adjacent pairs
361 5064270 : const auto mask = _mm_set1_epi32(0xFFFF);
362 : const auto horizLo =
363 15192800 : _mm_add_epi32(_mm_and_si128(a, mask), _mm_srli_epi32(a, 16));
364 : const auto horizHi =
365 15192800 : _mm_add_epi32(_mm_and_si128(b, mask), _mm_srli_epi32(b, 16));
366 :
367 : // Recombine low and high parts
368 5064270 : return _mm_packs_epi32(horizLo, horizHi);
369 : }
370 : #endif
371 :
372 : #ifdef __AVX2__
373 :
374 : #define set1_epi16 _mm256_set1_epi16
375 : #define set1_epi32 _mm256_set1_epi32
376 : #define setzero _mm256_setzero_si256
377 : #define set1_ps _mm256_set1_ps
378 : #define loadu_int(x) _mm256_loadu_si256(reinterpret_cast<__m256i const *>(x))
379 : #define unpacklo_epi8 _mm256_unpacklo_epi8
380 : #define unpackhi_epi8 _mm256_unpackhi_epi8
381 : #define madd_epi16 _mm256_madd_epi16
382 : #define add_epi32 _mm256_add_epi32
383 : #define mul_ps _mm256_mul_ps
384 : #define cvtepi32_ps _mm256_cvtepi32_ps
385 : #define sqrt_ps _mm256_sqrt_ps
386 : #define cvttps_epi32 _mm256_cvttps_epi32
387 : #define packs_epi32 _mm256_packs_epi32
388 : #define packus_epi32 _mm256_packus_epi32
389 : #define srli_epi32 _mm256_srli_epi32
390 : #define mullo_epi16 _mm256_mullo_epi16
391 : #define srli_epi16 _mm256_srli_epi16
392 : #define cmpgt_epi16 _mm256_cmpgt_epi16
393 : #define add_epi16 _mm256_add_epi16
394 : #define sub_epi16 _mm256_sub_epi16
395 : #define packus_epi16 _mm256_packus_epi16
396 :
397 : /* AVX2 operates on 2 separate 128-bit lanes, so we have to do shuffling */
398 : /* to get the lower 128-bit bits of what would be a true 256-bit vector register
399 : */
400 :
401 : inline __m256i FIXUP_LANES(__m256i x)
402 : {
403 : return _mm256_permute4x64_epi64(x, _MM_SHUFFLE(3, 1, 2, 0));
404 : }
405 :
406 : #define store_lo(x, y) \
407 : _mm_storeu_si128(reinterpret_cast<__m128i *>(x), \
408 : _mm256_extracti128_si256(FIXUP_LANES(y), 0))
409 : #define storeu_int(x, y) \
410 : _mm256_storeu_si256(reinterpret_cast<__m256i *>(x), FIXUP_LANES(y))
411 : #define hadd_epi16 _mm256_hadd_epi16
412 : #else
413 : #define set1_epi16 _mm_set1_epi16
414 : #define set1_epi32 _mm_set1_epi32
415 : #define setzero _mm_setzero_si128
416 : #define set1_ps _mm_set1_ps
417 : #define loadu_int(x) _mm_loadu_si128(reinterpret_cast<__m128i const *>(x))
418 : #define unpacklo_epi8 _mm_unpacklo_epi8
419 : #define unpackhi_epi8 _mm_unpackhi_epi8
420 : #define madd_epi16 _mm_madd_epi16
421 : #define add_epi32 _mm_add_epi32
422 : #define mul_ps _mm_mul_ps
423 : #define cvtepi32_ps _mm_cvtepi32_ps
424 : #define sqrt_ps _mm_sqrt_ps
425 : #define cvttps_epi32 _mm_cvttps_epi32
426 : #define packs_epi32 _mm_packs_epi32
427 : #define packus_epi32 GDAL_mm_packus_epi32
428 : #define srli_epi32 _mm_srli_epi32
429 : #define mullo_epi16 _mm_mullo_epi16
430 : #define srli_epi16 _mm_srli_epi16
431 : #define cmpgt_epi16 _mm_cmpgt_epi16
432 : #define add_epi16 _mm_add_epi16
433 : #define sub_epi16 _mm_sub_epi16
434 : #define packus_epi16 _mm_packus_epi16
435 : #define store_lo(x, y) _mm_storel_epi64(reinterpret_cast<__m128i *>(x), (y))
436 : #define storeu_int(x, y) _mm_storeu_si128(reinterpret_cast<__m128i *>(x), (y))
437 : #define hadd_epi16 sse2_hadd_epi16
438 : #endif
439 :
440 : template <class T>
441 : static int
442 : #if defined(__GNUC__)
443 : __attribute__((noinline))
444 : #endif
445 5389 : QuadraticMeanByteSSE2OrAVX2(int nDstXWidth, int nChunkXSize,
446 : const T *&CPL_RESTRICT pSrcScanlineShiftedInOut,
447 : T *CPL_RESTRICT pDstScanline)
448 : {
449 : // Optimized implementation for RMS on Byte by
450 : // processing by group of 8 output pixels, so as to use
451 : // a single _mm_sqrt_ps() call for 4 output pixels
452 5389 : const T *CPL_RESTRICT pSrcScanlineShifted = pSrcScanlineShiftedInOut;
453 :
454 5389 : int iDstPixel = 0;
455 5389 : const auto one16 = set1_epi16(1);
456 5389 : const auto one32 = set1_epi32(1);
457 5389 : const auto zero = setzero();
458 5389 : const auto minus32768 = set1_epi16(-32768);
459 :
460 5389 : constexpr int DEST_ELTS = static_cast<int>(sizeof(zero)) / 2;
461 521504 : for (; iDstPixel < nDstXWidth - (DEST_ELTS - 1); iDstPixel += DEST_ELTS)
462 : {
463 : // Load 2 * DEST_ELTS bytes from each line
464 516115 : auto firstLine = loadu_int(pSrcScanlineShifted);
465 1032230 : auto secondLine = loadu_int(pSrcScanlineShifted + nChunkXSize);
466 : // Extend those Bytes as UInt16s
467 516115 : auto firstLineLo = unpacklo_epi8(firstLine, zero);
468 516115 : auto firstLineHi = unpackhi_epi8(firstLine, zero);
469 516115 : auto secondLineLo = unpacklo_epi8(secondLine, zero);
470 516115 : auto secondLineHi = unpackhi_epi8(secondLine, zero);
471 :
472 : // Multiplication of 16 bit values and horizontal
473 : // addition of 32 bit results
474 : // [ src[2*i+0]^2 + src[2*i+1]^2 for i in range(4) ]
475 516115 : firstLineLo = madd_epi16(firstLineLo, firstLineLo);
476 516115 : firstLineHi = madd_epi16(firstLineHi, firstLineHi);
477 516115 : secondLineLo = madd_epi16(secondLineLo, secondLineLo);
478 516115 : secondLineHi = madd_epi16(secondLineHi, secondLineHi);
479 :
480 : // Vertical addition
481 516115 : const auto sumSquaresLo = add_epi32(firstLineLo, secondLineLo);
482 516115 : const auto sumSquaresHi = add_epi32(firstLineHi, secondLineHi);
483 :
484 : const auto sumSquaresPlusOneDiv4Lo =
485 1032230 : srli_epi32(add_epi32(sumSquaresLo, one32), 2);
486 : const auto sumSquaresPlusOneDiv4Hi =
487 1032230 : srli_epi32(add_epi32(sumSquaresHi, one32), 2);
488 :
489 : // Take square root and truncate/floor to int32
490 : const auto rmsLo =
491 1548340 : cvttps_epi32(sqrt_ps(cvtepi32_ps(sumSquaresPlusOneDiv4Lo)));
492 : const auto rmsHi =
493 1548340 : cvttps_epi32(sqrt_ps(cvtepi32_ps(sumSquaresPlusOneDiv4Hi)));
494 :
495 : // Merge back low and high registers with each RMS value
496 : // as a 16 bit value.
497 516115 : auto rms = packs_epi32(rmsLo, rmsHi);
498 :
499 : // Round to upper value if it minimizes the
500 : // error |rms^2 - sumSquares/4|
501 : // if( 2 * (2 * rms * (rms + 1) + 1) < sumSquares )
502 : // rms += 1;
503 : // which is equivalent to:
504 : // if( rms * (rms + 1) < (sumSquares+1) / 4 )
505 : // rms += 1;
506 : // And both left and right parts fit on 16 (unsigned) bits
507 : const auto sumSquaresPlusOneDiv4 =
508 516115 : packus_epi32(sumSquaresPlusOneDiv4Lo, sumSquaresPlusOneDiv4Hi);
509 : // cmpgt_epi16 operates on signed int16, but here
510 : // we have unsigned values, so shift them by -32768 before
511 2580580 : const auto mask = cmpgt_epi16(
512 : add_epi16(sumSquaresPlusOneDiv4, minus32768),
513 : add_epi16(mullo_epi16(rms, add_epi16(rms, one16)), minus32768));
514 : // The value of the mask will be -1 when the correction needs to be
515 : // applied
516 516115 : rms = sub_epi16(rms, mask);
517 :
518 : // Pack each 16 bit RMS value to 8 bits
519 516115 : rms = packus_epi16(rms, rms /* could be anything */);
520 516115 : store_lo(&pDstScanline[iDstPixel], rms);
521 516115 : pSrcScanlineShifted += 2 * DEST_ELTS;
522 : }
523 :
524 5389 : pSrcScanlineShiftedInOut = pSrcScanlineShifted;
525 5389 : return iDstPixel;
526 : }
527 :
528 : /************************************************************************/
529 : /* AverageByteSSE2OrAVX2() */
530 : /************************************************************************/
531 :
532 : static int
533 123976 : AverageByteSSE2OrAVX2(int nDstXWidth, int nChunkXSize,
534 : const GByte *&CPL_RESTRICT pSrcScanlineShiftedInOut,
535 : GByte *CPL_RESTRICT pDstScanline)
536 : {
537 : // Optimized implementation for average on Byte by
538 : // processing by group of 16 output pixels for SSE2, or 32 for AVX2
539 :
540 123976 : const auto zero = setzero();
541 123976 : const auto two16 = set1_epi16(2);
542 123976 : const GByte *CPL_RESTRICT pSrcScanlineShifted = pSrcScanlineShiftedInOut;
543 :
544 123976 : constexpr int DEST_ELTS = static_cast<int>(sizeof(zero)) / 2;
545 123976 : int iDstPixel = 0;
546 2656110 : for (; iDstPixel < nDstXWidth - (2 * DEST_ELTS - 1);
547 2532130 : iDstPixel += 2 * DEST_ELTS)
548 : {
549 : decltype(setzero()) average0;
550 : {
551 : // Load 2 * DEST_ELTS bytes from each line
552 2532130 : const auto firstLine = loadu_int(pSrcScanlineShifted);
553 : const auto secondLine =
554 5064270 : loadu_int(pSrcScanlineShifted + nChunkXSize);
555 : // Extend those Bytes as UInt16s
556 2532130 : const auto firstLineLo = unpacklo_epi8(firstLine, zero);
557 2532130 : const auto firstLineHi = unpackhi_epi8(firstLine, zero);
558 2532130 : const auto secondLineLo = unpacklo_epi8(secondLine, zero);
559 2532130 : const auto secondLineHi = unpackhi_epi8(secondLine, zero);
560 :
561 : // Vertical addition
562 2532130 : const auto sumLo = add_epi16(firstLineLo, secondLineLo);
563 2532130 : const auto sumHi = add_epi16(firstLineHi, secondLineHi);
564 :
565 : // Horizontal addition of adjacent pairs, and recombine low and high
566 : // parts
567 2532130 : const auto sum = hadd_epi16(sumLo, sumHi);
568 :
569 : // average = (sum + 2) / 4
570 2532130 : average0 = srli_epi16(add_epi16(sum, two16), 2);
571 :
572 2532130 : pSrcScanlineShifted += 2 * DEST_ELTS;
573 : }
574 :
575 : decltype(setzero()) average1;
576 : {
577 : // Load 2 * DEST_ELTS bytes from each line
578 2532130 : const auto firstLine = loadu_int(pSrcScanlineShifted);
579 : const auto secondLine =
580 5064270 : loadu_int(pSrcScanlineShifted + nChunkXSize);
581 : // Extend those Bytes as UInt16s
582 2532130 : const auto firstLineLo = unpacklo_epi8(firstLine, zero);
583 2532130 : const auto firstLineHi = unpackhi_epi8(firstLine, zero);
584 2532130 : const auto secondLineLo = unpacklo_epi8(secondLine, zero);
585 2532130 : const auto secondLineHi = unpackhi_epi8(secondLine, zero);
586 :
587 : // Vertical addition
588 2532130 : const auto sumLo = add_epi16(firstLineLo, secondLineLo);
589 2532130 : const auto sumHi = add_epi16(firstLineHi, secondLineHi);
590 :
591 : // Horizontal addition of adjacent pairs, and recombine low and high
592 : // parts
593 2532130 : const auto sum = hadd_epi16(sumLo, sumHi);
594 :
595 : // average = (sum + 2) / 4
596 2532130 : average1 = srli_epi16(add_epi16(sum, two16), 2);
597 :
598 2532130 : pSrcScanlineShifted += 2 * DEST_ELTS;
599 : }
600 :
601 : // Pack each 16 bit average value to 8 bits
602 2532130 : const auto average = packus_epi16(average0, average1);
603 2532130 : storeu_int(&pDstScanline[iDstPixel], average);
604 : }
605 :
606 123976 : pSrcScanlineShiftedInOut = pSrcScanlineShifted;
607 123976 : return iDstPixel;
608 : }
609 :
610 : /************************************************************************/
611 : /* QuadraticMeanUInt16SSE2() */
612 : /************************************************************************/
613 :
614 : #ifdef __SSE3__
615 : #define sse2_hadd_pd _mm_hadd_pd
616 : #else
617 185 : inline __m128d sse2_hadd_pd(__m128d a, __m128d b)
618 : {
619 : auto aLo_bLo =
620 740 : _mm_castps_pd(_mm_movelh_ps(_mm_castpd_ps(a), _mm_castpd_ps(b)));
621 : auto aHi_bHi =
622 740 : _mm_castps_pd(_mm_movehl_ps(_mm_castpd_ps(b), _mm_castpd_ps(a)));
623 185 : return _mm_add_pd(aLo_bLo, aHi_bHi); // (aLo + aHi, bLo + bHi)
624 : }
625 : #endif
626 :
627 120 : inline __m128d SQUARE_PD(__m128d x)
628 : {
629 120 : return _mm_mul_pd(x, x);
630 : }
631 :
632 : #ifdef __AVX2__
633 :
634 : inline __m256d SQUARE_PD(__m256d x)
635 : {
636 : return _mm256_mul_pd(x, x);
637 : }
638 :
639 : inline __m256d FIXUP_LANES(__m256d x)
640 : {
641 : return _mm256_permute4x64_pd(x, _MM_SHUFFLE(3, 1, 2, 0));
642 : }
643 :
644 : inline __m256 FIXUP_LANES(__m256 x)
645 : {
646 : return _mm256_castpd_ps(FIXUP_LANES(_mm256_castps_pd(x)));
647 : }
648 :
649 : #endif
650 :
651 : static int
652 14 : QuadraticMeanUInt16SSE2(int nDstXWidth, int nChunkXSize,
653 : const uint16_t *&CPL_RESTRICT pSrcScanlineShiftedInOut,
654 : uint16_t *CPL_RESTRICT pDstScanline)
655 : {
656 : // Optimized implementation for RMS on UInt16 by
657 : // processing by group of 4 output pixels.
658 14 : const uint16_t *CPL_RESTRICT pSrcScanlineShifted = pSrcScanlineShiftedInOut;
659 :
660 14 : int iDstPixel = 0;
661 14 : const auto zero = _mm_setzero_si128();
662 :
663 : #ifdef __AVX2__
664 : const auto zeroDot25 = _mm256_set1_pd(0.25);
665 : const auto zeroDot5 = _mm256_set1_pd(0.5);
666 :
667 : // The first four 0's could be anything, as we only take the bottom
668 : // 128 bits.
669 : const auto permutation = _mm256_set_epi32(0, 0, 0, 0, 6, 4, 2, 0);
670 : #else
671 14 : const auto zeroDot25 = _mm_set1_pd(0.25);
672 14 : const auto zeroDot5 = _mm_set1_pd(0.5);
673 : #endif
674 :
675 14 : constexpr int DEST_ELTS =
676 : static_cast<int>(sizeof(zero) / sizeof(uint16_t)) / 2;
677 52 : for (; iDstPixel < nDstXWidth - (DEST_ELTS - 1); iDstPixel += DEST_ELTS)
678 : {
679 : // Load 8 UInt16 from each line
680 38 : const auto firstLine = _mm_loadu_si128(
681 : reinterpret_cast<__m128i const *>(pSrcScanlineShifted));
682 : const auto secondLine =
683 38 : _mm_loadu_si128(reinterpret_cast<__m128i const *>(
684 38 : pSrcScanlineShifted + nChunkXSize));
685 :
686 : // Detect if all of the source values fit in 14 bits.
687 : // because if x < 2^14, then 4 * x^2 < 2^30 which fits in a signed int32
688 : // and we can do a much faster implementation.
689 : const auto maskTmp =
690 76 : _mm_srli_epi16(_mm_or_si128(firstLine, secondLine), 14);
691 : #if defined(__i386__) || defined(_M_IX86)
692 : uint64_t nMaskFitsIn14Bits = 0;
693 : _mm_storel_epi64(
694 : reinterpret_cast<__m128i *>(&nMaskFitsIn14Bits),
695 : _mm_packus_epi16(maskTmp, maskTmp /* could be anything */));
696 : #else
697 38 : const auto nMaskFitsIn14Bits = _mm_cvtsi128_si64(
698 : _mm_packus_epi16(maskTmp, maskTmp /* could be anything */));
699 : #endif
700 38 : if (nMaskFitsIn14Bits == 0)
701 : {
702 : // Multiplication of 16 bit values and horizontal
703 : // addition of 32 bit results
704 : const auto firstLineHSumSquare =
705 26 : _mm_madd_epi16(firstLine, firstLine);
706 : const auto secondLineHSumSquare =
707 26 : _mm_madd_epi16(secondLine, secondLine);
708 : // Vertical addition
709 : const auto sumSquares =
710 26 : _mm_add_epi32(firstLineHSumSquare, secondLineHSumSquare);
711 : // In theory we should take sqrt(sumSquares * 0.25f)
712 : // but given the rounding we do, this is equivalent to
713 : // sqrt((sumSquares + 1)/4). This has been verified exhaustively for
714 : // sumSquares <= 4 * 16383^2
715 26 : const auto one32 = _mm_set1_epi32(1);
716 : const auto sumSquaresPlusOneDiv4 =
717 52 : _mm_srli_epi32(_mm_add_epi32(sumSquares, one32), 2);
718 : // Take square root and truncate/floor to int32
719 78 : auto rms = _mm_cvttps_epi32(
720 : _mm_sqrt_ps(_mm_cvtepi32_ps(sumSquaresPlusOneDiv4)));
721 :
722 : // Round to upper value if it minimizes the
723 : // error |rms^2 - sumSquares/4|
724 : // if( 2 * (2 * rms * (rms + 1) + 1) < sumSquares )
725 : // rms += 1;
726 : // which is equivalent to:
727 : // if( rms * rms + rms < (sumSquares+1) / 4 )
728 : // rms += 1;
729 : auto mask =
730 78 : _mm_cmpgt_epi32(sumSquaresPlusOneDiv4,
731 : _mm_add_epi32(_mm_madd_epi16(rms, rms), rms));
732 26 : rms = _mm_sub_epi32(rms, mask);
733 : // Pack each 32 bit RMS value to 16 bits
734 26 : rms = _mm_packs_epi32(rms, rms /* could be anything */);
735 : _mm_storel_epi64(
736 26 : reinterpret_cast<__m128i *>(&pDstScanline[iDstPixel]), rms);
737 26 : pSrcScanlineShifted += 2 * DEST_ELTS;
738 26 : continue;
739 : }
740 :
741 : // An approach using _mm_mullo_epi16, _mm_mulhi_epu16 before extending
742 : // to 32 bit would result in 4 multiplications instead of 8, but
743 : // mullo/mulhi have a worse throughput than mul_pd.
744 :
745 : // Extend those UInt16s as UInt32s
746 12 : const auto firstLineLo = _mm_unpacklo_epi16(firstLine, zero);
747 12 : const auto firstLineHi = _mm_unpackhi_epi16(firstLine, zero);
748 12 : const auto secondLineLo = _mm_unpacklo_epi16(secondLine, zero);
749 12 : const auto secondLineHi = _mm_unpackhi_epi16(secondLine, zero);
750 :
751 : #ifdef __AVX2__
752 : // Multiplication of 32 bit values previously converted to 64 bit double
753 : const auto firstLineLoDbl = SQUARE_PD(_mm256_cvtepi32_pd(firstLineLo));
754 : const auto firstLineHiDbl = SQUARE_PD(_mm256_cvtepi32_pd(firstLineHi));
755 : const auto secondLineLoDbl =
756 : SQUARE_PD(_mm256_cvtepi32_pd(secondLineLo));
757 : const auto secondLineHiDbl =
758 : SQUARE_PD(_mm256_cvtepi32_pd(secondLineHi));
759 :
760 : // Vertical addition of squares
761 : const auto sumSquaresLo =
762 : _mm256_add_pd(firstLineLoDbl, secondLineLoDbl);
763 : const auto sumSquaresHi =
764 : _mm256_add_pd(firstLineHiDbl, secondLineHiDbl);
765 :
766 : // Horizontal addition of squares
767 : const auto sumSquares =
768 : FIXUP_LANES(_mm256_hadd_pd(sumSquaresLo, sumSquaresHi));
769 :
770 : const auto sumDivWeight = _mm256_mul_pd(sumSquares, zeroDot25);
771 :
772 : // Take square root and truncate/floor to int32
773 : auto rms = _mm256_cvttpd_epi32(_mm256_sqrt_pd(sumDivWeight));
774 : const auto rmsDouble = _mm256_cvtepi32_pd(rms);
775 : const auto right = _mm256_sub_pd(
776 : sumDivWeight, _mm256_add_pd(SQUARE_PD(rmsDouble), rmsDouble));
777 :
778 : auto mask =
779 : _mm256_castpd_ps(_mm256_cmp_pd(zeroDot5, right, _CMP_LT_OS));
780 : // Extract 32-bit from each of the 4 64-bit masks
781 : // mask = FIXUP_LANES(_mm256_shuffle_ps(mask, mask,
782 : // _MM_SHUFFLE(2,0,2,0)));
783 : mask = _mm256_permutevar8x32_ps(mask, permutation);
784 : const auto maskI = _mm_castps_si128(_mm256_extractf128_ps(mask, 0));
785 :
786 : // Apply the correction
787 : rms = _mm_sub_epi32(rms, maskI);
788 :
789 : // Pack each 32 bit RMS value to 16 bits
790 : rms = _mm_packus_epi32(rms, rms /* could be anything */);
791 : #else
792 : // Multiplication of 32 bit values previously converted to 64 bit double
793 12 : const auto firstLineLoLo = SQUARE_PD(_mm_cvtepi32_pd(firstLineLo));
794 : const auto firstLineLoHi =
795 24 : SQUARE_PD(_mm_cvtepi32_pd(_mm_srli_si128(firstLineLo, 8)));
796 12 : const auto firstLineHiLo = SQUARE_PD(_mm_cvtepi32_pd(firstLineHi));
797 : const auto firstLineHiHi =
798 24 : SQUARE_PD(_mm_cvtepi32_pd(_mm_srli_si128(firstLineHi, 8)));
799 :
800 12 : const auto secondLineLoLo = SQUARE_PD(_mm_cvtepi32_pd(secondLineLo));
801 : const auto secondLineLoHi =
802 24 : SQUARE_PD(_mm_cvtepi32_pd(_mm_srli_si128(secondLineLo, 8)));
803 12 : const auto secondLineHiLo = SQUARE_PD(_mm_cvtepi32_pd(secondLineHi));
804 : const auto secondLineHiHi =
805 24 : SQUARE_PD(_mm_cvtepi32_pd(_mm_srli_si128(secondLineHi, 8)));
806 :
807 : // Vertical addition of squares
808 12 : const auto sumSquaresLoLo = _mm_add_pd(firstLineLoLo, secondLineLoLo);
809 12 : const auto sumSquaresLoHi = _mm_add_pd(firstLineLoHi, secondLineLoHi);
810 12 : const auto sumSquaresHiLo = _mm_add_pd(firstLineHiLo, secondLineHiLo);
811 12 : const auto sumSquaresHiHi = _mm_add_pd(firstLineHiHi, secondLineHiHi);
812 :
813 : // Horizontal addition of squares
814 12 : const auto sumSquaresLo = sse2_hadd_pd(sumSquaresLoLo, sumSquaresLoHi);
815 12 : const auto sumSquaresHi = sse2_hadd_pd(sumSquaresHiLo, sumSquaresHiHi);
816 :
817 12 : const auto sumDivWeightLo = _mm_mul_pd(sumSquaresLo, zeroDot25);
818 12 : const auto sumDivWeightHi = _mm_mul_pd(sumSquaresHi, zeroDot25);
819 : // Take square root and truncate/floor to int32
820 24 : const auto rmsLo = _mm_cvttpd_epi32(_mm_sqrt_pd(sumDivWeightLo));
821 24 : const auto rmsHi = _mm_cvttpd_epi32(_mm_sqrt_pd(sumDivWeightHi));
822 :
823 : // Correctly round rms to minimize | rms^2 - sumSquares / 4 |
824 : // if( 0.5 < sumDivWeight - (rms * rms + rms) )
825 : // rms += 1;
826 12 : const auto rmsLoDouble = _mm_cvtepi32_pd(rmsLo);
827 12 : const auto rmsHiDouble = _mm_cvtepi32_pd(rmsHi);
828 24 : const auto rightLo = _mm_sub_pd(
829 : sumDivWeightLo, _mm_add_pd(SQUARE_PD(rmsLoDouble), rmsLoDouble));
830 36 : const auto rightHi = _mm_sub_pd(
831 : sumDivWeightHi, _mm_add_pd(SQUARE_PD(rmsHiDouble), rmsHiDouble));
832 :
833 24 : const auto maskLo = _mm_castpd_ps(_mm_cmplt_pd(zeroDot5, rightLo));
834 12 : const auto maskHi = _mm_castpd_ps(_mm_cmplt_pd(zeroDot5, rightHi));
835 : // The value of the mask will be -1 when the correction needs to be
836 : // applied
837 24 : const auto mask = _mm_castps_si128(_mm_shuffle_ps(
838 : maskLo, maskHi, (0 << 0) | (2 << 2) | (0 << 4) | (2 << 6)));
839 :
840 48 : auto rms = _mm_castps_si128(
841 : _mm_movelh_ps(_mm_castsi128_ps(rmsLo), _mm_castsi128_ps(rmsHi)));
842 : // Apply the correction
843 12 : rms = _mm_sub_epi32(rms, mask);
844 :
845 : // Pack each 32 bit RMS value to 16 bits
846 12 : rms = GDAL_mm_int32_to_uint16(rms);
847 : #endif
848 :
849 12 : _mm_storel_epi64(reinterpret_cast<__m128i *>(&pDstScanline[iDstPixel]),
850 : rms);
851 12 : pSrcScanlineShifted += 2 * DEST_ELTS;
852 : }
853 :
854 14 : pSrcScanlineShiftedInOut = pSrcScanlineShifted;
855 14 : return iDstPixel;
856 : }
857 :
858 : /************************************************************************/
859 : /* AverageUInt16SSE2() */
860 : /************************************************************************/
861 :
862 : static int
863 13 : AverageUInt16SSE2(int nDstXWidth, int nChunkXSize,
864 : const uint16_t *&CPL_RESTRICT pSrcScanlineShiftedInOut,
865 : uint16_t *CPL_RESTRICT pDstScanline)
866 : {
867 : // Optimized implementation for average on UInt16 by
868 : // processing by group of 8 output pixels.
869 :
870 13 : const auto mask = _mm_set1_epi32(0xFFFF);
871 13 : const auto two = _mm_set1_epi32(2);
872 13 : const uint16_t *CPL_RESTRICT pSrcScanlineShifted = pSrcScanlineShiftedInOut;
873 :
874 13 : int iDstPixel = 0;
875 13 : constexpr int DEST_ELTS = static_cast<int>(sizeof(mask) / sizeof(uint16_t));
876 25 : for (; iDstPixel < nDstXWidth - (DEST_ELTS - 1); iDstPixel += DEST_ELTS)
877 : {
878 : __m128i averageLow;
879 : // Load 8 UInt16 from each line
880 : {
881 12 : const auto firstLine = _mm_loadu_si128(
882 : reinterpret_cast<__m128i const *>(pSrcScanlineShifted));
883 : const auto secondLine =
884 12 : _mm_loadu_si128(reinterpret_cast<__m128i const *>(
885 12 : pSrcScanlineShifted + nChunkXSize));
886 :
887 : // Horizontal addition and extension to 32 bit
888 36 : const auto horizAddFirstLine = _mm_add_epi32(
889 : _mm_and_si128(firstLine, mask), _mm_srli_epi32(firstLine, 16));
890 : const auto horizAddSecondLine =
891 36 : _mm_add_epi32(_mm_and_si128(secondLine, mask),
892 : _mm_srli_epi32(secondLine, 16));
893 :
894 : // Vertical addition and average computation
895 : // average = (sum + 2) >> 2
896 24 : const auto sum = _mm_add_epi32(
897 : _mm_add_epi32(horizAddFirstLine, horizAddSecondLine), two);
898 12 : averageLow = _mm_srli_epi32(sum, 2);
899 : }
900 : // Load 8 UInt16 from each line
901 : __m128i averageHigh;
902 : {
903 : const auto firstLine =
904 12 : _mm_loadu_si128(reinterpret_cast<__m128i const *>(
905 12 : pSrcScanlineShifted + DEST_ELTS));
906 : const auto secondLine =
907 12 : _mm_loadu_si128(reinterpret_cast<__m128i const *>(
908 12 : pSrcScanlineShifted + DEST_ELTS + nChunkXSize));
909 :
910 : // Horizontal addition and extension to 32 bit
911 36 : const auto horizAddFirstLine = _mm_add_epi32(
912 : _mm_and_si128(firstLine, mask), _mm_srli_epi32(firstLine, 16));
913 : const auto horizAddSecondLine =
914 36 : _mm_add_epi32(_mm_and_si128(secondLine, mask),
915 : _mm_srli_epi32(secondLine, 16));
916 :
917 : // Vertical addition and average computation
918 : // average = (sum + 2) >> 2
919 24 : const auto sum = _mm_add_epi32(
920 : _mm_add_epi32(horizAddFirstLine, horizAddSecondLine), two);
921 12 : averageHigh = _mm_srli_epi32(sum, 2);
922 : }
923 :
924 : // Pack each 32 bit average value to 16 bits
925 12 : auto average = GDAL_mm_packus_epi32(averageLow, averageHigh);
926 12 : _mm_storeu_si128(reinterpret_cast<__m128i *>(&pDstScanline[iDstPixel]),
927 : average);
928 12 : pSrcScanlineShifted += 2 * DEST_ELTS;
929 : }
930 :
931 13 : pSrcScanlineShiftedInOut = pSrcScanlineShifted;
932 13 : return iDstPixel;
933 : }
934 :
935 : /************************************************************************/
936 : /* QuadraticMeanFloatSSE2() */
937 : /************************************************************************/
938 :
939 : #if !defined(ARM_V7)
940 :
941 : #ifdef __SSE3__
942 : #define sse2_hadd_ps _mm_hadd_ps
943 : #else
944 82 : inline __m128 sse2_hadd_ps(__m128 a, __m128 b)
945 : {
946 82 : auto aEven_bEven = _mm_shuffle_ps(a, b, _MM_SHUFFLE(2, 0, 2, 0));
947 82 : auto aOdd_bOdd = _mm_shuffle_ps(a, b, _MM_SHUFFLE(3, 1, 3, 1));
948 82 : return _mm_add_ps(aEven_bEven, aOdd_bOdd); // (aEven + aOdd, bEven + bOdd)
949 : }
950 : #endif
951 :
952 : #ifdef __AVX2__
953 : #define set1_ps _mm256_set1_ps
954 : #define loadu_ps _mm256_loadu_ps
955 : #define andnot_ps _mm256_andnot_ps
956 : #define and_ps _mm256_and_ps
957 : #define max_ps _mm256_max_ps
958 : #define shuffle_ps _mm256_shuffle_ps
959 : #define div_ps _mm256_div_ps
960 : #define cmpeq_ps(x, y) _mm256_cmp_ps((x), (y), _CMP_EQ_OQ)
961 : #define mul_ps _mm256_mul_ps
962 : #define add_ps _mm256_add_ps
963 : #define hadd_ps _mm256_hadd_ps
964 : #define sqrt_ps _mm256_sqrt_ps
965 : #define or_ps _mm256_or_ps
966 : #define unpacklo_ps _mm256_unpacklo_ps
967 : #define unpackhi_ps _mm256_unpackhi_ps
968 : #define storeu_ps _mm256_storeu_ps
969 : #define blendv_ps _mm256_blendv_ps
970 :
971 : inline __m256 SQUARE_PS(__m256 x)
972 : {
973 : return _mm256_mul_ps(x, x);
974 : }
975 :
976 : #else
977 :
978 : #define set1_ps _mm_set1_ps
979 : #define loadu_ps _mm_loadu_ps
980 : #define andnot_ps _mm_andnot_ps
981 : #define and_ps _mm_and_ps
982 : #define max_ps _mm_max_ps
983 : #define shuffle_ps _mm_shuffle_ps
984 : #define div_ps _mm_div_ps
985 : #define cmpeq_ps _mm_cmpeq_ps
986 : #define mul_ps _mm_mul_ps
987 : #define add_ps _mm_add_ps
988 : #define hadd_ps sse2_hadd_ps
989 : #define sqrt_ps _mm_sqrt_ps
990 : #define or_ps _mm_or_ps
991 : #define unpacklo_ps _mm_unpacklo_ps
992 : #define unpackhi_ps _mm_unpackhi_ps
993 : #define storeu_ps _mm_storeu_ps
994 :
995 132 : inline __m128 blendv_ps(__m128 a, __m128 b, __m128 mask)
996 : {
997 : #if defined(__SSE4_1__) || defined(__AVX__) || defined(USE_NEON_OPTIMIZATIONS)
998 : return _mm_blendv_ps(a, b, mask);
999 : #else
1000 396 : return _mm_or_ps(_mm_andnot_ps(mask, a), _mm_and_ps(mask, b));
1001 : #endif
1002 : }
1003 :
1004 528 : inline __m128 SQUARE_PS(__m128 x)
1005 : {
1006 528 : return _mm_mul_ps(x, x);
1007 : }
1008 :
1009 132 : inline __m128 FIXUP_LANES(__m128 x)
1010 : {
1011 132 : return x;
1012 : }
1013 :
1014 : #endif
1015 :
1016 : static int
1017 : #if defined(__GNUC__)
1018 : __attribute__((noinline))
1019 : #endif
1020 66 : QuadraticMeanFloatSSE2(int nDstXWidth, int nChunkXSize,
1021 : const float *&CPL_RESTRICT pSrcScanlineShiftedInOut,
1022 : float *CPL_RESTRICT pDstScanline)
1023 : {
1024 : // Optimized implementation for RMS on Float32 by
1025 : // processing by group of output pixels.
1026 66 : const float *CPL_RESTRICT pSrcScanlineShifted = pSrcScanlineShiftedInOut;
1027 :
1028 66 : int iDstPixel = 0;
1029 66 : const auto minus_zero = set1_ps(-0.0f);
1030 66 : const auto zeroDot25 = set1_ps(0.25f);
1031 66 : const auto one = set1_ps(1.0f);
1032 66 : const auto infv = set1_ps(std::numeric_limits<float>::infinity());
1033 66 : constexpr int DEST_ELTS = static_cast<int>(sizeof(one) / sizeof(float));
1034 :
1035 198 : for (; iDstPixel < nDstXWidth - (DEST_ELTS - 1); iDstPixel += DEST_ELTS)
1036 : {
1037 : // Load 2*DEST_ELTS Float32 from each line
1038 132 : auto firstLineLo = loadu_ps(pSrcScanlineShifted);
1039 132 : auto firstLineHi = loadu_ps(pSrcScanlineShifted + DEST_ELTS);
1040 132 : auto secondLineLo = loadu_ps(pSrcScanlineShifted + nChunkXSize);
1041 : auto secondLineHi =
1042 264 : loadu_ps(pSrcScanlineShifted + DEST_ELTS + nChunkXSize);
1043 :
1044 : // Take the absolute value
1045 132 : firstLineLo = andnot_ps(minus_zero, firstLineLo);
1046 132 : firstLineHi = andnot_ps(minus_zero, firstLineHi);
1047 132 : secondLineLo = andnot_ps(minus_zero, secondLineLo);
1048 132 : secondLineHi = andnot_ps(minus_zero, secondLineHi);
1049 :
1050 : auto firstLineEven =
1051 132 : shuffle_ps(firstLineLo, firstLineHi, _MM_SHUFFLE(2, 0, 2, 0));
1052 : auto firstLineOdd =
1053 132 : shuffle_ps(firstLineLo, firstLineHi, _MM_SHUFFLE(3, 1, 3, 1));
1054 : auto secondLineEven =
1055 132 : shuffle_ps(secondLineLo, secondLineHi, _MM_SHUFFLE(2, 0, 2, 0));
1056 : auto secondLineOdd =
1057 132 : shuffle_ps(secondLineLo, secondLineHi, _MM_SHUFFLE(3, 1, 3, 1));
1058 :
1059 : // Compute the maximum of each DEST_ELTS value to RMS-average
1060 396 : const auto maxV = max_ps(max_ps(firstLineEven, firstLineOdd),
1061 : max_ps(secondLineEven, secondLineOdd));
1062 :
1063 : // Normalize each value by the maximum of the DEST_ELTS ones.
1064 : // This step is important to avoid that the square evaluates to infinity
1065 : // for sufficiently big input.
1066 132 : auto invMax = div_ps(one, maxV);
1067 : // Deal with 0 being the maximum to correct division by zero
1068 : // note: comparing to -0 leads to identical results as to comparing with
1069 : // 0
1070 264 : invMax = andnot_ps(cmpeq_ps(maxV, minus_zero), invMax);
1071 :
1072 132 : firstLineEven = mul_ps(firstLineEven, invMax);
1073 132 : firstLineOdd = mul_ps(firstLineOdd, invMax);
1074 132 : secondLineEven = mul_ps(secondLineEven, invMax);
1075 132 : secondLineOdd = mul_ps(secondLineOdd, invMax);
1076 :
1077 : // Compute squares
1078 132 : firstLineEven = SQUARE_PS(firstLineEven);
1079 132 : firstLineOdd = SQUARE_PS(firstLineOdd);
1080 132 : secondLineEven = SQUARE_PS(secondLineEven);
1081 132 : secondLineOdd = SQUARE_PS(secondLineOdd);
1082 :
1083 396 : const auto sumSquares = add_ps(add_ps(firstLineEven, firstLineOdd),
1084 : add_ps(secondLineEven, secondLineOdd));
1085 :
1086 396 : auto rms = mul_ps(maxV, sqrt_ps(mul_ps(sumSquares, zeroDot25)));
1087 :
1088 : // Deal with infinity being the maximum
1089 132 : const auto maskIsInf = cmpeq_ps(maxV, infv);
1090 132 : rms = blendv_ps(rms, infv, maskIsInf);
1091 :
1092 132 : rms = FIXUP_LANES(rms);
1093 :
1094 132 : storeu_ps(&pDstScanline[iDstPixel], rms);
1095 132 : pSrcScanlineShifted += DEST_ELTS * 2;
1096 : }
1097 :
1098 66 : pSrcScanlineShiftedInOut = pSrcScanlineShifted;
1099 66 : return iDstPixel;
1100 : }
1101 :
1102 : /************************************************************************/
1103 : /* AverageFloatSSE2() */
1104 : /************************************************************************/
1105 :
1106 50 : static int AverageFloatSSE2(int nDstXWidth, int nChunkXSize,
1107 : const float *&CPL_RESTRICT pSrcScanlineShiftedInOut,
1108 : float *CPL_RESTRICT pDstScanline)
1109 : {
1110 : // Optimized implementation for average on Float32 by
1111 : // processing by group of output pixels.
1112 50 : const float *CPL_RESTRICT pSrcScanlineShifted = pSrcScanlineShiftedInOut;
1113 :
1114 50 : int iDstPixel = 0;
1115 50 : const auto zeroDot25 = _mm_set1_ps(0.25f);
1116 50 : constexpr int DEST_ELTS =
1117 : static_cast<int>(sizeof(zeroDot25) / sizeof(float));
1118 :
1119 132 : for (; iDstPixel < nDstXWidth - (DEST_ELTS - 1); iDstPixel += DEST_ELTS)
1120 : {
1121 : // Load 2 * DEST_ELTS Float32 from each line
1122 : const auto firstLineLo =
1123 82 : _mm_mul_ps(_mm_loadu_ps(pSrcScanlineShifted), zeroDot25);
1124 164 : const auto firstLineHi = _mm_mul_ps(
1125 : _mm_loadu_ps(pSrcScanlineShifted + DEST_ELTS), zeroDot25);
1126 82 : const auto secondLineLo = _mm_mul_ps(
1127 82 : _mm_loadu_ps(pSrcScanlineShifted + nChunkXSize), zeroDot25);
1128 164 : const auto secondLineHi = _mm_mul_ps(
1129 82 : _mm_loadu_ps(pSrcScanlineShifted + DEST_ELTS + nChunkXSize),
1130 : zeroDot25);
1131 :
1132 : // Vertical addition
1133 82 : const auto tmpLo = _mm_add_ps(firstLineLo, secondLineLo);
1134 82 : const auto tmpHi = _mm_add_ps(firstLineHi, secondLineHi);
1135 :
1136 : // Horizontal addition
1137 82 : const auto average = sse2_hadd_ps(tmpLo, tmpHi);
1138 :
1139 82 : _mm_storeu_ps(&pDstScanline[iDstPixel], average);
1140 82 : pSrcScanlineShifted += DEST_ELTS * 2;
1141 : }
1142 :
1143 50 : pSrcScanlineShiftedInOut = pSrcScanlineShifted;
1144 50 : return iDstPixel;
1145 : }
1146 :
1147 : /************************************************************************/
1148 : /* AverageDoubleSSE2() */
1149 : /************************************************************************/
1150 :
1151 : static int
1152 50 : AverageDoubleSSE2(int nDstXWidth, int nChunkXSize,
1153 : const double *&CPL_RESTRICT pSrcScanlineShiftedInOut,
1154 : double *CPL_RESTRICT pDstScanline)
1155 : {
1156 : // Optimized implementation for average on Float64 by
1157 : // processing by group of output pixels.
1158 50 : const double *CPL_RESTRICT pSrcScanlineShifted = pSrcScanlineShiftedInOut;
1159 :
1160 50 : int iDstPixel = 0;
1161 50 : const auto zeroDot25 = _mm_set1_pd(0.25);
1162 50 : constexpr int DEST_ELTS =
1163 : static_cast<int>(sizeof(zeroDot25) / sizeof(double));
1164 :
1165 211 : for (; iDstPixel < nDstXWidth - (DEST_ELTS - 1); iDstPixel += DEST_ELTS)
1166 : {
1167 : // Load 4 * DEST_ELTS Float64 from each line
1168 161 : const auto firstLine0 = _mm_mul_pd(
1169 : _mm_loadu_pd(pSrcScanlineShifted + 0 * DEST_ELTS), zeroDot25);
1170 322 : const auto firstLine1 = _mm_mul_pd(
1171 : _mm_loadu_pd(pSrcScanlineShifted + 1 * DEST_ELTS), zeroDot25);
1172 161 : const auto secondLine0 = _mm_mul_pd(
1173 161 : _mm_loadu_pd(pSrcScanlineShifted + 0 * DEST_ELTS + nChunkXSize),
1174 : zeroDot25);
1175 322 : const auto secondLine1 = _mm_mul_pd(
1176 161 : _mm_loadu_pd(pSrcScanlineShifted + 1 * DEST_ELTS + nChunkXSize),
1177 : zeroDot25);
1178 :
1179 : // Vertical addition
1180 161 : const auto tmp0 = _mm_add_pd(firstLine0, secondLine0);
1181 161 : const auto tmp1 = _mm_add_pd(firstLine1, secondLine1);
1182 :
1183 : // Horizontal addition
1184 161 : const auto average0 = sse2_hadd_pd(tmp0, tmp1);
1185 :
1186 161 : _mm_storeu_pd(&pDstScanline[iDstPixel + 0], average0);
1187 161 : pSrcScanlineShifted += DEST_ELTS * 2;
1188 : }
1189 :
1190 50 : pSrcScanlineShiftedInOut = pSrcScanlineShifted;
1191 50 : return iDstPixel;
1192 : }
1193 :
1194 : #endif
1195 :
1196 : #endif
1197 :
1198 : /************************************************************************/
1199 : /* GDALResampleChunk_AverageOrRMS() */
1200 : /************************************************************************/
1201 :
1202 : template <class T, class Tsum, GDALDataType eWrkDataType, bool bQuadraticMean>
1203 : static CPLErr
1204 7362 : GDALResampleChunk_AverageOrRMS_T(const GDALOverviewResampleArgs &args,
1205 : const T *pChunk, void **ppDstBuffer)
1206 : {
1207 7362 : const double dfXRatioDstToSrc = args.dfXRatioDstToSrc;
1208 7362 : const double dfYRatioDstToSrc = args.dfYRatioDstToSrc;
1209 7362 : const double dfSrcXDelta = args.dfSrcXDelta;
1210 7362 : const double dfSrcYDelta = args.dfSrcYDelta;
1211 7362 : const GByte *pabyChunkNodataMask = args.pabyChunkNodataMask;
1212 7362 : const int nChunkXOff = args.nChunkXOff;
1213 7362 : const int nChunkYOff = args.nChunkYOff;
1214 7362 : const int nChunkXSize = args.nChunkXSize;
1215 7362 : const int nChunkYSize = args.nChunkYSize;
1216 7362 : const int nDstXOff = args.nDstXOff;
1217 7362 : const int nDstXOff2 = args.nDstXOff2;
1218 7362 : const int nDstYOff = args.nDstYOff;
1219 7362 : const int nDstYOff2 = args.nDstYOff2;
1220 7362 : const char *pszResampling = args.pszResampling;
1221 7362 : bool bHasNoData = args.bHasNoData;
1222 7362 : const double dfNoDataValue = args.dfNoDataValue;
1223 7362 : const GDALColorTable *const poColorTable =
1224 : !bQuadraticMean &&
1225 : // AVERAGE_BIT2GRAYSCALE
1226 7279 : STARTS_WITH_CI(pszResampling, "AVERAGE_BIT2G")
1227 : ? nullptr
1228 : : args.poColorTable;
1229 7362 : const bool bPropagateNoData = args.bPropagateNoData;
1230 :
1231 7362 : T tNoDataValue = (!bHasNoData) ? 0 : static_cast<T>(dfNoDataValue);
1232 7362 : const T tReplacementVal =
1233 206 : bHasNoData ? static_cast<T>(GDALGetNoDataReplacementValue(
1234 72 : args.eOvrDataType, dfNoDataValue))
1235 : : 0;
1236 :
1237 7362 : const int nChunkRightXOff = nChunkXOff + nChunkXSize;
1238 7362 : const int nChunkBottomYOff = nChunkYOff + nChunkYSize;
1239 7362 : const int nDstXWidth = nDstXOff2 - nDstXOff;
1240 :
1241 : /* -------------------------------------------------------------------- */
1242 : /* Allocate buffers. */
1243 : /* -------------------------------------------------------------------- */
1244 7362 : *ppDstBuffer = static_cast<T *>(
1245 7362 : VSI_MALLOC3_VERBOSE(nDstXWidth, nDstYOff2 - nDstYOff,
1246 : GDALGetDataTypeSizeBytes(eWrkDataType)));
1247 7362 : if (*ppDstBuffer == nullptr)
1248 : {
1249 0 : return CE_Failure;
1250 : }
1251 7362 : T *const pDstBuffer = static_cast<T *>(*ppDstBuffer);
1252 :
1253 : struct PrecomputedXValue
1254 : {
1255 : int nLeftXOffShifted;
1256 : int nRightXOffShifted;
1257 : double dfLeftWeight;
1258 : double dfRightWeight;
1259 : double dfTotalWeightFullLine;
1260 : };
1261 :
1262 : PrecomputedXValue *pasSrcX = static_cast<PrecomputedXValue *>(
1263 7362 : VSI_MALLOC2_VERBOSE(nDstXWidth, sizeof(PrecomputedXValue)));
1264 :
1265 7362 : if (pasSrcX == nullptr)
1266 : {
1267 0 : return CE_Failure;
1268 : }
1269 :
1270 7362 : std::vector<GDALColorEntry> colorEntries;
1271 :
1272 7362 : if (poColorTable)
1273 : {
1274 5 : int nTransparentIdx = -1;
1275 5 : colorEntries = ReadColorTable(*poColorTable, nTransparentIdx);
1276 :
1277 : // Force c4 of nodata entry to 0 so that GDALFindBestEntry() identifies
1278 : // it as nodata value
1279 6 : if (bHasNoData && dfNoDataValue >= 0.0 &&
1280 1 : tNoDataValue < colorEntries.size())
1281 1 : colorEntries[static_cast<int>(tNoDataValue)].c4 = 0;
1282 :
1283 : // Or if we have no explicit nodata, but a color table entry that is
1284 : // transparent, consider it as the nodata value
1285 4 : else if (!bHasNoData && nTransparentIdx >= 0)
1286 : {
1287 0 : bHasNoData = true;
1288 0 : tNoDataValue = static_cast<T>(nTransparentIdx);
1289 : }
1290 : }
1291 :
1292 : /* ==================================================================== */
1293 : /* Precompute inner loop constants. */
1294 : /* ==================================================================== */
1295 7362 : bool bSrcXSpacingIsTwo = true;
1296 7362 : int nLastSrcXOff2 = -1;
1297 1689160 : for (int iDstPixel = nDstXOff; iDstPixel < nDstXOff2; ++iDstPixel)
1298 : {
1299 1681805 : const double dfSrcXOff = dfSrcXDelta + iDstPixel * dfXRatioDstToSrc;
1300 : // Apply some epsilon to avoid numerical precision issues
1301 1681805 : const int nSrcXOff =
1302 1681805 : std::max(static_cast<int>(dfSrcXOff + 1e-8), nChunkXOff);
1303 1681805 : const double dfSrcXOff2 =
1304 1681805 : dfSrcXDelta + (iDstPixel + 1) * dfXRatioDstToSrc;
1305 1681805 : int nSrcXOff2 = static_cast<int>(ceil(dfSrcXOff2 - 1e-8));
1306 1681805 : if (nSrcXOff2 == nSrcXOff)
1307 0 : nSrcXOff2++;
1308 1681805 : if (nSrcXOff2 > nChunkRightXOff)
1309 1 : nSrcXOff2 = nChunkRightXOff;
1310 :
1311 1681805 : pasSrcX[iDstPixel - nDstXOff].nLeftXOffShifted = nSrcXOff - nChunkXOff;
1312 1681805 : pasSrcX[iDstPixel - nDstXOff].nRightXOffShifted =
1313 1681805 : nSrcXOff2 - nChunkXOff;
1314 21 : pasSrcX[iDstPixel - nDstXOff].dfLeftWeight =
1315 1681805 : (nSrcXOff2 == nSrcXOff + 1) ? 1.0 : 1 - (dfSrcXOff - nSrcXOff);
1316 1681805 : pasSrcX[iDstPixel - nDstXOff].dfRightWeight =
1317 1681805 : 1 - (nSrcXOff2 - dfSrcXOff2);
1318 1681805 : pasSrcX[iDstPixel - nDstXOff].dfTotalWeightFullLine =
1319 1681805 : pasSrcX[iDstPixel - nDstXOff].dfLeftWeight;
1320 1681805 : if (nSrcXOff + 1 < nSrcXOff2)
1321 : {
1322 1681779 : pasSrcX[iDstPixel - nDstXOff].dfTotalWeightFullLine +=
1323 1681779 : nSrcXOff2 - nSrcXOff - 2;
1324 1681779 : pasSrcX[iDstPixel - nDstXOff].dfTotalWeightFullLine +=
1325 1681779 : pasSrcX[iDstPixel - nDstXOff].dfRightWeight;
1326 : }
1327 :
1328 1681805 : if (nSrcXOff2 - nSrcXOff != 2 ||
1329 1583882 : (nLastSrcXOff2 >= 0 && nLastSrcXOff2 != nSrcXOff))
1330 : {
1331 91989 : bSrcXSpacingIsTwo = false;
1332 : }
1333 1681805 : nLastSrcXOff2 = nSrcXOff2;
1334 : }
1335 :
1336 : /* ==================================================================== */
1337 : /* Loop over destination scanlines. */
1338 : /* ==================================================================== */
1339 705422 : for (int iDstLine = nDstYOff; iDstLine < nDstYOff2; ++iDstLine)
1340 : {
1341 698060 : const double dfSrcYOff = dfSrcYDelta + iDstLine * dfYRatioDstToSrc;
1342 698060 : int nSrcYOff = std::max(static_cast<int>(dfSrcYOff + 1e-8), nChunkYOff);
1343 :
1344 698060 : const double dfSrcYOff2 =
1345 698060 : dfSrcYDelta + (iDstLine + 1) * dfYRatioDstToSrc;
1346 698060 : int nSrcYOff2 = static_cast<int>(ceil(dfSrcYOff2 - 1e-8));
1347 698060 : if (nSrcYOff2 == nSrcYOff)
1348 0 : ++nSrcYOff2;
1349 698060 : if (nSrcYOff2 > nChunkBottomYOff)
1350 3 : nSrcYOff2 = nChunkBottomYOff;
1351 :
1352 698060 : T *const pDstScanline =
1353 698060 : pDstBuffer + static_cast<size_t>(iDstLine - nDstYOff) * nDstXWidth;
1354 :
1355 : /* --------------------------------------------------------------------
1356 : */
1357 : /* Loop over destination pixels */
1358 : /* --------------------------------------------------------------------
1359 : */
1360 698060 : if (poColorTable == nullptr)
1361 : {
1362 697945 : if (bSrcXSpacingIsTwo && nSrcYOff2 == nSrcYOff + 2 &&
1363 : pabyChunkNodataMask == nullptr)
1364 : {
1365 : if constexpr (eWrkDataType == GDT_UInt8 ||
1366 : eWrkDataType == GDT_UInt16)
1367 : {
1368 : // Optimized case : no nodata, overview by a factor of 2 and
1369 : // regular x and y src spacing.
1370 129392 : const T *pSrcScanlineShifted =
1371 129392 : pChunk + pasSrcX[0].nLeftXOffShifted +
1372 129392 : static_cast<size_t>(nSrcYOff - nChunkYOff) *
1373 129392 : nChunkXSize;
1374 129392 : int iDstPixel = 0;
1375 : #ifdef USE_SSE2
1376 : if constexpr (eWrkDataType == GDT_UInt8)
1377 : {
1378 : if constexpr (bQuadraticMean)
1379 : {
1380 5389 : iDstPixel = QuadraticMeanByteSSE2OrAVX2(
1381 : nDstXWidth, nChunkXSize, pSrcScanlineShifted,
1382 : pDstScanline);
1383 : }
1384 : else
1385 : {
1386 123976 : iDstPixel = AverageByteSSE2OrAVX2(
1387 : nDstXWidth, nChunkXSize, pSrcScanlineShifted,
1388 : pDstScanline);
1389 : }
1390 : }
1391 : else
1392 : {
1393 : static_assert(eWrkDataType == GDT_UInt16);
1394 : if constexpr (bQuadraticMean)
1395 : {
1396 14 : iDstPixel = QuadraticMeanUInt16SSE2(
1397 : nDstXWidth, nChunkXSize, pSrcScanlineShifted,
1398 : pDstScanline);
1399 : }
1400 : else
1401 : {
1402 13 : iDstPixel = AverageUInt16SSE2(
1403 : nDstXWidth, nChunkXSize, pSrcScanlineShifted,
1404 : pDstScanline);
1405 : }
1406 : }
1407 : #endif
1408 303851 : for (; iDstPixel < nDstXWidth; ++iDstPixel)
1409 : {
1410 174459 : Tsum nTotal = 0;
1411 : T nVal;
1412 : if constexpr (bQuadraticMean)
1413 52 : nTotal =
1414 52 : SQUARE<Tsum>(pSrcScanlineShifted[0]) +
1415 52 : SQUARE<Tsum>(pSrcScanlineShifted[1]) +
1416 52 : SQUARE<Tsum>(pSrcScanlineShifted[nChunkXSize]) +
1417 52 : SQUARE<Tsum>(
1418 52 : pSrcScanlineShifted[1 + nChunkXSize]);
1419 : else
1420 174407 : nTotal = pSrcScanlineShifted[0] +
1421 174407 : pSrcScanlineShifted[1] +
1422 174407 : pSrcScanlineShifted[nChunkXSize] +
1423 174407 : pSrcScanlineShifted[1 + nChunkXSize];
1424 :
1425 174459 : constexpr int nTotalWeight = 4;
1426 : if constexpr (bQuadraticMean)
1427 52 : nVal = ComputeIntegerRMS_4values<T>(nTotal);
1428 : else
1429 174407 : nVal = static_cast<T>((nTotal + nTotalWeight / 2) /
1430 : nTotalWeight);
1431 :
1432 : // No need to compare nVal against tNoDataValue as we
1433 : // are in a case where pabyChunkNodataMask == nullptr
1434 : // implies the absence of nodata value.
1435 174459 : pDstScanline[iDstPixel] = nVal;
1436 174459 : pSrcScanlineShifted += 2;
1437 : }
1438 : }
1439 : else
1440 : {
1441 : static_assert(eWrkDataType == GDT_Float32 ||
1442 : eWrkDataType == GDT_Float64);
1443 202 : const T *pSrcScanlineShifted =
1444 202 : pChunk + pasSrcX[0].nLeftXOffShifted +
1445 202 : static_cast<size_t>(nSrcYOff - nChunkYOff) *
1446 202 : nChunkXSize;
1447 202 : int iDstPixel = 0;
1448 : #if defined(USE_SSE2) && !defined(ARM_V7)
1449 : if constexpr (eWrkDataType == GDT_Float32)
1450 : {
1451 : static_assert(std::is_same_v<T, float>);
1452 : if constexpr (bQuadraticMean)
1453 : {
1454 66 : iDstPixel = QuadraticMeanFloatSSE2(
1455 : nDstXWidth, nChunkXSize, pSrcScanlineShifted,
1456 : pDstScanline);
1457 : }
1458 : else
1459 : {
1460 50 : iDstPixel = AverageFloatSSE2(
1461 : nDstXWidth, nChunkXSize, pSrcScanlineShifted,
1462 : pDstScanline);
1463 : }
1464 : }
1465 : else
1466 : {
1467 : if constexpr (!bQuadraticMean)
1468 : {
1469 50 : iDstPixel = AverageDoubleSSE2(
1470 : nDstXWidth, nChunkXSize, pSrcScanlineShifted,
1471 : pDstScanline);
1472 : }
1473 : }
1474 : #endif
1475 :
1476 726 : for (; iDstPixel < nDstXWidth; ++iDstPixel)
1477 : {
1478 : T nVal;
1479 :
1480 : if constexpr (bQuadraticMean)
1481 : {
1482 : // Avoid issues with large values by renormalizing
1483 96 : const auto max = std::max(
1484 420 : {std::fabs(pSrcScanlineShifted[0]),
1485 420 : std::fabs(pSrcScanlineShifted[1]),
1486 420 : std::fabs(pSrcScanlineShifted[nChunkXSize]),
1487 420 : std::fabs(
1488 420 : pSrcScanlineShifted[1 + nChunkXSize])});
1489 420 : if (max == 0)
1490 : {
1491 8 : nVal = 0;
1492 : }
1493 412 : else if (std::isinf(max))
1494 : {
1495 : // If there is at least one infinity value,
1496 : // then just summing, and taking the abs
1497 : // value will give the expected result:
1498 : // * +inf if all values are +inf
1499 : // * +inf if all values are -inf
1500 : // * NaN otherwise
1501 82 : nVal = std::fabs(
1502 82 : pSrcScanlineShifted[0] +
1503 82 : pSrcScanlineShifted[1] +
1504 82 : pSrcScanlineShifted[nChunkXSize] +
1505 82 : pSrcScanlineShifted[1 + nChunkXSize]);
1506 : }
1507 : else
1508 : {
1509 330 : const auto inv_max = static_cast<T>(1.0) / max;
1510 330 : nVal =
1511 : max *
1512 330 : std::sqrt(
1513 : static_cast<T>(0.25) *
1514 330 : (SQUARE(pSrcScanlineShifted[0] *
1515 330 : inv_max) +
1516 330 : SQUARE(pSrcScanlineShifted[1] *
1517 330 : inv_max) +
1518 330 : SQUARE(
1519 330 : pSrcScanlineShifted[nChunkXSize] *
1520 330 : inv_max) +
1521 330 : SQUARE(
1522 330 : pSrcScanlineShifted[1 +
1523 : nChunkXSize] *
1524 : inv_max)));
1525 : }
1526 : }
1527 : else
1528 : {
1529 104 : constexpr auto weight = static_cast<T>(0.25);
1530 : // Multiply each value by weight to avoid
1531 : // potential overflow
1532 104 : nVal =
1533 104 : (weight * pSrcScanlineShifted[0] +
1534 104 : weight * pSrcScanlineShifted[1] +
1535 104 : weight * pSrcScanlineShifted[nChunkXSize] +
1536 104 : weight * pSrcScanlineShifted[1 + nChunkXSize]);
1537 : }
1538 :
1539 : // No need to compare nVal against tNoDataValue as we
1540 : // are in a case where pabyChunkNodataMask == nullptr
1541 : // implies the absence of nodata value.
1542 524 : pDstScanline[iDstPixel] = nVal;
1543 524 : pSrcScanlineShifted += 2;
1544 : }
1545 129594 : }
1546 : }
1547 : else
1548 : {
1549 17 : const double dfBottomWeight =
1550 568351 : (nSrcYOff + 1 == nSrcYOff2) ? 1.0
1551 568334 : : 1.0 - (dfSrcYOff - nSrcYOff);
1552 568351 : const double dfTopWeight = 1.0 - (nSrcYOff2 - dfSrcYOff2);
1553 568351 : nSrcYOff -= nChunkYOff;
1554 568351 : nSrcYOff2 -= nChunkYOff;
1555 :
1556 568351 : double dfTotalWeightFullColumn = dfBottomWeight;
1557 568351 : if (nSrcYOff + 1 < nSrcYOff2)
1558 : {
1559 568334 : dfTotalWeightFullColumn += nSrcYOff2 - nSrcYOff - 2;
1560 568334 : dfTotalWeightFullColumn += dfTopWeight;
1561 : }
1562 :
1563 9784185 : for (int iDstPixel = 0; iDstPixel < nDstXWidth; ++iDstPixel)
1564 : {
1565 9215839 : const int nSrcXOff = pasSrcX[iDstPixel].nLeftXOffShifted;
1566 9215839 : const int nSrcXOff2 = pasSrcX[iDstPixel].nRightXOffShifted;
1567 :
1568 9215839 : double dfTotal = 0;
1569 9215839 : double dfTotalWeight = 0;
1570 9215839 : [[maybe_unused]] double dfMulFactor = 1.0;
1571 9215839 : [[maybe_unused]] double dfInvMulFactor = 1.0;
1572 9215839 : constexpr bool bUseMulFactor =
1573 : (eWrkDataType == GDT_Float32 ||
1574 : eWrkDataType == GDT_Float64);
1575 9215839 : if (pabyChunkNodataMask == nullptr)
1576 : {
1577 : if constexpr (bUseMulFactor)
1578 : {
1579 : if constexpr (bQuadraticMean)
1580 : {
1581 80 : T mulFactor = 0;
1582 80 : auto pChunkShifted =
1583 80 : pChunk +
1584 80 : static_cast<size_t>(nSrcYOff) * nChunkXSize;
1585 :
1586 240 : for (int iY = nSrcYOff; iY < nSrcYOff2;
1587 160 : ++iY, pChunkShifted += nChunkXSize)
1588 : {
1589 480 : for (int iX = nSrcXOff; iX < nSrcXOff2;
1590 : ++iX)
1591 640 : mulFactor = std::max(
1592 : mulFactor,
1593 320 : std::fabs(pChunkShifted[iX]));
1594 : }
1595 80 : dfMulFactor = double(mulFactor);
1596 142 : dfInvMulFactor =
1597 62 : dfMulFactor > 0 &&
1598 62 : std::isfinite(dfMulFactor)
1599 : ? 1.0 / dfMulFactor
1600 : : 1.0;
1601 : }
1602 : else
1603 : {
1604 139 : dfMulFactor = (nSrcYOff2 - nSrcYOff) *
1605 139 : (nSrcXOff2 - nSrcXOff);
1606 139 : dfInvMulFactor = 1.0 / dfMulFactor;
1607 : }
1608 : }
1609 :
1610 1746545 : auto pChunkShifted =
1611 227 : pChunk +
1612 1746545 : static_cast<size_t>(nSrcYOff) * nChunkXSize;
1613 1746545 : int nCounterY = nSrcYOff2 - nSrcYOff - 1;
1614 1746545 : double dfWeightY = dfBottomWeight;
1615 3493539 : while (true)
1616 : {
1617 : double dfTotalLine;
1618 : if constexpr (bQuadraticMean)
1619 : {
1620 : // Left pixel
1621 : {
1622 216 : const T val = pChunkShifted[nSrcXOff];
1623 216 : dfTotalLine =
1624 216 : SQUARE(double(val) * dfInvMulFactor) *
1625 216 : pasSrcX[iDstPixel].dfLeftWeight;
1626 : }
1627 :
1628 216 : if (nSrcXOff + 1 < nSrcXOff2)
1629 : {
1630 : // Middle pixels
1631 216 : for (int iX = nSrcXOff + 1;
1632 536 : iX < nSrcXOff2 - 1; ++iX)
1633 : {
1634 320 : const T val = pChunkShifted[iX];
1635 320 : dfTotalLine += SQUARE(double(val) *
1636 : dfInvMulFactor);
1637 : }
1638 :
1639 : // Right pixel
1640 : {
1641 216 : const T val =
1642 216 : pChunkShifted[nSrcXOff2 - 1];
1643 216 : dfTotalLine +=
1644 216 : SQUARE(double(val) *
1645 216 : dfInvMulFactor) *
1646 216 : pasSrcX[iDstPixel].dfRightWeight;
1647 : }
1648 : }
1649 : }
1650 : else
1651 : {
1652 : // Left pixel
1653 : {
1654 5239868 : const T val = pChunkShifted[nSrcXOff];
1655 5239868 : dfTotalLine =
1656 5239868 : double(val) * dfInvMulFactor *
1657 5239868 : pasSrcX[iDstPixel].dfLeftWeight;
1658 : }
1659 :
1660 5239868 : if (nSrcXOff + 1 < nSrcXOff2)
1661 : {
1662 : // Middle pixels
1663 4239442 : for (int iX = nSrcXOff + 1;
1664 64183238 : iX < nSrcXOff2 - 1; ++iX)
1665 : {
1666 59943836 : const T val = pChunkShifted[iX];
1667 59943836 : dfTotalLine +=
1668 59943836 : double(val) * dfInvMulFactor;
1669 : }
1670 :
1671 : // Right pixel
1672 : {
1673 4239442 : const T val =
1674 4239442 : pChunkShifted[nSrcXOff2 - 1];
1675 4239442 : dfTotalLine +=
1676 4239442 : double(val) * dfInvMulFactor *
1677 4239442 : pasSrcX[iDstPixel].dfRightWeight;
1678 : }
1679 : }
1680 : }
1681 :
1682 5240084 : dfTotal += dfTotalLine * dfWeightY;
1683 5240084 : --nCounterY;
1684 5240084 : if (nCounterY < 0)
1685 1746545 : break;
1686 3493539 : pChunkShifted += nChunkXSize;
1687 3493539 : dfWeightY = (nCounterY == 0) ? dfTopWeight : 1.0;
1688 : }
1689 :
1690 1746545 : dfTotalWeight =
1691 1746545 : pasSrcX[iDstPixel].dfTotalWeightFullLine *
1692 : dfTotalWeightFullColumn;
1693 : }
1694 : else
1695 : {
1696 7469294 : size_t nCount = 0;
1697 30285576 : for (int iY = nSrcYOff; iY < nSrcYOff2; ++iY)
1698 : {
1699 22816292 : const auto pChunkShifted =
1700 22816292 : pChunk + static_cast<size_t>(iY) * nChunkXSize;
1701 :
1702 22816292 : double dfTotalLine = 0;
1703 22816292 : double dfTotalWeightLine = 0;
1704 : // Left pixel
1705 : {
1706 22816292 : const int iX = nSrcXOff;
1707 22816292 : const T val = pChunkShifted[iX];
1708 22816292 : if (pabyChunkNodataMask
1709 22816292 : [iX +
1710 22816292 : static_cast<size_t>(iY) * nChunkXSize])
1711 : {
1712 17325139 : nCount++;
1713 17325139 : const double dfWeightX =
1714 17325139 : pasSrcX[iDstPixel].dfLeftWeight;
1715 17325139 : dfTotalWeightLine = dfWeightX;
1716 : if constexpr (bQuadraticMean)
1717 508 : dfTotalLine =
1718 508 : SQUARE(double(val)) * dfWeightX;
1719 : else
1720 17324631 : dfTotalLine = double(val) * dfWeightX;
1721 : }
1722 : }
1723 :
1724 22816292 : if (nSrcXOff < nSrcXOff2 - 1)
1725 : {
1726 : // Middle pixels
1727 61618372 : for (int iX = nSrcXOff + 1; iX < nSrcXOff2 - 1;
1728 : ++iX)
1729 : {
1730 38802080 : const T val = pChunkShifted[iX];
1731 38802080 : if (pabyChunkNodataMask
1732 38802080 : [iX + static_cast<size_t>(iY) *
1733 38802080 : nChunkXSize])
1734 : {
1735 28038780 : nCount++;
1736 28038780 : dfTotalWeightLine += 1;
1737 : if constexpr (bQuadraticMean)
1738 640 : dfTotalLine += SQUARE(double(val));
1739 : else
1740 28038140 : dfTotalLine += double(val);
1741 : }
1742 : }
1743 :
1744 : // Right pixel
1745 : {
1746 22816292 : const int iX = nSrcXOff2 - 1;
1747 22816292 : const T val = pChunkShifted[iX];
1748 22816292 : if (pabyChunkNodataMask
1749 22816292 : [iX + static_cast<size_t>(iY) *
1750 22816292 : nChunkXSize])
1751 : {
1752 17324495 : nCount++;
1753 17324495 : const double dfWeightX =
1754 17324495 : pasSrcX[iDstPixel].dfRightWeight;
1755 17324495 : dfTotalWeightLine += dfWeightX;
1756 : if constexpr (bQuadraticMean)
1757 503 : dfTotalLine +=
1758 503 : SQUARE(double(val)) * dfWeightX;
1759 : else
1760 17323992 : dfTotalLine +=
1761 17323992 : double(val) * dfWeightX;
1762 : }
1763 : }
1764 : }
1765 :
1766 38163300 : const double dfWeightY =
1767 : (iY == nSrcYOff) ? dfBottomWeight
1768 15347008 : : (iY + 1 == nSrcYOff2) ? dfTopWeight
1769 : : 1.0;
1770 22816292 : dfTotal += dfTotalLine * dfWeightY;
1771 22816292 : dfTotalWeight += dfTotalWeightLine * dfWeightY;
1772 : }
1773 :
1774 7469294 : if (nCount == 0 ||
1775 8 : (bPropagateNoData &&
1776 : nCount <
1777 8 : static_cast<size_t>(nSrcYOff2 - nSrcYOff) *
1778 8 : (nSrcXOff2 - nSrcXOff)))
1779 : {
1780 2307682 : pDstScanline[iDstPixel] = tNoDataValue;
1781 2307682 : continue;
1782 : }
1783 : }
1784 : if constexpr (eWrkDataType == GDT_UInt8)
1785 : {
1786 : T nVal;
1787 : if constexpr (bQuadraticMean)
1788 38 : nVal = ComputeIntegerRMS<T, int>(dfTotal,
1789 : dfTotalWeight);
1790 : else
1791 6901260 : nVal =
1792 6901260 : static_cast<T>(dfTotal / dfTotalWeight + 0.5);
1793 6901298 : if (bHasNoData && nVal == tNoDataValue)
1794 0 : nVal = tReplacementVal;
1795 6901298 : pDstScanline[iDstPixel] = nVal;
1796 : }
1797 : else if constexpr (eWrkDataType == GDT_UInt16)
1798 : {
1799 : T nVal;
1800 : if constexpr (bQuadraticMean)
1801 4 : nVal = ComputeIntegerRMS<T, uint64_t>(
1802 : dfTotal, dfTotalWeight);
1803 : else
1804 4 : nVal =
1805 4 : static_cast<T>(dfTotal / dfTotalWeight + 0.5);
1806 8 : if (bHasNoData && nVal == tNoDataValue)
1807 0 : nVal = tReplacementVal;
1808 8 : pDstScanline[iDstPixel] = nVal;
1809 : }
1810 : else
1811 : {
1812 : T nVal;
1813 : if constexpr (bQuadraticMean)
1814 : {
1815 : if constexpr (bUseMulFactor)
1816 249 : nVal = static_cast<T>(
1817 132 : dfMulFactor *
1818 249 : sqrt(dfTotal / dfTotalWeight));
1819 : else
1820 : nVal = static_cast<T>(
1821 : sqrt(dfTotal / dfTotalWeight));
1822 : }
1823 : else
1824 : {
1825 : if constexpr (bUseMulFactor)
1826 6602 : nVal = static_cast<T>(
1827 6602 : dfMulFactor * (dfTotal / dfTotalWeight));
1828 : else
1829 : nVal = static_cast<T>(dfTotal / dfTotalWeight);
1830 : }
1831 6851 : if (bHasNoData && nVal == tNoDataValue)
1832 2 : nVal = tReplacementVal;
1833 6851 : pDstScanline[iDstPixel] = nVal;
1834 : }
1835 : }
1836 : }
1837 : }
1838 : else
1839 : {
1840 115 : nSrcYOff -= nChunkYOff;
1841 115 : nSrcYOff2 -= nChunkYOff;
1842 :
1843 6590 : for (int iDstPixel = 0; iDstPixel < nDstXWidth; ++iDstPixel)
1844 : {
1845 6475 : const int nSrcXOff = pasSrcX[iDstPixel].nLeftXOffShifted;
1846 6475 : const int nSrcXOff2 = pasSrcX[iDstPixel].nRightXOffShifted;
1847 :
1848 6475 : uint64_t nTotalR = 0;
1849 6475 : uint64_t nTotalG = 0;
1850 6475 : uint64_t nTotalB = 0;
1851 6475 : size_t nCount = 0;
1852 :
1853 19425 : for (int iY = nSrcYOff; iY < nSrcYOff2; ++iY)
1854 : {
1855 38850 : for (int iX = nSrcXOff; iX < nSrcXOff2; ++iX)
1856 : {
1857 25900 : const T val =
1858 25900 : pChunk[iX + static_cast<size_t>(iY) * nChunkXSize];
1859 : // cppcheck-suppress unsignedLessThanZero
1860 25900 : if (val < 0 || val >= colorEntries.size())
1861 0 : continue;
1862 25900 : const size_t idx = static_cast<size_t>(val);
1863 25900 : const auto &entry = colorEntries[idx];
1864 25900 : if (entry.c4)
1865 : {
1866 : if constexpr (bQuadraticMean)
1867 : {
1868 800 : nTotalR += SQUARE<int>(entry.c1);
1869 800 : nTotalG += SQUARE<int>(entry.c2);
1870 800 : nTotalB += SQUARE<int>(entry.c3);
1871 800 : ++nCount;
1872 : }
1873 : else
1874 : {
1875 13328 : nTotalR += entry.c1;
1876 13328 : nTotalG += entry.c2;
1877 13328 : nTotalB += entry.c3;
1878 13328 : ++nCount;
1879 : }
1880 : }
1881 : }
1882 : }
1883 :
1884 6475 : if (nCount == 0 ||
1885 0 : (bPropagateNoData &&
1886 0 : nCount < static_cast<size_t>(nSrcYOff2 - nSrcYOff) *
1887 0 : (nSrcXOff2 - nSrcXOff)))
1888 : {
1889 2838 : pDstScanline[iDstPixel] = tNoDataValue;
1890 : }
1891 : else
1892 : {
1893 : GDALColorEntry color;
1894 : if constexpr (bQuadraticMean)
1895 : {
1896 200 : color.c1 =
1897 200 : static_cast<short>(sqrt(nTotalR / nCount) + 0.5);
1898 200 : color.c2 =
1899 200 : static_cast<short>(sqrt(nTotalG / nCount) + 0.5);
1900 200 : color.c3 =
1901 200 : static_cast<short>(sqrt(nTotalB / nCount) + 0.5);
1902 : }
1903 : else
1904 : {
1905 3437 : color.c1 =
1906 3437 : static_cast<short>((nTotalR + nCount / 2) / nCount);
1907 3437 : color.c2 =
1908 3437 : static_cast<short>((nTotalG + nCount / 2) / nCount);
1909 3437 : color.c3 =
1910 3437 : static_cast<short>((nTotalB + nCount / 2) / nCount);
1911 : }
1912 3637 : pDstScanline[iDstPixel] =
1913 3637 : static_cast<T>(BestColorEntry(colorEntries, color));
1914 : }
1915 : }
1916 : }
1917 : }
1918 :
1919 7362 : CPLFree(pasSrcX);
1920 :
1921 7362 : return CE_None;
1922 : }
1923 :
1924 : template <bool bQuadraticMean>
1925 : static CPLErr
1926 7362 : GDALResampleChunk_AverageOrRMSInternal(const GDALOverviewResampleArgs &args,
1927 : const void *pChunk, void **ppDstBuffer,
1928 : GDALDataType *peDstBufferDataType)
1929 : {
1930 7362 : *peDstBufferDataType = args.eWrkDataType;
1931 7362 : switch (args.eWrkDataType)
1932 : {
1933 7217 : case GDT_UInt8:
1934 : {
1935 : return GDALResampleChunk_AverageOrRMS_T<GByte, int, GDT_UInt8,
1936 7217 : bQuadraticMean>(
1937 7217 : args, static_cast<const GByte *>(pChunk), ppDstBuffer);
1938 : }
1939 :
1940 11 : case GDT_UInt16:
1941 : {
1942 : if constexpr (bQuadraticMean)
1943 : {
1944 : // Use double as accumulation type, because UInt32 could overflow
1945 : return GDALResampleChunk_AverageOrRMS_T<
1946 6 : GUInt16, double, GDT_UInt16, bQuadraticMean>(
1947 6 : args, static_cast<const GUInt16 *>(pChunk), ppDstBuffer);
1948 : }
1949 : else
1950 : {
1951 : return GDALResampleChunk_AverageOrRMS_T<
1952 5 : GUInt16, GUInt32, GDT_UInt16, bQuadraticMean>(
1953 5 : args, static_cast<const GUInt16 *>(pChunk), ppDstBuffer);
1954 : }
1955 : }
1956 :
1957 81 : case GDT_Float32:
1958 : {
1959 : return GDALResampleChunk_AverageOrRMS_T<float, double, GDT_Float32,
1960 81 : bQuadraticMean>(
1961 81 : args, static_cast<const float *>(pChunk), ppDstBuffer);
1962 : }
1963 :
1964 53 : case GDT_Float64:
1965 : {
1966 : return GDALResampleChunk_AverageOrRMS_T<double, double, GDT_Float64,
1967 53 : bQuadraticMean>(
1968 53 : args, static_cast<const double *>(pChunk), ppDstBuffer);
1969 : }
1970 :
1971 0 : default:
1972 0 : break;
1973 : }
1974 :
1975 0 : CPLAssert(false);
1976 : return CE_Failure;
1977 : }
1978 :
1979 : static CPLErr
1980 7362 : GDALResampleChunk_AverageOrRMS(const GDALOverviewResampleArgs &args,
1981 : const void *pChunk, void **ppDstBuffer,
1982 : GDALDataType *peDstBufferDataType)
1983 : {
1984 7362 : if (EQUAL(args.pszResampling, "RMS"))
1985 83 : return GDALResampleChunk_AverageOrRMSInternal<true>(
1986 83 : args, pChunk, ppDstBuffer, peDstBufferDataType);
1987 : else
1988 7279 : return GDALResampleChunk_AverageOrRMSInternal<false>(
1989 7279 : args, pChunk, ppDstBuffer, peDstBufferDataType);
1990 : }
1991 :
1992 : /************************************************************************/
1993 : /* GDALResampleChunk_Gauss() */
1994 : /************************************************************************/
1995 :
1996 86 : static CPLErr GDALResampleChunk_Gauss(const GDALOverviewResampleArgs &args,
1997 : const void *pChunk, void **ppDstBuffer,
1998 : GDALDataType *peDstBufferDataType)
1999 :
2000 : {
2001 86 : const double dfXRatioDstToSrc = args.dfXRatioDstToSrc;
2002 86 : const double dfYRatioDstToSrc = args.dfYRatioDstToSrc;
2003 86 : const GByte *pabyChunkNodataMask = args.pabyChunkNodataMask;
2004 86 : const int nChunkXOff = args.nChunkXOff;
2005 86 : const int nChunkXSize = args.nChunkXSize;
2006 86 : const int nChunkYOff = args.nChunkYOff;
2007 86 : const int nChunkYSize = args.nChunkYSize;
2008 86 : const int nDstXOff = args.nDstXOff;
2009 86 : const int nDstXOff2 = args.nDstXOff2;
2010 86 : const int nDstYOff = args.nDstYOff;
2011 86 : const int nDstYOff2 = args.nDstYOff2;
2012 86 : const bool bHasNoData = args.bHasNoData;
2013 86 : double dfNoDataValue = args.dfNoDataValue;
2014 86 : const GDALColorTable *poColorTable = args.poColorTable;
2015 :
2016 86 : const double *const padfChunk = static_cast<const double *>(pChunk);
2017 :
2018 86 : *ppDstBuffer =
2019 86 : VSI_MALLOC3_VERBOSE(nDstXOff2 - nDstXOff, nDstYOff2 - nDstYOff,
2020 : GDALGetDataTypeSizeBytes(GDT_Float64));
2021 86 : if (*ppDstBuffer == nullptr)
2022 : {
2023 0 : return CE_Failure;
2024 : }
2025 86 : *peDstBufferDataType = GDT_Float64;
2026 86 : double *const padfDstBuffer = static_cast<double *>(*ppDstBuffer);
2027 :
2028 : /* -------------------------------------------------------------------- */
2029 : /* Create the filter kernel and allocate scanline buffer. */
2030 : /* -------------------------------------------------------------------- */
2031 86 : int nGaussMatrixDim = 3;
2032 : const int *panGaussMatrix;
2033 86 : constexpr int anGaussMatrix3x3[] = {1, 2, 1, 2, 4, 2, 1, 2, 1};
2034 86 : constexpr int anGaussMatrix5x5[] = {1, 4, 6, 4, 1, 4, 16, 24, 16,
2035 : 4, 6, 24, 36, 24, 6, 4, 16, 24,
2036 : 16, 4, 1, 4, 6, 4, 1};
2037 86 : constexpr int anGaussMatrix7x7[] = {
2038 : 1, 6, 15, 20, 15, 6, 1, 6, 36, 90, 120, 90, 36,
2039 : 6, 15, 90, 225, 300, 225, 90, 15, 20, 120, 300, 400, 300,
2040 : 120, 20, 15, 90, 225, 300, 225, 90, 15, 6, 36, 90, 120,
2041 : 90, 36, 6, 1, 6, 15, 20, 15, 6, 1};
2042 :
2043 86 : const int nOXSize = args.nOvrXSize;
2044 86 : const int nOYSize = args.nOvrYSize;
2045 86 : const int nResYFactor = static_cast<int>(0.5 + dfYRatioDstToSrc);
2046 :
2047 : // matrix for gauss filter
2048 86 : if (nResYFactor <= 2)
2049 : {
2050 85 : panGaussMatrix = anGaussMatrix3x3;
2051 85 : nGaussMatrixDim = 3;
2052 : }
2053 1 : else if (nResYFactor <= 4)
2054 : {
2055 0 : panGaussMatrix = anGaussMatrix5x5;
2056 0 : nGaussMatrixDim = 5;
2057 : }
2058 : else
2059 : {
2060 1 : panGaussMatrix = anGaussMatrix7x7;
2061 1 : nGaussMatrixDim = 7;
2062 : }
2063 :
2064 : #ifdef DEBUG_OUT_OF_BOUND_ACCESS
2065 : int *panGaussMatrixDup = static_cast<int *>(
2066 : CPLMalloc(sizeof(int) * nGaussMatrixDim * nGaussMatrixDim));
2067 : memcpy(panGaussMatrixDup, panGaussMatrix,
2068 : sizeof(int) * nGaussMatrixDim * nGaussMatrixDim);
2069 : panGaussMatrix = panGaussMatrixDup;
2070 : #endif
2071 :
2072 86 : if (!bHasNoData)
2073 79 : dfNoDataValue = 0.0;
2074 :
2075 86 : std::vector<GDALColorEntry> colorEntries;
2076 86 : int nTransparentIdx = -1;
2077 86 : if (poColorTable)
2078 2 : colorEntries = ReadColorTable(*poColorTable, nTransparentIdx);
2079 :
2080 : // Force c4 of nodata entry to 0 so that GDALFindBestEntry() identifies
2081 : // it as nodata value.
2082 92 : if (bHasNoData && dfNoDataValue >= 0.0 &&
2083 6 : dfNoDataValue < colorEntries.size())
2084 0 : colorEntries[static_cast<int>(dfNoDataValue)].c4 = 0;
2085 :
2086 : // Or if we have no explicit nodata, but a color table entry that is
2087 : // transparent, consider it as the nodata value.
2088 86 : else if (!bHasNoData && nTransparentIdx >= 0)
2089 : {
2090 0 : dfNoDataValue = nTransparentIdx;
2091 : }
2092 :
2093 86 : const int nChunkRightXOff = nChunkXOff + nChunkXSize;
2094 86 : const int nChunkBottomYOff = nChunkYOff + nChunkYSize;
2095 86 : const int nDstXWidth = nDstXOff2 - nDstXOff;
2096 :
2097 : /* ==================================================================== */
2098 : /* Loop over destination scanlines. */
2099 : /* ==================================================================== */
2100 16488 : for (int iDstLine = nDstYOff; iDstLine < nDstYOff2; ++iDstLine)
2101 : {
2102 16402 : int nSrcYOff = static_cast<int>(0.5 + iDstLine * dfYRatioDstToSrc);
2103 16402 : int nSrcYOff2 =
2104 16402 : static_cast<int>(0.5 + (iDstLine + 1) * dfYRatioDstToSrc) + 1;
2105 :
2106 16402 : if (nSrcYOff < nChunkYOff)
2107 : {
2108 0 : nSrcYOff = nChunkYOff;
2109 0 : nSrcYOff2++;
2110 : }
2111 :
2112 16402 : const int iSizeY = nSrcYOff2 - nSrcYOff;
2113 16402 : nSrcYOff = nSrcYOff + iSizeY / 2 - nGaussMatrixDim / 2;
2114 16402 : nSrcYOff2 = nSrcYOff + nGaussMatrixDim;
2115 :
2116 16402 : if (nSrcYOff2 > nChunkBottomYOff ||
2117 16359 : (dfYRatioDstToSrc > 1 && iDstLine == nOYSize - 1))
2118 : {
2119 44 : nSrcYOff2 = std::min(nChunkBottomYOff, nSrcYOff + nGaussMatrixDim);
2120 : }
2121 :
2122 16402 : int nYShiftGaussMatrix = 0;
2123 16402 : if (nSrcYOff < nChunkYOff)
2124 : {
2125 0 : nYShiftGaussMatrix = -(nSrcYOff - nChunkYOff);
2126 0 : nSrcYOff = nChunkYOff;
2127 : }
2128 :
2129 16402 : const double *const padfSrcScanline =
2130 16402 : padfChunk + ((nSrcYOff - nChunkYOff) * nChunkXSize);
2131 16402 : const GByte *pabySrcScanlineNodataMask = nullptr;
2132 16402 : if (pabyChunkNodataMask != nullptr)
2133 152 : pabySrcScanlineNodataMask =
2134 152 : pabyChunkNodataMask + ((nSrcYOff - nChunkYOff) * nChunkXSize);
2135 :
2136 : /* --------------------------------------------------------------------
2137 : */
2138 : /* Loop over destination pixels */
2139 : /* --------------------------------------------------------------------
2140 : */
2141 16402 : double *const padfDstScanline =
2142 16402 : padfDstBuffer + (iDstLine - nDstYOff) * nDstXWidth;
2143 4149980 : for (int iDstPixel = nDstXOff; iDstPixel < nDstXOff2; ++iDstPixel)
2144 : {
2145 4133580 : int nSrcXOff = static_cast<int>(0.5 + iDstPixel * dfXRatioDstToSrc);
2146 4133580 : int nSrcXOff2 =
2147 4133580 : static_cast<int>(0.5 + (iDstPixel + 1) * dfXRatioDstToSrc) + 1;
2148 :
2149 4133580 : if (nSrcXOff < nChunkXOff)
2150 : {
2151 0 : nSrcXOff = nChunkXOff;
2152 0 : nSrcXOff2++;
2153 : }
2154 :
2155 4133580 : const int iSizeX = nSrcXOff2 - nSrcXOff;
2156 4133580 : nSrcXOff = nSrcXOff + iSizeX / 2 - nGaussMatrixDim / 2;
2157 4133580 : nSrcXOff2 = nSrcXOff + nGaussMatrixDim;
2158 :
2159 4133580 : if (nSrcXOff2 > nChunkRightXOff ||
2160 4127930 : (dfXRatioDstToSrc > 1 && iDstPixel == nOXSize - 1))
2161 : {
2162 5650 : nSrcXOff2 =
2163 5650 : std::min(nChunkRightXOff, nSrcXOff + nGaussMatrixDim);
2164 : }
2165 :
2166 4133580 : int nXShiftGaussMatrix = 0;
2167 4133580 : if (nSrcXOff < nChunkXOff)
2168 : {
2169 0 : nXShiftGaussMatrix = -(nSrcXOff - nChunkXOff);
2170 0 : nSrcXOff = nChunkXOff;
2171 : }
2172 :
2173 4133580 : if (poColorTable == nullptr)
2174 : {
2175 4133380 : double dfTotal = 0.0;
2176 4133380 : GInt64 nCount = 0;
2177 4133380 : const int *panLineWeight =
2178 4133380 : panGaussMatrix + nYShiftGaussMatrix * nGaussMatrixDim +
2179 : nXShiftGaussMatrix;
2180 :
2181 16527900 : for (int iY = nSrcYOff; iY < nSrcYOff2;
2182 12394500 : ++iY, panLineWeight += nGaussMatrixDim)
2183 : {
2184 49561300 : for (int i = 0, iX = nSrcXOff; iX < nSrcXOff2; ++iX, ++i)
2185 : {
2186 37166800 : const double val =
2187 37166800 : padfSrcScanline[iX - nChunkXOff +
2188 37166800 : static_cast<GPtrDiff_t>(iY -
2189 37166800 : nSrcYOff) *
2190 37166800 : nChunkXSize];
2191 37166800 : if (pabySrcScanlineNodataMask == nullptr ||
2192 32872 : pabySrcScanlineNodataMask[iX - nChunkXOff +
2193 32872 : static_cast<GPtrDiff_t>(
2194 32872 : iY - nSrcYOff) *
2195 32872 : nChunkXSize])
2196 : {
2197 37146100 : const int nWeight = panLineWeight[i];
2198 37146100 : dfTotal += val * nWeight;
2199 37146100 : nCount += nWeight;
2200 : }
2201 : }
2202 : }
2203 :
2204 4133380 : if (nCount == 0)
2205 : {
2206 2217 : padfDstScanline[iDstPixel - nDstXOff] = dfNoDataValue;
2207 : }
2208 : else
2209 : {
2210 4131160 : padfDstScanline[iDstPixel - nDstXOff] = dfTotal / nCount;
2211 : }
2212 : }
2213 : else
2214 : {
2215 200 : GInt64 nTotalR = 0;
2216 200 : GInt64 nTotalG = 0;
2217 200 : GInt64 nTotalB = 0;
2218 200 : GInt64 nTotalWeight = 0;
2219 200 : const int *panLineWeight =
2220 200 : panGaussMatrix + nYShiftGaussMatrix * nGaussMatrixDim +
2221 : nXShiftGaussMatrix;
2222 :
2223 780 : for (int iY = nSrcYOff; iY < nSrcYOff2;
2224 580 : ++iY, panLineWeight += nGaussMatrixDim)
2225 : {
2226 2262 : for (int i = 0, iX = nSrcXOff; iX < nSrcXOff2; ++iX, ++i)
2227 : {
2228 1682 : const double val =
2229 1682 : padfSrcScanline[iX - nChunkXOff +
2230 1682 : static_cast<GPtrDiff_t>(iY -
2231 1682 : nSrcYOff) *
2232 1682 : nChunkXSize];
2233 1682 : if (val < 0 || val >= colorEntries.size())
2234 0 : continue;
2235 :
2236 1682 : size_t idx = static_cast<size_t>(val);
2237 1682 : if (colorEntries[idx].c4)
2238 : {
2239 1682 : const int nWeight = panLineWeight[i];
2240 1682 : nTotalR +=
2241 1682 : static_cast<GInt64>(colorEntries[idx].c1) *
2242 1682 : nWeight;
2243 1682 : nTotalG +=
2244 1682 : static_cast<GInt64>(colorEntries[idx].c2) *
2245 1682 : nWeight;
2246 1682 : nTotalB +=
2247 1682 : static_cast<GInt64>(colorEntries[idx].c3) *
2248 1682 : nWeight;
2249 1682 : nTotalWeight += nWeight;
2250 : }
2251 : }
2252 : }
2253 :
2254 200 : if (nTotalWeight == 0)
2255 : {
2256 0 : padfDstScanline[iDstPixel - nDstXOff] = dfNoDataValue;
2257 : }
2258 : else
2259 : {
2260 : GDALColorEntry color;
2261 :
2262 200 : color.c1 = static_cast<short>((nTotalR + nTotalWeight / 2) /
2263 : nTotalWeight);
2264 200 : color.c2 = static_cast<short>((nTotalG + nTotalWeight / 2) /
2265 : nTotalWeight);
2266 200 : color.c3 = static_cast<short>((nTotalB + nTotalWeight / 2) /
2267 : nTotalWeight);
2268 200 : padfDstScanline[iDstPixel - nDstXOff] =
2269 200 : BestColorEntry(colorEntries, color);
2270 : }
2271 : }
2272 : }
2273 : }
2274 :
2275 : #ifdef DEBUG_OUT_OF_BOUND_ACCESS
2276 : CPLFree(panGaussMatrixDup);
2277 : #endif
2278 :
2279 86 : return CE_None;
2280 : }
2281 :
2282 : /************************************************************************/
2283 : /* GDALResampleChunk_Mode() */
2284 : /************************************************************************/
2285 :
2286 688 : template <class T> static inline bool IsSame(T a, T b)
2287 : {
2288 688 : return a == b;
2289 : }
2290 :
2291 60 : template <> bool IsSame<GFloat16>(GFloat16 a, GFloat16 b)
2292 : {
2293 60 : return a == b || (CPLIsNan(a) && CPLIsNan(b));
2294 : }
2295 :
2296 5583 : template <> bool IsSame<float>(float a, float b)
2297 : {
2298 5583 : return a == b || (std::isnan(a) && std::isnan(b));
2299 : }
2300 :
2301 1701 : template <> bool IsSame<double>(double a, double b)
2302 : {
2303 1701 : return a == b || (std::isnan(a) && std::isnan(b));
2304 : }
2305 :
2306 : namespace
2307 : {
2308 : struct ComplexFloat16
2309 : {
2310 : GFloat16 r;
2311 : GFloat16 i;
2312 : };
2313 : } // namespace
2314 :
2315 60 : template <> bool IsSame<ComplexFloat16>(ComplexFloat16 a, ComplexFloat16 b)
2316 : {
2317 90 : return (a.r == b.r && a.i == b.i) ||
2318 90 : (CPLIsNan(a.r) && CPLIsNan(a.i) && CPLIsNan(b.r) && CPLIsNan(b.i));
2319 : }
2320 :
2321 : template <>
2322 60 : bool IsSame<std::complex<float>>(std::complex<float> a, std::complex<float> b)
2323 : {
2324 120 : return a == b || (std::isnan(a.real()) && std::isnan(a.imag()) &&
2325 120 : std::isnan(b.real()) && std::isnan(b.imag()));
2326 : }
2327 :
2328 : template <>
2329 60 : bool IsSame<std::complex<double>>(std::complex<double> a,
2330 : std::complex<double> b)
2331 : {
2332 120 : return a == b || (std::isnan(a.real()) && std::isnan(a.imag()) &&
2333 120 : std::isnan(b.real()) && std::isnan(b.imag()));
2334 : }
2335 :
2336 : template <class T>
2337 182 : static CPLErr GDALResampleChunk_ModeT(const GDALOverviewResampleArgs &args,
2338 : const T *pChunk, T *const pDstBuffer)
2339 :
2340 : {
2341 182 : const double dfXRatioDstToSrc = args.dfXRatioDstToSrc;
2342 182 : const double dfYRatioDstToSrc = args.dfYRatioDstToSrc;
2343 182 : const double dfSrcXDelta = args.dfSrcXDelta;
2344 182 : const double dfSrcYDelta = args.dfSrcYDelta;
2345 182 : const GByte *pabyChunkNodataMask = args.pabyChunkNodataMask;
2346 182 : const int nChunkXOff = args.nChunkXOff;
2347 182 : const int nChunkXSize = args.nChunkXSize;
2348 182 : const int nChunkYOff = args.nChunkYOff;
2349 182 : const int nChunkYSize = args.nChunkYSize;
2350 182 : const int nDstXOff = args.nDstXOff;
2351 182 : const int nDstXOff2 = args.nDstXOff2;
2352 182 : const int nDstYOff = args.nDstYOff;
2353 182 : const int nDstYOff2 = args.nDstYOff2;
2354 182 : const bool bHasNoData = args.bHasNoData;
2355 182 : const GDALColorTable *poColorTable = args.poColorTable;
2356 182 : const int nDstXSize = nDstXOff2 - nDstXOff;
2357 :
2358 8 : T tNoDataValue;
2359 : if constexpr (std::is_same<T, ComplexFloat16>::value)
2360 : {
2361 4 : tNoDataValue.r = cpl::NumericLimits<GFloat16>::quiet_NaN();
2362 4 : tNoDataValue.i = cpl::NumericLimits<GFloat16>::quiet_NaN();
2363 : }
2364 : else if constexpr (std::is_same<T, std::complex<float>>::value ||
2365 : std::is_same<T, std::complex<double>>::value)
2366 : {
2367 : using BaseT = typename T::value_type;
2368 8 : tNoDataValue =
2369 : std::complex<BaseT>(std::numeric_limits<BaseT>::quiet_NaN(),
2370 : std::numeric_limits<BaseT>::quiet_NaN());
2371 : }
2372 170 : else if (!bHasNoData || !GDALIsValueInRange<T>(args.dfNoDataValue))
2373 169 : tNoDataValue = 0;
2374 : else
2375 1 : tNoDataValue = static_cast<T>(args.dfNoDataValue);
2376 :
2377 : using CountType = uint32_t;
2378 182 : CountType nMaxNumPx = 0;
2379 182 : T *paVals = nullptr;
2380 182 : CountType *panCounts = nullptr;
2381 :
2382 182 : const int nChunkRightXOff = nChunkXOff + nChunkXSize;
2383 182 : const int nChunkBottomYOff = nChunkYOff + nChunkYSize;
2384 364 : std::vector<int> anVals(256, 0);
2385 :
2386 : /* ==================================================================== */
2387 : /* Loop over destination scanlines. */
2388 : /* ==================================================================== */
2389 7713 : for (int iDstLine = nDstYOff; iDstLine < nDstYOff2; ++iDstLine)
2390 : {
2391 7531 : const double dfSrcYOff = dfSrcYDelta + iDstLine * dfYRatioDstToSrc;
2392 7531 : int nSrcYOff = static_cast<int>(dfSrcYOff + 1e-8);
2393 : #ifdef only_pixels_with_more_than_10_pct_participation
2394 : // When oversampling, don't take into account pixels that have a tiny
2395 : // participation in the resulting pixel
2396 : if (dfYRatioDstToSrc > 1 && dfSrcYOff - nSrcYOff > 0.9 &&
2397 : nSrcYOff < nChunkBottomYOff)
2398 : nSrcYOff++;
2399 : #endif
2400 7531 : if (nSrcYOff < nChunkYOff)
2401 0 : nSrcYOff = nChunkYOff;
2402 :
2403 7531 : const double dfSrcYOff2 =
2404 7531 : dfSrcYDelta + (iDstLine + 1) * dfYRatioDstToSrc;
2405 7531 : int nSrcYOff2 = static_cast<int>(ceil(dfSrcYOff2 - 1e-8));
2406 : #ifdef only_pixels_with_more_than_10_pct_participation
2407 : // When oversampling, don't take into account pixels that have a tiny
2408 : // participation in the resulting pixel
2409 : if (dfYRatioDstToSrc > 1 && nSrcYOff2 - dfSrcYOff2 > 0.9 &&
2410 : nSrcYOff2 > nChunkYOff)
2411 : nSrcYOff2--;
2412 : #endif
2413 7531 : if (nSrcYOff2 == nSrcYOff)
2414 0 : ++nSrcYOff2;
2415 7531 : if (nSrcYOff2 > nChunkBottomYOff)
2416 0 : nSrcYOff2 = nChunkBottomYOff;
2417 :
2418 7531 : const T *const paSrcScanline =
2419 281 : pChunk +
2420 7531 : (static_cast<GPtrDiff_t>(nSrcYOff - nChunkYOff) * nChunkXSize);
2421 7531 : const GByte *pabySrcScanlineNodataMask = nullptr;
2422 7531 : if (pabyChunkNodataMask != nullptr)
2423 1838 : pabySrcScanlineNodataMask =
2424 : pabyChunkNodataMask +
2425 1838 : static_cast<GPtrDiff_t>(nSrcYOff - nChunkYOff) * nChunkXSize;
2426 :
2427 7531 : T *const paDstScanline = pDstBuffer + (iDstLine - nDstYOff) * nDstXSize;
2428 : /* --------------------------------------------------------------------
2429 : */
2430 : /* Loop over destination pixels */
2431 : /* --------------------------------------------------------------------
2432 : */
2433 4260596 : for (int iDstPixel = nDstXOff; iDstPixel < nDstXOff2; ++iDstPixel)
2434 : {
2435 4253061 : const double dfSrcXOff = dfSrcXDelta + iDstPixel * dfXRatioDstToSrc;
2436 : // Apply some epsilon to avoid numerical precision issues
2437 4253061 : int nSrcXOff = static_cast<int>(dfSrcXOff + 1e-8);
2438 : #ifdef only_pixels_with_more_than_10_pct_participation
2439 : // When oversampling, don't take into account pixels that have a
2440 : // tiny participation in the resulting pixel
2441 : if (dfXRatioDstToSrc > 1 && dfSrcXOff - nSrcXOff > 0.9 &&
2442 : nSrcXOff < nChunkRightXOff)
2443 : nSrcXOff++;
2444 : #endif
2445 4253061 : if (nSrcXOff < nChunkXOff)
2446 0 : nSrcXOff = nChunkXOff;
2447 :
2448 4253061 : const double dfSrcXOff2 =
2449 4253061 : dfSrcXDelta + (iDstPixel + 1) * dfXRatioDstToSrc;
2450 4253061 : int nSrcXOff2 = static_cast<int>(ceil(dfSrcXOff2 - 1e-8));
2451 : #ifdef only_pixels_with_more_than_10_pct_participation
2452 : // When oversampling, don't take into account pixels that have a
2453 : // tiny participation in the resulting pixel
2454 : if (dfXRatioDstToSrc > 1 && nSrcXOff2 - dfSrcXOff2 > 0.9 &&
2455 : nSrcXOff2 > nChunkXOff)
2456 : nSrcXOff2--;
2457 : #endif
2458 4253061 : if (nSrcXOff2 == nSrcXOff)
2459 0 : nSrcXOff2++;
2460 4253061 : if (nSrcXOff2 > nChunkRightXOff)
2461 0 : nSrcXOff2 = nChunkRightXOff;
2462 :
2463 4253061 : bool bRegularProcessing = false;
2464 : if constexpr (!std::is_same<T, GByte>::value)
2465 1671 : bRegularProcessing = true;
2466 4251390 : else if (poColorTable && poColorTable->GetColorEntryCount() > 256)
2467 0 : bRegularProcessing = true;
2468 :
2469 4253061 : if (bRegularProcessing)
2470 : {
2471 : // Sanity check to make sure the allocation of paVals and
2472 : // panCounts don't overflow.
2473 : static_assert(sizeof(CountType) <= sizeof(size_t));
2474 3342 : if (nSrcYOff2 - nSrcYOff <= 0 || nSrcXOff2 - nSrcXOff <= 0 ||
2475 1671 : static_cast<CountType>(nSrcYOff2 - nSrcYOff) >
2476 1671 : (std::numeric_limits<CountType>::max() /
2477 3342 : std::max(sizeof(T), sizeof(CountType))) /
2478 1671 : static_cast<CountType>(nSrcXOff2 - nSrcXOff))
2479 : {
2480 0 : CPLError(CE_Failure, CPLE_NotSupported,
2481 : "Too big downsampling factor");
2482 0 : CPLFree(paVals);
2483 0 : CPLFree(panCounts);
2484 0 : return CE_Failure;
2485 : }
2486 1671 : const CountType nNumPx =
2487 1671 : static_cast<CountType>(nSrcYOff2 - nSrcYOff) *
2488 1671 : (nSrcXOff2 - nSrcXOff);
2489 1671 : CountType iMaxInd = 0;
2490 1671 : CountType iMaxVal = 0;
2491 :
2492 1671 : if (paVals == nullptr || nNumPx > nMaxNumPx)
2493 : {
2494 : T *paValsNew = static_cast<T *>(
2495 116 : VSI_REALLOC_VERBOSE(paVals, nNumPx * sizeof(T)));
2496 : CountType *panCountsNew =
2497 116 : static_cast<CountType *>(VSI_REALLOC_VERBOSE(
2498 : panCounts, nNumPx * sizeof(CountType)));
2499 116 : if (paValsNew != nullptr)
2500 116 : paVals = paValsNew;
2501 116 : if (panCountsNew != nullptr)
2502 116 : panCounts = panCountsNew;
2503 116 : if (paValsNew == nullptr || panCountsNew == nullptr)
2504 : {
2505 0 : CPLFree(paVals);
2506 0 : CPLFree(panCounts);
2507 0 : return CE_Failure;
2508 : }
2509 116 : nMaxNumPx = nNumPx;
2510 : }
2511 :
2512 5245 : for (int iY = nSrcYOff; iY < nSrcYOff2; ++iY)
2513 : {
2514 3574 : const GPtrDiff_t iTotYOff =
2515 3574 : static_cast<GPtrDiff_t>(iY - nSrcYOff) * nChunkXSize -
2516 3574 : nChunkXOff;
2517 11842 : for (int iX = nSrcXOff; iX < nSrcXOff2; ++iX)
2518 : {
2519 8268 : if (pabySrcScanlineNodataMask == nullptr ||
2520 1552 : pabySrcScanlineNodataMask[iX + iTotYOff])
2521 : {
2522 8247 : const T val = paSrcScanline[iX + iTotYOff];
2523 8247 : CountType i = 0; // Used after for.
2524 :
2525 : // Check array for existing entry.
2526 11611 : for (; i < iMaxInd; ++i)
2527 : {
2528 8212 : if (IsSame(paVals[i], val))
2529 : {
2530 4848 : if (++panCounts[i] > panCounts[iMaxVal])
2531 : {
2532 246 : iMaxVal = i;
2533 : }
2534 4848 : break;
2535 : }
2536 : }
2537 :
2538 : // Add to arr if entry not already there.
2539 8247 : if (i == iMaxInd)
2540 : {
2541 3399 : paVals[iMaxInd] = val;
2542 3399 : panCounts[iMaxInd] = 1;
2543 :
2544 3399 : if (iMaxInd == 0)
2545 : {
2546 1668 : iMaxVal = iMaxInd;
2547 : }
2548 :
2549 3399 : ++iMaxInd;
2550 : }
2551 : }
2552 : }
2553 : }
2554 :
2555 1671 : if (iMaxInd == 0)
2556 3 : paDstScanline[iDstPixel - nDstXOff] = tNoDataValue;
2557 : else
2558 1668 : paDstScanline[iDstPixel - nDstXOff] = paVals[iMaxVal];
2559 : }
2560 : else if constexpr (std::is_same<T, GByte>::value)
2561 : // ( eSrcDataType == GDT_UInt8 && nEntryCount < 256 )
2562 : {
2563 : // So we go here for a paletted or non-paletted byte band.
2564 : // The input values are then between 0 and 255.
2565 4251390 : int nMaxVal = 0;
2566 4251390 : int iMaxInd = -1;
2567 :
2568 : // The cost of this zeroing might be high. Perhaps we should
2569 : // just use the above generic case, and go to this one if the
2570 : // number of source pixels is large enough
2571 4251390 : std::fill(anVals.begin(), anVals.end(), 0);
2572 :
2573 12777800 : for (int iY = nSrcYOff; iY < nSrcYOff2; ++iY)
2574 : {
2575 8526440 : const GPtrDiff_t iTotYOff =
2576 8526440 : static_cast<GPtrDiff_t>(iY - nSrcYOff) * nChunkXSize -
2577 8526440 : nChunkXOff;
2578 25649600 : for (int iX = nSrcXOff; iX < nSrcXOff2; ++iX)
2579 : {
2580 17123100 : const T val = paSrcScanline[iX + iTotYOff];
2581 17123100 : if (!bHasNoData || val != tNoDataValue)
2582 : {
2583 17123100 : int nVal = static_cast<int>(val);
2584 17123100 : if (++anVals[nVal] > nMaxVal)
2585 : {
2586 : // Sum the density.
2587 : // Is it the most common value so far?
2588 17006400 : iMaxInd = nVal;
2589 17006400 : nMaxVal = anVals[nVal];
2590 : }
2591 : }
2592 : }
2593 : }
2594 :
2595 4251390 : if (iMaxInd == -1)
2596 0 : paDstScanline[iDstPixel - nDstXOff] = tNoDataValue;
2597 : else
2598 4251390 : paDstScanline[iDstPixel - nDstXOff] =
2599 : static_cast<T>(iMaxInd);
2600 : }
2601 : }
2602 : }
2603 :
2604 182 : CPLFree(paVals);
2605 182 : CPLFree(panCounts);
2606 :
2607 182 : return CE_None;
2608 : }
2609 :
2610 182 : static CPLErr GDALResampleChunk_Mode(const GDALOverviewResampleArgs &args,
2611 : const void *pChunk, void **ppDstBuffer,
2612 : GDALDataType *peDstBufferDataType)
2613 : {
2614 182 : *ppDstBuffer = VSI_MALLOC3_VERBOSE(
2615 : args.nDstXOff2 - args.nDstXOff, args.nDstYOff2 - args.nDstYOff,
2616 : GDALGetDataTypeSizeBytes(args.eWrkDataType));
2617 182 : if (*ppDstBuffer == nullptr)
2618 : {
2619 0 : return CE_Failure;
2620 : }
2621 :
2622 182 : CPLAssert(args.eSrcDataType == args.eWrkDataType);
2623 :
2624 182 : *peDstBufferDataType = args.eWrkDataType;
2625 182 : switch (args.eWrkDataType)
2626 : {
2627 : // For mode resampling, as no computation is done, only the
2628 : // size of the data type matters... except for Byte where we have
2629 : // special processing. And for floating point values
2630 66 : case GDT_UInt8:
2631 : {
2632 66 : return GDALResampleChunk_ModeT(args,
2633 : static_cast<const GByte *>(pChunk),
2634 66 : static_cast<GByte *>(*ppDstBuffer));
2635 : }
2636 :
2637 4 : case GDT_Int8:
2638 : {
2639 4 : return GDALResampleChunk_ModeT(args,
2640 : static_cast<const int8_t *>(pChunk),
2641 4 : static_cast<int8_t *>(*ppDstBuffer));
2642 : }
2643 :
2644 10 : case GDT_Int16:
2645 : case GDT_UInt16:
2646 : {
2647 10 : CPLAssert(GDALGetDataTypeSizeBytes(args.eWrkDataType) == 2);
2648 10 : return GDALResampleChunk_ModeT(
2649 : args, static_cast<const uint16_t *>(pChunk),
2650 10 : static_cast<uint16_t *>(*ppDstBuffer));
2651 : }
2652 :
2653 15 : case GDT_CInt16:
2654 : case GDT_Int32:
2655 : case GDT_UInt32:
2656 : {
2657 15 : CPLAssert(GDALGetDataTypeSizeBytes(args.eWrkDataType) == 4);
2658 15 : return GDALResampleChunk_ModeT(
2659 : args, static_cast<const uint32_t *>(pChunk),
2660 15 : static_cast<uint32_t *>(*ppDstBuffer));
2661 : }
2662 :
2663 12 : case GDT_CInt32:
2664 : case GDT_Int64:
2665 : case GDT_UInt64:
2666 : {
2667 12 : CPLAssert(GDALGetDataTypeSizeBytes(args.eWrkDataType) == 8);
2668 12 : return GDALResampleChunk_ModeT(
2669 : args, static_cast<const uint64_t *>(pChunk),
2670 12 : static_cast<uint64_t *>(*ppDstBuffer));
2671 : }
2672 :
2673 4 : case GDT_Float16:
2674 : {
2675 4 : return GDALResampleChunk_ModeT(
2676 : args, static_cast<const GFloat16 *>(pChunk),
2677 4 : static_cast<GFloat16 *>(*ppDstBuffer));
2678 : }
2679 :
2680 35 : case GDT_Float32:
2681 : {
2682 35 : return GDALResampleChunk_ModeT(args,
2683 : static_cast<const float *>(pChunk),
2684 35 : static_cast<float *>(*ppDstBuffer));
2685 : }
2686 :
2687 24 : case GDT_Float64:
2688 : {
2689 24 : return GDALResampleChunk_ModeT(args,
2690 : static_cast<const double *>(pChunk),
2691 24 : static_cast<double *>(*ppDstBuffer));
2692 : }
2693 :
2694 4 : case GDT_CFloat16:
2695 : {
2696 4 : return GDALResampleChunk_ModeT(
2697 : args, static_cast<const ComplexFloat16 *>(pChunk),
2698 4 : static_cast<ComplexFloat16 *>(*ppDstBuffer));
2699 : }
2700 :
2701 4 : case GDT_CFloat32:
2702 : {
2703 4 : return GDALResampleChunk_ModeT(
2704 : args, static_cast<const std::complex<float> *>(pChunk),
2705 4 : static_cast<std::complex<float> *>(*ppDstBuffer));
2706 : }
2707 :
2708 4 : case GDT_CFloat64:
2709 : {
2710 4 : return GDALResampleChunk_ModeT(
2711 : args, static_cast<const std::complex<double> *>(pChunk),
2712 4 : static_cast<std::complex<double> *>(*ppDstBuffer));
2713 : }
2714 :
2715 0 : case GDT_Unknown:
2716 : case GDT_TypeCount:
2717 0 : break;
2718 : }
2719 :
2720 0 : CPLAssert(false);
2721 : return CE_Failure;
2722 : }
2723 :
2724 : /************************************************************************/
2725 : /* GDALResampleConvolutionHorizontal() */
2726 : /************************************************************************/
2727 :
2728 : template <class T>
2729 : static inline double
2730 46038 : GDALResampleConvolutionHorizontal(const T *pChunk, const double *padfWeights,
2731 : int nSrcPixelCount)
2732 : {
2733 46038 : double dfVal1 = 0.0;
2734 46038 : double dfVal2 = 0.0;
2735 46038 : int i = 0; // Used after for.
2736 : // Intel Compiler 2024.0.2.29 (maybe other versions?) crashes on this
2737 : // manually (untypical) unrolled loop in -O2 and -O3:
2738 : // https://github.com/OSGeo/gdal/issues/9508
2739 : #if !defined(__INTEL_CLANG_COMPILER)
2740 92396 : for (; i < nSrcPixelCount - 3; i += 4)
2741 : {
2742 46358 : dfVal1 += double(pChunk[i + 0]) * padfWeights[i];
2743 46358 : dfVal1 += double(pChunk[i + 1]) * padfWeights[i + 1];
2744 46358 : dfVal2 += double(pChunk[i + 2]) * padfWeights[i + 2];
2745 46358 : dfVal2 += double(pChunk[i + 3]) * padfWeights[i + 3];
2746 : }
2747 : #endif
2748 48662 : for (; i < nSrcPixelCount; ++i)
2749 : {
2750 2624 : dfVal1 += double(pChunk[i]) * padfWeights[i];
2751 : }
2752 46038 : return dfVal1 + dfVal2;
2753 : }
2754 :
2755 : template <class T, bool bHasNaN>
2756 46368 : static inline void GDALResampleConvolutionHorizontalWithMask(
2757 : const T *pChunk, const GByte *pabyMask, const double *padfWeights,
2758 : int nSrcPixelCount, double &dfWeightValMaskSum, double &dfWeightMaskSum,
2759 : double &dfWeightSum)
2760 : {
2761 46368 : dfWeightValMaskSum = 0;
2762 46368 : dfWeightMaskSum = 0;
2763 46368 : dfWeightSum = 0;
2764 46368 : int i = 0;
2765 103804 : for (; i < nSrcPixelCount - 3; i += 4)
2766 : {
2767 57436 : double dfWeightMask0 = padfWeights[i + 0] * pabyMask[i + 0];
2768 57436 : double dfWeightMask1 = padfWeights[i + 1] * pabyMask[i + 1];
2769 57436 : double dfWeightMask2 = padfWeights[i + 2] * pabyMask[i + 2];
2770 57436 : double dfWeightMask3 = padfWeights[i + 3] * pabyMask[i + 3];
2771 :
2772 229744 : const auto MulNaNAware = [](double v, double &w, double &val)
2773 : {
2774 : if constexpr (bHasNaN)
2775 : {
2776 14848 : if (std::isnan(v))
2777 : {
2778 76 : w = 0;
2779 76 : return;
2780 : }
2781 : }
2782 14772 : val += v * w;
2783 : };
2784 :
2785 57436 : MulNaNAware(double(pChunk[i + 0]), dfWeightMask0, dfWeightValMaskSum);
2786 57436 : MulNaNAware(double(pChunk[i + 1]), dfWeightMask1, dfWeightValMaskSum);
2787 57436 : MulNaNAware(double(pChunk[i + 2]), dfWeightMask2, dfWeightValMaskSum);
2788 57436 : MulNaNAware(double(pChunk[i + 3]), dfWeightMask3, dfWeightValMaskSum);
2789 57436 : dfWeightMaskSum +=
2790 57436 : dfWeightMask0 + dfWeightMask1 + dfWeightMask2 + dfWeightMask3;
2791 57436 : dfWeightSum += padfWeights[i + 0] + padfWeights[i + 1] +
2792 57436 : padfWeights[i + 2] + padfWeights[i + 3];
2793 : }
2794 64874 : for (; i < nSrcPixelCount; ++i)
2795 : {
2796 18506 : const double dfWeightMask = padfWeights[i] * pabyMask[i];
2797 : if constexpr (bHasNaN)
2798 : {
2799 1920 : if (!std::isnan(pChunk[i]))
2800 : {
2801 1920 : dfWeightValMaskSum += double(pChunk[i]) * dfWeightMask;
2802 1920 : dfWeightMaskSum += dfWeightMask;
2803 1920 : dfWeightSum += padfWeights[i];
2804 : }
2805 : }
2806 : else
2807 : {
2808 16586 : dfWeightValMaskSum += double(pChunk[i]) * dfWeightMask;
2809 16586 : dfWeightMaskSum += dfWeightMask;
2810 16586 : dfWeightSum += padfWeights[i];
2811 : }
2812 : }
2813 46368 : }
2814 :
2815 : template <class T, bool bHasNaN>
2816 1341366 : static inline void GDALResampleConvolutionHorizontal_3rows(
2817 : const T *pChunkRow1, const T *pChunkRow2, const T *pChunkRow3,
2818 : const double *padfWeights, int nSrcPixelCount, double &dfRes1,
2819 : double &dfRes2, double &dfRes3)
2820 : {
2821 1341366 : double dfVal1 = 0.0;
2822 1341366 : double dfVal2 = 0.0;
2823 1341366 : double dfVal3 = 0.0;
2824 1341366 : double dfVal4 = 0.0;
2825 1341366 : double dfVal5 = 0.0;
2826 1341366 : double dfVal6 = 0.0;
2827 1341366 : int i = 0; // Used after for.
2828 :
2829 16866840 : const auto MulNaNAware = [](double a, double w)
2830 : {
2831 : if constexpr (bHasNaN)
2832 : {
2833 0 : if (std::isnan(a))
2834 0 : return 0.0;
2835 : }
2836 16866900 : return a * w;
2837 : };
2838 :
2839 2736937 : for (; i < nSrcPixelCount - 3; i += 4)
2840 : {
2841 1395570 : dfVal1 += MulNaNAware(double(pChunkRow1[i + 0]), padfWeights[i + 0]);
2842 1395570 : dfVal1 += MulNaNAware(double(pChunkRow1[i + 1]), padfWeights[i + 1]);
2843 1395570 : dfVal2 += MulNaNAware(double(pChunkRow1[i + 2]), padfWeights[i + 2]);
2844 1395570 : dfVal2 += MulNaNAware(double(pChunkRow1[i + 3]), padfWeights[i + 3]);
2845 1395570 : dfVal3 += MulNaNAware(double(pChunkRow2[i + 0]), padfWeights[i + 0]);
2846 1395570 : dfVal3 += MulNaNAware(double(pChunkRow2[i + 1]), padfWeights[i + 1]);
2847 1395570 : dfVal4 += MulNaNAware(double(pChunkRow2[i + 2]), padfWeights[i + 2]);
2848 1395570 : dfVal4 += MulNaNAware(double(pChunkRow2[i + 3]), padfWeights[i + 3]);
2849 1395570 : dfVal5 += MulNaNAware(double(pChunkRow3[i + 0]), padfWeights[i + 0]);
2850 1395570 : dfVal5 += MulNaNAware(double(pChunkRow3[i + 1]), padfWeights[i + 1]);
2851 1395570 : dfVal6 += MulNaNAware(double(pChunkRow3[i + 2]), padfWeights[i + 2]);
2852 1395570 : dfVal6 += MulNaNAware(double(pChunkRow3[i + 3]), padfWeights[i + 3]);
2853 : }
2854 1381377 : for (; i < nSrcPixelCount; ++i)
2855 : {
2856 40011 : dfVal1 += MulNaNAware(double(pChunkRow1[i]), padfWeights[i]);
2857 40011 : dfVal3 += MulNaNAware(double(pChunkRow2[i]), padfWeights[i]);
2858 40011 : dfVal5 += MulNaNAware(double(pChunkRow3[i]), padfWeights[i]);
2859 : }
2860 1341366 : dfRes1 = dfVal1 + dfVal2;
2861 1341366 : dfRes2 = dfVal3 + dfVal4;
2862 1341366 : dfRes3 = dfVal5 + dfVal6;
2863 1341366 : }
2864 :
2865 : template <class T, bool bHasNaN>
2866 18980 : static inline void GDALResampleConvolutionHorizontalPixelCountLess8_3rows(
2867 : const T *pChunkRow1, const T *pChunkRow2, const T *pChunkRow3,
2868 : const double *padfWeights, int nSrcPixelCount, double &dfRes1,
2869 : double &dfRes2, double &dfRes3)
2870 : {
2871 18980 : GDALResampleConvolutionHorizontal_3rows<T, bHasNaN>(
2872 : pChunkRow1, pChunkRow2, pChunkRow3, padfWeights, nSrcPixelCount, dfRes1,
2873 : dfRes2, dfRes3);
2874 18980 : }
2875 :
2876 : template <class T, bool bHasNaN>
2877 1256690 : static inline void GDALResampleConvolutionHorizontalPixelCount4_3rows(
2878 : const T *pChunkRow1, const T *pChunkRow2, const T *pChunkRow3,
2879 : const double *padfWeights, double &dfRes1, double &dfRes2, double &dfRes3)
2880 : {
2881 1256690 : GDALResampleConvolutionHorizontal_3rows<T, bHasNaN>(
2882 : pChunkRow1, pChunkRow2, pChunkRow3, padfWeights, 4, dfRes1, dfRes2,
2883 : dfRes3);
2884 1256690 : }
2885 :
2886 : /************************************************************************/
2887 : /* GDALResampleConvolutionVertical() */
2888 : /************************************************************************/
2889 :
2890 : template <class T>
2891 : static inline double
2892 472545 : GDALResampleConvolutionVertical(const T *pChunk, size_t nStride,
2893 : const double *padfWeights, int nSrcLineCount)
2894 : {
2895 472545 : double dfVal1 = 0.0;
2896 472545 : double dfVal2 = 0.0;
2897 472545 : int i = 0;
2898 472545 : size_t j = 0;
2899 936186 : for (; i < nSrcLineCount - 3; i += 4, j += 4 * nStride)
2900 : {
2901 463641 : dfVal1 += pChunk[j + 0 * nStride] * padfWeights[i + 0];
2902 463641 : dfVal1 += pChunk[j + 1 * nStride] * padfWeights[i + 1];
2903 463641 : dfVal2 += pChunk[j + 2 * nStride] * padfWeights[i + 2];
2904 463641 : dfVal2 += pChunk[j + 3 * nStride] * padfWeights[i + 3];
2905 : }
2906 526884 : for (; i < nSrcLineCount; ++i, j += nStride)
2907 : {
2908 54339 : dfVal1 += pChunk[j] * padfWeights[i];
2909 : }
2910 472545 : return dfVal1 + dfVal2;
2911 : }
2912 :
2913 : template <class T>
2914 2930610 : static inline void GDALResampleConvolutionVertical_2cols(
2915 : const T *pChunk, size_t nStride, const double *padfWeights,
2916 : int nSrcLineCount, double &dfRes1, double &dfRes2)
2917 : {
2918 2930610 : double dfVal1 = 0.0;
2919 2930610 : double dfVal2 = 0.0;
2920 2930610 : double dfVal3 = 0.0;
2921 2930610 : double dfVal4 = 0.0;
2922 2930610 : int i = 0;
2923 2930610 : size_t j = 0;
2924 5863170 : for (; i < nSrcLineCount - 3; i += 4, j += 4 * nStride)
2925 : {
2926 2932560 : dfVal1 += pChunk[j + 0 + 0 * nStride] * padfWeights[i + 0];
2927 2932560 : dfVal3 += pChunk[j + 1 + 0 * nStride] * padfWeights[i + 0];
2928 2932560 : dfVal1 += pChunk[j + 0 + 1 * nStride] * padfWeights[i + 1];
2929 2932560 : dfVal3 += pChunk[j + 1 + 1 * nStride] * padfWeights[i + 1];
2930 2932560 : dfVal2 += pChunk[j + 0 + 2 * nStride] * padfWeights[i + 2];
2931 2932560 : dfVal4 += pChunk[j + 1 + 2 * nStride] * padfWeights[i + 2];
2932 2932560 : dfVal2 += pChunk[j + 0 + 3 * nStride] * padfWeights[i + 3];
2933 2932560 : dfVal4 += pChunk[j + 1 + 3 * nStride] * padfWeights[i + 3];
2934 : }
2935 3053490 : for (; i < nSrcLineCount; ++i, j += nStride)
2936 : {
2937 122880 : dfVal1 += pChunk[j + 0] * padfWeights[i];
2938 122880 : dfVal3 += pChunk[j + 1] * padfWeights[i];
2939 : }
2940 2930610 : dfRes1 = dfVal1 + dfVal2;
2941 2930610 : dfRes2 = dfVal3 + dfVal4;
2942 2930610 : }
2943 :
2944 : #ifdef USE_SSE2
2945 :
2946 : #ifdef __AVX__
2947 : /************************************************************************/
2948 : /* GDALResampleConvolutionVertical_16cols<T> */
2949 : /************************************************************************/
2950 :
2951 : template <class T>
2952 : static inline void
2953 : GDALResampleConvolutionVertical_16cols(const T *pChunk, size_t nStride,
2954 : const double *padfWeights,
2955 : int nSrcLineCount, float *afDest)
2956 : {
2957 : int i = 0;
2958 : size_t j = 0;
2959 : XMMReg4Double v_acc0 = XMMReg4Double::Zero();
2960 : XMMReg4Double v_acc1 = XMMReg4Double::Zero();
2961 : XMMReg4Double v_acc2 = XMMReg4Double::Zero();
2962 : XMMReg4Double v_acc3 = XMMReg4Double::Zero();
2963 : for (; i < nSrcLineCount - 3; i += 4, j += 4 * nStride)
2964 : {
2965 : XMMReg4Double w0 =
2966 : XMMReg4Double::Load1ValHighAndLow(padfWeights + i + 0);
2967 : XMMReg4Double w1 =
2968 : XMMReg4Double::Load1ValHighAndLow(padfWeights + i + 1);
2969 : XMMReg4Double w2 =
2970 : XMMReg4Double::Load1ValHighAndLow(padfWeights + i + 2);
2971 : XMMReg4Double w3 =
2972 : XMMReg4Double::Load1ValHighAndLow(padfWeights + i + 3);
2973 : v_acc0 += XMMReg4Double::Load4Val(pChunk + j + 0 + 0 * nStride) * w0;
2974 : v_acc1 += XMMReg4Double::Load4Val(pChunk + j + 4 + 0 * nStride) * w0;
2975 : v_acc2 += XMMReg4Double::Load4Val(pChunk + j + 8 + 0 * nStride) * w0;
2976 : v_acc3 += XMMReg4Double::Load4Val(pChunk + j + 12 + 0 * nStride) * w0;
2977 : v_acc0 += XMMReg4Double::Load4Val(pChunk + j + 0 + 1 * nStride) * w1;
2978 : v_acc1 += XMMReg4Double::Load4Val(pChunk + j + 4 + 1 * nStride) * w1;
2979 : v_acc2 += XMMReg4Double::Load4Val(pChunk + j + 8 + 1 * nStride) * w1;
2980 : v_acc3 += XMMReg4Double::Load4Val(pChunk + j + 12 + 1 * nStride) * w1;
2981 : v_acc0 += XMMReg4Double::Load4Val(pChunk + j + 0 + 2 * nStride) * w2;
2982 : v_acc1 += XMMReg4Double::Load4Val(pChunk + j + 4 + 2 * nStride) * w2;
2983 : v_acc2 += XMMReg4Double::Load4Val(pChunk + j + 8 + 2 * nStride) * w2;
2984 : v_acc3 += XMMReg4Double::Load4Val(pChunk + j + 12 + 2 * nStride) * w2;
2985 : v_acc0 += XMMReg4Double::Load4Val(pChunk + j + 0 + 3 * nStride) * w3;
2986 : v_acc1 += XMMReg4Double::Load4Val(pChunk + j + 4 + 3 * nStride) * w3;
2987 : v_acc2 += XMMReg4Double::Load4Val(pChunk + j + 8 + 3 * nStride) * w3;
2988 : v_acc3 += XMMReg4Double::Load4Val(pChunk + j + 12 + 3 * nStride) * w3;
2989 : }
2990 : for (; i < nSrcLineCount; ++i, j += nStride)
2991 : {
2992 : XMMReg4Double w = XMMReg4Double::Load1ValHighAndLow(padfWeights + i);
2993 : v_acc0 += XMMReg4Double::Load4Val(pChunk + j + 0) * w;
2994 : v_acc1 += XMMReg4Double::Load4Val(pChunk + j + 4) * w;
2995 : v_acc2 += XMMReg4Double::Load4Val(pChunk + j + 8) * w;
2996 : v_acc3 += XMMReg4Double::Load4Val(pChunk + j + 12) * w;
2997 : }
2998 : v_acc0.Store4Val(afDest);
2999 : v_acc1.Store4Val(afDest + 4);
3000 : v_acc2.Store4Val(afDest + 8);
3001 : v_acc3.Store4Val(afDest + 12);
3002 : }
3003 :
3004 : template <class T>
3005 : static inline void GDALResampleConvolutionVertical_16cols(const T *, int,
3006 : const double *, int,
3007 : double *)
3008 : {
3009 : // Cannot be reached
3010 : CPLAssert(false);
3011 : }
3012 :
3013 : #else
3014 :
3015 : /************************************************************************/
3016 : /* GDALResampleConvolutionVertical_8cols<T> */
3017 : /************************************************************************/
3018 :
3019 : template <class T>
3020 : static inline void
3021 25804000 : GDALResampleConvolutionVertical_8cols(const T *pChunk, size_t nStride,
3022 : const double *padfWeights,
3023 : int nSrcLineCount, float *afDest)
3024 : {
3025 25804000 : int i = 0;
3026 25804000 : size_t j = 0;
3027 25804000 : XMMReg4Double v_acc0 = XMMReg4Double::Zero();
3028 25804000 : XMMReg4Double v_acc1 = XMMReg4Double::Zero();
3029 53883400 : for (; i < nSrcLineCount - 3; i += 4, j += 4 * nStride)
3030 : {
3031 28079400 : XMMReg4Double w0 =
3032 28079400 : XMMReg4Double::Load1ValHighAndLow(padfWeights + i + 0);
3033 28079400 : XMMReg4Double w1 =
3034 28079400 : XMMReg4Double::Load1ValHighAndLow(padfWeights + i + 1);
3035 28079400 : XMMReg4Double w2 =
3036 28079400 : XMMReg4Double::Load1ValHighAndLow(padfWeights + i + 2);
3037 28079400 : XMMReg4Double w3 =
3038 28079400 : XMMReg4Double::Load1ValHighAndLow(padfWeights + i + 3);
3039 28079400 : v_acc0 += XMMReg4Double::Load4Val(pChunk + j + 0 + 0 * nStride) * w0;
3040 28079400 : v_acc1 += XMMReg4Double::Load4Val(pChunk + j + 4 + 0 * nStride) * w0;
3041 28079400 : v_acc0 += XMMReg4Double::Load4Val(pChunk + j + 0 + 1 * nStride) * w1;
3042 28079400 : v_acc1 += XMMReg4Double::Load4Val(pChunk + j + 4 + 1 * nStride) * w1;
3043 28079400 : v_acc0 += XMMReg4Double::Load4Val(pChunk + j + 0 + 2 * nStride) * w2;
3044 28079400 : v_acc1 += XMMReg4Double::Load4Val(pChunk + j + 4 + 2 * nStride) * w2;
3045 28079400 : v_acc0 += XMMReg4Double::Load4Val(pChunk + j + 0 + 3 * nStride) * w3;
3046 28079400 : v_acc1 += XMMReg4Double::Load4Val(pChunk + j + 4 + 3 * nStride) * w3;
3047 : }
3048 37376100 : for (; i < nSrcLineCount; ++i, j += nStride)
3049 : {
3050 11572100 : XMMReg4Double w = XMMReg4Double::Load1ValHighAndLow(padfWeights + i);
3051 11572100 : v_acc0 += XMMReg4Double::Load4Val(pChunk + j + 0) * w;
3052 11572100 : v_acc1 += XMMReg4Double::Load4Val(pChunk + j + 4) * w;
3053 : }
3054 25804000 : v_acc0.Store4Val(afDest);
3055 25804000 : v_acc1.Store4Val(afDest + 4);
3056 25804000 : }
3057 :
3058 : template <class T>
3059 : static inline void GDALResampleConvolutionVertical_8cols(const T *, int,
3060 : const double *, int,
3061 : double *)
3062 : {
3063 : // Cannot be reached
3064 : CPLAssert(false);
3065 : }
3066 :
3067 : #endif // __AVX__
3068 :
3069 : /************************************************************************/
3070 : /* GDALResampleConvolutionHorizontalSSE2<T> */
3071 : /************************************************************************/
3072 :
3073 : template <class T>
3074 3375702 : static inline double GDALResampleConvolutionHorizontalSSE2(
3075 : const T *pChunk, const double *padfWeightsAligned, int nSrcPixelCount)
3076 : {
3077 3375702 : XMMReg4Double v_acc1 = XMMReg4Double::Zero();
3078 3375702 : XMMReg4Double v_acc2 = XMMReg4Double::Zero();
3079 3375702 : int i = 0; // Used after for.
3080 3754648 : for (; i < nSrcPixelCount - 7; i += 8)
3081 : {
3082 : // Retrieve the pixel & accumulate
3083 378952 : const XMMReg4Double v_pixels1 = XMMReg4Double::Load4Val(pChunk + i);
3084 378952 : const XMMReg4Double v_pixels2 = XMMReg4Double::Load4Val(pChunk + i + 4);
3085 378952 : const XMMReg4Double v_weight1 =
3086 378952 : XMMReg4Double::Load4ValAligned(padfWeightsAligned + i);
3087 378952 : const XMMReg4Double v_weight2 =
3088 378952 : XMMReg4Double::Load4ValAligned(padfWeightsAligned + i + 4);
3089 :
3090 378952 : v_acc1 += v_pixels1 * v_weight1;
3091 378952 : v_acc2 += v_pixels2 * v_weight2;
3092 : }
3093 :
3094 3375702 : v_acc1 += v_acc2;
3095 :
3096 3375702 : double dfVal = v_acc1.GetHorizSum();
3097 11491480 : for (; i < nSrcPixelCount; ++i)
3098 : {
3099 8115780 : dfVal += pChunk[i] * padfWeightsAligned[i];
3100 : }
3101 3375702 : return dfVal;
3102 : }
3103 :
3104 : /************************************************************************/
3105 : /* GDALResampleConvolutionHorizontal<GByte> */
3106 : /************************************************************************/
3107 :
3108 : template <>
3109 2826540 : inline double GDALResampleConvolutionHorizontal<GByte>(
3110 : const GByte *pChunk, const double *padfWeightsAligned, int nSrcPixelCount)
3111 : {
3112 2826540 : return GDALResampleConvolutionHorizontalSSE2(pChunk, padfWeightsAligned,
3113 2826540 : nSrcPixelCount);
3114 : }
3115 :
3116 : template <>
3117 549162 : inline double GDALResampleConvolutionHorizontal<GUInt16>(
3118 : const GUInt16 *pChunk, const double *padfWeightsAligned, int nSrcPixelCount)
3119 : {
3120 549162 : return GDALResampleConvolutionHorizontalSSE2(pChunk, padfWeightsAligned,
3121 549162 : nSrcPixelCount);
3122 : }
3123 :
3124 : /************************************************************************/
3125 : /* GDALResampleConvolutionHorizontalWithMaskSSE2<T> */
3126 : /************************************************************************/
3127 :
3128 : template <class T>
3129 10626463 : static inline void GDALResampleConvolutionHorizontalWithMaskSSE2(
3130 : const T *pChunk, const GByte *pabyMask, const double *padfWeightsAligned,
3131 : int nSrcPixelCount, double &dfWeightValMaskSum, double &dfWeightMaskSum,
3132 : double &dfWeightSum)
3133 : {
3134 10626463 : int i = 0; // Used after for.
3135 10626463 : XMMReg4Double v_acc_val_mask_weight = XMMReg4Double::Zero();
3136 10626463 : XMMReg4Double v_acc_mask_weight = XMMReg4Double::Zero();
3137 10626463 : XMMReg4Double v_acc_weight = XMMReg4Double::Zero();
3138 26199121 : for (; i < nSrcPixelCount - 3; i += 4)
3139 : {
3140 15572658 : const XMMReg4Double v_pixels = XMMReg4Double::Load4Val(pChunk + i);
3141 15572658 : const XMMReg4Double v_mask = XMMReg4Double::Load4Val(pabyMask + i);
3142 15572658 : XMMReg4Double v_weight =
3143 15572658 : XMMReg4Double::Load4ValAligned(padfWeightsAligned + i);
3144 15572658 : v_acc_weight += v_weight;
3145 15572658 : v_weight *= v_mask;
3146 15572658 : v_acc_val_mask_weight += v_pixels * v_weight;
3147 15572658 : v_acc_mask_weight += v_weight;
3148 : }
3149 :
3150 10626463 : dfWeightValMaskSum = v_acc_val_mask_weight.GetHorizSum();
3151 10626463 : dfWeightMaskSum = v_acc_mask_weight.GetHorizSum();
3152 10626463 : dfWeightSum = v_acc_weight.GetHorizSum();
3153 10910963 : for (; i < nSrcPixelCount; ++i)
3154 : {
3155 284454 : const double dfWeight = padfWeightsAligned[i];
3156 284454 : const double dfWeightMask = dfWeight * pabyMask[i];
3157 284454 : dfWeightValMaskSum += pChunk[i] * dfWeightMask;
3158 284454 : dfWeightMaskSum += dfWeightMask;
3159 284454 : dfWeightSum += dfWeight;
3160 : }
3161 10626463 : }
3162 :
3163 : /************************************************************************/
3164 : /* GDALResampleConvolutionHorizontalWithMask<GByte> */
3165 : /************************************************************************/
3166 :
3167 : template <>
3168 10626400 : inline void GDALResampleConvolutionHorizontalWithMask<GByte, false>(
3169 : const GByte *pChunk, const GByte *pabyMask,
3170 : const double *padfWeightsAligned, int nSrcPixelCount,
3171 : double &dfWeightValMaskSum, double &dfWeightMaskSum, double &dfWeightSum)
3172 : {
3173 10626400 : GDALResampleConvolutionHorizontalWithMaskSSE2(
3174 : pChunk, pabyMask, padfWeightsAligned, nSrcPixelCount,
3175 : dfWeightValMaskSum, dfWeightMaskSum, dfWeightSum);
3176 10626400 : }
3177 :
3178 : template <>
3179 63 : inline void GDALResampleConvolutionHorizontalWithMask<GUInt16, false>(
3180 : const GUInt16 *pChunk, const GByte *pabyMask,
3181 : const double *padfWeightsAligned, int nSrcPixelCount,
3182 : double &dfWeightValMaskSum, double &dfWeightMaskSum, double &dfWeightSum)
3183 : {
3184 63 : GDALResampleConvolutionHorizontalWithMaskSSE2(
3185 : pChunk, pabyMask, padfWeightsAligned, nSrcPixelCount,
3186 : dfWeightValMaskSum, dfWeightMaskSum, dfWeightSum);
3187 63 : }
3188 :
3189 : /************************************************************************/
3190 : /* GDALResampleConvolutionHorizontal_3rows_SSE2<T> */
3191 : /************************************************************************/
3192 :
3193 : template <class T>
3194 35560186 : static inline void GDALResampleConvolutionHorizontal_3rows_SSE2(
3195 : const T *pChunkRow1, const T *pChunkRow2, const T *pChunkRow3,
3196 : const double *padfWeightsAligned, int nSrcPixelCount, double &dfRes1,
3197 : double &dfRes2, double &dfRes3)
3198 : {
3199 35560186 : XMMReg4Double v_acc1 = XMMReg4Double::Zero(),
3200 35560186 : v_acc2 = XMMReg4Double::Zero(),
3201 35560186 : v_acc3 = XMMReg4Double::Zero();
3202 35560186 : int i = 0;
3203 70929556 : for (; i < nSrcPixelCount - 7; i += 8)
3204 : {
3205 : // Retrieve the pixel & accumulate.
3206 35369370 : XMMReg4Double v_pixels1 = XMMReg4Double::Load4Val(pChunkRow1 + i);
3207 35369370 : XMMReg4Double v_pixels2 = XMMReg4Double::Load4Val(pChunkRow1 + i + 4);
3208 35369370 : const XMMReg4Double v_weight1 =
3209 35369370 : XMMReg4Double::Load4ValAligned(padfWeightsAligned + i);
3210 35369370 : const XMMReg4Double v_weight2 =
3211 35369370 : XMMReg4Double::Load4ValAligned(padfWeightsAligned + i + 4);
3212 :
3213 35369370 : v_acc1 += v_pixels1 * v_weight1;
3214 35369370 : v_acc1 += v_pixels2 * v_weight2;
3215 :
3216 35369370 : v_pixels1 = XMMReg4Double::Load4Val(pChunkRow2 + i);
3217 35369370 : v_pixels2 = XMMReg4Double::Load4Val(pChunkRow2 + i + 4);
3218 35369370 : v_acc2 += v_pixels1 * v_weight1;
3219 35369370 : v_acc2 += v_pixels2 * v_weight2;
3220 :
3221 35369370 : v_pixels1 = XMMReg4Double::Load4Val(pChunkRow3 + i);
3222 35369370 : v_pixels2 = XMMReg4Double::Load4Val(pChunkRow3 + i + 4);
3223 35369370 : v_acc3 += v_pixels1 * v_weight1;
3224 35369370 : v_acc3 += v_pixels2 * v_weight2;
3225 : }
3226 :
3227 35560186 : dfRes1 = v_acc1.GetHorizSum();
3228 35560186 : dfRes2 = v_acc2.GetHorizSum();
3229 35560186 : dfRes3 = v_acc3.GetHorizSum();
3230 47825952 : for (; i < nSrcPixelCount; ++i)
3231 : {
3232 12265766 : dfRes1 += pChunkRow1[i] * padfWeightsAligned[i];
3233 12265766 : dfRes2 += pChunkRow2[i] * padfWeightsAligned[i];
3234 12265766 : dfRes3 += pChunkRow3[i] * padfWeightsAligned[i];
3235 : }
3236 35560186 : }
3237 :
3238 : /************************************************************************/
3239 : /* GDALResampleConvolutionHorizontal_3rows<GByte> */
3240 : /************************************************************************/
3241 :
3242 : template <>
3243 35560100 : inline void GDALResampleConvolutionHorizontal_3rows<GByte, false>(
3244 : const GByte *pChunkRow1, const GByte *pChunkRow2, const GByte *pChunkRow3,
3245 : const double *padfWeightsAligned, int nSrcPixelCount, double &dfRes1,
3246 : double &dfRes2, double &dfRes3)
3247 : {
3248 35560100 : GDALResampleConvolutionHorizontal_3rows_SSE2(
3249 : pChunkRow1, pChunkRow2, pChunkRow3, padfWeightsAligned, nSrcPixelCount,
3250 : dfRes1, dfRes2, dfRes3);
3251 35560100 : }
3252 :
3253 : template <>
3254 86 : inline void GDALResampleConvolutionHorizontal_3rows<GUInt16, false>(
3255 : const GUInt16 *pChunkRow1, const GUInt16 *pChunkRow2,
3256 : const GUInt16 *pChunkRow3, const double *padfWeightsAligned,
3257 : int nSrcPixelCount, double &dfRes1, double &dfRes2, double &dfRes3)
3258 : {
3259 86 : GDALResampleConvolutionHorizontal_3rows_SSE2(
3260 : pChunkRow1, pChunkRow2, pChunkRow3, padfWeightsAligned, nSrcPixelCount,
3261 : dfRes1, dfRes2, dfRes3);
3262 86 : }
3263 :
3264 : /************************************************************************/
3265 : /* GDALResampleConvolutionHorizontalPixelCountLess8_3rows_SSE2<T> */
3266 : /************************************************************************/
3267 :
3268 : template <class T>
3269 7849120 : static inline void GDALResampleConvolutionHorizontalPixelCountLess8_3rows_SSE2(
3270 : const T *pChunkRow1, const T *pChunkRow2, const T *pChunkRow3,
3271 : const double *padfWeightsAligned, int nSrcPixelCount, double &dfRes1,
3272 : double &dfRes2, double &dfRes3)
3273 : {
3274 7849120 : XMMReg4Double v_acc1 = XMMReg4Double::Zero();
3275 7849120 : XMMReg4Double v_acc2 = XMMReg4Double::Zero();
3276 7849120 : XMMReg4Double v_acc3 = XMMReg4Double::Zero();
3277 7849120 : int i = 0; // Use after for.
3278 19113750 : for (; i < nSrcPixelCount - 3; i += 4)
3279 : {
3280 : // Retrieve the pixel & accumulate.
3281 11264600 : const XMMReg4Double v_pixels1 = XMMReg4Double::Load4Val(pChunkRow1 + i);
3282 11264600 : const XMMReg4Double v_pixels2 = XMMReg4Double::Load4Val(pChunkRow2 + i);
3283 11264600 : const XMMReg4Double v_pixels3 = XMMReg4Double::Load4Val(pChunkRow3 + i);
3284 11264600 : const XMMReg4Double v_weight =
3285 11264600 : XMMReg4Double::Load4ValAligned(padfWeightsAligned + i);
3286 :
3287 11264600 : v_acc1 += v_pixels1 * v_weight;
3288 11264600 : v_acc2 += v_pixels2 * v_weight;
3289 11264600 : v_acc3 += v_pixels3 * v_weight;
3290 : }
3291 :
3292 7849120 : dfRes1 = v_acc1.GetHorizSum();
3293 7849120 : dfRes2 = v_acc2.GetHorizSum();
3294 7849120 : dfRes3 = v_acc3.GetHorizSum();
3295 :
3296 12324622 : for (; i < nSrcPixelCount; ++i)
3297 : {
3298 4475522 : dfRes1 += pChunkRow1[i] * padfWeightsAligned[i];
3299 4475522 : dfRes2 += pChunkRow2[i] * padfWeightsAligned[i];
3300 4475522 : dfRes3 += pChunkRow3[i] * padfWeightsAligned[i];
3301 : }
3302 7849120 : }
3303 :
3304 : /************************************************************************/
3305 : /* GDALResampleConvolutionHorizontalPixelCountLess8_3rows<GByte> */
3306 : /************************************************************************/
3307 :
3308 : template <>
3309 : inline void
3310 7781970 : GDALResampleConvolutionHorizontalPixelCountLess8_3rows<GByte, false>(
3311 : const GByte *pChunkRow1, const GByte *pChunkRow2, const GByte *pChunkRow3,
3312 : const double *padfWeightsAligned, int nSrcPixelCount, double &dfRes1,
3313 : double &dfRes2, double &dfRes3)
3314 : {
3315 7781970 : GDALResampleConvolutionHorizontalPixelCountLess8_3rows_SSE2(
3316 : pChunkRow1, pChunkRow2, pChunkRow3, padfWeightsAligned, nSrcPixelCount,
3317 : dfRes1, dfRes2, dfRes3);
3318 7781970 : }
3319 :
3320 : template <>
3321 : inline void
3322 67150 : GDALResampleConvolutionHorizontalPixelCountLess8_3rows<GUInt16, false>(
3323 : const GUInt16 *pChunkRow1, const GUInt16 *pChunkRow2,
3324 : const GUInt16 *pChunkRow3, const double *padfWeightsAligned,
3325 : int nSrcPixelCount, double &dfRes1, double &dfRes2, double &dfRes3)
3326 : {
3327 67150 : GDALResampleConvolutionHorizontalPixelCountLess8_3rows_SSE2(
3328 : pChunkRow1, pChunkRow2, pChunkRow3, padfWeightsAligned, nSrcPixelCount,
3329 : dfRes1, dfRes2, dfRes3);
3330 67150 : }
3331 :
3332 : /************************************************************************/
3333 : /* GDALResampleConvolutionHorizontalPixelCount4_3rows_SSE2<T> */
3334 : /************************************************************************/
3335 :
3336 : template <class T>
3337 14904860 : static inline void GDALResampleConvolutionHorizontalPixelCount4_3rows_SSE2(
3338 : const T *pChunkRow1, const T *pChunkRow2, const T *pChunkRow3,
3339 : const double *padfWeightsAligned, double &dfRes1, double &dfRes2,
3340 : double &dfRes3)
3341 : {
3342 14904860 : const XMMReg4Double v_weight =
3343 : XMMReg4Double::Load4ValAligned(padfWeightsAligned);
3344 :
3345 : // Retrieve the pixel & accumulate.
3346 14904860 : const XMMReg4Double v_pixels1 = XMMReg4Double::Load4Val(pChunkRow1);
3347 14904860 : const XMMReg4Double v_pixels2 = XMMReg4Double::Load4Val(pChunkRow2);
3348 14904860 : const XMMReg4Double v_pixels3 = XMMReg4Double::Load4Val(pChunkRow3);
3349 :
3350 14904860 : XMMReg4Double v_acc1 = v_pixels1 * v_weight;
3351 14904860 : XMMReg4Double v_acc2 = v_pixels2 * v_weight;
3352 14904860 : XMMReg4Double v_acc3 = v_pixels3 * v_weight;
3353 :
3354 14904860 : dfRes1 = v_acc1.GetHorizSum();
3355 14904860 : dfRes2 = v_acc2.GetHorizSum();
3356 14904860 : dfRes3 = v_acc3.GetHorizSum();
3357 14904860 : }
3358 :
3359 : /************************************************************************/
3360 : /* GDALResampleConvolutionHorizontalPixelCount4_3rows<GByte> */
3361 : /************************************************************************/
3362 :
3363 : template <>
3364 9192140 : inline void GDALResampleConvolutionHorizontalPixelCount4_3rows<GByte, false>(
3365 : const GByte *pChunkRow1, const GByte *pChunkRow2, const GByte *pChunkRow3,
3366 : const double *padfWeightsAligned, double &dfRes1, double &dfRes2,
3367 : double &dfRes3)
3368 : {
3369 9192140 : GDALResampleConvolutionHorizontalPixelCount4_3rows_SSE2(
3370 : pChunkRow1, pChunkRow2, pChunkRow3, padfWeightsAligned, dfRes1, dfRes2,
3371 : dfRes3);
3372 9192140 : }
3373 :
3374 : template <>
3375 5712720 : inline void GDALResampleConvolutionHorizontalPixelCount4_3rows<GUInt16, false>(
3376 : const GUInt16 *pChunkRow1, const GUInt16 *pChunkRow2,
3377 : const GUInt16 *pChunkRow3, const double *padfWeightsAligned, double &dfRes1,
3378 : double &dfRes2, double &dfRes3)
3379 : {
3380 5712720 : GDALResampleConvolutionHorizontalPixelCount4_3rows_SSE2(
3381 : pChunkRow1, pChunkRow2, pChunkRow3, padfWeightsAligned, dfRes1, dfRes2,
3382 : dfRes3);
3383 5712720 : }
3384 :
3385 : #endif // USE_SSE2
3386 :
3387 : /************************************************************************/
3388 : /* GDALResampleChunk_Convolution() */
3389 : /************************************************************************/
3390 :
3391 : template <class T, class Twork, GDALDataType eWrkDataType,
3392 : bool bKernelWithNegativeWeights, bool bNeedRescale>
3393 9597 : static CPLErr GDALResampleChunk_ConvolutionT(
3394 : const GDALOverviewResampleArgs &args, const T *pChunk, void *pDstBuffer,
3395 : FilterFuncType pfnFilterFunc, FilterFunc4ValuesType pfnFilterFunc4Values,
3396 : int nKernelRadius, float fMaxVal)
3397 :
3398 : {
3399 9597 : const double dfXRatioDstToSrc = args.dfXRatioDstToSrc;
3400 9597 : const double dfYRatioDstToSrc = args.dfYRatioDstToSrc;
3401 9597 : const double dfSrcXDelta = args.dfSrcXDelta;
3402 9597 : const double dfSrcYDelta = args.dfSrcYDelta;
3403 9597 : constexpr int nBands = 1;
3404 9597 : const GByte *pabyChunkNodataMask = args.pabyChunkNodataMask;
3405 9597 : const int nChunkXOff = args.nChunkXOff;
3406 9597 : const int nChunkXSize = args.nChunkXSize;
3407 9597 : const int nChunkYOff = args.nChunkYOff;
3408 9597 : const int nChunkYSize = args.nChunkYSize;
3409 9597 : const int nDstXOff = args.nDstXOff;
3410 9597 : const int nDstXOff2 = args.nDstXOff2;
3411 9597 : const int nDstYOff = args.nDstYOff;
3412 9597 : const int nDstYOff2 = args.nDstYOff2;
3413 9597 : const bool bHasNoData = args.bHasNoData;
3414 9597 : double dfNoDataValue = args.dfNoDataValue;
3415 :
3416 9597 : if (!bHasNoData)
3417 9498 : dfNoDataValue = 0.0;
3418 9597 : const auto dstDataType = args.eOvrDataType;
3419 9597 : const int nDstDataTypeSize = GDALGetDataTypeSizeBytes(dstDataType);
3420 9597 : const double dfReplacementVal =
3421 99 : bHasNoData ? GDALGetNoDataReplacementValue(dstDataType, dfNoDataValue)
3422 : : dfNoDataValue;
3423 : // cppcheck-suppress unreadVariable
3424 9597 : const int isIntegerDT = GDALDataTypeIsInteger(dstDataType);
3425 9597 : const bool bNoDataValueInt64Valid =
3426 9597 : isIntegerDT && GDALIsValueExactAs<GInt64>(dfNoDataValue);
3427 9597 : const auto nNodataValueInt64 =
3428 : bNoDataValueInt64Valid ? static_cast<GInt64>(dfNoDataValue) : 0;
3429 9597 : constexpr int nWrkDataTypeSize = static_cast<int>(sizeof(Twork));
3430 :
3431 : // TODO: we should have some generic function to do this.
3432 9597 : Twork fDstMin = cpl::NumericLimits<Twork>::lowest();
3433 9597 : Twork fDstMax = cpl::NumericLimits<Twork>::max();
3434 9597 : if (dstDataType == GDT_UInt8)
3435 : {
3436 8667 : fDstMin = std::numeric_limits<GByte>::min();
3437 8667 : fDstMax = std::numeric_limits<GByte>::max();
3438 : }
3439 930 : else if (dstDataType == GDT_Int8)
3440 : {
3441 1 : fDstMin = std::numeric_limits<GInt8>::min();
3442 1 : fDstMax = std::numeric_limits<GInt8>::max();
3443 : }
3444 929 : else if (dstDataType == GDT_UInt16)
3445 : {
3446 402 : fDstMin = std::numeric_limits<GUInt16>::min();
3447 402 : fDstMax = std::numeric_limits<GUInt16>::max();
3448 : }
3449 527 : else if (dstDataType == GDT_Int16)
3450 : {
3451 292 : fDstMin = std::numeric_limits<GInt16>::min();
3452 292 : fDstMax = std::numeric_limits<GInt16>::max();
3453 : }
3454 235 : else if (dstDataType == GDT_UInt32)
3455 : {
3456 1 : fDstMin = static_cast<Twork>(std::numeric_limits<GUInt32>::min());
3457 1 : fDstMax = static_cast<Twork>(std::numeric_limits<GUInt32>::max());
3458 : }
3459 234 : else if (dstDataType == GDT_Int32)
3460 : {
3461 : // cppcheck-suppress unreadVariable
3462 6 : fDstMin = static_cast<Twork>(std::numeric_limits<GInt32>::min());
3463 : // cppcheck-suppress unreadVariable
3464 6 : fDstMax = static_cast<Twork>(std::numeric_limits<GInt32>::max());
3465 : }
3466 228 : else if (dstDataType == GDT_UInt64)
3467 : {
3468 : // cppcheck-suppress unreadVariable
3469 1 : fDstMin = static_cast<Twork>(std::numeric_limits<uint64_t>::min());
3470 : // cppcheck-suppress unreadVariable
3471 : // (1 << 64) - 2048: largest uint64 value a double can hold
3472 1 : fDstMax = static_cast<Twork>(18446744073709549568ULL);
3473 : }
3474 227 : else if (dstDataType == GDT_Int64)
3475 : {
3476 : // cppcheck-suppress unreadVariable
3477 1 : fDstMin = static_cast<Twork>(std::numeric_limits<int64_t>::min());
3478 : // cppcheck-suppress unreadVariable
3479 : // (1 << 63) - 1024: largest int64 that a double can hold
3480 1 : fDstMax = static_cast<Twork>(9223372036854774784LL);
3481 : }
3482 :
3483 9597 : bool bHasNaN = false;
3484 490 : if (pabyChunkNodataMask)
3485 : {
3486 : if constexpr (std::is_floating_point_v<T>)
3487 : {
3488 120140 : for (size_t i = 0;
3489 120140 : i < static_cast<size_t>(nChunkXSize) * nChunkYSize; ++i)
3490 : {
3491 120122 : if (std::isnan(pChunk[i]))
3492 : {
3493 24 : bHasNaN = true;
3494 24 : break;
3495 : }
3496 : }
3497 : }
3498 : }
3499 :
3500 37413146 : auto replaceValIfNodata = [bHasNoData, isIntegerDT, fDstMin, fDstMax,
3501 : bNoDataValueInt64Valid, nNodataValueInt64,
3502 : dfNoDataValue, dfReplacementVal](Twork fVal)
3503 : {
3504 16299800 : if (!bHasNoData)
3505 12078600 : return fVal;
3506 :
3507 : // Clamp value before comparing to nodata: this is only needed for
3508 : // kernels with negative weights (Lanczos)
3509 4221160 : Twork fClamped = fVal;
3510 4221160 : if (fClamped < fDstMin)
3511 14504 : fClamped = fDstMin;
3512 4206660 : else if (fClamped > fDstMax)
3513 13638 : fClamped = fDstMax;
3514 4221160 : if (isIntegerDT)
3515 : {
3516 4220480 : if (bNoDataValueInt64Valid)
3517 : {
3518 4220470 : const double fClampedRounded = double(std::round(fClamped));
3519 8440960 : if (fClampedRounded >=
3520 : static_cast<double>(static_cast<Twork>(
3521 8440960 : std::numeric_limits<int64_t>::min())) &&
3522 : fClampedRounded <= static_cast<double>(static_cast<Twork>(
3523 8440960 : 9223372036854774784LL)) &&
3524 4220470 : nNodataValueInt64 ==
3525 4220480 : static_cast<GInt64>(std::round(fClamped)))
3526 : {
3527 : // Do not use the nodata value
3528 13195 : return static_cast<Twork>(dfReplacementVal);
3529 : }
3530 : }
3531 : }
3532 679 : else if (dfNoDataValue == static_cast<double>(fClamped))
3533 : {
3534 : // Do not use the nodata value
3535 1 : return static_cast<Twork>(dfReplacementVal);
3536 : }
3537 4207960 : return fClamped;
3538 : };
3539 :
3540 : /* -------------------------------------------------------------------- */
3541 : /* Allocate work buffers. */
3542 : /* -------------------------------------------------------------------- */
3543 9597 : const int nDstXSize = nDstXOff2 - nDstXOff;
3544 9597 : Twork *pafWrkScanline = nullptr;
3545 9597 : if (dstDataType != eWrkDataType)
3546 : {
3547 : pafWrkScanline =
3548 9385 : static_cast<Twork *>(VSI_MALLOC2_VERBOSE(nDstXSize, sizeof(Twork)));
3549 9385 : if (pafWrkScanline == nullptr)
3550 0 : return CE_Failure;
3551 : }
3552 :
3553 9597 : const double dfXScale = 1.0 / dfXRatioDstToSrc;
3554 9597 : const double dfXScaleWeight = (dfXScale >= 1.0) ? 1.0 : dfXScale;
3555 9597 : const double dfXScaledRadius = nKernelRadius / dfXScaleWeight;
3556 9597 : const double dfYScale = 1.0 / dfYRatioDstToSrc;
3557 9597 : const double dfYScaleWeight = (dfYScale >= 1.0) ? 1.0 : dfYScale;
3558 9597 : const double dfYScaledRadius = nKernelRadius / dfYScaleWeight;
3559 :
3560 9597 : const uint64_t nWeightCount = static_cast<uint64_t>(
3561 9597 : 2 + 2 * std::max(dfXScaledRadius, dfYScaledRadius) + 0.5);
3562 9597 : if (nWeightCount > std::numeric_limits<uint32_t>::max() / sizeof(double))
3563 : {
3564 0 : VSIFree(pafWrkScanline);
3565 0 : CPLError(CE_Failure, CPLE_NotSupported,
3566 : "Too large downsampling factor");
3567 0 : return CE_Failure;
3568 : }
3569 :
3570 : // Temporary array to store result of horizontal filter.
3571 : double *const padfHorizontalFiltered = static_cast<double *>(
3572 9597 : VSI_MALLOC3_VERBOSE(nChunkYSize, nDstXSize, sizeof(double) * nBands));
3573 : // To store convolution coefficients.
3574 : double *const padfWeights =
3575 9597 : static_cast<double *>(VSI_MALLOC_ALIGNED_AUTO_VERBOSE(
3576 : static_cast<size_t>(nWeightCount) * sizeof(double)));
3577 :
3578 9597 : GByte *pabyChunkNodataMaskHorizontalFiltered = nullptr;
3579 9597 : if (pabyChunkNodataMask)
3580 : pabyChunkNodataMaskHorizontalFiltered =
3581 3357 : static_cast<GByte *>(VSI_MALLOC2_VERBOSE(nChunkYSize, nDstXSize));
3582 9597 : if (padfHorizontalFiltered == nullptr || padfWeights == nullptr ||
3583 3357 : (pabyChunkNodataMask != nullptr &&
3584 : pabyChunkNodataMaskHorizontalFiltered == nullptr))
3585 : {
3586 0 : VSIFree(pafWrkScanline);
3587 0 : VSIFree(padfHorizontalFiltered);
3588 0 : VSIFreeAligned(padfWeights);
3589 0 : VSIFree(pabyChunkNodataMaskHorizontalFiltered);
3590 0 : return CE_Failure;
3591 : }
3592 :
3593 : /* ==================================================================== */
3594 : /* First pass: horizontal filter */
3595 : /* ==================================================================== */
3596 9597 : const int nChunkRightXOff = nChunkXOff + nChunkXSize;
3597 : #ifdef USE_SSE2
3598 9597 : const bool bSrcPixelCountLess8 = dfXScaledRadius < 4;
3599 : #endif
3600 3723494 : for (int iDstPixel = nDstXOff; iDstPixel < nDstXOff2; ++iDstPixel)
3601 : {
3602 3713892 : const double dfSrcPixel =
3603 3713892 : (iDstPixel + 0.5) * dfXRatioDstToSrc + dfSrcXDelta;
3604 3713892 : const int nSrcPixelStart = std::max(
3605 3713892 : static_cast<int>(floor(dfSrcPixel - dfXScaledRadius + 0.5)),
3606 3713892 : nChunkXOff);
3607 3713892 : const int nSrcPixelStop =
3608 3713892 : std::min(static_cast<int>(dfSrcPixel + dfXScaledRadius + 0.5),
3609 3713892 : nChunkRightXOff);
3610 : #if 0
3611 : if( nSrcPixelStart < nChunkXOff && nChunkXOff > 0 )
3612 : {
3613 : printf( "truncated iDstPixel = %d\n", iDstPixel );/*ok*/
3614 : }
3615 : if( nSrcPixelStop > nChunkRightXOff && nChunkRightXOff < nSrcWidth )
3616 : {
3617 : printf( "truncated iDstPixel = %d\n", iDstPixel );/*ok*/
3618 : }
3619 : #endif
3620 3713892 : const int nSrcPixelCount = nSrcPixelStop - nSrcPixelStart;
3621 3713892 : double dfWeightSum = 0.0;
3622 :
3623 : // Compute convolution coefficients.
3624 3713892 : int nSrcPixel = nSrcPixelStart;
3625 3713892 : double dfX = dfXScaleWeight * (nSrcPixel - dfSrcPixel + 0.5);
3626 5823636 : for (; nSrcPixel < nSrcPixelStop - 3; nSrcPixel += 4)
3627 : {
3628 2109749 : padfWeights[nSrcPixel - nSrcPixelStart] = dfX;
3629 2109749 : dfX += dfXScaleWeight;
3630 2109749 : padfWeights[nSrcPixel + 1 - nSrcPixelStart] = dfX;
3631 2109749 : dfX += dfXScaleWeight;
3632 2109749 : padfWeights[nSrcPixel + 2 - nSrcPixelStart] = dfX;
3633 2109749 : dfX += dfXScaleWeight;
3634 2109749 : padfWeights[nSrcPixel + 3 - nSrcPixelStart] = dfX;
3635 2109749 : dfX += dfXScaleWeight;
3636 2109749 : dfWeightSum +=
3637 2109749 : pfnFilterFunc4Values(padfWeights + nSrcPixel - nSrcPixelStart);
3638 : }
3639 7719022 : for (; nSrcPixel < nSrcPixelStop; ++nSrcPixel, dfX += dfXScaleWeight)
3640 : {
3641 4005130 : const double dfWeight = pfnFilterFunc(dfX);
3642 4005130 : padfWeights[nSrcPixel - nSrcPixelStart] = dfWeight;
3643 4005130 : dfWeightSum += dfWeight;
3644 : }
3645 :
3646 3713892 : const int nHeight = nChunkYSize * nBands;
3647 3713892 : if (pabyChunkNodataMask == nullptr)
3648 : {
3649 : // For floating-point data types, we must scale down a bit values
3650 : // if input values are close to +/- std::numeric_limits<T>::max()
3651 : #ifdef OLD_CPPCHECK
3652 : constexpr double mulFactor = 1;
3653 : #else
3654 3191883 : constexpr double mulFactor =
3655 : (bNeedRescale &&
3656 : (std::is_same_v<T, float> || std::is_same_v<T, double>))
3657 : ? 2
3658 : : 1;
3659 : #endif
3660 :
3661 3191883 : if (dfWeightSum != 0)
3662 : {
3663 3191883 : const double dfInvWeightSum = 1.0 / (mulFactor * dfWeightSum);
3664 13086524 : for (int i = 0; i < nSrcPixelCount; ++i)
3665 : {
3666 9894651 : padfWeights[i] *= dfInvWeightSum;
3667 : }
3668 : }
3669 :
3670 182388430 : const auto ScaleValue = [
3671 : #ifdef _MSC_VER
3672 : mulFactor
3673 : #endif
3674 : ](double dfVal, [[maybe_unused]] const T *inputValues,
3675 : [[maybe_unused]] int nInputValues)
3676 : {
3677 182388000 : constexpr bool isFloat =
3678 : std::is_same_v<T, float> || std::is_same_v<T, double>;
3679 : if constexpr (isFloat)
3680 : {
3681 4070140 : if (std::isfinite(dfVal))
3682 : {
3683 : return std::clamp(dfVal,
3684 12204800 : -std::numeric_limits<double>::max() /
3685 : mulFactor,
3686 4068260 : std::numeric_limits<double>::max() /
3687 4068260 : mulFactor) *
3688 4068260 : mulFactor;
3689 : }
3690 : else if constexpr (bKernelWithNegativeWeights)
3691 : {
3692 936 : if (std::isnan(dfVal))
3693 : {
3694 : // Either one of the input value is NaN or they are +/-Inf
3695 936 : const bool isPositive = inputValues[0] >= 0;
3696 6008 : for (int i = 0; i < nInputValues; ++i)
3697 : {
3698 5384 : if (std::isnan(inputValues[i]))
3699 312 : return dfVal;
3700 : // cppcheck-suppress knownConditionTrueFalse
3701 5072 : if ((inputValues[i] >= 0) != isPositive)
3702 0 : return dfVal;
3703 : }
3704 : // All values are positive or negative infinity
3705 624 : return static_cast<double>(inputValues[0]);
3706 : }
3707 : }
3708 : }
3709 178319000 : return dfVal;
3710 : };
3711 :
3712 3191883 : int iSrcLineOff = 0;
3713 : #ifdef USE_SSE2
3714 3191883 : if (nSrcPixelCount == 4)
3715 : {
3716 17007029 : for (; iSrcLineOff < nHeight - 2; iSrcLineOff += 3)
3717 : {
3718 16161558 : const size_t j =
3719 16161558 : static_cast<size_t>(iSrcLineOff) * nChunkXSize +
3720 16161558 : (nSrcPixelStart - nChunkXOff);
3721 16161558 : double dfVal1 = 0.0;
3722 16161558 : double dfVal2 = 0.0;
3723 16161558 : double dfVal3 = 0.0;
3724 : if constexpr (std::is_floating_point_v<T>)
3725 : {
3726 1256690 : if (bHasNaN)
3727 : {
3728 : GDALResampleConvolutionHorizontalPixelCount4_3rows<
3729 0 : T, true>(pChunk + j, pChunk + j + nChunkXSize,
3730 0 : pChunk + j + 2 * nChunkXSize,
3731 : padfWeights, dfVal1, dfVal2, dfVal3);
3732 : }
3733 : else
3734 : {
3735 : GDALResampleConvolutionHorizontalPixelCount4_3rows<
3736 1256690 : T, false>(pChunk + j, pChunk + j + nChunkXSize,
3737 1256690 : pChunk + j + 2 * nChunkXSize,
3738 : padfWeights, dfVal1, dfVal2, dfVal3);
3739 : }
3740 : }
3741 : else
3742 : {
3743 : GDALResampleConvolutionHorizontalPixelCount4_3rows<
3744 14904868 : T, false>(pChunk + j, pChunk + j + nChunkXSize,
3745 14904868 : pChunk + j + 2 * nChunkXSize, padfWeights,
3746 : dfVal1, dfVal2, dfVal3);
3747 : }
3748 32323080 : padfHorizontalFiltered[static_cast<size_t>(iSrcLineOff) *
3749 16161558 : nDstXSize +
3750 16161558 : iDstPixel - nDstXOff] =
3751 16161558 : ScaleValue(dfVal1, pChunk + j, 4);
3752 32323080 : padfHorizontalFiltered[(static_cast<size_t>(iSrcLineOff) +
3753 16161558 : 1) *
3754 16161558 : nDstXSize +
3755 16161558 : iDstPixel - nDstXOff] =
3756 16161558 : ScaleValue(dfVal2, pChunk + j + nChunkXSize, 4);
3757 16161967 : padfHorizontalFiltered[(static_cast<size_t>(iSrcLineOff) +
3758 16161558 : 2) *
3759 16161558 : nDstXSize +
3760 16161558 : iDstPixel - nDstXOff] =
3761 16161558 : ScaleValue(dfVal3, pChunk + j + 2 * nChunkXSize, 4);
3762 : }
3763 : }
3764 2346404 : else if (bSrcPixelCountLess8)
3765 : {
3766 9938308 : for (; iSrcLineOff < nHeight - 2; iSrcLineOff += 3)
3767 : {
3768 7868098 : const size_t j =
3769 7868098 : static_cast<size_t>(iSrcLineOff) * nChunkXSize +
3770 7868098 : (nSrcPixelStart - nChunkXOff);
3771 7868098 : double dfVal1 = 0.0;
3772 7868098 : double dfVal2 = 0.0;
3773 7868098 : double dfVal3 = 0.0;
3774 : if constexpr (std::is_floating_point_v<T>)
3775 : {
3776 18980 : if (bHasNaN)
3777 : {
3778 : GDALResampleConvolutionHorizontalPixelCountLess8_3rows<
3779 0 : T, true>(pChunk + j, pChunk + j + nChunkXSize,
3780 0 : pChunk + j + 2 * nChunkXSize,
3781 : padfWeights, nSrcPixelCount, dfVal1,
3782 : dfVal2, dfVal3);
3783 : }
3784 : else
3785 : {
3786 : GDALResampleConvolutionHorizontalPixelCountLess8_3rows<
3787 18980 : T, false>(pChunk + j, pChunk + j + nChunkXSize,
3788 18980 : pChunk + j + 2 * nChunkXSize,
3789 : padfWeights, nSrcPixelCount, dfVal1,
3790 : dfVal2, dfVal3);
3791 : }
3792 : }
3793 : else
3794 : {
3795 : GDALResampleConvolutionHorizontalPixelCountLess8_3rows<
3796 7849118 : T, false>(pChunk + j, pChunk + j + nChunkXSize,
3797 7849118 : pChunk + j + 2 * nChunkXSize, padfWeights,
3798 : nSrcPixelCount, dfVal1, dfVal2, dfVal3);
3799 : }
3800 15736156 : padfHorizontalFiltered[static_cast<size_t>(iSrcLineOff) *
3801 7868098 : nDstXSize +
3802 7868098 : iDstPixel - nDstXOff] =
3803 7868098 : ScaleValue(dfVal1, pChunk + j, nSrcPixelCount);
3804 15736156 : padfHorizontalFiltered[(static_cast<size_t>(iSrcLineOff) +
3805 7868098 : 1) *
3806 7868098 : nDstXSize +
3807 7868098 : iDstPixel - nDstXOff] =
3808 7868098 : ScaleValue(dfVal2, pChunk + j + nChunkXSize,
3809 : nSrcPixelCount);
3810 7868186 : padfHorizontalFiltered[(static_cast<size_t>(iSrcLineOff) +
3811 7868098 : 2) *
3812 7868098 : nDstXSize +
3813 7868098 : iDstPixel - nDstXOff] =
3814 7868098 : ScaleValue(dfVal3, pChunk + j + 2 * nChunkXSize,
3815 : nSrcPixelCount);
3816 : }
3817 : }
3818 : else
3819 : #endif
3820 : {
3821 35902058 : for (; iSrcLineOff < nHeight - 2; iSrcLineOff += 3)
3822 : {
3823 35625944 : const size_t j =
3824 35625944 : static_cast<size_t>(iSrcLineOff) * nChunkXSize +
3825 35625944 : (nSrcPixelStart - nChunkXOff);
3826 35625944 : double dfVal1 = 0.0;
3827 35625944 : double dfVal2 = 0.0;
3828 35625944 : double dfVal3 = 0.0;
3829 : if constexpr (std::is_floating_point_v<T>)
3830 : {
3831 65696 : if (bHasNaN)
3832 : {
3833 0 : GDALResampleConvolutionHorizontal_3rows<T, true>(
3834 0 : pChunk + j, pChunk + j + nChunkXSize,
3835 0 : pChunk + j + 2 * nChunkXSize, padfWeights,
3836 : nSrcPixelCount, dfVal1, dfVal2, dfVal3);
3837 : }
3838 : else
3839 : {
3840 65696 : GDALResampleConvolutionHorizontal_3rows<T, false>(
3841 65696 : pChunk + j, pChunk + j + nChunkXSize,
3842 65696 : pChunk + j + 2 * nChunkXSize, padfWeights,
3843 : nSrcPixelCount, dfVal1, dfVal2, dfVal3);
3844 : }
3845 : }
3846 : else
3847 : {
3848 35560248 : GDALResampleConvolutionHorizontal_3rows<T, false>(
3849 35560248 : pChunk + j, pChunk + j + nChunkXSize,
3850 35560248 : pChunk + j + 2 * nChunkXSize, padfWeights,
3851 : nSrcPixelCount, dfVal1, dfVal2, dfVal3);
3852 : }
3853 71251798 : padfHorizontalFiltered[static_cast<size_t>(iSrcLineOff) *
3854 35625944 : nDstXSize +
3855 35625944 : iDstPixel - nDstXOff] =
3856 35625944 : ScaleValue(dfVal1, pChunk + j, nSrcPixelCount);
3857 71251798 : padfHorizontalFiltered[(static_cast<size_t>(iSrcLineOff) +
3858 35625944 : 1) *
3859 35625944 : nDstXSize +
3860 35625944 : iDstPixel - nDstXOff] =
3861 35625944 : ScaleValue(dfVal2, pChunk + j + nChunkXSize,
3862 : nSrcPixelCount);
3863 35691048 : padfHorizontalFiltered[(static_cast<size_t>(iSrcLineOff) +
3864 35625944 : 2) *
3865 35625944 : nDstXSize +
3866 35625944 : iDstPixel - nDstXOff] =
3867 35625944 : ScaleValue(dfVal3, pChunk + j + 2 * nChunkXSize,
3868 : nSrcPixelCount);
3869 : }
3870 : }
3871 6613620 : for (; iSrcLineOff < nHeight; ++iSrcLineOff)
3872 : {
3873 3421743 : const size_t j =
3874 3421743 : static_cast<size_t>(iSrcLineOff) * nChunkXSize +
3875 3421743 : (nSrcPixelStart - nChunkXOff);
3876 3970903 : const double dfVal = GDALResampleConvolutionHorizontal(
3877 595200 : pChunk + j, padfWeights, nSrcPixelCount);
3878 3422192 : padfHorizontalFiltered[static_cast<size_t>(iSrcLineOff) *
3879 3421743 : nDstXSize +
3880 3421743 : iDstPixel - nDstXOff] =
3881 3421743 : ScaleValue(dfVal, pChunk + j, nSrcPixelCount);
3882 : }
3883 : }
3884 : else
3885 : {
3886 32759623 : for (int iSrcLineOff = 0; iSrcLineOff < nHeight; ++iSrcLineOff)
3887 : {
3888 32237528 : const size_t j =
3889 32237528 : static_cast<size_t>(iSrcLineOff) * nChunkXSize +
3890 32237528 : (nSrcPixelStart - nChunkXOff);
3891 :
3892 : if (bKernelWithNegativeWeights)
3893 : {
3894 27492508 : int nConsecutiveValid = 0;
3895 27492508 : int nMaxConsecutiveValid = 0;
3896 747674146 : for (int k = 0; k < nSrcPixelCount; k++)
3897 : {
3898 720181938 : if (pabyChunkNodataMask[j + k])
3899 43694301 : nConsecutiveValid++;
3900 676487837 : else if (nConsecutiveValid)
3901 : {
3902 107658 : nMaxConsecutiveValid = std::max(
3903 107658 : nMaxConsecutiveValid, nConsecutiveValid);
3904 107658 : nConsecutiveValid = 0;
3905 : }
3906 : }
3907 27492508 : nMaxConsecutiveValid =
3908 27492508 : std::max(nMaxConsecutiveValid, nConsecutiveValid);
3909 27492508 : if (nMaxConsecutiveValid < nSrcPixelCount / 2)
3910 : {
3911 21564707 : const size_t nTempOffset =
3912 21564707 : static_cast<size_t>(iSrcLineOff) * nDstXSize +
3913 21564707 : iDstPixel - nDstXOff;
3914 21564707 : padfHorizontalFiltered[nTempOffset] = 0.0;
3915 21564707 : pabyChunkNodataMaskHorizontalFiltered[nTempOffset] = 0;
3916 21564707 : continue;
3917 : }
3918 : }
3919 :
3920 10672871 : double dfSumWeightedVal = 0.0;
3921 10672871 : double dfSumWeightedAlpha = 0.0;
3922 : if constexpr (std::is_floating_point_v<T>)
3923 : {
3924 46368 : if (bHasNaN)
3925 : {
3926 1792 : GDALResampleConvolutionHorizontalWithMask<T, true>(
3927 1792 : pChunk + j, pabyChunkNodataMask + j, padfWeights,
3928 : nSrcPixelCount, dfSumWeightedVal,
3929 : dfSumWeightedAlpha, dfWeightSum);
3930 : }
3931 : else
3932 : {
3933 44576 : GDALResampleConvolutionHorizontalWithMask<T, false>(
3934 44576 : pChunk + j, pabyChunkNodataMask + j, padfWeights,
3935 : nSrcPixelCount, dfSumWeightedVal,
3936 : dfSumWeightedAlpha, dfWeightSum);
3937 : }
3938 : }
3939 : else
3940 : {
3941 10626503 : GDALResampleConvolutionHorizontalWithMask<T, false>(
3942 63 : pChunk + j, pabyChunkNodataMask + j, padfWeights,
3943 : nSrcPixelCount, dfSumWeightedVal, dfSumWeightedAlpha,
3944 : dfWeightSum);
3945 : }
3946 10672871 : const size_t nTempOffset =
3947 10672871 : static_cast<size_t>(iSrcLineOff) * nDstXSize + iDstPixel -
3948 10672871 : nDstXOff;
3949 10672871 : if (dfSumWeightedAlpha > 0.0)
3950 : {
3951 8760088 : padfHorizontalFiltered[nTempOffset] =
3952 8760088 : dfSumWeightedVal / dfSumWeightedAlpha;
3953 : // Not entirely clear if clamping values in the horizontal filter
3954 : // is the right thing to do, but otherwise, for
3955 : // https://github.com/OSGeo/gdal/issues/14728
3956 : // with very small values of alpha, we get very strong under
3957 : // and over shoots.
3958 : if constexpr (std::is_same_v<T, uint8_t>)
3959 : {
3960 8713690 : padfHorizontalFiltered[nTempOffset] = std::clamp(
3961 8713690 : padfHorizontalFiltered[nTempOffset], 0.0, 255.0);
3962 : }
3963 : else if constexpr (std::is_same_v<T, uint16_t>)
3964 : {
3965 60 : padfHorizontalFiltered[nTempOffset] = std::clamp(
3966 60 : padfHorizontalFiltered[nTempOffset], 0.0, 65535.0);
3967 : }
3968 8760088 : const double dfAlpha = dfSumWeightedAlpha / dfWeightSum;
3969 8760088 : pabyChunkNodataMaskHorizontalFiltered[nTempOffset] =
3970 8760088 : static_cast<uint8_t>(std::min(dfAlpha + 0.5, 255.0));
3971 : }
3972 : else
3973 : {
3974 1912797 : padfHorizontalFiltered[nTempOffset] = 0.0;
3975 1912797 : pabyChunkNodataMaskHorizontalFiltered[nTempOffset] = 0;
3976 : }
3977 : }
3978 : }
3979 : }
3980 :
3981 : /* ==================================================================== */
3982 : /* Second pass: vertical filter */
3983 : /* ==================================================================== */
3984 9597 : const int nChunkBottomYOff = nChunkYOff + nChunkYSize;
3985 :
3986 414141 : for (int iDstLine = nDstYOff; iDstLine < nDstYOff2; ++iDstLine)
3987 : {
3988 404544 : Twork *const pafDstScanline =
3989 : pafWrkScanline
3990 404544 : ? pafWrkScanline
3991 14028 : : static_cast<Twork *>(pDstBuffer) +
3992 14028 : static_cast<size_t>(iDstLine - nDstYOff) * nDstXSize;
3993 :
3994 404544 : const double dfSrcLine =
3995 404544 : (iDstLine + 0.5) * dfYRatioDstToSrc + dfSrcYDelta;
3996 404544 : const int nSrcLineStart =
3997 404544 : std::max(static_cast<int>(floor(dfSrcLine - dfYScaledRadius + 0.5)),
3998 404544 : nChunkYOff);
3999 404544 : const int nSrcLineStop =
4000 404544 : std::min(static_cast<int>(dfSrcLine + dfYScaledRadius + 0.5),
4001 404544 : nChunkBottomYOff);
4002 : #if 0
4003 : if( nSrcLineStart < nChunkYOff &&
4004 : nChunkYOff > 0 )
4005 : {
4006 : printf( "truncated iDstLine = %d\n", iDstLine );/*ok*/
4007 : }
4008 : if( nSrcLineStop > nChunkBottomYOff && nChunkBottomYOff < nSrcHeight )
4009 : {
4010 : printf( "truncated iDstLine = %d\n", iDstLine );/*ok*/
4011 : }
4012 : #endif
4013 404544 : const int nSrcLineCount = nSrcLineStop - nSrcLineStart;
4014 404544 : double dfWeightSum = 0.0;
4015 :
4016 : // Compute convolution coefficients.
4017 404544 : int nSrcLine = nSrcLineStart; // Used after for.
4018 404544 : double dfY = dfYScaleWeight * (nSrcLine - dfSrcLine + 0.5);
4019 1076797 : for (; nSrcLine < nSrcLineStop - 3;
4020 672253 : nSrcLine += 4, dfY += 4 * dfYScaleWeight)
4021 : {
4022 672253 : padfWeights[nSrcLine - nSrcLineStart] = dfY;
4023 672253 : padfWeights[nSrcLine + 1 - nSrcLineStart] = dfY + dfYScaleWeight;
4024 672253 : padfWeights[nSrcLine + 2 - nSrcLineStart] =
4025 672253 : dfY + 2 * dfYScaleWeight;
4026 672253 : padfWeights[nSrcLine + 3 - nSrcLineStart] =
4027 672253 : dfY + 3 * dfYScaleWeight;
4028 672253 : dfWeightSum +=
4029 672253 : pfnFilterFunc4Values(padfWeights + nSrcLine - nSrcLineStart);
4030 : }
4031 443434 : for (; nSrcLine < nSrcLineStop; ++nSrcLine, dfY += dfYScaleWeight)
4032 : {
4033 38890 : const double dfWeight = pfnFilterFunc(dfY);
4034 38890 : padfWeights[nSrcLine - nSrcLineStart] = dfWeight;
4035 38890 : dfWeightSum += dfWeight;
4036 : }
4037 :
4038 404544 : if (pabyChunkNodataMask == nullptr)
4039 : {
4040 : // For floating-point data types, we must scale down a bit values
4041 : // if input values are close to +/- std::numeric_limits<T>::max()
4042 : #ifdef OLD_CPPCHECK
4043 : constexpr double mulFactor = 1;
4044 : #else
4045 360192 : constexpr double mulFactor =
4046 : (bNeedRescale &&
4047 : (std::is_same_v<T, float> || std::is_same_v<T, double>))
4048 : ? 2
4049 : : 1;
4050 : #endif
4051 :
4052 360192 : if (dfWeightSum != 0)
4053 : {
4054 360192 : const double dfInvWeightSum = 1.0 / (mulFactor * dfWeightSum);
4055 2617653 : for (int i = 0; i < nSrcLineCount; ++i)
4056 2257467 : padfWeights[i] *= dfInvWeightSum;
4057 : }
4058 :
4059 360192 : int iFilteredPixelOff = 0; // Used after for.
4060 : // j used after for.
4061 360192 : size_t j =
4062 360192 : (nSrcLineStart - nChunkYOff) * static_cast<size_t>(nDstXSize);
4063 : #ifdef USE_SSE2
4064 : if constexpr ((!bNeedRescale || !std::is_same_v<T, float>) &&
4065 : eWrkDataType == GDT_Float32)
4066 : {
4067 : #ifdef __AVX__
4068 : for (; iFilteredPixelOff < nDstXSize - 15;
4069 : iFilteredPixelOff += 16, j += 16)
4070 : {
4071 : GDALResampleConvolutionVertical_16cols(
4072 : padfHorizontalFiltered + j, nDstXSize, padfWeights,
4073 : nSrcLineCount, pafDstScanline + iFilteredPixelOff);
4074 : if (bHasNoData)
4075 : {
4076 : for (int k = 0; k < 16; k++)
4077 : {
4078 : pafDstScanline[iFilteredPixelOff + k] =
4079 : replaceValIfNodata(
4080 : pafDstScanline[iFilteredPixelOff + k]);
4081 : }
4082 : }
4083 : }
4084 : #else
4085 26155459 : for (; iFilteredPixelOff < nDstXSize - 7;
4086 : iFilteredPixelOff += 8, j += 8)
4087 : {
4088 25804048 : GDALResampleConvolutionVertical_8cols(
4089 25804048 : padfHorizontalFiltered + j, nDstXSize, padfWeights,
4090 25804048 : nSrcLineCount, pafDstScanline + iFilteredPixelOff);
4091 25804048 : if (bHasNoData)
4092 : {
4093 123192 : for (int k = 0; k < 8; k++)
4094 : {
4095 109504 : pafDstScanline[iFilteredPixelOff + k] =
4096 109504 : replaceValIfNodata(
4097 109504 : pafDstScanline[iFilteredPixelOff + k]);
4098 : }
4099 : }
4100 : }
4101 : #endif
4102 :
4103 822491 : for (; iFilteredPixelOff < nDstXSize; iFilteredPixelOff++, j++)
4104 : {
4105 471118 : const Twork fVal =
4106 471118 : static_cast<Twork>(GDALResampleConvolutionVertical(
4107 471118 : padfHorizontalFiltered + j, nDstXSize, padfWeights,
4108 : nSrcLineCount));
4109 471118 : pafDstScanline[iFilteredPixelOff] =
4110 471118 : replaceValIfNodata(fVal);
4111 : }
4112 : }
4113 : else
4114 : #endif
4115 : {
4116 5862642 : const auto ScaleValue = [
4117 : #ifdef _MSC_VER
4118 : mulFactor
4119 : #endif
4120 : ](double dfVal, [[maybe_unused]] const double *inputValues,
4121 : [[maybe_unused]] int nStride,
4122 : [[maybe_unused]] int nInputValues)
4123 : {
4124 5862640 : constexpr bool isFloat =
4125 : std::is_same_v<T, float> || std::is_same_v<T, double>;
4126 : if constexpr (isFloat)
4127 : {
4128 5862640 : if (std::isfinite(dfVal))
4129 : {
4130 : return std::clamp(
4131 : dfVal,
4132 : static_cast<double>(
4133 17585400 : -std::numeric_limits<Twork>::max()) /
4134 : mulFactor,
4135 : static_cast<double>(
4136 5861800 : std::numeric_limits<Twork>::max()) /
4137 5861800 : mulFactor) *
4138 5861800 : mulFactor;
4139 : }
4140 : else if constexpr (bKernelWithNegativeWeights)
4141 : {
4142 480 : if (std::isnan(dfVal))
4143 : {
4144 : // Either one of the input value is NaN or they are +/-Inf
4145 480 : const bool isPositive = inputValues[0] >= 0;
4146 2520 : for (int i = 0; i < nInputValues; ++i)
4147 : {
4148 2200 : if (std::isnan(inputValues[i * nStride]))
4149 160 : return dfVal;
4150 : // cppcheck-suppress knownConditionTrueFalse
4151 2040 : if ((inputValues[i] >= 0) != isPositive)
4152 0 : return dfVal;
4153 : }
4154 : // All values are positive or negative infinity
4155 320 : return inputValues[0];
4156 : }
4157 : }
4158 : }
4159 :
4160 360 : return dfVal;
4161 : };
4162 :
4163 2939422 : for (; iFilteredPixelOff < nDstXSize - 1;
4164 : iFilteredPixelOff += 2, j += 2)
4165 : {
4166 2930610 : double dfVal1 = 0.0;
4167 2930610 : double dfVal2 = 0.0;
4168 2930610 : GDALResampleConvolutionVertical_2cols(
4169 2930610 : padfHorizontalFiltered + j, nDstXSize, padfWeights,
4170 : nSrcLineCount, dfVal1, dfVal2);
4171 5861220 : pafDstScanline[iFilteredPixelOff] =
4172 2930610 : replaceValIfNodata(static_cast<Twork>(
4173 2930610 : ScaleValue(dfVal1, padfHorizontalFiltered + j,
4174 : nDstXSize, nSrcLineCount)));
4175 2930610 : pafDstScanline[iFilteredPixelOff + 1] =
4176 2930610 : replaceValIfNodata(static_cast<Twork>(
4177 2930610 : ScaleValue(dfVal2, padfHorizontalFiltered + j + 1,
4178 : nDstXSize, nSrcLineCount)));
4179 : }
4180 8819 : if (iFilteredPixelOff < nDstXSize)
4181 : {
4182 1427 : const double dfVal = GDALResampleConvolutionVertical(
4183 1427 : padfHorizontalFiltered + j, nDstXSize, padfWeights,
4184 : nSrcLineCount);
4185 1427 : pafDstScanline[iFilteredPixelOff] =
4186 1427 : replaceValIfNodata(static_cast<Twork>(
4187 1427 : ScaleValue(dfVal, padfHorizontalFiltered + j,
4188 : nDstXSize, nSrcLineCount)));
4189 : }
4190 : }
4191 : }
4192 : else
4193 : {
4194 19948965 : for (int iFilteredPixelOff = 0; iFilteredPixelOff < nDstXSize;
4195 : ++iFilteredPixelOff)
4196 : {
4197 19904685 : double dfVal = 0.0;
4198 19904685 : dfWeightSum = 0.0;
4199 19904685 : size_t j = (nSrcLineStart - nChunkYOff) *
4200 19904685 : static_cast<size_t>(nDstXSize) +
4201 19904685 : iFilteredPixelOff;
4202 : if (bKernelWithNegativeWeights)
4203 : {
4204 18637437 : int nConsecutiveValid = 0;
4205 18637437 : int nMaxConsecutiveValid = 0;
4206 162845921 : for (int i = 0; i < nSrcLineCount; ++i, j += nDstXSize)
4207 : {
4208 144208284 : const double dfWeight =
4209 144208284 : padfWeights[i] *
4210 : pabyChunkNodataMaskHorizontalFiltered[j];
4211 144208284 : if (pabyChunkNodataMaskHorizontalFiltered[j])
4212 : {
4213 45969501 : nConsecutiveValid++;
4214 : }
4215 98238683 : else if (nConsecutiveValid)
4216 : {
4217 211128 : nMaxConsecutiveValid = std::max(
4218 211128 : nMaxConsecutiveValid, nConsecutiveValid);
4219 211128 : nConsecutiveValid = 0;
4220 : }
4221 144208284 : dfVal += padfHorizontalFiltered[j] * dfWeight;
4222 144208284 : dfWeightSum += dfWeight;
4223 : }
4224 18637437 : nMaxConsecutiveValid =
4225 18637437 : std::max(nMaxConsecutiveValid, nConsecutiveValid);
4226 18637437 : if (nMaxConsecutiveValid < nSrcLineCount / 2)
4227 : {
4228 9501801 : pafDstScanline[iFilteredPixelOff] =
4229 9501709 : static_cast<Twork>(dfNoDataValue);
4230 9501801 : continue;
4231 : }
4232 : }
4233 : else
4234 : {
4235 6353336 : for (int i = 0; i < nSrcLineCount; ++i, j += nDstXSize)
4236 : {
4237 5086078 : const double dfWeight =
4238 5086078 : padfWeights[i] *
4239 : pabyChunkNodataMaskHorizontalFiltered[j];
4240 5086078 : dfVal += padfHorizontalFiltered[j] * dfWeight;
4241 5086078 : dfWeightSum += dfWeight;
4242 : }
4243 : }
4244 10402854 : if (dfWeightSum > 0.0)
4245 : {
4246 9856520 : pafDstScanline[iFilteredPixelOff] = replaceValIfNodata(
4247 9856172 : static_cast<Twork>(dfVal / dfWeightSum));
4248 : }
4249 : else
4250 : {
4251 546347 : pafDstScanline[iFilteredPixelOff] =
4252 546323 : static_cast<Twork>(dfNoDataValue);
4253 : }
4254 : }
4255 : }
4256 :
4257 404544 : if (fMaxVal != 0.0f)
4258 : {
4259 : if constexpr (std::is_same_v<T, double>)
4260 : {
4261 0 : for (int i = 0; i < nDstXSize; ++i)
4262 : {
4263 0 : if (pafDstScanline[i] > static_cast<double>(fMaxVal))
4264 0 : pafDstScanline[i] = static_cast<double>(fMaxVal);
4265 : }
4266 : }
4267 : else
4268 : {
4269 192324 : for (int i = 0; i < nDstXSize; ++i)
4270 : {
4271 192088 : if (pafDstScanline[i] > fMaxVal)
4272 96022 : pafDstScanline[i] = fMaxVal;
4273 : }
4274 : }
4275 : }
4276 :
4277 404544 : if (pafWrkScanline)
4278 : {
4279 390516 : GDALCopyWords64(pafWrkScanline, eWrkDataType, nWrkDataTypeSize,
4280 : static_cast<GByte *>(pDstBuffer) +
4281 390516 : static_cast<size_t>(iDstLine - nDstYOff) *
4282 390516 : nDstXSize * nDstDataTypeSize,
4283 : dstDataType, nDstDataTypeSize, nDstXSize);
4284 : }
4285 : }
4286 :
4287 9597 : VSIFree(pafWrkScanline);
4288 9597 : VSIFreeAligned(padfWeights);
4289 9597 : VSIFree(padfHorizontalFiltered);
4290 9597 : VSIFree(pabyChunkNodataMaskHorizontalFiltered);
4291 :
4292 9597 : return CE_None;
4293 : }
4294 :
4295 : template <bool bKernelWithNegativeWeights, bool bNeedRescale>
4296 : static CPLErr
4297 9597 : GDALResampleChunk_ConvolutionInternal(const GDALOverviewResampleArgs &args,
4298 : const void *pChunk, void **ppDstBuffer,
4299 : GDALDataType *peDstBufferDataType)
4300 : {
4301 : GDALResampleAlg eResample;
4302 9597 : if (EQUAL(args.pszResampling, "BILINEAR"))
4303 7097 : eResample = GRA_Bilinear;
4304 2500 : else if (EQUAL(args.pszResampling, "CUBIC"))
4305 2318 : eResample = GRA_Cubic;
4306 182 : else if (EQUAL(args.pszResampling, "CUBICSPLINE"))
4307 86 : eResample = GRA_CubicSpline;
4308 96 : else if (EQUAL(args.pszResampling, "LANCZOS"))
4309 96 : eResample = GRA_Lanczos;
4310 : else
4311 : {
4312 0 : CPLAssert(false);
4313 : return CE_Failure;
4314 : }
4315 9597 : const int nKernelRadius = GWKGetFilterRadius(eResample);
4316 9597 : FilterFuncType pfnFilterFunc = GWKGetFilterFunc(eResample);
4317 : const FilterFunc4ValuesType pfnFilterFunc4Values =
4318 9597 : GWKGetFilterFunc4Values(eResample);
4319 :
4320 9597 : float fMaxVal = 0.f;
4321 : // Cubic, etc... can have overshoots, so make sure we clamp values to the
4322 : // maximum value if NBITS is set.
4323 9597 : if (eResample != GRA_Bilinear && args.nOvrNBITS > 0 &&
4324 8 : (args.eOvrDataType == GDT_UInt8 || args.eOvrDataType == GDT_UInt16 ||
4325 0 : args.eOvrDataType == GDT_UInt32))
4326 : {
4327 8 : int nBits = args.nOvrNBITS;
4328 8 : if (nBits == GDALGetDataTypeSizeBits(args.eOvrDataType))
4329 1 : nBits = 0;
4330 8 : if (nBits > 0 && nBits < 32)
4331 7 : fMaxVal = static_cast<float>((1U << nBits) - 1);
4332 : }
4333 :
4334 9597 : *ppDstBuffer = VSI_MALLOC3_VERBOSE(
4335 : args.nDstXOff2 - args.nDstXOff, args.nDstYOff2 - args.nDstYOff,
4336 : GDALGetDataTypeSizeBytes(args.eOvrDataType));
4337 9597 : if (*ppDstBuffer == nullptr)
4338 : {
4339 0 : return CE_Failure;
4340 : }
4341 9597 : *peDstBufferDataType = args.eOvrDataType;
4342 :
4343 9597 : switch (args.eWrkDataType)
4344 : {
4345 8705 : case GDT_UInt8:
4346 : {
4347 : return GDALResampleChunk_ConvolutionT<GByte, float, GDT_Float32,
4348 : bKernelWithNegativeWeights,
4349 8705 : bNeedRescale>(
4350 : args, static_cast<const GByte *>(pChunk), *ppDstBuffer,
4351 8705 : pfnFilterFunc, pfnFilterFunc4Values, nKernelRadius, fMaxVal);
4352 : }
4353 :
4354 402 : case GDT_UInt16:
4355 : {
4356 : return GDALResampleChunk_ConvolutionT<GUInt16, float, GDT_Float32,
4357 : bKernelWithNegativeWeights,
4358 402 : bNeedRescale>(
4359 : args, static_cast<const GUInt16 *>(pChunk), *ppDstBuffer,
4360 402 : pfnFilterFunc, pfnFilterFunc4Values, nKernelRadius, fMaxVal);
4361 : }
4362 :
4363 387 : case GDT_Float32:
4364 : {
4365 : return GDALResampleChunk_ConvolutionT<float, float, GDT_Float32,
4366 : bKernelWithNegativeWeights,
4367 387 : bNeedRescale>(
4368 : args, static_cast<const float *>(pChunk), *ppDstBuffer,
4369 387 : pfnFilterFunc, pfnFilterFunc4Values, nKernelRadius, fMaxVal);
4370 : }
4371 :
4372 103 : case GDT_Float64:
4373 : {
4374 : return GDALResampleChunk_ConvolutionT<double, double, GDT_Float64,
4375 : bKernelWithNegativeWeights,
4376 103 : bNeedRescale>(
4377 : args, static_cast<const double *>(pChunk), *ppDstBuffer,
4378 103 : pfnFilterFunc, pfnFilterFunc4Values, nKernelRadius, fMaxVal);
4379 : }
4380 :
4381 0 : default:
4382 0 : break;
4383 : }
4384 :
4385 0 : CPLAssert(false);
4386 : return CE_Failure;
4387 : }
4388 :
4389 : static CPLErr
4390 9597 : GDALResampleChunk_Convolution(const GDALOverviewResampleArgs &args,
4391 : const void *pChunk, void **ppDstBuffer,
4392 : GDALDataType *peDstBufferDataType)
4393 : {
4394 9597 : if (EQUAL(args.pszResampling, "CUBIC") ||
4395 7279 : EQUAL(args.pszResampling, "LANCZOS"))
4396 : return GDALResampleChunk_ConvolutionInternal<
4397 2414 : /* bKernelWithNegativeWeights=*/true, /* bNeedRescale = */ true>(
4398 2414 : args, pChunk, ppDstBuffer, peDstBufferDataType);
4399 7183 : else if (EQUAL(args.pszResampling, "CUBICSPLINE"))
4400 86 : return GDALResampleChunk_ConvolutionInternal<false, true>(
4401 86 : args, pChunk, ppDstBuffer, peDstBufferDataType);
4402 : else
4403 7097 : return GDALResampleChunk_ConvolutionInternal<false, false>(
4404 7097 : args, pChunk, ppDstBuffer, peDstBufferDataType);
4405 : }
4406 :
4407 : /************************************************************************/
4408 : /* GDALResampleChunkC32R() */
4409 : /************************************************************************/
4410 :
4411 2 : static CPLErr GDALResampleChunkC32R(const int nSrcWidth, const int nSrcHeight,
4412 : const float *pafChunk, const int nChunkYOff,
4413 : const int nChunkYSize, const int nDstYOff,
4414 : const int nDstYOff2, const int nOvrXSize,
4415 : const int nOvrYSize, void **ppDstBuffer,
4416 : GDALDataType *peDstBufferDataType,
4417 : const char *pszResampling)
4418 :
4419 : {
4420 : enum Method
4421 : {
4422 : NEAR,
4423 : AVERAGE,
4424 : AVERAGE_MAGPHASE,
4425 : RMS,
4426 : };
4427 :
4428 2 : Method eMethod = NEAR;
4429 2 : if (STARTS_WITH_CI(pszResampling, "NEAR"))
4430 : {
4431 0 : eMethod = NEAR;
4432 : }
4433 2 : else if (EQUAL(pszResampling, "AVERAGE_MAGPHASE"))
4434 : {
4435 0 : eMethod = AVERAGE_MAGPHASE;
4436 : }
4437 2 : else if (EQUAL(pszResampling, "RMS"))
4438 : {
4439 2 : eMethod = RMS;
4440 : }
4441 0 : else if (STARTS_WITH_CI(pszResampling, "AVER"))
4442 : {
4443 0 : eMethod = AVERAGE;
4444 : }
4445 : else
4446 : {
4447 0 : CPLError(
4448 : CE_Failure, CPLE_NotSupported,
4449 : "Resampling method %s is not supported for complex data types. "
4450 : "Only NEAREST, AVERAGE, AVERAGE_MAGPHASE and RMS are supported",
4451 : pszResampling);
4452 0 : return CE_Failure;
4453 : }
4454 :
4455 2 : const int nOXSize = nOvrXSize;
4456 2 : *ppDstBuffer = VSI_MALLOC3_VERBOSE(nOXSize, nDstYOff2 - nDstYOff,
4457 : GDALGetDataTypeSizeBytes(GDT_CFloat32));
4458 2 : if (*ppDstBuffer == nullptr)
4459 : {
4460 0 : return CE_Failure;
4461 : }
4462 2 : float *const pafDstBuffer = static_cast<float *>(*ppDstBuffer);
4463 2 : *peDstBufferDataType = GDT_CFloat32;
4464 :
4465 2 : const int nOYSize = nOvrYSize;
4466 2 : const double dfXRatioDstToSrc = static_cast<double>(nSrcWidth) / nOXSize;
4467 2 : const double dfYRatioDstToSrc = static_cast<double>(nSrcHeight) / nOYSize;
4468 :
4469 : /* ==================================================================== */
4470 : /* Loop over destination scanlines. */
4471 : /* ==================================================================== */
4472 8 : for (int iDstLine = nDstYOff; iDstLine < nDstYOff2; ++iDstLine)
4473 : {
4474 6 : int nSrcYOff = static_cast<int>(0.5 + iDstLine * dfYRatioDstToSrc);
4475 6 : if (nSrcYOff < nChunkYOff)
4476 0 : nSrcYOff = nChunkYOff;
4477 :
4478 6 : int nSrcYOff2 =
4479 6 : static_cast<int>(0.5 + (iDstLine + 1) * dfYRatioDstToSrc);
4480 6 : if (nSrcYOff2 == nSrcYOff)
4481 0 : nSrcYOff2++;
4482 :
4483 6 : if (nSrcYOff2 > nSrcHeight || iDstLine == nOYSize - 1)
4484 : {
4485 2 : if (nSrcYOff == nSrcHeight && nSrcHeight - 1 >= nChunkYOff)
4486 0 : nSrcYOff = nSrcHeight - 1;
4487 2 : nSrcYOff2 = nSrcHeight;
4488 : }
4489 6 : if (nSrcYOff2 > nChunkYOff + nChunkYSize)
4490 0 : nSrcYOff2 = nChunkYOff + nChunkYSize;
4491 :
4492 6 : const float *const pafSrcScanline =
4493 6 : pafChunk +
4494 6 : (static_cast<size_t>(nSrcYOff - nChunkYOff) * nSrcWidth) * 2;
4495 6 : float *const pafDstScanline =
4496 6 : pafDstBuffer +
4497 6 : static_cast<size_t>(iDstLine - nDstYOff) * 2 * nOXSize;
4498 :
4499 : /* --------------------------------------------------------------------
4500 : */
4501 : /* Loop over destination pixels */
4502 : /* --------------------------------------------------------------------
4503 : */
4504 18 : for (int iDstPixel = 0; iDstPixel < nOXSize; ++iDstPixel)
4505 : {
4506 12 : const size_t iDstPixelSZ = static_cast<size_t>(iDstPixel);
4507 12 : int nSrcXOff = static_cast<int>(0.5 + iDstPixel * dfXRatioDstToSrc);
4508 12 : int nSrcXOff2 =
4509 12 : static_cast<int>(0.5 + (iDstPixel + 1) * dfXRatioDstToSrc);
4510 12 : if (nSrcXOff2 == nSrcXOff)
4511 0 : nSrcXOff2++;
4512 12 : if (nSrcXOff2 > nSrcWidth || iDstPixel == nOXSize - 1)
4513 : {
4514 6 : if (nSrcXOff == nSrcWidth && nSrcWidth - 1 >= 0)
4515 0 : nSrcXOff = nSrcWidth - 1;
4516 6 : nSrcXOff2 = nSrcWidth;
4517 : }
4518 12 : const size_t nSrcXOffSZ = static_cast<size_t>(nSrcXOff);
4519 :
4520 12 : if (eMethod == NEAR)
4521 : {
4522 0 : pafDstScanline[iDstPixelSZ * 2] =
4523 0 : pafSrcScanline[nSrcXOffSZ * 2];
4524 0 : pafDstScanline[iDstPixelSZ * 2 + 1] =
4525 0 : pafSrcScanline[nSrcXOffSZ * 2 + 1];
4526 : }
4527 12 : else if (eMethod == AVERAGE_MAGPHASE)
4528 : {
4529 0 : double dfTotalR = 0.0;
4530 0 : double dfTotalI = 0.0;
4531 0 : double dfTotalM = 0.0;
4532 0 : size_t nCount = 0;
4533 :
4534 0 : for (int iY = nSrcYOff; iY < nSrcYOff2; ++iY)
4535 : {
4536 0 : for (int iX = nSrcXOff; iX < nSrcXOff2; ++iX)
4537 : {
4538 0 : const double dfR = double(
4539 0 : pafSrcScanline[static_cast<size_t>(iX) * 2 +
4540 0 : static_cast<size_t>(iY - nSrcYOff) *
4541 0 : nSrcWidth * 2]);
4542 0 : const double dfI = double(
4543 0 : pafSrcScanline[static_cast<size_t>(iX) * 2 +
4544 0 : static_cast<size_t>(iY - nSrcYOff) *
4545 0 : nSrcWidth * 2 +
4546 0 : 1]);
4547 0 : dfTotalR += dfR;
4548 0 : dfTotalI += dfI;
4549 0 : dfTotalM += std::hypot(dfR, dfI);
4550 0 : ++nCount;
4551 : }
4552 : }
4553 :
4554 0 : CPLAssert(nCount > 0);
4555 0 : if (nCount == 0)
4556 : {
4557 0 : pafDstScanline[iDstPixelSZ * 2] = 0.0;
4558 0 : pafDstScanline[iDstPixelSZ * 2 + 1] = 0.0;
4559 : }
4560 : else
4561 : {
4562 0 : pafDstScanline[iDstPixelSZ * 2] = static_cast<float>(
4563 0 : dfTotalR / static_cast<double>(nCount));
4564 0 : pafDstScanline[iDstPixelSZ * 2 + 1] = static_cast<float>(
4565 0 : dfTotalI / static_cast<double>(nCount));
4566 : const double dfM =
4567 0 : double(std::hypot(pafDstScanline[iDstPixelSZ * 2],
4568 0 : pafDstScanline[iDstPixelSZ * 2 + 1]));
4569 0 : const double dfDesiredM =
4570 0 : dfTotalM / static_cast<double>(nCount);
4571 0 : double dfRatio = 1.0;
4572 0 : if (dfM != 0.0)
4573 0 : dfRatio = dfDesiredM / dfM;
4574 :
4575 0 : pafDstScanline[iDstPixelSZ * 2] *=
4576 0 : static_cast<float>(dfRatio);
4577 0 : pafDstScanline[iDstPixelSZ * 2 + 1] *=
4578 0 : static_cast<float>(dfRatio);
4579 : }
4580 : }
4581 12 : else if (eMethod == RMS)
4582 : {
4583 12 : double dfTotalR = 0.0;
4584 12 : double dfTotalI = 0.0;
4585 12 : size_t nCount = 0;
4586 :
4587 36 : for (int iY = nSrcYOff; iY < nSrcYOff2; ++iY)
4588 : {
4589 72 : for (int iX = nSrcXOff; iX < nSrcXOff2; ++iX)
4590 : {
4591 48 : const double dfR = double(
4592 48 : pafSrcScanline[static_cast<size_t>(iX) * 2 +
4593 48 : static_cast<size_t>(iY - nSrcYOff) *
4594 48 : nSrcWidth * 2]);
4595 48 : const double dfI = double(
4596 48 : pafSrcScanline[static_cast<size_t>(iX) * 2 +
4597 48 : static_cast<size_t>(iY - nSrcYOff) *
4598 48 : nSrcWidth * 2 +
4599 48 : 1]);
4600 :
4601 48 : dfTotalR += SQUARE(dfR);
4602 48 : dfTotalI += SQUARE(dfI);
4603 :
4604 48 : ++nCount;
4605 : }
4606 : }
4607 :
4608 12 : CPLAssert(nCount > 0);
4609 12 : if (nCount == 0)
4610 : {
4611 0 : pafDstScanline[iDstPixelSZ * 2] = 0.0;
4612 0 : pafDstScanline[iDstPixelSZ * 2 + 1] = 0.0;
4613 : }
4614 : else
4615 : {
4616 : /* compute RMS */
4617 12 : pafDstScanline[iDstPixelSZ * 2] = static_cast<float>(
4618 12 : sqrt(dfTotalR / static_cast<double>(nCount)));
4619 12 : pafDstScanline[iDstPixelSZ * 2 + 1] = static_cast<float>(
4620 12 : sqrt(dfTotalI / static_cast<double>(nCount)));
4621 : }
4622 : }
4623 0 : else if (eMethod == AVERAGE)
4624 : {
4625 0 : double dfTotalR = 0.0;
4626 0 : double dfTotalI = 0.0;
4627 0 : size_t nCount = 0;
4628 :
4629 0 : for (int iY = nSrcYOff; iY < nSrcYOff2; ++iY)
4630 : {
4631 0 : for (int iX = nSrcXOff; iX < nSrcXOff2; ++iX)
4632 : {
4633 : // TODO(schwehr): Maybe use std::complex?
4634 0 : dfTotalR += double(
4635 0 : pafSrcScanline[static_cast<size_t>(iX) * 2 +
4636 0 : static_cast<size_t>(iY - nSrcYOff) *
4637 0 : nSrcWidth * 2]);
4638 0 : dfTotalI += double(
4639 0 : pafSrcScanline[static_cast<size_t>(iX) * 2 +
4640 0 : static_cast<size_t>(iY - nSrcYOff) *
4641 0 : nSrcWidth * 2 +
4642 0 : 1]);
4643 0 : ++nCount;
4644 : }
4645 : }
4646 :
4647 0 : CPLAssert(nCount > 0);
4648 0 : if (nCount == 0)
4649 : {
4650 0 : pafDstScanline[iDstPixelSZ * 2] = 0.0;
4651 0 : pafDstScanline[iDstPixelSZ * 2 + 1] = 0.0;
4652 : }
4653 : else
4654 : {
4655 0 : pafDstScanline[iDstPixelSZ * 2] = static_cast<float>(
4656 0 : dfTotalR / static_cast<double>(nCount));
4657 0 : pafDstScanline[iDstPixelSZ * 2 + 1] = static_cast<float>(
4658 0 : dfTotalI / static_cast<double>(nCount));
4659 : }
4660 : }
4661 : }
4662 : }
4663 :
4664 2 : return CE_None;
4665 : }
4666 :
4667 : /************************************************************************/
4668 : /* GDALRegenerateCascadingOverviews() */
4669 : /* */
4670 : /* Generate a list of overviews in order from largest to */
4671 : /* smallest, computing each from the next larger. */
4672 : /************************************************************************/
4673 :
4674 44 : static CPLErr GDALRegenerateCascadingOverviews(
4675 : GDALRasterBand *poSrcBand, int nOverviews, GDALRasterBand **papoOvrBands,
4676 : const char *pszResampling, GDALProgressFunc pfnProgress,
4677 : void *pProgressData, CSLConstList papszOptions)
4678 :
4679 : {
4680 : /* -------------------------------------------------------------------- */
4681 : /* First, we must put the overviews in order from largest to */
4682 : /* smallest. */
4683 : /* -------------------------------------------------------------------- */
4684 127 : for (int i = 0; i < nOverviews - 1; ++i)
4685 : {
4686 292 : for (int j = 0; j < nOverviews - i - 1; ++j)
4687 : {
4688 209 : if (papoOvrBands[j]->GetXSize() *
4689 209 : static_cast<float>(papoOvrBands[j]->GetYSize()) <
4690 209 : papoOvrBands[j + 1]->GetXSize() *
4691 209 : static_cast<float>(papoOvrBands[j + 1]->GetYSize()))
4692 : {
4693 0 : GDALRasterBand *poTempBand = papoOvrBands[j];
4694 0 : papoOvrBands[j] = papoOvrBands[j + 1];
4695 0 : papoOvrBands[j + 1] = poTempBand;
4696 : }
4697 : }
4698 : }
4699 :
4700 : /* -------------------------------------------------------------------- */
4701 : /* Count total pixels so we can prepare appropriate scaled */
4702 : /* progress functions. */
4703 : /* -------------------------------------------------------------------- */
4704 44 : double dfTotalPixels = 0.0;
4705 :
4706 171 : for (int i = 0; i < nOverviews; ++i)
4707 : {
4708 127 : dfTotalPixels += papoOvrBands[i]->GetXSize() *
4709 127 : static_cast<double>(papoOvrBands[i]->GetYSize());
4710 : }
4711 :
4712 : /* -------------------------------------------------------------------- */
4713 : /* Generate all the bands. */
4714 : /* -------------------------------------------------------------------- */
4715 44 : double dfPixelsProcessed = 0.0;
4716 :
4717 88 : CPLStringList aosOptions(papszOptions);
4718 44 : aosOptions.SetNameValue("CASCADING", "YES");
4719 171 : for (int i = 0; i < nOverviews; ++i)
4720 : {
4721 127 : GDALRasterBand *poBaseBand = poSrcBand;
4722 127 : if (i != 0)
4723 83 : poBaseBand = papoOvrBands[i - 1];
4724 :
4725 127 : double dfPixels = papoOvrBands[i]->GetXSize() *
4726 127 : static_cast<double>(papoOvrBands[i]->GetYSize());
4727 :
4728 254 : void *pScaledProgressData = GDALCreateScaledProgress(
4729 : dfPixelsProcessed / dfTotalPixels,
4730 127 : (dfPixelsProcessed + dfPixels) / dfTotalPixels, pfnProgress,
4731 : pProgressData);
4732 :
4733 254 : const CPLErr eErr = GDALRegenerateOverviewsEx(
4734 : poBaseBand, 1,
4735 127 : reinterpret_cast<GDALRasterBandH *>(papoOvrBands) + i,
4736 : pszResampling, GDALScaledProgress, pScaledProgressData,
4737 127 : aosOptions.List());
4738 127 : GDALDestroyScaledProgress(pScaledProgressData);
4739 :
4740 127 : if (eErr != CE_None)
4741 0 : return eErr;
4742 :
4743 127 : dfPixelsProcessed += dfPixels;
4744 :
4745 : // Only do the bit2grayscale promotion on the base band.
4746 127 : if (STARTS_WITH_CI(pszResampling,
4747 : "AVERAGE_BIT2G" /* AVERAGE_BIT2GRAYSCALE */))
4748 8 : pszResampling = "AVERAGE";
4749 : }
4750 :
4751 44 : return CE_None;
4752 : }
4753 :
4754 : /************************************************************************/
4755 : /* GDALGetResampleFunction() */
4756 : /************************************************************************/
4757 :
4758 19313 : GDALResampleFunction GDALGetResampleFunction(const char *pszResampling,
4759 : int *pnRadius)
4760 : {
4761 19313 : if (pnRadius)
4762 19313 : *pnRadius = 0;
4763 19313 : if (STARTS_WITH_CI(pszResampling, "NEAR"))
4764 577 : return GDALResampleChunk_Near;
4765 18736 : else if (STARTS_WITH_CI(pszResampling, "AVER") ||
4766 7508 : EQUAL(pszResampling, "RMS"))
4767 11293 : return GDALResampleChunk_AverageOrRMS;
4768 7443 : else if (EQUAL(pszResampling, "GAUSS"))
4769 : {
4770 26 : if (pnRadius)
4771 26 : *pnRadius = 1;
4772 26 : return GDALResampleChunk_Gauss;
4773 : }
4774 7417 : else if (EQUAL(pszResampling, "MODE"))
4775 142 : return GDALResampleChunk_Mode;
4776 7275 : else if (EQUAL(pszResampling, "CUBIC"))
4777 : {
4778 1648 : if (pnRadius)
4779 1648 : *pnRadius = GWKGetFilterRadius(GRA_Cubic);
4780 1648 : return GDALResampleChunk_Convolution;
4781 : }
4782 5627 : else if (EQUAL(pszResampling, "CUBICSPLINE"))
4783 : {
4784 60 : if (pnRadius)
4785 60 : *pnRadius = GWKGetFilterRadius(GRA_CubicSpline);
4786 60 : return GDALResampleChunk_Convolution;
4787 : }
4788 5567 : else if (EQUAL(pszResampling, "LANCZOS"))
4789 : {
4790 50 : if (pnRadius)
4791 50 : *pnRadius = GWKGetFilterRadius(GRA_Lanczos);
4792 50 : return GDALResampleChunk_Convolution;
4793 : }
4794 5517 : else if (EQUAL(pszResampling, "BILINEAR"))
4795 : {
4796 5517 : if (pnRadius)
4797 5517 : *pnRadius = GWKGetFilterRadius(GRA_Bilinear);
4798 5517 : return GDALResampleChunk_Convolution;
4799 : }
4800 : else
4801 : {
4802 0 : CPLError(
4803 : CE_Failure, CPLE_AppDefined,
4804 : "GDALGetResampleFunction: Unsupported resampling method \"%s\".",
4805 : pszResampling);
4806 0 : return nullptr;
4807 : }
4808 : }
4809 :
4810 : /************************************************************************/
4811 : /* GDALGetOvrWorkDataType() */
4812 : /************************************************************************/
4813 :
4814 19195 : GDALDataType GDALGetOvrWorkDataType(const char *pszResampling,
4815 : GDALDataType eSrcDataType)
4816 : {
4817 19195 : if (STARTS_WITH_CI(pszResampling, "NEAR") || EQUAL(pszResampling, "MODE"))
4818 : {
4819 711 : return eSrcDataType;
4820 : }
4821 18484 : else if (eSrcDataType == GDT_UInt8 &&
4822 17911 : (STARTS_WITH_CI(pszResampling, "AVER") ||
4823 6781 : EQUAL(pszResampling, "RMS") || EQUAL(pszResampling, "CUBIC") ||
4824 5375 : EQUAL(pszResampling, "CUBICSPLINE") ||
4825 5355 : EQUAL(pszResampling, "LANCZOS") ||
4826 5348 : EQUAL(pszResampling, "BILINEAR") || EQUAL(pszResampling, "MODE")))
4827 : {
4828 17904 : return GDT_UInt8;
4829 : }
4830 580 : else if (eSrcDataType == GDT_UInt16 &&
4831 131 : (STARTS_WITH_CI(pszResampling, "AVER") ||
4832 126 : EQUAL(pszResampling, "RMS") || EQUAL(pszResampling, "CUBIC") ||
4833 8 : EQUAL(pszResampling, "CUBICSPLINE") ||
4834 6 : EQUAL(pszResampling, "LANCZOS") ||
4835 3 : EQUAL(pszResampling, "BILINEAR") || EQUAL(pszResampling, "MODE")))
4836 : {
4837 131 : return GDT_UInt16;
4838 : }
4839 449 : else if (EQUAL(pszResampling, "GAUSS"))
4840 20 : return GDT_Float64;
4841 :
4842 429 : if (eSrcDataType == GDT_UInt8 || eSrcDataType == GDT_Int8 ||
4843 428 : eSrcDataType == GDT_UInt16 || eSrcDataType == GDT_Int16 ||
4844 : eSrcDataType == GDT_Float32)
4845 : {
4846 277 : return GDT_Float32;
4847 : }
4848 152 : return GDT_Float64;
4849 : }
4850 :
4851 : namespace
4852 : {
4853 : // Structure to hold a pointer to free with CPLFree()
4854 : struct PointerHolder
4855 : {
4856 : void *ptr = nullptr;
4857 :
4858 4134 : template <class T> explicit PointerHolder(T *&ptrIn) : ptr(ptrIn)
4859 : {
4860 4134 : ptrIn = nullptr;
4861 4134 : }
4862 :
4863 : template <class T>
4864 32 : explicit PointerHolder(std::unique_ptr<T, VSIFreeReleaser> ptrIn)
4865 32 : : ptr(ptrIn.release())
4866 : {
4867 32 : }
4868 :
4869 4166 : ~PointerHolder()
4870 4166 : {
4871 4166 : CPLFree(ptr);
4872 4166 : }
4873 :
4874 : PointerHolder(const PointerHolder &) = delete;
4875 : PointerHolder &operator=(const PointerHolder &) = delete;
4876 : };
4877 : } // namespace
4878 :
4879 : /************************************************************************/
4880 : /* GDALRegenerateOverviews() */
4881 : /************************************************************************/
4882 :
4883 : /**
4884 : * \brief Generate downsampled overviews.
4885 : *
4886 : * This function will generate one or more overview images from a base image
4887 : * using the requested downsampling algorithm. Its primary use is for
4888 : * generating overviews via GDALDataset::BuildOverviews(), but it can also be
4889 : * used to generate downsampled images in one file from another outside the
4890 : * overview architecture.
4891 : *
4892 : * The output bands need to exist in advance.
4893 : *
4894 : * The full set of resampling algorithms is documented in
4895 : * GDALDataset::BuildOverviews().
4896 : *
4897 : * This function will honour properly NODATA_VALUES tuples (special dataset
4898 : * metadata) so that only a given RGB triplet (in case of a RGB image) will be
4899 : * considered as the nodata value and not each value of the triplet
4900 : * independently per band.
4901 : *
4902 : * Starting with GDAL 3.2, the GDAL_NUM_THREADS configuration option can be set
4903 : * to "ALL_CPUS" or a integer value to specify the number of threads to use for
4904 : * overview computation.
4905 : *
4906 : * @param hSrcBand the source (base level) band.
4907 : * @param nOverviewCount the number of downsampled bands being generated.
4908 : * @param pahOvrBands the list of downsampled bands to be generated.
4909 : * @param pszResampling Resampling algorithm (e.g. "AVERAGE").
4910 : * @param pfnProgress progress report function.
4911 : * @param pProgressData progress function callback data.
4912 : * @return CE_None on success or CE_Failure on failure.
4913 : */
4914 113 : CPLErr GDALRegenerateOverviews(GDALRasterBandH hSrcBand, int nOverviewCount,
4915 : GDALRasterBandH *pahOvrBands,
4916 : const char *pszResampling,
4917 : GDALProgressFunc pfnProgress,
4918 : void *pProgressData)
4919 :
4920 : {
4921 113 : return GDALRegenerateOverviewsEx(hSrcBand, nOverviewCount, pahOvrBands,
4922 : pszResampling, pfnProgress, pProgressData,
4923 113 : nullptr);
4924 : }
4925 :
4926 : /************************************************************************/
4927 : /* GDALRegenerateOverviewsEx() */
4928 : /************************************************************************/
4929 :
4930 : constexpr int RADIUS_TO_DIAMETER = 2;
4931 :
4932 : /**
4933 : * \brief Generate downsampled overviews.
4934 : *
4935 : * This function will generate one or more overview images from a base image
4936 : * using the requested downsampling algorithm. Its primary use is for
4937 : * generating overviews via GDALDataset::BuildOverviews(), but it can also be
4938 : * used to generate downsampled images in one file from another outside the
4939 : * overview architecture.
4940 : *
4941 : * The output bands need to exist in advance.
4942 : *
4943 : * The full set of resampling algorithms is documented in
4944 : * GDALDataset::BuildOverviews().
4945 : *
4946 : * This function will honour properly NODATA_VALUES tuples (special dataset
4947 : * metadata) so that only a given RGB triplet (in case of a RGB image) will be
4948 : * considered as the nodata value and not each value of the triplet
4949 : * independently per band.
4950 : *
4951 : * Starting with GDAL 3.2, the GDAL_NUM_THREADS configuration option can be set
4952 : * to "ALL_CPUS" or a integer value to specify the number of threads to use for
4953 : * overview computation.
4954 : *
4955 : * @param hSrcBand the source (base level) band.
4956 : * @param nOverviewCount the number of downsampled bands being generated.
4957 : * @param pahOvrBands the list of downsampled bands to be generated.
4958 : * @param pszResampling Resampling algorithm (e.g. "AVERAGE").
4959 : * @param pfnProgress progress report function.
4960 : * @param pProgressData progress function callback data.
4961 : * @param papszOptions NULL terminated list of options as key=value pairs, or
4962 : * NULL
4963 : * @return CE_None on success or CE_Failure on failure.
4964 : * @since GDAL 3.6
4965 : */
4966 826 : CPLErr GDALRegenerateOverviewsEx(GDALRasterBandH hSrcBand, int nOverviewCount,
4967 : GDALRasterBandH *pahOvrBands,
4968 : const char *pszResampling,
4969 : GDALProgressFunc pfnProgress,
4970 : void *pProgressData, CSLConstList papszOptions)
4971 :
4972 : {
4973 826 : GDALRasterBand *poSrcBand = GDALRasterBand::FromHandle(hSrcBand);
4974 826 : GDALRasterBand **papoOvrBands =
4975 : reinterpret_cast<GDALRasterBand **>(pahOvrBands);
4976 :
4977 826 : if (pfnProgress == nullptr)
4978 102 : pfnProgress = GDALDummyProgress;
4979 :
4980 826 : if (EQUAL(pszResampling, "NONE"))
4981 51 : return CE_None;
4982 :
4983 775 : int nKernelRadius = 0;
4984 : GDALResampleFunction pfnResampleFn =
4985 775 : GDALGetResampleFunction(pszResampling, &nKernelRadius);
4986 :
4987 775 : if (pfnResampleFn == nullptr)
4988 0 : return CE_Failure;
4989 :
4990 : /* -------------------------------------------------------------------- */
4991 : /* Check color tables... */
4992 : /* -------------------------------------------------------------------- */
4993 775 : GDALColorTable *poColorTable = nullptr;
4994 :
4995 552 : if ((STARTS_WITH_CI(pszResampling, "AVER") || EQUAL(pszResampling, "RMS") ||
4996 1628 : EQUAL(pszResampling, "MODE") || EQUAL(pszResampling, "GAUSS")) &&
4997 312 : poSrcBand->GetColorInterpretation() == GCI_PaletteIndex)
4998 : {
4999 9 : poColorTable = poSrcBand->GetColorTable();
5000 9 : if (poColorTable != nullptr)
5001 : {
5002 9 : if (poColorTable->GetPaletteInterpretation() != GPI_RGB)
5003 : {
5004 0 : CPLError(CE_Warning, CPLE_AppDefined,
5005 : "Computing overviews on palette index raster bands "
5006 : "with a palette whose color interpretation is not RGB "
5007 : "will probably lead to unexpected results.");
5008 0 : poColorTable = nullptr;
5009 : }
5010 9 : else if (poColorTable->IsIdentity())
5011 : {
5012 0 : poColorTable = nullptr;
5013 : }
5014 : }
5015 : else
5016 : {
5017 0 : CPLError(CE_Warning, CPLE_AppDefined,
5018 : "Computing overviews on palette index raster bands "
5019 : "without a palette will probably lead to unexpected "
5020 : "results.");
5021 : }
5022 : }
5023 : // Not ready yet
5024 2244 : else if ((EQUAL(pszResampling, "CUBIC") ||
5025 712 : EQUAL(pszResampling, "CUBICSPLINE") ||
5026 712 : EQUAL(pszResampling, "LANCZOS") ||
5027 1558 : EQUAL(pszResampling, "BILINEAR")) &&
5028 80 : poSrcBand->GetColorInterpretation() == GCI_PaletteIndex)
5029 : {
5030 0 : CPLError(CE_Warning, CPLE_AppDefined,
5031 : "Computing %s overviews on palette index raster bands "
5032 : "will probably lead to unexpected results.",
5033 : pszResampling);
5034 : }
5035 :
5036 : // If we have a nodata mask and we are doing something more complicated
5037 : // than nearest neighbouring, we have to fetch to nodata mask.
5038 :
5039 775 : GDALRasterBand *poMaskBand = nullptr;
5040 775 : bool bUseNoDataMask = false;
5041 775 : bool bCanUseCascaded = true;
5042 :
5043 775 : if (!STARTS_WITH_CI(pszResampling, "NEAR"))
5044 : {
5045 : // Special case if we are an alpha/mask band. We want it to be
5046 : // considered as the mask band to avoid alpha=0 to be taken into account
5047 : // in average computation.
5048 392 : if (poSrcBand->IsMaskBand())
5049 : {
5050 51 : poMaskBand = poSrcBand;
5051 51 : bUseNoDataMask = true;
5052 : }
5053 : else
5054 : {
5055 341 : poMaskBand = poSrcBand->GetMaskBand();
5056 341 : const int nMaskFlags = poSrcBand->GetMaskFlags();
5057 341 : bCanUseCascaded =
5058 341 : (nMaskFlags == GMF_NODATA || nMaskFlags == GMF_ALL_VALID);
5059 341 : bUseNoDataMask = (nMaskFlags & GMF_ALL_VALID) == 0;
5060 : }
5061 : }
5062 :
5063 775 : int nHasNoData = 0;
5064 775 : const double dfNoDataValue = poSrcBand->GetNoDataValue(&nHasNoData);
5065 775 : const bool bHasNoData = CPL_TO_BOOL(nHasNoData);
5066 : const bool bPropagateNoData =
5067 775 : CPLTestBool(CPLGetConfigOption("GDAL_OVR_PROPAGATE_NODATA", "NO"));
5068 :
5069 843 : if (poSrcBand->GetBand() == 1 && bUseNoDataMask &&
5070 68 : CSLFetchNameValue(papszOptions, "CASCADING") == nullptr)
5071 : {
5072 112 : std::string osDetailMessage;
5073 56 : if (poSrcBand->HasConflictingMaskSources(&osDetailMessage, false))
5074 : {
5075 2 : CPLError(
5076 : CE_Warning, CPLE_AppDefined, "%s%s", osDetailMessage.c_str(),
5077 : bHasNoData
5078 : ? "Only the nodata value will be taken into account."
5079 : : "Only the first listed one will be taken into account.");
5080 : }
5081 : }
5082 :
5083 : /* -------------------------------------------------------------------- */
5084 : /* If we are operating on multiple overviews, and using */
5085 : /* averaging, lets do them in cascading order to reduce the */
5086 : /* amount of computation. */
5087 : /* -------------------------------------------------------------------- */
5088 :
5089 : // In case the mask made be computed from another band of the dataset,
5090 : // we can't use cascaded generation, as the computation of the overviews
5091 : // of the band used for the mask band may not have yet occurred (#3033).
5092 775 : if ((STARTS_WITH_CI(pszResampling, "AVER") ||
5093 552 : EQUAL(pszResampling, "GAUSS") || EQUAL(pszResampling, "RMS") ||
5094 521 : EQUAL(pszResampling, "CUBIC") || EQUAL(pszResampling, "CUBICSPLINE") ||
5095 467 : EQUAL(pszResampling, "LANCZOS") || EQUAL(pszResampling, "BILINEAR") ||
5096 775 : EQUAL(pszResampling, "MODE")) &&
5097 44 : nOverviewCount > 1 && bCanUseCascaded)
5098 44 : return GDALRegenerateCascadingOverviews(
5099 : poSrcBand, nOverviewCount, papoOvrBands, pszResampling, pfnProgress,
5100 44 : pProgressData, papszOptions);
5101 :
5102 : /* -------------------------------------------------------------------- */
5103 : /* Setup one horizontal swath to read from the raw buffer. */
5104 : /* -------------------------------------------------------------------- */
5105 731 : int nFRXBlockSize = 0;
5106 731 : int nFRYBlockSize = 0;
5107 731 : poSrcBand->GetBlockSize(&nFRXBlockSize, &nFRYBlockSize);
5108 :
5109 731 : const GDALDataType eSrcDataType = poSrcBand->GetRasterDataType();
5110 1079 : const bool bUseGenericResampleFn = STARTS_WITH_CI(pszResampling, "NEAR") ||
5111 1029 : EQUAL(pszResampling, "MODE") ||
5112 298 : !GDALDataTypeIsComplex(eSrcDataType);
5113 : const GDALDataType eWrkDataType =
5114 : bUseGenericResampleFn
5115 731 : ? GDALGetOvrWorkDataType(pszResampling, eSrcDataType)
5116 731 : : GDT_CFloat32;
5117 :
5118 731 : const int nWidth = poSrcBand->GetXSize();
5119 731 : const int nHeight = poSrcBand->GetYSize();
5120 :
5121 731 : int nMaxOvrFactor = 1;
5122 1585 : for (int iOverview = 0; iOverview < nOverviewCount; ++iOverview)
5123 : {
5124 854 : const int nDstWidth = papoOvrBands[iOverview]->GetXSize();
5125 854 : const int nDstHeight = papoOvrBands[iOverview]->GetYSize();
5126 854 : nMaxOvrFactor = std::max(
5127 : nMaxOvrFactor,
5128 854 : static_cast<int>(static_cast<double>(nWidth) / nDstWidth + 0.5));
5129 854 : nMaxOvrFactor = std::max(
5130 : nMaxOvrFactor,
5131 854 : static_cast<int>(static_cast<double>(nHeight) / nDstHeight + 0.5));
5132 : }
5133 :
5134 731 : int nFullResYChunk = nFRYBlockSize;
5135 731 : int nMaxChunkYSizeQueried = 0;
5136 :
5137 : const auto UpdateChunkHeightAndGetChunkSize =
5138 10081 : [&nFullResYChunk, &nMaxChunkYSizeQueried, nKernelRadius, nMaxOvrFactor,
5139 81609 : eWrkDataType, nWidth]()
5140 : {
5141 : // Make sure that round(nChunkYOff / nMaxOvrFactor) < round((nChunkYOff
5142 : // + nFullResYChunk) / nMaxOvrFactor)
5143 10081 : if (nMaxOvrFactor > INT_MAX / RADIUS_TO_DIAMETER)
5144 : {
5145 1 : return GINTBIG_MAX;
5146 : }
5147 10080 : nFullResYChunk =
5148 10080 : std::max(nFullResYChunk, RADIUS_TO_DIAMETER * nMaxOvrFactor);
5149 10080 : if ((nKernelRadius > 0 &&
5150 970 : nMaxOvrFactor > INT_MAX / (RADIUS_TO_DIAMETER * nKernelRadius)) ||
5151 10080 : nFullResYChunk >
5152 10080 : INT_MAX - RADIUS_TO_DIAMETER * nKernelRadius * nMaxOvrFactor)
5153 : {
5154 0 : return GINTBIG_MAX;
5155 : }
5156 10080 : nMaxChunkYSizeQueried =
5157 10080 : nFullResYChunk + RADIUS_TO_DIAMETER * nKernelRadius * nMaxOvrFactor;
5158 10080 : if (GDALGetDataTypeSizeBytes(eWrkDataType) >
5159 10080 : std::numeric_limits<int64_t>::max() /
5160 10080 : (static_cast<int64_t>(nMaxChunkYSizeQueried) * nWidth))
5161 : {
5162 1 : return GINTBIG_MAX;
5163 : }
5164 10079 : return static_cast<GIntBig>(GDALGetDataTypeSizeBytes(eWrkDataType)) *
5165 10079 : nMaxChunkYSizeQueried * nWidth;
5166 731 : };
5167 :
5168 : const char *pszChunkYSize =
5169 731 : CPLGetConfigOption("GDAL_OVR_CHUNKYSIZE", nullptr);
5170 : #ifndef __COVERITY__
5171 : // Only configurable for debug / testing
5172 731 : if (pszChunkYSize)
5173 : {
5174 0 : nFullResYChunk = atoi(pszChunkYSize);
5175 : }
5176 : #endif
5177 :
5178 : // Only configurable for debug / testing
5179 : const int nChunkMaxSize =
5180 731 : atoi(CPLGetConfigOption("GDAL_OVR_CHUNK_MAX_SIZE", "10485760"));
5181 :
5182 731 : auto nChunkSize = UpdateChunkHeightAndGetChunkSize();
5183 731 : if (nChunkSize > nChunkMaxSize)
5184 : {
5185 15 : if (poColorTable == nullptr && nFRXBlockSize < nWidth &&
5186 44 : !GDALDataTypeIsComplex(eSrcDataType) &&
5187 14 : (!STARTS_WITH_CI(pszResampling, "AVER") ||
5188 2 : EQUAL(pszResampling, "AVERAGE")))
5189 : {
5190 : // If this is tiled, then use GDALRegenerateOverviewsMultiBand()
5191 : // which use a block based strategy, which is much less memory
5192 : // hungry.
5193 14 : return GDALRegenerateOverviewsMultiBand(
5194 : 1, &poSrcBand, nOverviewCount, &papoOvrBands, pszResampling,
5195 14 : pfnProgress, pProgressData, papszOptions);
5196 : }
5197 1 : else if (nOverviewCount > 1 && STARTS_WITH_CI(pszResampling, "NEAR"))
5198 : {
5199 0 : return GDALRegenerateCascadingOverviews(
5200 : poSrcBand, nOverviewCount, papoOvrBands, pszResampling,
5201 0 : pfnProgress, pProgressData, papszOptions);
5202 : }
5203 : }
5204 716 : else if (pszChunkYSize == nullptr)
5205 : {
5206 : // Try to get as close as possible to nChunkMaxSize
5207 10066 : while (nChunkSize < nChunkMaxSize / 2)
5208 : {
5209 9350 : nFullResYChunk *= 2;
5210 9350 : nChunkSize = UpdateChunkHeightAndGetChunkSize();
5211 : }
5212 : }
5213 :
5214 : // Structure describing a resampling job
5215 : struct OvrJob
5216 : {
5217 : // Buffers to free when job is finished
5218 : std::shared_ptr<PointerHolder> oSrcMaskBufferHolder{};
5219 : std::shared_ptr<PointerHolder> oSrcBufferHolder{};
5220 : std::unique_ptr<PointerHolder> oDstBufferHolder{};
5221 :
5222 : GDALRasterBand *poDstBand = nullptr;
5223 :
5224 : // Input parameters of pfnResampleFn
5225 : GDALResampleFunction pfnResampleFn = nullptr;
5226 : int nSrcWidth = 0;
5227 : int nSrcHeight = 0;
5228 : int nDstWidth = 0;
5229 : GDALOverviewResampleArgs args{};
5230 : const void *pChunk = nullptr;
5231 : bool bUseGenericResampleFn = false;
5232 :
5233 : // Output values of resampling function
5234 : CPLErr eErr = CE_Failure;
5235 : void *pDstBuffer = nullptr;
5236 : GDALDataType eDstBufferDataType = GDT_Unknown;
5237 :
5238 0 : void SetSrcMaskBufferHolder(
5239 : const std::shared_ptr<PointerHolder> &oSrcMaskBufferHolderIn)
5240 : {
5241 0 : oSrcMaskBufferHolder = oSrcMaskBufferHolderIn;
5242 0 : }
5243 :
5244 0 : void SetSrcBufferHolder(
5245 : const std::shared_ptr<PointerHolder> &oSrcBufferHolderIn)
5246 : {
5247 0 : oSrcBufferHolder = oSrcBufferHolderIn;
5248 0 : }
5249 :
5250 823 : void NotifyFinished()
5251 : {
5252 1646 : std::lock_guard guard(mutex);
5253 823 : bFinished = true;
5254 823 : cv.notify_one();
5255 823 : }
5256 :
5257 0 : bool IsFinished()
5258 : {
5259 0 : std::lock_guard guard(mutex);
5260 0 : return bFinished;
5261 : }
5262 :
5263 0 : void WaitFinished()
5264 : {
5265 0 : std::unique_lock oGuard(mutex);
5266 0 : while (!bFinished)
5267 : {
5268 0 : cv.wait(oGuard);
5269 : }
5270 0 : }
5271 :
5272 : private:
5273 : // Synchronization
5274 : bool bFinished = false;
5275 : std::mutex mutex{};
5276 : std::condition_variable cv{};
5277 : };
5278 :
5279 : // Thread function to resample
5280 823 : const auto JobResampleFunc = [](void *pData)
5281 : {
5282 823 : OvrJob *poJob = static_cast<OvrJob *>(pData);
5283 :
5284 823 : if (poJob->bUseGenericResampleFn)
5285 : {
5286 821 : poJob->eErr = poJob->pfnResampleFn(poJob->args, poJob->pChunk,
5287 : &(poJob->pDstBuffer),
5288 : &(poJob->eDstBufferDataType));
5289 : }
5290 : else
5291 : {
5292 2 : poJob->eErr = GDALResampleChunkC32R(
5293 : poJob->nSrcWidth, poJob->nSrcHeight,
5294 2 : static_cast<const float *>(poJob->pChunk),
5295 : poJob->args.nChunkYOff, poJob->args.nChunkYSize,
5296 : poJob->args.nDstYOff, poJob->args.nDstYOff2,
5297 : poJob->args.nOvrXSize, poJob->args.nOvrYSize,
5298 : &(poJob->pDstBuffer), &(poJob->eDstBufferDataType),
5299 : poJob->args.pszResampling);
5300 : }
5301 :
5302 823 : auto pDstBuffer = poJob->pDstBuffer;
5303 823 : poJob->oDstBufferHolder = std::make_unique<PointerHolder>(pDstBuffer);
5304 :
5305 823 : poJob->NotifyFinished();
5306 823 : };
5307 :
5308 : // Function to write resample data to target band
5309 823 : const auto WriteJobData = [](const OvrJob *poJob)
5310 : {
5311 1646 : return poJob->poDstBand->RasterIO(
5312 823 : GF_Write, 0, poJob->args.nDstYOff, poJob->nDstWidth,
5313 823 : poJob->args.nDstYOff2 - poJob->args.nDstYOff, poJob->pDstBuffer,
5314 823 : poJob->nDstWidth, poJob->args.nDstYOff2 - poJob->args.nDstYOff,
5315 823 : poJob->eDstBufferDataType, 0, 0, nullptr);
5316 : };
5317 :
5318 : // Wait for completion of oldest job and serialize it
5319 : const auto WaitAndFinalizeOldestJob =
5320 0 : [WriteJobData](std::list<std::unique_ptr<OvrJob>> &jobList)
5321 : {
5322 0 : auto poOldestJob = jobList.front().get();
5323 0 : poOldestJob->WaitFinished();
5324 0 : CPLErr l_eErr = poOldestJob->eErr;
5325 0 : if (l_eErr == CE_None)
5326 : {
5327 0 : l_eErr = WriteJobData(poOldestJob);
5328 : }
5329 :
5330 0 : jobList.pop_front();
5331 0 : return l_eErr;
5332 : };
5333 :
5334 : // Queue of jobs
5335 1434 : std::list<std::unique_ptr<OvrJob>> jobList;
5336 :
5337 717 : GByte *pabyChunkNodataMask = nullptr;
5338 717 : void *pChunk = nullptr;
5339 :
5340 717 : const int nThreads = GDALGetNumThreads(GDAL_DEFAULT_MAX_THREAD_COUNT,
5341 : /* bDefaultToAllCPUs=*/false);
5342 : auto poThreadPool =
5343 717 : nThreads > 1 ? GDALGetGlobalThreadPool(nThreads) : nullptr;
5344 : auto poJobQueue = poThreadPool ? poThreadPool->CreateJobQueue()
5345 1434 : : std::unique_ptr<CPLJobQueue>(nullptr);
5346 :
5347 : /* -------------------------------------------------------------------- */
5348 : /* Loop over image operating on chunks. */
5349 : /* -------------------------------------------------------------------- */
5350 717 : int nChunkYOff = 0;
5351 717 : CPLErr eErr = CE_None;
5352 :
5353 1439 : for (nChunkYOff = 0; nChunkYOff < nHeight && eErr == CE_None;
5354 722 : nChunkYOff += nFullResYChunk)
5355 : {
5356 722 : if (!pfnProgress(nChunkYOff / static_cast<double>(nHeight), nullptr,
5357 : pProgressData))
5358 : {
5359 0 : CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
5360 0 : eErr = CE_Failure;
5361 : }
5362 :
5363 722 : if (nFullResYChunk + nChunkYOff > nHeight)
5364 714 : nFullResYChunk = nHeight - nChunkYOff;
5365 :
5366 722 : int nChunkYOffQueried = nChunkYOff - nKernelRadius * nMaxOvrFactor;
5367 722 : int nChunkYSizeQueried =
5368 722 : nFullResYChunk + 2 * nKernelRadius * nMaxOvrFactor;
5369 722 : if (nChunkYOffQueried < 0)
5370 : {
5371 83 : nChunkYSizeQueried += nChunkYOffQueried;
5372 83 : nChunkYOffQueried = 0;
5373 : }
5374 722 : if (nChunkYOffQueried + nChunkYSizeQueried > nHeight)
5375 83 : nChunkYSizeQueried = nHeight - nChunkYOffQueried;
5376 :
5377 : // Avoid accumulating too many tasks and exhaust RAM
5378 : // Try to complete already finished jobs
5379 722 : while (eErr == CE_None && !jobList.empty())
5380 : {
5381 0 : auto poOldestJob = jobList.front().get();
5382 0 : if (!poOldestJob->IsFinished())
5383 0 : break;
5384 0 : eErr = poOldestJob->eErr;
5385 0 : if (eErr == CE_None)
5386 : {
5387 0 : eErr = WriteJobData(poOldestJob);
5388 : }
5389 :
5390 0 : jobList.pop_front();
5391 : }
5392 :
5393 : // And in case we have saturated the number of threads,
5394 : // wait for completion of tasks to go below the threshold.
5395 1444 : while (eErr == CE_None &&
5396 722 : jobList.size() >= static_cast<size_t>(nThreads))
5397 : {
5398 0 : eErr = WaitAndFinalizeOldestJob(jobList);
5399 : }
5400 :
5401 : // (Re)allocate buffers if needed
5402 722 : if (pChunk == nullptr)
5403 : {
5404 717 : pChunk = VSI_MALLOC3_VERBOSE(GDALGetDataTypeSizeBytes(eWrkDataType),
5405 : nMaxChunkYSizeQueried, nWidth);
5406 : }
5407 722 : if (bUseNoDataMask && pabyChunkNodataMask == nullptr)
5408 : {
5409 139 : pabyChunkNodataMask = static_cast<GByte *>(
5410 139 : VSI_MALLOC2_VERBOSE(nMaxChunkYSizeQueried, nWidth));
5411 : }
5412 :
5413 722 : if (pChunk == nullptr ||
5414 139 : (bUseNoDataMask && pabyChunkNodataMask == nullptr))
5415 : {
5416 0 : CPLFree(pChunk);
5417 0 : CPLFree(pabyChunkNodataMask);
5418 0 : return CE_Failure;
5419 : }
5420 :
5421 : // Read chunk.
5422 722 : if (eErr == CE_None)
5423 722 : eErr = poSrcBand->RasterIO(GF_Read, 0, nChunkYOffQueried, nWidth,
5424 : nChunkYSizeQueried, pChunk, nWidth,
5425 : nChunkYSizeQueried, eWrkDataType, 0, 0,
5426 : nullptr);
5427 722 : if (eErr == CE_None && bUseNoDataMask)
5428 139 : eErr = poMaskBand->RasterIO(GF_Read, 0, nChunkYOffQueried, nWidth,
5429 : nChunkYSizeQueried, pabyChunkNodataMask,
5430 : nWidth, nChunkYSizeQueried, GDT_UInt8,
5431 : 0, 0, nullptr);
5432 :
5433 : // Special case to promote 1bit data to 8bit 0/255 values.
5434 722 : if (EQUAL(pszResampling, "AVERAGE_BIT2GRAYSCALE"))
5435 : {
5436 9 : if (eWrkDataType == GDT_Float32)
5437 : {
5438 0 : float *pafChunk = static_cast<float *>(pChunk);
5439 0 : for (size_t i = 0;
5440 0 : i < static_cast<size_t>(nChunkYSizeQueried) * nWidth; i++)
5441 : {
5442 0 : if (pafChunk[i] == 1.0f)
5443 0 : pafChunk[i] = 255.0f;
5444 : }
5445 : }
5446 9 : else if (eWrkDataType == GDT_UInt8)
5447 : {
5448 9 : GByte *pabyChunk = static_cast<GByte *>(pChunk);
5449 168417 : for (size_t i = 0;
5450 168417 : i < static_cast<size_t>(nChunkYSizeQueried) * nWidth; i++)
5451 : {
5452 168408 : if (pabyChunk[i] == 1)
5453 127437 : pabyChunk[i] = 255;
5454 : }
5455 : }
5456 0 : else if (eWrkDataType == GDT_UInt16)
5457 : {
5458 0 : GUInt16 *pasChunk = static_cast<GUInt16 *>(pChunk);
5459 0 : for (size_t i = 0;
5460 0 : i < static_cast<size_t>(nChunkYSizeQueried) * nWidth; i++)
5461 : {
5462 0 : if (pasChunk[i] == 1)
5463 0 : pasChunk[i] = 255;
5464 : }
5465 : }
5466 0 : else if (eWrkDataType == GDT_Float64)
5467 : {
5468 0 : double *padfChunk = static_cast<double *>(pChunk);
5469 0 : for (size_t i = 0;
5470 0 : i < static_cast<size_t>(nChunkYSizeQueried) * nWidth; i++)
5471 : {
5472 0 : if (padfChunk[i] == 1.0)
5473 0 : padfChunk[i] = 255.0;
5474 : }
5475 : }
5476 : else
5477 : {
5478 0 : CPLAssert(false);
5479 : }
5480 : }
5481 713 : else if (EQUAL(pszResampling, "AVERAGE_BIT2GRAYSCALE_MINISWHITE"))
5482 : {
5483 0 : if (eWrkDataType == GDT_Float32)
5484 : {
5485 0 : float *pafChunk = static_cast<float *>(pChunk);
5486 0 : for (size_t i = 0;
5487 0 : i < static_cast<size_t>(nChunkYSizeQueried) * nWidth; i++)
5488 : {
5489 0 : if (pafChunk[i] == 1.0f)
5490 0 : pafChunk[i] = 0.0f;
5491 0 : else if (pafChunk[i] == 0.0f)
5492 0 : pafChunk[i] = 255.0f;
5493 : }
5494 : }
5495 0 : else if (eWrkDataType == GDT_UInt8)
5496 : {
5497 0 : GByte *pabyChunk = static_cast<GByte *>(pChunk);
5498 0 : for (size_t i = 0;
5499 0 : i < static_cast<size_t>(nChunkYSizeQueried) * nWidth; i++)
5500 : {
5501 0 : if (pabyChunk[i] == 1)
5502 0 : pabyChunk[i] = 0;
5503 0 : else if (pabyChunk[i] == 0)
5504 0 : pabyChunk[i] = 255;
5505 : }
5506 : }
5507 0 : else if (eWrkDataType == GDT_UInt16)
5508 : {
5509 0 : GUInt16 *pasChunk = static_cast<GUInt16 *>(pChunk);
5510 0 : for (size_t i = 0;
5511 0 : i < static_cast<size_t>(nChunkYSizeQueried) * nWidth; i++)
5512 : {
5513 0 : if (pasChunk[i] == 1)
5514 0 : pasChunk[i] = 0;
5515 0 : else if (pasChunk[i] == 0)
5516 0 : pasChunk[i] = 255;
5517 : }
5518 : }
5519 0 : else if (eWrkDataType == GDT_Float64)
5520 : {
5521 0 : double *padfChunk = static_cast<double *>(pChunk);
5522 0 : for (size_t i = 0;
5523 0 : i < static_cast<size_t>(nChunkYSizeQueried) * nWidth; i++)
5524 : {
5525 0 : if (padfChunk[i] == 1.0)
5526 0 : padfChunk[i] = 0.0;
5527 0 : else if (padfChunk[i] == 0.0)
5528 0 : padfChunk[i] = 255.0;
5529 : }
5530 : }
5531 : else
5532 : {
5533 0 : CPLAssert(false);
5534 : }
5535 : }
5536 :
5537 722 : auto pChunkRaw = pChunk;
5538 722 : auto pabyChunkNodataMaskRaw = pabyChunkNodataMask;
5539 722 : std::shared_ptr<PointerHolder> oSrcBufferHolder;
5540 722 : std::shared_ptr<PointerHolder> oSrcMaskBufferHolder;
5541 722 : if (poJobQueue)
5542 : {
5543 0 : oSrcBufferHolder = std::make_shared<PointerHolder>(pChunk);
5544 : oSrcMaskBufferHolder =
5545 0 : std::make_shared<PointerHolder>(pabyChunkNodataMask);
5546 : }
5547 :
5548 1545 : for (int iOverview = 0; iOverview < nOverviewCount && eErr == CE_None;
5549 : ++iOverview)
5550 : {
5551 823 : GDALRasterBand *poDstBand = papoOvrBands[iOverview];
5552 823 : const int nDstWidth = poDstBand->GetXSize();
5553 823 : const int nDstHeight = poDstBand->GetYSize();
5554 :
5555 823 : const double dfXRatioDstToSrc =
5556 823 : static_cast<double>(nWidth) / nDstWidth;
5557 823 : const double dfYRatioDstToSrc =
5558 823 : static_cast<double>(nHeight) / nDstHeight;
5559 :
5560 : /* --------------------------------------------------------------------
5561 : */
5562 : /* Figure out the line to start writing to, and the first line
5563 : */
5564 : /* to not write to. In theory this approach should ensure that
5565 : */
5566 : /* every output line will be written if all input chunks are */
5567 : /* processed. */
5568 : /* --------------------------------------------------------------------
5569 : */
5570 823 : int nDstYOff =
5571 823 : static_cast<int>(0.5 + nChunkYOff / dfYRatioDstToSrc);
5572 823 : if (nDstYOff == nDstHeight)
5573 0 : continue;
5574 823 : int nDstYOff2 = static_cast<int>(
5575 823 : 0.5 + (nChunkYOff + nFullResYChunk) / dfYRatioDstToSrc);
5576 :
5577 823 : if (nChunkYOff + nFullResYChunk == nHeight)
5578 816 : nDstYOff2 = nDstHeight;
5579 : #if DEBUG_VERBOSE
5580 : CPLDebug("GDAL",
5581 : "Reading (%dx%d -> %dx%d) for output (%dx%d -> %dx%d)", 0,
5582 : nChunkYOffQueried, nWidth, nChunkYSizeQueried, 0, nDstYOff,
5583 : nDstWidth, nDstYOff2 - nDstYOff);
5584 : #endif
5585 :
5586 1646 : auto poJob = std::make_unique<OvrJob>();
5587 823 : poJob->pfnResampleFn = pfnResampleFn;
5588 823 : poJob->bUseGenericResampleFn = bUseGenericResampleFn;
5589 823 : poJob->args.eOvrDataType = poDstBand->GetRasterDataType();
5590 823 : poJob->args.nOvrXSize = poDstBand->GetXSize();
5591 823 : poJob->args.nOvrYSize = poDstBand->GetYSize();
5592 1646 : const char *pszNBITS = poDstBand->GetMetadataItem(
5593 823 : GDALMD_NBITS, GDAL_MDD_IMAGE_STRUCTURE);
5594 823 : poJob->args.nOvrNBITS = pszNBITS ? atoi(pszNBITS) : 0;
5595 823 : poJob->args.dfXRatioDstToSrc = dfXRatioDstToSrc;
5596 823 : poJob->args.dfYRatioDstToSrc = dfYRatioDstToSrc;
5597 823 : poJob->args.eWrkDataType = eWrkDataType;
5598 823 : poJob->pChunk = pChunkRaw;
5599 823 : poJob->args.pabyChunkNodataMask = pabyChunkNodataMaskRaw;
5600 823 : poJob->nSrcWidth = nWidth;
5601 823 : poJob->nSrcHeight = nHeight;
5602 823 : poJob->args.nChunkXOff = 0;
5603 823 : poJob->args.nChunkXSize = nWidth;
5604 823 : poJob->args.nChunkYOff = nChunkYOffQueried;
5605 823 : poJob->args.nChunkYSize = nChunkYSizeQueried;
5606 823 : poJob->nDstWidth = nDstWidth;
5607 823 : poJob->args.nDstXOff = 0;
5608 823 : poJob->args.nDstXOff2 = nDstWidth;
5609 823 : poJob->args.nDstYOff = nDstYOff;
5610 823 : poJob->args.nDstYOff2 = nDstYOff2;
5611 823 : poJob->poDstBand = poDstBand;
5612 823 : poJob->args.pszResampling = pszResampling;
5613 823 : poJob->args.bHasNoData = bHasNoData;
5614 823 : poJob->args.dfNoDataValue = dfNoDataValue;
5615 823 : poJob->args.poColorTable = poColorTable;
5616 823 : poJob->args.eSrcDataType = eSrcDataType;
5617 823 : poJob->args.bPropagateNoData = bPropagateNoData;
5618 :
5619 823 : if (poJobQueue)
5620 : {
5621 0 : poJob->SetSrcMaskBufferHolder(oSrcMaskBufferHolder);
5622 0 : poJob->SetSrcBufferHolder(oSrcBufferHolder);
5623 0 : poJobQueue->SubmitJob(JobResampleFunc, poJob.get());
5624 0 : jobList.emplace_back(std::move(poJob));
5625 : }
5626 : else
5627 : {
5628 823 : JobResampleFunc(poJob.get());
5629 823 : eErr = poJob->eErr;
5630 823 : if (eErr == CE_None)
5631 : {
5632 823 : eErr = WriteJobData(poJob.get());
5633 : }
5634 : }
5635 : }
5636 : }
5637 :
5638 717 : VSIFree(pChunk);
5639 717 : VSIFree(pabyChunkNodataMask);
5640 :
5641 : // Wait for all pending jobs to complete
5642 717 : while (!jobList.empty())
5643 : {
5644 0 : const auto l_eErr = WaitAndFinalizeOldestJob(jobList);
5645 0 : if (l_eErr != CE_None && eErr == CE_None)
5646 0 : eErr = l_eErr;
5647 : }
5648 :
5649 : /* -------------------------------------------------------------------- */
5650 : /* Renormalized overview mean / stddev if needed. */
5651 : /* -------------------------------------------------------------------- */
5652 717 : if (eErr == CE_None && EQUAL(pszResampling, "AVERAGE_MP"))
5653 : {
5654 0 : GDALOverviewMagnitudeCorrection(
5655 : poSrcBand, nOverviewCount,
5656 : reinterpret_cast<GDALRasterBandH *>(papoOvrBands),
5657 : GDALDummyProgress, nullptr);
5658 : }
5659 :
5660 : /* -------------------------------------------------------------------- */
5661 : /* It can be important to flush out data to overviews. */
5662 : /* -------------------------------------------------------------------- */
5663 1533 : for (int iOverview = 0; eErr == CE_None && iOverview < nOverviewCount;
5664 : ++iOverview)
5665 : {
5666 816 : eErr = papoOvrBands[iOverview]->FlushCache(false);
5667 : }
5668 :
5669 717 : if (eErr == CE_None)
5670 717 : pfnProgress(1.0, nullptr, pProgressData);
5671 :
5672 717 : return eErr;
5673 : }
5674 :
5675 : /************************************************************************/
5676 : /* GDALRegenerateOverviewsMultiBand() */
5677 : /************************************************************************/
5678 :
5679 : /**
5680 : * \brief Variant of GDALRegenerateOverviews, specially dedicated for generating
5681 : * compressed pixel-interleaved overviews (JPEG-IN-TIFF for example)
5682 : *
5683 : * This function will generate one or more overview images from a base
5684 : * image using the requested downsampling algorithm. Its primary use
5685 : * is for generating overviews via GDALDataset::BuildOverviews(), but it
5686 : * can also be used to generate downsampled images in one file from another
5687 : * outside the overview architecture.
5688 : *
5689 : * The output bands need to exist in advance and share the same characteristics
5690 : * (type, dimensions)
5691 : *
5692 : * The resampling algorithms supported for the moment are "NEAREST", "AVERAGE",
5693 : * "RMS", "GAUSS", "CUBIC", "CUBICSPLINE", "LANCZOS" and "BILINEAR"
5694 : *
5695 : * It does not support color tables or complex data types.
5696 : *
5697 : * The pseudo-algorithm used by the function is :
5698 : * for each overview
5699 : * iterate on lines of the source by a step of deltay
5700 : * iterate on columns of the source by a step of deltax
5701 : * read the source data of size deltax * deltay for all the bands
5702 : * generate the corresponding overview block for all the bands
5703 : *
5704 : * This function will honour properly NODATA_VALUES tuples (special dataset
5705 : * metadata) so that only a given RGB triplet (in case of a RGB image) will be
5706 : * considered as the nodata value and not each value of the triplet
5707 : * independently per band.
5708 : *
5709 : * Starting with GDAL 3.2, the GDAL_NUM_THREADS configuration option can be set
5710 : * to "ALL_CPUS" or a integer value to specify the number of threads to use for
5711 : * overview computation.
5712 : *
5713 : * @param nBands the number of bands, size of papoSrcBands and size of
5714 : * first dimension of papapoOverviewBands
5715 : * @param papoSrcBands the list of source bands to downsample
5716 : * @param nOverviews the number of downsampled overview levels being generated.
5717 : * @param papapoOverviewBands bidimension array of bands. First dimension is
5718 : * indexed by nBands. Second dimension is indexed by
5719 : * nOverviews.
5720 : * @param pszResampling Resampling algorithm ("NEAREST", "AVERAGE", "RMS",
5721 : * "GAUSS", "CUBIC", "CUBICSPLINE", "LANCZOS" or "BILINEAR").
5722 : * @param pfnProgress progress report function.
5723 : * @param pProgressData progress function callback data.
5724 : * @param papszOptions (GDAL >= 3.6) NULL terminated list of options as
5725 : * key=value pairs, or NULL
5726 : * Starting with GDAL 3.8, the XOFF, YOFF, XSIZE and YSIZE
5727 : * options can be specified to express that overviews should
5728 : * be regenerated only in the specified subset of the source
5729 : * dataset.
5730 : * @return CE_None on success or CE_Failure on failure.
5731 : */
5732 :
5733 390 : CPLErr GDALRegenerateOverviewsMultiBand(
5734 : int nBands, GDALRasterBand *const *papoSrcBands, int nOverviews,
5735 : GDALRasterBand *const *const *papapoOverviewBands,
5736 : const char *pszResampling, GDALProgressFunc pfnProgress,
5737 : void *pProgressData, CSLConstList papszOptions)
5738 : {
5739 390 : CPL_IGNORE_RET_VAL(papszOptions);
5740 :
5741 390 : if (pfnProgress == nullptr)
5742 11 : pfnProgress = GDALDummyProgress;
5743 :
5744 390 : if (EQUAL(pszResampling, "NONE") || nBands == 0 || nOverviews == 0)
5745 3 : return CE_None;
5746 :
5747 : // Sanity checks.
5748 387 : if (!STARTS_WITH_CI(pszResampling, "NEAR") &&
5749 193 : !EQUAL(pszResampling, "RMS") && !EQUAL(pszResampling, "AVERAGE") &&
5750 84 : !EQUAL(pszResampling, "GAUSS") && !EQUAL(pszResampling, "CUBIC") &&
5751 25 : !EQUAL(pszResampling, "CUBICSPLINE") &&
5752 24 : !EQUAL(pszResampling, "LANCZOS") && !EQUAL(pszResampling, "BILINEAR") &&
5753 5 : !EQUAL(pszResampling, "MODE"))
5754 : {
5755 0 : CPLError(CE_Failure, CPLE_NotSupported,
5756 : "GDALRegenerateOverviewsMultiBand: pszResampling='%s' "
5757 : "not supported",
5758 : pszResampling);
5759 0 : return CE_Failure;
5760 : }
5761 :
5762 387 : int nKernelRadius = 0;
5763 : GDALResampleFunction pfnResampleFn =
5764 387 : GDALGetResampleFunction(pszResampling, &nKernelRadius);
5765 387 : if (pfnResampleFn == nullptr)
5766 0 : return CE_Failure;
5767 :
5768 387 : const int nToplevelSrcWidth = papoSrcBands[0]->GetXSize();
5769 387 : const int nToplevelSrcHeight = papoSrcBands[0]->GetYSize();
5770 387 : if (nToplevelSrcWidth <= 0 || nToplevelSrcHeight <= 0)
5771 0 : return CE_None;
5772 387 : GDALDataType eDataType = papoSrcBands[0]->GetRasterDataType();
5773 66235 : for (int iBand = 1; iBand < nBands; ++iBand)
5774 : {
5775 131696 : if (papoSrcBands[iBand]->GetXSize() != nToplevelSrcWidth ||
5776 65848 : papoSrcBands[iBand]->GetYSize() != nToplevelSrcHeight)
5777 : {
5778 0 : CPLError(
5779 : CE_Failure, CPLE_NotSupported,
5780 : "GDALRegenerateOverviewsMultiBand: all the source bands must "
5781 : "have the same dimensions");
5782 0 : return CE_Failure;
5783 : }
5784 65848 : if (papoSrcBands[iBand]->GetRasterDataType() != eDataType)
5785 : {
5786 0 : CPLError(
5787 : CE_Failure, CPLE_NotSupported,
5788 : "GDALRegenerateOverviewsMultiBand: all the source bands must "
5789 : "have the same data type");
5790 0 : return CE_Failure;
5791 : }
5792 : }
5793 :
5794 1030 : for (int iOverview = 0; iOverview < nOverviews; ++iOverview)
5795 : {
5796 643 : const auto poOvrFirstBand = papapoOverviewBands[0][iOverview];
5797 643 : const int nDstWidth = poOvrFirstBand->GetXSize();
5798 643 : const int nDstHeight = poOvrFirstBand->GetYSize();
5799 66751 : for (int iBand = 1; iBand < nBands; ++iBand)
5800 : {
5801 66108 : const auto poOvrBand = papapoOverviewBands[iBand][iOverview];
5802 132216 : if (poOvrBand->GetXSize() != nDstWidth ||
5803 66108 : poOvrBand->GetYSize() != nDstHeight)
5804 : {
5805 0 : CPLError(
5806 : CE_Failure, CPLE_NotSupported,
5807 : "GDALRegenerateOverviewsMultiBand: all the overviews bands "
5808 : "of the same level must have the same dimensions");
5809 0 : return CE_Failure;
5810 : }
5811 66108 : if (poOvrBand->GetRasterDataType() != eDataType)
5812 : {
5813 0 : CPLError(
5814 : CE_Failure, CPLE_NotSupported,
5815 : "GDALRegenerateOverviewsMultiBand: all the overviews bands "
5816 : "must have the same data type as the source bands");
5817 0 : return CE_Failure;
5818 : }
5819 : }
5820 : }
5821 :
5822 : // First pass to compute the total number of pixels to write.
5823 387 : double dfTotalPixelCount = 0;
5824 387 : const int nSrcXOff = atoi(CSLFetchNameValueDef(papszOptions, "XOFF", "0"));
5825 387 : const int nSrcYOff = atoi(CSLFetchNameValueDef(papszOptions, "YOFF", "0"));
5826 387 : const int nSrcXSize = atoi(CSLFetchNameValueDef(
5827 : papszOptions, "XSIZE", CPLSPrintf("%d", nToplevelSrcWidth)));
5828 387 : const int nSrcYSize = atoi(CSLFetchNameValueDef(
5829 : papszOptions, "YSIZE", CPLSPrintf("%d", nToplevelSrcHeight)));
5830 1030 : for (int iOverview = 0; iOverview < nOverviews; ++iOverview)
5831 : {
5832 643 : dfTotalPixelCount +=
5833 1286 : static_cast<double>(nSrcXSize) / nToplevelSrcWidth *
5834 643 : papapoOverviewBands[0][iOverview]->GetXSize() *
5835 1286 : static_cast<double>(nSrcYSize) / nToplevelSrcHeight *
5836 643 : papapoOverviewBands[0][iOverview]->GetYSize();
5837 : }
5838 :
5839 : const GDALDataType eWrkDataType =
5840 387 : GDALGetOvrWorkDataType(pszResampling, eDataType);
5841 : const int nWrkDataTypeSize =
5842 387 : std::max(1, GDALGetDataTypeSizeBytes(eWrkDataType));
5843 :
5844 387 : const bool bIsMask = papoSrcBands[0]->IsMaskBand();
5845 :
5846 : // If we have a nodata mask and we are doing something more complicated
5847 : // than nearest neighbouring, we have to fetch to nodata mask.
5848 : const bool bUseNoDataMask =
5849 574 : !STARTS_WITH_CI(pszResampling, "NEAR") &&
5850 187 : (bIsMask || (papoSrcBands[0]->GetMaskFlags() & GMF_ALL_VALID) == 0);
5851 :
5852 774 : std::vector<bool> abHasNoData(nBands);
5853 774 : std::vector<double> adfNoDataValue(nBands);
5854 :
5855 66622 : for (int iBand = 0; iBand < nBands; ++iBand)
5856 : {
5857 66235 : int nHasNoData = 0;
5858 132470 : adfNoDataValue[iBand] =
5859 66235 : papoSrcBands[iBand]->GetNoDataValue(&nHasNoData);
5860 66235 : abHasNoData[iBand] = CPL_TO_BOOL(nHasNoData);
5861 : }
5862 :
5863 774 : std::string osDetailMessage;
5864 440 : if (bUseNoDataMask &&
5865 53 : papoSrcBands[0]->HasConflictingMaskSources(&osDetailMessage, false))
5866 : {
5867 9 : CPLError(CE_Warning, CPLE_AppDefined, "%s%s", osDetailMessage.c_str(),
5868 18 : abHasNoData[0]
5869 : ? "Only the nodata value will be taken into account."
5870 9 : : "Only the first listed one will be taken into account.");
5871 : }
5872 :
5873 : const bool bPropagateNoData =
5874 387 : CPLTestBool(CPLGetConfigOption("GDAL_OVR_PROPAGATE_NODATA", "NO"));
5875 :
5876 387 : const int nThreads = GDALGetNumThreads(GDAL_DEFAULT_MAX_THREAD_COUNT,
5877 : /* bDefaultToAllCPUs=*/false);
5878 : auto poThreadPool =
5879 387 : nThreads > 1 ? GDALGetGlobalThreadPool(nThreads) : nullptr;
5880 : auto poJobQueue = poThreadPool ? poThreadPool->CreateJobQueue()
5881 774 : : std::unique_ptr<CPLJobQueue>(nullptr);
5882 :
5883 : // Only configurable for debug / testing
5884 387 : const GIntBig nChunkMaxSize = []() -> GIntBig
5885 : {
5886 : const char *pszVal =
5887 387 : CPLGetConfigOption("GDAL_OVR_CHUNK_MAX_SIZE", nullptr);
5888 387 : if (pszVal)
5889 : {
5890 15 : GIntBig nRet = 0;
5891 15 : CPLParseMemorySize(pszVal, &nRet, nullptr);
5892 15 : return std::max<GIntBig>(100, nRet);
5893 : }
5894 372 : return 10 * 1024 * 1024;
5895 387 : }();
5896 :
5897 : // Only configurable for debug / testing
5898 387 : const GIntBig nChunkMaxSizeForTempFile = []() -> GIntBig
5899 : {
5900 387 : const char *pszVal = CPLGetConfigOption(
5901 : "GDAL_OVR_CHUNK_MAX_SIZE_FOR_TEMP_FILE", nullptr);
5902 387 : if (pszVal)
5903 : {
5904 14 : GIntBig nRet = 0;
5905 14 : CPLParseMemorySize(pszVal, &nRet, nullptr);
5906 14 : return std::max<GIntBig>(100, nRet);
5907 : }
5908 373 : const auto nUsableRAM = CPLGetUsablePhysicalRAM();
5909 373 : if (nUsableRAM > 0)
5910 373 : return nUsableRAM / 10;
5911 : // Select a value to be able to at least downsample by 2 for a RGB
5912 : // 1024x1024 tiled output: (2 * 1024 + 2) * (2 * 1024 + 2) * 3 = 12 MB
5913 0 : return 100 * 1024 * 1024;
5914 387 : }();
5915 :
5916 : // Second pass to do the real job.
5917 387 : double dfCurPixelCount = 0;
5918 387 : CPLErr eErr = CE_None;
5919 1024 : for (int iOverview = 0; iOverview < nOverviews && eErr == CE_None;
5920 : ++iOverview)
5921 : {
5922 642 : int iSrcOverview = -1; // -1 means the source bands.
5923 :
5924 : const int nDstTotalWidth =
5925 642 : papapoOverviewBands[0][iOverview]->GetXSize();
5926 : const int nDstTotalHeight =
5927 642 : papapoOverviewBands[0][iOverview]->GetYSize();
5928 :
5929 : // Compute the coordinates of the target region to refresh
5930 642 : constexpr double EPS = 1e-8;
5931 642 : const int nDstXOffStart = static_cast<int>(
5932 642 : static_cast<double>(nSrcXOff) / nToplevelSrcWidth * nDstTotalWidth +
5933 : EPS);
5934 : const int nDstXOffEnd =
5935 1284 : std::min(static_cast<int>(
5936 642 : std::ceil(static_cast<double>(nSrcXOff + nSrcXSize) /
5937 642 : nToplevelSrcWidth * nDstTotalWidth -
5938 : EPS)),
5939 642 : nDstTotalWidth);
5940 642 : const int nDstWidth = nDstXOffEnd - nDstXOffStart;
5941 642 : const int nDstYOffStart =
5942 642 : static_cast<int>(static_cast<double>(nSrcYOff) /
5943 642 : nToplevelSrcHeight * nDstTotalHeight +
5944 : EPS);
5945 : const int nDstYOffEnd =
5946 1284 : std::min(static_cast<int>(
5947 642 : std::ceil(static_cast<double>(nSrcYOff + nSrcYSize) /
5948 642 : nToplevelSrcHeight * nDstTotalHeight -
5949 : EPS)),
5950 642 : nDstTotalHeight);
5951 642 : const int nDstHeight = nDstYOffEnd - nDstYOffStart;
5952 :
5953 : // Try to use previous level of overview as the source to compute
5954 : // the next level.
5955 642 : int nSrcWidth = nToplevelSrcWidth;
5956 642 : int nSrcHeight = nToplevelSrcHeight;
5957 897 : if (iOverview > 0 &&
5958 255 : papapoOverviewBands[0][iOverview - 1]->GetXSize() > nDstTotalWidth)
5959 : {
5960 247 : nSrcWidth = papapoOverviewBands[0][iOverview - 1]->GetXSize();
5961 247 : nSrcHeight = papapoOverviewBands[0][iOverview - 1]->GetYSize();
5962 247 : iSrcOverview = iOverview - 1;
5963 : }
5964 :
5965 642 : const double dfXRatioDstToSrc =
5966 642 : static_cast<double>(nSrcWidth) / nDstTotalWidth;
5967 642 : const double dfYRatioDstToSrc =
5968 642 : static_cast<double>(nSrcHeight) / nDstTotalHeight;
5969 :
5970 : const int nOvrFactor =
5971 1926 : std::max(1, std::max(static_cast<int>(0.5 + dfXRatioDstToSrc),
5972 642 : static_cast<int>(0.5 + dfYRatioDstToSrc)));
5973 :
5974 642 : int nDstChunkXSize = 0;
5975 642 : int nDstChunkYSize = 0;
5976 642 : papapoOverviewBands[0][iOverview]->GetBlockSize(&nDstChunkXSize,
5977 : &nDstChunkYSize);
5978 :
5979 642 : constexpr int PIXEL_MARGIN = 2;
5980 : // Try to extend the chunk size so that the memory needed to acquire
5981 : // source pixels goes up to 10 MB.
5982 : // This can help for drivers that support multi-threaded reading
5983 642 : const int nFullResYChunk = static_cast<int>(std::min<double>(
5984 642 : nSrcHeight, PIXEL_MARGIN + nDstChunkYSize * dfYRatioDstToSrc));
5985 642 : const int nFullResYChunkQueried = static_cast<int>(std::min<int64_t>(
5986 1284 : nSrcHeight,
5987 1284 : nFullResYChunk + static_cast<int64_t>(RADIUS_TO_DIAMETER) *
5988 642 : nKernelRadius * nOvrFactor));
5989 876 : while (nDstChunkXSize < nDstWidth)
5990 : {
5991 254 : constexpr int INCREASE_FACTOR = 2;
5992 :
5993 254 : const int nFullResXChunk = static_cast<int>(std::min<double>(
5994 508 : nSrcWidth, PIXEL_MARGIN + INCREASE_FACTOR * nDstChunkXSize *
5995 254 : dfXRatioDstToSrc));
5996 :
5997 : const int nFullResXChunkQueried =
5998 254 : static_cast<int>(std::min<int64_t>(
5999 508 : nSrcWidth,
6000 508 : nFullResXChunk + static_cast<int64_t>(RADIUS_TO_DIAMETER) *
6001 254 : nKernelRadius * nOvrFactor));
6002 :
6003 254 : if (nBands > nChunkMaxSize / nFullResXChunkQueried /
6004 254 : nFullResYChunkQueried / nWrkDataTypeSize)
6005 : {
6006 20 : break;
6007 : }
6008 :
6009 234 : nDstChunkXSize *= INCREASE_FACTOR;
6010 : }
6011 642 : nDstChunkXSize = std::min(nDstChunkXSize, nDstWidth);
6012 :
6013 642 : const int nFullResXChunk = static_cast<int>(std::min<double>(
6014 642 : nSrcWidth, PIXEL_MARGIN + nDstChunkXSize * dfXRatioDstToSrc));
6015 642 : const int nFullResXChunkQueried = static_cast<int>(std::min<int64_t>(
6016 1284 : nSrcWidth,
6017 1284 : nFullResXChunk + static_cast<int64_t>(RADIUS_TO_DIAMETER) *
6018 642 : nKernelRadius * nOvrFactor));
6019 :
6020 : // Make sure that the RAM requirements to acquire the source data does
6021 : // not exceed nChunkMaxSizeForTempFile
6022 : // If so, reduce the destination chunk size, generate overviews in a
6023 : // temporary dataset, and copy that temporary dataset over the target
6024 : // overview bands (to avoid issues with lossy compression)
6025 : const bool bOverflowFullResXChunkYChunkQueried =
6026 642 : nBands > std::numeric_limits<int64_t>::max() /
6027 642 : nFullResXChunkQueried / nFullResYChunkQueried /
6028 642 : nWrkDataTypeSize;
6029 :
6030 642 : const auto nMemRequirement =
6031 : bOverflowFullResXChunkYChunkQueried
6032 642 : ? 0
6033 638 : : static_cast<GIntBig>(nFullResXChunkQueried) *
6034 638 : nFullResYChunkQueried * nBands * nWrkDataTypeSize;
6035 : // Use a temporary dataset with a smaller destination chunk size
6036 642 : const auto nOverShootFactor =
6037 : nMemRequirement / nChunkMaxSizeForTempFile;
6038 :
6039 642 : constexpr int MIN_OVERSHOOT_FACTOR = 4;
6040 : const auto nSqrtOverShootFactor = std::max<GIntBig>(
6041 1284 : MIN_OVERSHOOT_FACTOR, static_cast<GIntBig>(std::ceil(std::sqrt(
6042 642 : static_cast<double>(nOverShootFactor)))));
6043 642 : constexpr int DEFAULT_CHUNK_SIZE = 256;
6044 642 : constexpr int GTIFF_BLOCK_SIZE_MULTIPLE = 16;
6045 : const int nReducedDstChunkXSize =
6046 : bOverflowFullResXChunkYChunkQueried
6047 1280 : ? DEFAULT_CHUNK_SIZE
6048 1280 : : std::max(1, static_cast<int>(nDstChunkXSize /
6049 1280 : nSqrtOverShootFactor) &
6050 638 : ~(GTIFF_BLOCK_SIZE_MULTIPLE - 1));
6051 : const int nReducedDstChunkYSize =
6052 : bOverflowFullResXChunkYChunkQueried
6053 1280 : ? DEFAULT_CHUNK_SIZE
6054 1280 : : std::max(1, static_cast<int>(nDstChunkYSize /
6055 1280 : nSqrtOverShootFactor) &
6056 638 : ~(GTIFF_BLOCK_SIZE_MULTIPLE - 1));
6057 :
6058 642 : if (bOverflowFullResXChunkYChunkQueried ||
6059 : nMemRequirement > nChunkMaxSizeForTempFile)
6060 : {
6061 : const auto nDTSize =
6062 43 : std::max(1, GDALGetDataTypeSizeBytes(eDataType));
6063 : const bool bTmpDSMemRequirementOverflow =
6064 43 : nBands > std::numeric_limits<int64_t>::max() / nDstWidth /
6065 43 : nDstHeight / nDTSize;
6066 43 : const auto nTmpDSMemRequirement =
6067 : bTmpDSMemRequirementOverflow
6068 43 : ? 0
6069 41 : : static_cast<GIntBig>(nDstWidth) * nDstHeight * nBands *
6070 41 : nDTSize;
6071 :
6072 : // make sure that one band buffer doesn't overflow size_t
6073 : const bool bChunkSizeOverflow =
6074 43 : static_cast<size_t>(nDTSize) >
6075 43 : std::numeric_limits<size_t>::max() / nDstWidth / nDstHeight;
6076 43 : const size_t nChunkSize =
6077 : bChunkSizeOverflow
6078 43 : ? 0
6079 41 : : static_cast<size_t>(nDstWidth) * nDstHeight * nDTSize;
6080 :
6081 : const auto CreateVRT =
6082 41 : [nBands, nSrcWidth, nSrcHeight, nDstTotalWidth, nDstTotalHeight,
6083 : pszResampling, eWrkDataType, papoSrcBands, papapoOverviewBands,
6084 : iSrcOverview, &abHasNoData,
6085 393585 : &adfNoDataValue](int nVRTBlockXSize, int nVRTBlockYSize)
6086 : {
6087 : auto poVRTDS = std::make_unique<VRTDataset>(
6088 41 : nDstTotalWidth, nDstTotalHeight, nVRTBlockXSize,
6089 41 : nVRTBlockYSize);
6090 :
6091 65620 : for (int iBand = 0; iBand < nBands; ++iBand)
6092 : {
6093 131158 : auto poVRTSrc = std::make_unique<VRTSimpleSource>();
6094 65579 : poVRTSrc->SetResampling(pszResampling);
6095 65579 : poVRTDS->AddBand(eWrkDataType);
6096 : auto poVRTBand = static_cast<VRTSourcedRasterBand *>(
6097 65579 : poVRTDS->GetRasterBand(iBand + 1));
6098 :
6099 65579 : auto poSrcBand = papoSrcBands[iBand];
6100 65579 : if (iSrcOverview != -1)
6101 24 : poSrcBand = papapoOverviewBands[iBand][iSrcOverview];
6102 65579 : poVRTBand->ConfigureSource(
6103 : poVRTSrc.get(), poSrcBand, false, 0, 0, nSrcWidth,
6104 : nSrcHeight, 0, 0, nDstTotalWidth, nDstTotalHeight);
6105 : // Add the source to the band
6106 65579 : poVRTBand->AddSource(poVRTSrc.release());
6107 65579 : if (abHasNoData[iBand])
6108 3 : poVRTBand->SetNoDataValue(adfNoDataValue[iBand]);
6109 : }
6110 :
6111 42 : if (papoSrcBands[0]->GetMaskFlags() == GMF_PER_DATASET &&
6112 1 : poVRTDS->CreateMaskBand(GMF_PER_DATASET) == CE_None)
6113 : {
6114 : VRTSourcedRasterBand *poMaskVRTBand =
6115 1 : cpl::down_cast<VRTSourcedRasterBand *>(
6116 1 : poVRTDS->GetRasterBand(1)->GetMaskBand());
6117 1 : auto poSrcBand = papoSrcBands[0];
6118 1 : if (iSrcOverview != -1)
6119 0 : poSrcBand = papapoOverviewBands[0][iSrcOverview];
6120 1 : poMaskVRTBand->AddMaskBandSource(
6121 1 : poSrcBand->GetMaskBand(), 0, 0, nSrcWidth, nSrcHeight,
6122 : 0, 0, nDstTotalWidth, nDstTotalHeight);
6123 : }
6124 :
6125 41 : return poVRTDS;
6126 43 : };
6127 :
6128 : // If the overview accommodates chunking, do so and recurse
6129 : // to avoid generating full size temporary files
6130 43 : if (!bOverflowFullResXChunkYChunkQueried &&
6131 39 : !bTmpDSMemRequirementOverflow && !bChunkSizeOverflow &&
6132 39 : (nDstChunkXSize < nDstWidth || nDstChunkYSize < nDstHeight))
6133 : {
6134 : // Create a VRT with the smaller chunk to do the scaling
6135 : auto poVRTDS =
6136 13 : CreateVRT(nReducedDstChunkXSize, nReducedDstChunkYSize);
6137 :
6138 13 : std::vector<GDALRasterBand *> apoVRTBand(nBands);
6139 13 : std::vector<GDALRasterBand *> apoDstBand(nBands);
6140 65560 : for (int iBand = 0; iBand < nBands; ++iBand)
6141 : {
6142 65547 : apoDstBand[iBand] = papapoOverviewBands[iBand][iOverview];
6143 65547 : apoVRTBand[iBand] = poVRTDS->GetRasterBand(iBand + 1);
6144 : }
6145 :
6146 : // Use a flag to avoid reading from the overview being built
6147 : GDALRasterIOExtraArg sExtraArg;
6148 13 : INIT_RASTERIO_EXTRA_ARG(sExtraArg);
6149 13 : if (iSrcOverview == -1)
6150 13 : sExtraArg.bUseOnlyThisScale = true;
6151 :
6152 : // A single band buffer for data transfer to the overview
6153 13 : std::vector<GByte> abyChunk;
6154 : try
6155 : {
6156 13 : abyChunk.resize(nChunkSize);
6157 : }
6158 0 : catch (const std::exception &)
6159 : {
6160 0 : CPLError(CE_Failure, CPLE_OutOfMemory,
6161 : "Out of memory allocating temporary buffer");
6162 0 : return CE_Failure;
6163 : }
6164 :
6165 : // Loop over output height, in chunks
6166 13 : for (int nDstYOff = nDstYOffStart;
6167 38 : nDstYOff < nDstYOffEnd && eErr == CE_None;
6168 : /* */)
6169 : {
6170 : const int nDstYCount =
6171 25 : std::min(nDstChunkYSize, nDstYOffEnd - nDstYOff);
6172 : // Loop over output width, in output chunks
6173 25 : for (int nDstXOff = nDstXOffStart;
6174 74 : nDstXOff < nDstXOffEnd && eErr == CE_None;
6175 : /* */)
6176 : {
6177 : const int nDstXCount =
6178 49 : std::min(nDstChunkXSize, nDstXOffEnd - nDstXOff);
6179 : // Read and transfer the chunk to the overview
6180 98 : for (int iBand = 0; iBand < nBands && eErr == CE_None;
6181 : ++iBand)
6182 : {
6183 98 : eErr = apoVRTBand[iBand]->RasterIO(
6184 : GF_Read, nDstXOff, nDstYOff, nDstXCount,
6185 49 : nDstYCount, abyChunk.data(), nDstXCount,
6186 : nDstYCount, eDataType, 0, 0, &sExtraArg);
6187 49 : if (eErr == CE_None)
6188 : {
6189 96 : eErr = apoDstBand[iBand]->RasterIO(
6190 : GF_Write, nDstXOff, nDstYOff, nDstXCount,
6191 48 : nDstYCount, abyChunk.data(), nDstXCount,
6192 : nDstYCount, eDataType, 0, 0, nullptr);
6193 : }
6194 : }
6195 :
6196 49 : dfCurPixelCount +=
6197 49 : static_cast<double>(nDstXCount) * nDstYCount;
6198 :
6199 49 : nDstXOff += nDstXCount;
6200 : } // width
6201 :
6202 25 : if (!pfnProgress(dfCurPixelCount / dfTotalPixelCount,
6203 : nullptr, pProgressData))
6204 : {
6205 0 : CPLError(CE_Failure, CPLE_UserInterrupt,
6206 : "User terminated");
6207 0 : eErr = CE_Failure;
6208 : }
6209 :
6210 25 : nDstYOff += nDstYCount;
6211 : } // height
6212 :
6213 13 : if (CE_None != eErr)
6214 : {
6215 1 : CPLError(CE_Failure, CPLE_AppDefined,
6216 : "Error while writing overview");
6217 1 : return CE_Failure;
6218 : }
6219 :
6220 12 : pfnProgress(1.0, nullptr, pProgressData);
6221 : // Flush the overviews we just generated
6222 24 : for (int iBand = 0; iBand < nBands; ++iBand)
6223 12 : apoDstBand[iBand]->FlushCache(false);
6224 :
6225 12 : continue; // Next overview
6226 : } // chunking via temporary dataset
6227 :
6228 0 : std::unique_ptr<GDALDataset> poTmpDS;
6229 : // Config option mostly/only for autotest purposes
6230 : const char *pszGDAL_OVR_TEMP_DRIVER =
6231 30 : CPLGetConfigOption("GDAL_OVR_TEMP_DRIVER", "");
6232 30 : if ((!bTmpDSMemRequirementOverflow &&
6233 4 : nTmpDSMemRequirement <= nChunkMaxSizeForTempFile &&
6234 4 : !EQUAL(pszGDAL_OVR_TEMP_DRIVER, "GTIFF")) ||
6235 26 : EQUAL(pszGDAL_OVR_TEMP_DRIVER, "MEM"))
6236 : {
6237 10 : auto poTmpDrv = GetGDALDriverManager()->GetDriverByName("MEM");
6238 10 : if (!poTmpDrv)
6239 : {
6240 0 : eErr = CE_Failure;
6241 0 : break;
6242 : }
6243 10 : poTmpDS.reset(poTmpDrv->Create("", nDstTotalWidth,
6244 : nDstTotalHeight, nBands,
6245 10 : eDataType, nullptr));
6246 : }
6247 : else
6248 : {
6249 : // Create a temporary file for the overview
6250 : auto poTmpDrv =
6251 20 : GetGDALDriverManager()->GetDriverByName("GTiff");
6252 20 : if (!poTmpDrv)
6253 : {
6254 0 : eErr = CE_Failure;
6255 0 : break;
6256 : }
6257 40 : std::string osTmpFilename;
6258 20 : auto poDstDS = papapoOverviewBands[0][0]->GetDataset();
6259 20 : if (poDstDS)
6260 : {
6261 20 : osTmpFilename = poDstDS->GetDescription();
6262 : VSIStatBufL sStatBuf;
6263 20 : if (!osTmpFilename.empty() &&
6264 0 : VSIStatL(osTmpFilename.c_str(), &sStatBuf) == 0)
6265 0 : osTmpFilename += "_tmp_ovr.tif";
6266 : }
6267 20 : if (osTmpFilename.empty())
6268 : {
6269 20 : osTmpFilename = CPLGenerateTempFilenameSafe(nullptr);
6270 20 : osTmpFilename += ".tif";
6271 : }
6272 20 : CPLDebug("GDAL", "Creating temporary file %s of %d x %d x %d",
6273 : osTmpFilename.c_str(), nDstWidth, nDstHeight, nBands);
6274 40 : CPLStringList aosCO;
6275 20 : if (0 == ((nReducedDstChunkXSize % GTIFF_BLOCK_SIZE_MULTIPLE) |
6276 20 : (nReducedDstChunkYSize % GTIFF_BLOCK_SIZE_MULTIPLE)))
6277 : {
6278 14 : aosCO.SetNameValue("TILED", "YES");
6279 : aosCO.SetNameValue("BLOCKXSIZE",
6280 14 : CPLSPrintf("%d", nReducedDstChunkXSize));
6281 : aosCO.SetNameValue("BLOCKYSIZE",
6282 14 : CPLSPrintf("%d", nReducedDstChunkYSize));
6283 : }
6284 20 : if (const char *pszCOList =
6285 20 : poTmpDrv->GetMetadataItem(GDAL_DMD_CREATIONOPTIONLIST))
6286 : {
6287 : aosCO.SetNameValue(
6288 20 : "COMPRESS", strstr(pszCOList, "ZSTD") ? "ZSTD" : "LZW");
6289 : }
6290 20 : poTmpDS.reset(poTmpDrv->Create(osTmpFilename.c_str(), nDstWidth,
6291 : nDstHeight, nBands, eDataType,
6292 20 : aosCO.List()));
6293 20 : if (poTmpDS)
6294 : {
6295 18 : poTmpDS->MarkSuppressOnClose();
6296 18 : VSIUnlink(osTmpFilename.c_str());
6297 : }
6298 : }
6299 30 : if (!poTmpDS)
6300 : {
6301 2 : eErr = CE_Failure;
6302 2 : break;
6303 : }
6304 :
6305 : // Create a full size VRT to do the resampling without edge effects
6306 : auto poVRTDS =
6307 28 : CreateVRT(nReducedDstChunkXSize, nReducedDstChunkYSize);
6308 :
6309 : // Allocate a band buffer with the overview chunk size
6310 : std::unique_ptr<void, VSIFreeReleaser> pDstBuffer(
6311 : VSI_MALLOC3_VERBOSE(size_t(nWrkDataTypeSize), nDstChunkXSize,
6312 28 : nDstChunkYSize));
6313 28 : if (pDstBuffer == nullptr)
6314 : {
6315 0 : eErr = CE_Failure;
6316 0 : break;
6317 : }
6318 :
6319 : // Use a flag to avoid reading the overview being built
6320 : GDALRasterIOExtraArg sExtraArg;
6321 28 : INIT_RASTERIO_EXTRA_ARG(sExtraArg);
6322 28 : if (iSrcOverview == -1)
6323 4 : sExtraArg.bUseOnlyThisScale = true;
6324 :
6325 : // Scale and copy data from the VRT to the temp file
6326 28 : for (int nDstYOff = nDstYOffStart;
6327 914 : nDstYOff < nDstYOffEnd && eErr == CE_None;
6328 : /* */)
6329 : {
6330 : const int nDstYCount =
6331 886 : std::min(nReducedDstChunkYSize, nDstYOffEnd - nDstYOff);
6332 886 : for (int nDstXOff = nDstXOffStart;
6333 201218 : nDstXOff < nDstXOffEnd && eErr == CE_None;
6334 : /* */)
6335 : {
6336 : const int nDstXCount =
6337 200332 : std::min(nReducedDstChunkXSize, nDstXOffEnd - nDstXOff);
6338 400668 : for (int iBand = 0; iBand < nBands && eErr == CE_None;
6339 : ++iBand)
6340 : {
6341 200336 : auto poSrcBand = poVRTDS->GetRasterBand(iBand + 1);
6342 200336 : eErr = poSrcBand->RasterIO(
6343 : GF_Read, nDstXOff, nDstYOff, nDstXCount, nDstYCount,
6344 : pDstBuffer.get(), nDstXCount, nDstYCount,
6345 : eWrkDataType, 0, 0, &sExtraArg);
6346 200336 : if (eErr == CE_None)
6347 : {
6348 : // Write to the temporary dataset, shifted
6349 200334 : auto poOvrBand = poTmpDS->GetRasterBand(iBand + 1);
6350 200334 : eErr = poOvrBand->RasterIO(
6351 : GF_Write, nDstXOff - nDstXOffStart,
6352 : nDstYOff - nDstYOffStart, nDstXCount,
6353 : nDstYCount, pDstBuffer.get(), nDstXCount,
6354 : nDstYCount, eWrkDataType, 0, 0, nullptr);
6355 : }
6356 : }
6357 200332 : nDstXOff += nDstXCount;
6358 : }
6359 886 : nDstYOff += nDstYCount;
6360 : }
6361 :
6362 : // Copy from the temporary to the overview
6363 28 : for (int nDstYOff = nDstYOffStart;
6364 54 : nDstYOff < nDstYOffEnd && eErr == CE_None;
6365 : /* */)
6366 : {
6367 : const int nDstYCount =
6368 26 : std::min(nDstChunkYSize, nDstYOffEnd - nDstYOff);
6369 26 : for (int nDstXOff = nDstXOffStart;
6370 52 : nDstXOff < nDstXOffEnd && eErr == CE_None;
6371 : /* */)
6372 : {
6373 : const int nDstXCount =
6374 26 : std::min(nDstChunkXSize, nDstXOffEnd - nDstXOff);
6375 56 : for (int iBand = 0; iBand < nBands && eErr == CE_None;
6376 : ++iBand)
6377 : {
6378 30 : auto poSrcBand = poTmpDS->GetRasterBand(iBand + 1);
6379 30 : eErr = poSrcBand->RasterIO(
6380 : GF_Read, nDstXOff - nDstXOffStart,
6381 : nDstYOff - nDstYOffStart, nDstXCount, nDstYCount,
6382 : pDstBuffer.get(), nDstXCount, nDstYCount,
6383 : eWrkDataType, 0, 0, nullptr);
6384 30 : if (eErr == CE_None)
6385 : {
6386 : // Write to the destination overview bands
6387 30 : auto poOvrBand =
6388 30 : papapoOverviewBands[iBand][iOverview];
6389 30 : eErr = poOvrBand->RasterIO(
6390 : GF_Write, nDstXOff, nDstYOff, nDstXCount,
6391 : nDstYCount, pDstBuffer.get(), nDstXCount,
6392 : nDstYCount, eWrkDataType, 0, 0, nullptr);
6393 : }
6394 : }
6395 26 : nDstXOff += nDstXCount;
6396 : }
6397 26 : nDstYOff += nDstYCount;
6398 : }
6399 :
6400 28 : if (eErr != CE_None)
6401 : {
6402 2 : CPLError(CE_Failure, CPLE_AppDefined,
6403 : "Failed to write overview %d", iOverview);
6404 2 : return eErr;
6405 : }
6406 :
6407 : // Flush the data to overviews.
6408 56 : for (int iBand = 0; iBand < nBands; ++iBand)
6409 30 : papapoOverviewBands[iBand][iOverview]->FlushCache(false);
6410 :
6411 26 : continue;
6412 : }
6413 :
6414 : // Structure describing a resampling job
6415 : struct OvrJob
6416 : {
6417 : // Buffers to free when job is finished
6418 : std::unique_ptr<PointerHolder> oSrcMaskBufferHolder{};
6419 : std::unique_ptr<PointerHolder> oSrcBufferHolder{};
6420 : std::unique_ptr<PointerHolder> oDstBufferHolder{};
6421 :
6422 : GDALRasterBand *poDstBand = nullptr;
6423 :
6424 : // Input parameters of pfnResampleFn
6425 : GDALResampleFunction pfnResampleFn = nullptr;
6426 : GDALOverviewResampleArgs args{};
6427 : const void *pChunk = nullptr;
6428 :
6429 : // Output values of resampling function
6430 : CPLErr eErr = CE_Failure;
6431 : void *pDstBuffer = nullptr;
6432 : GDALDataType eDstBufferDataType = GDT_Unknown;
6433 :
6434 3311 : void NotifyFinished()
6435 : {
6436 6622 : std::lock_guard guard(mutex);
6437 3311 : bFinished = true;
6438 3311 : cv.notify_one();
6439 3311 : }
6440 :
6441 2 : bool IsFinished()
6442 : {
6443 2 : std::lock_guard guard(mutex);
6444 4 : return bFinished;
6445 : }
6446 :
6447 16 : void WaitFinished()
6448 : {
6449 32 : std::unique_lock oGuard(mutex);
6450 21 : while (!bFinished)
6451 : {
6452 5 : cv.wait(oGuard);
6453 : }
6454 16 : }
6455 :
6456 : private:
6457 : // Synchronization
6458 : bool bFinished = false;
6459 : std::mutex mutex{};
6460 : std::condition_variable cv{};
6461 : };
6462 :
6463 : // Thread function to resample
6464 3311 : const auto JobResampleFunc = [](void *pData)
6465 : {
6466 3311 : OvrJob *poJob = static_cast<OvrJob *>(pData);
6467 :
6468 3311 : poJob->eErr = poJob->pfnResampleFn(poJob->args, poJob->pChunk,
6469 : &(poJob->pDstBuffer),
6470 : &(poJob->eDstBufferDataType));
6471 :
6472 3311 : auto pDstBuffer = poJob->pDstBuffer;
6473 : poJob->oDstBufferHolder =
6474 3311 : std::make_unique<PointerHolder>(pDstBuffer);
6475 :
6476 3311 : poJob->NotifyFinished();
6477 3311 : };
6478 :
6479 : // Function to write resample data to target band
6480 3311 : const auto WriteJobData = [](const OvrJob *poJob)
6481 : {
6482 6622 : return poJob->poDstBand->RasterIO(
6483 3311 : GF_Write, poJob->args.nDstXOff, poJob->args.nDstYOff,
6484 3311 : poJob->args.nDstXOff2 - poJob->args.nDstXOff,
6485 3311 : poJob->args.nDstYOff2 - poJob->args.nDstYOff, poJob->pDstBuffer,
6486 3311 : poJob->args.nDstXOff2 - poJob->args.nDstXOff,
6487 3311 : poJob->args.nDstYOff2 - poJob->args.nDstYOff,
6488 3311 : poJob->eDstBufferDataType, 0, 0, nullptr);
6489 : };
6490 :
6491 : // Wait for completion of oldest job and serialize it
6492 : const auto WaitAndFinalizeOldestJob =
6493 16 : [WriteJobData](std::list<std::unique_ptr<OvrJob>> &jobList)
6494 : {
6495 16 : auto poOldestJob = jobList.front().get();
6496 16 : poOldestJob->WaitFinished();
6497 16 : CPLErr l_eErr = poOldestJob->eErr;
6498 16 : if (l_eErr == CE_None)
6499 : {
6500 16 : l_eErr = WriteJobData(poOldestJob);
6501 : }
6502 :
6503 16 : jobList.pop_front();
6504 16 : return l_eErr;
6505 : };
6506 :
6507 : // Queue of jobs
6508 1198 : std::list<std::unique_ptr<OvrJob>> jobList;
6509 :
6510 1198 : std::vector<std::unique_ptr<void, VSIFreeReleaser>> apaChunk(nBands);
6511 : std::vector<std::unique_ptr<GByte, VSIFreeReleaser>>
6512 1198 : apabyChunkNoDataMask(nBands);
6513 :
6514 : // Iterate on destination overview, block by block.
6515 599 : for (int nDstYOff = nDstYOffStart;
6516 2106 : nDstYOff < nDstYOffEnd && eErr == CE_None;
6517 1507 : nDstYOff += nDstChunkYSize)
6518 : {
6519 : int nDstYCount;
6520 1507 : if (nDstYOff + nDstChunkYSize <= nDstYOffEnd)
6521 1086 : nDstYCount = nDstChunkYSize;
6522 : else
6523 421 : nDstYCount = nDstYOffEnd - nDstYOff;
6524 :
6525 1507 : int nChunkYOff = static_cast<int>(nDstYOff * dfYRatioDstToSrc);
6526 1507 : int nChunkYOff2 = static_cast<int>(
6527 1507 : ceil((nDstYOff + nDstYCount) * dfYRatioDstToSrc));
6528 1507 : if (nChunkYOff2 > nSrcHeight ||
6529 1507 : nDstYOff + nDstYCount == nDstTotalHeight)
6530 592 : nChunkYOff2 = nSrcHeight;
6531 1507 : int nYCount = nChunkYOff2 - nChunkYOff;
6532 1507 : CPLAssert(nYCount <= nFullResYChunk);
6533 :
6534 1507 : int nChunkYOffQueried = nChunkYOff - nKernelRadius * nOvrFactor;
6535 1507 : int nChunkYSizeQueried =
6536 1507 : nYCount + RADIUS_TO_DIAMETER * nKernelRadius * nOvrFactor;
6537 1507 : if (nChunkYOffQueried < 0)
6538 : {
6539 146 : nChunkYSizeQueried += nChunkYOffQueried;
6540 146 : nChunkYOffQueried = 0;
6541 : }
6542 1507 : if (nChunkYSizeQueried + nChunkYOffQueried > nSrcHeight)
6543 146 : nChunkYSizeQueried = nSrcHeight - nChunkYOffQueried;
6544 1507 : CPLAssert(nChunkYSizeQueried <= nFullResYChunkQueried);
6545 :
6546 1507 : if (!pfnProgress(std::min(1.0, dfCurPixelCount / dfTotalPixelCount),
6547 : nullptr, pProgressData))
6548 : {
6549 1 : CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
6550 1 : eErr = CE_Failure;
6551 : }
6552 :
6553 : // Iterate on destination overview, block by block.
6554 1507 : for (int nDstXOff = nDstXOffStart;
6555 3059 : nDstXOff < nDstXOffEnd && eErr == CE_None;
6556 1552 : nDstXOff += nDstChunkXSize)
6557 : {
6558 1552 : int nDstXCount = 0;
6559 1552 : if (nDstXOff + nDstChunkXSize <= nDstXOffEnd)
6560 1532 : nDstXCount = nDstChunkXSize;
6561 : else
6562 20 : nDstXCount = nDstXOffEnd - nDstXOff;
6563 :
6564 1552 : dfCurPixelCount += static_cast<double>(nDstXCount) * nDstYCount;
6565 :
6566 1552 : int nChunkXOff = static_cast<int>(nDstXOff * dfXRatioDstToSrc);
6567 1552 : int nChunkXOff2 = static_cast<int>(
6568 1552 : ceil((nDstXOff + nDstXCount) * dfXRatioDstToSrc));
6569 1552 : if (nChunkXOff2 > nSrcWidth ||
6570 1552 : nDstXOff + nDstXCount == nDstTotalWidth)
6571 1471 : nChunkXOff2 = nSrcWidth;
6572 1552 : const int nXCount = nChunkXOff2 - nChunkXOff;
6573 1552 : CPLAssert(nXCount <= nFullResXChunk);
6574 :
6575 1552 : int nChunkXOffQueried = nChunkXOff - nKernelRadius * nOvrFactor;
6576 1552 : int nChunkXSizeQueried =
6577 1552 : nXCount + RADIUS_TO_DIAMETER * nKernelRadius * nOvrFactor;
6578 1552 : if (nChunkXOffQueried < 0)
6579 : {
6580 209 : nChunkXSizeQueried += nChunkXOffQueried;
6581 209 : nChunkXOffQueried = 0;
6582 : }
6583 1552 : if (nChunkXSizeQueried + nChunkXOffQueried > nSrcWidth)
6584 218 : nChunkXSizeQueried = nSrcWidth - nChunkXOffQueried;
6585 1552 : CPLAssert(nChunkXSizeQueried <= nFullResXChunkQueried);
6586 : #if DEBUG_VERBOSE
6587 : CPLDebug("GDAL",
6588 : "Reading (%dx%d -> %dx%d) for output (%dx%d -> %dx%d)",
6589 : nChunkXOffQueried, nChunkYOffQueried,
6590 : nChunkXSizeQueried, nChunkYSizeQueried, nDstXOff,
6591 : nDstYOff, nDstXCount, nDstYCount);
6592 : #endif
6593 :
6594 : // Avoid accumulating too many tasks and exhaust RAM
6595 :
6596 : // Try to complete already finished jobs
6597 1552 : while (eErr == CE_None && !jobList.empty())
6598 : {
6599 2 : auto poOldestJob = jobList.front().get();
6600 2 : if (!poOldestJob->IsFinished())
6601 2 : break;
6602 0 : eErr = poOldestJob->eErr;
6603 0 : if (eErr == CE_None)
6604 : {
6605 0 : eErr = WriteJobData(poOldestJob);
6606 : }
6607 :
6608 0 : jobList.pop_front();
6609 : }
6610 :
6611 : // And in case we have saturated the number of threads,
6612 : // wait for completion of tasks to go below the threshold.
6613 3104 : while (eErr == CE_None &&
6614 1552 : jobList.size() >= static_cast<size_t>(nThreads))
6615 : {
6616 0 : eErr = WaitAndFinalizeOldestJob(jobList);
6617 : }
6618 :
6619 : // Read the source buffers for all the bands.
6620 4864 : for (int iBand = 0; iBand < nBands && eErr == CE_None; ++iBand)
6621 : {
6622 : // (Re)allocate buffers if needed
6623 3312 : if (apaChunk[iBand] == nullptr)
6624 : {
6625 1171 : apaChunk[iBand].reset(VSI_MALLOC3_VERBOSE(
6626 : nFullResXChunkQueried, nFullResYChunkQueried,
6627 : nWrkDataTypeSize));
6628 1171 : if (apaChunk[iBand] == nullptr)
6629 : {
6630 0 : eErr = CE_Failure;
6631 : }
6632 : }
6633 3647 : if (bUseNoDataMask &&
6634 335 : apabyChunkNoDataMask[iBand] == nullptr)
6635 : {
6636 268 : apabyChunkNoDataMask[iBand].reset(
6637 268 : static_cast<GByte *>(VSI_MALLOC2_VERBOSE(
6638 : nFullResXChunkQueried, nFullResYChunkQueried)));
6639 268 : if (apabyChunkNoDataMask[iBand] == nullptr)
6640 : {
6641 0 : eErr = CE_Failure;
6642 : }
6643 : }
6644 :
6645 3312 : if (eErr == CE_None)
6646 : {
6647 3312 : GDALRasterBand *poSrcBand = nullptr;
6648 3312 : if (iSrcOverview == -1)
6649 2420 : poSrcBand = papoSrcBands[iBand];
6650 : else
6651 892 : poSrcBand =
6652 892 : papapoOverviewBands[iBand][iSrcOverview];
6653 3312 : eErr = poSrcBand->RasterIO(
6654 : GF_Read, nChunkXOffQueried, nChunkYOffQueried,
6655 : nChunkXSizeQueried, nChunkYSizeQueried,
6656 3312 : apaChunk[iBand].get(), nChunkXSizeQueried,
6657 : nChunkYSizeQueried, eWrkDataType, 0, 0, nullptr);
6658 :
6659 3312 : if (bUseNoDataMask && eErr == CE_None)
6660 : {
6661 335 : auto poMaskBand = poSrcBand->IsMaskBand()
6662 335 : ? poSrcBand
6663 253 : : poSrcBand->GetMaskBand();
6664 335 : eErr = poMaskBand->RasterIO(
6665 : GF_Read, nChunkXOffQueried, nChunkYOffQueried,
6666 : nChunkXSizeQueried, nChunkYSizeQueried,
6667 335 : apabyChunkNoDataMask[iBand].get(),
6668 : nChunkXSizeQueried, nChunkYSizeQueried,
6669 : GDT_UInt8, 0, 0, nullptr);
6670 : }
6671 : }
6672 : }
6673 :
6674 : // Compute the resulting overview block.
6675 4863 : for (int iBand = 0; iBand < nBands && eErr == CE_None; ++iBand)
6676 : {
6677 6622 : auto poJob = std::make_unique<OvrJob>();
6678 3311 : poJob->pfnResampleFn = pfnResampleFn;
6679 3311 : poJob->poDstBand = papapoOverviewBands[iBand][iOverview];
6680 6622 : poJob->args.eOvrDataType =
6681 3311 : poJob->poDstBand->GetRasterDataType();
6682 3311 : poJob->args.nOvrXSize = poJob->poDstBand->GetXSize();
6683 3311 : poJob->args.nOvrYSize = poJob->poDstBand->GetYSize();
6684 3311 : const char *pszNBITS = poJob->poDstBand->GetMetadataItem(
6685 3311 : GDALMD_NBITS, GDAL_MDD_IMAGE_STRUCTURE);
6686 3311 : poJob->args.nOvrNBITS = pszNBITS ? atoi(pszNBITS) : 0;
6687 3311 : poJob->args.dfXRatioDstToSrc = dfXRatioDstToSrc;
6688 3311 : poJob->args.dfYRatioDstToSrc = dfYRatioDstToSrc;
6689 3311 : poJob->args.eWrkDataType = eWrkDataType;
6690 3311 : poJob->pChunk = apaChunk[iBand].get();
6691 3311 : poJob->args.pabyChunkNodataMask =
6692 3311 : apabyChunkNoDataMask[iBand].get();
6693 3311 : poJob->args.nChunkXOff = nChunkXOffQueried;
6694 3311 : poJob->args.nChunkXSize = nChunkXSizeQueried;
6695 3311 : poJob->args.nChunkYOff = nChunkYOffQueried;
6696 3311 : poJob->args.nChunkYSize = nChunkYSizeQueried;
6697 3311 : poJob->args.nDstXOff = nDstXOff;
6698 3311 : poJob->args.nDstXOff2 = nDstXOff + nDstXCount;
6699 3311 : poJob->args.nDstYOff = nDstYOff;
6700 3311 : poJob->args.nDstYOff2 = nDstYOff + nDstYCount;
6701 3311 : poJob->args.pszResampling = pszResampling;
6702 3311 : poJob->args.bHasNoData = abHasNoData[iBand];
6703 3311 : poJob->args.dfNoDataValue = adfNoDataValue[iBand];
6704 3311 : poJob->args.eSrcDataType = eDataType;
6705 3311 : poJob->args.bPropagateNoData = bPropagateNoData;
6706 :
6707 3311 : if (poJobQueue)
6708 : {
6709 16 : poJob->oSrcMaskBufferHolder =
6710 32 : std::make_unique<PointerHolder>(
6711 32 : std::move(apabyChunkNoDataMask[iBand]));
6712 :
6713 16 : poJob->oSrcBufferHolder =
6714 32 : std::make_unique<PointerHolder>(
6715 32 : std::move(apaChunk[iBand]));
6716 :
6717 16 : poJobQueue->SubmitJob(JobResampleFunc, poJob.get());
6718 16 : jobList.emplace_back(std::move(poJob));
6719 : }
6720 : else
6721 : {
6722 3295 : JobResampleFunc(poJob.get());
6723 3295 : eErr = poJob->eErr;
6724 3295 : if (eErr == CE_None)
6725 : {
6726 3295 : eErr = WriteJobData(poJob.get());
6727 : }
6728 : }
6729 : }
6730 : }
6731 : }
6732 :
6733 : // Wait for all pending jobs to complete
6734 615 : while (!jobList.empty())
6735 : {
6736 16 : const auto l_eErr = WaitAndFinalizeOldestJob(jobList);
6737 16 : if (l_eErr != CE_None && eErr == CE_None)
6738 0 : eErr = l_eErr;
6739 : }
6740 :
6741 : // Flush the data to overviews.
6742 1768 : for (int iBand = 0; iBand < nBands; ++iBand)
6743 : {
6744 1169 : if (papapoOverviewBands[iBand][iOverview]->FlushCache(false) !=
6745 : CE_None)
6746 0 : eErr = CE_Failure;
6747 : }
6748 : }
6749 :
6750 384 : if (eErr == CE_None)
6751 380 : pfnProgress(1.0, nullptr, pProgressData);
6752 :
6753 384 : return eErr;
6754 : }
6755 :
6756 : /************************************************************************/
6757 : /* GDALRegenerateOverviewsMultiBand() */
6758 : /************************************************************************/
6759 :
6760 : /**
6761 : * \brief Variant of GDALRegenerateOverviews, specially dedicated for generating
6762 : * compressed pixel-interleaved overviews (JPEG-IN-TIFF for example)
6763 : *
6764 : * This function will generate one or more overview images from a base
6765 : * image using the requested downsampling algorithm. Its primary use
6766 : * is for generating overviews via GDALDataset::BuildOverviews(), but it
6767 : * can also be used to generate downsampled images in one file from another
6768 : * outside the overview architecture.
6769 : *
6770 : * The output bands need to exist in advance and share the same characteristics
6771 : * (type, dimensions)
6772 : *
6773 : * The resampling algorithms supported for the moment are "NEAREST", "AVERAGE",
6774 : * "RMS", "GAUSS", "CUBIC", "CUBICSPLINE", "LANCZOS" and "BILINEAR"
6775 : *
6776 : * It does not support color tables or complex data types.
6777 : *
6778 : * The pseudo-algorithm used by the function is :
6779 : * for each overview
6780 : * iterate on lines of the source by a step of deltay
6781 : * iterate on columns of the source by a step of deltax
6782 : * read the source data of size deltax * deltay for all the bands
6783 : * generate the corresponding overview block for all the bands
6784 : *
6785 : * This function will honour properly NODATA_VALUES tuples (special dataset
6786 : * metadata) so that only a given RGB triplet (in case of a RGB image) will be
6787 : * considered as the nodata value and not each value of the triplet
6788 : * independently per band.
6789 : *
6790 : * The GDAL_NUM_THREADS configuration option can be set
6791 : * to "ALL_CPUS" or a integer value to specify the number of threads to use for
6792 : * overview computation.
6793 : *
6794 : * @param apoSrcBands the list of source bands to downsample
6795 : * @param aapoOverviewBands bidimension array of bands. First dimension is
6796 : * indexed by bands. Second dimension is indexed by
6797 : * overview levels. All aapoOverviewBands[i] arrays
6798 : * must have the same size (i.e. same number of
6799 : * overviews)
6800 : * @param pszResampling Resampling algorithm ("NEAREST", "AVERAGE", "RMS",
6801 : * "GAUSS", "CUBIC", "CUBICSPLINE", "LANCZOS" or "BILINEAR").
6802 : * @param pfnProgress progress report function.
6803 : * @param pProgressData progress function callback data.
6804 : * @param papszOptions NULL terminated list of options as
6805 : * key=value pairs, or NULL
6806 : * The XOFF, YOFF, XSIZE and YSIZE
6807 : * options can be specified to express that overviews should
6808 : * be regenerated only in the specified subset of the source
6809 : * dataset.
6810 : * @return CE_None on success or CE_Failure on failure.
6811 : * @since 3.10
6812 : */
6813 :
6814 19 : CPLErr GDALRegenerateOverviewsMultiBand(
6815 : const std::vector<GDALRasterBand *> &apoSrcBands,
6816 : const std::vector<std::vector<GDALRasterBand *>> &aapoOverviewBands,
6817 : const char *pszResampling, GDALProgressFunc pfnProgress,
6818 : void *pProgressData, CSLConstList papszOptions)
6819 : {
6820 19 : CPLAssert(apoSrcBands.size() == aapoOverviewBands.size());
6821 29 : for (size_t i = 1; i < aapoOverviewBands.size(); ++i)
6822 : {
6823 10 : CPLAssert(aapoOverviewBands[i].size() == aapoOverviewBands[0].size());
6824 : }
6825 :
6826 19 : if (aapoOverviewBands.empty())
6827 0 : return CE_None;
6828 :
6829 19 : std::vector<GDALRasterBand **> apapoOverviewBands;
6830 48 : for (auto &apoOverviewBands : aapoOverviewBands)
6831 : {
6832 : auto papoOverviewBands = static_cast<GDALRasterBand **>(
6833 29 : CPLMalloc(apoOverviewBands.size() * sizeof(GDALRasterBand *)));
6834 61 : for (size_t i = 0; i < apoOverviewBands.size(); ++i)
6835 : {
6836 32 : papoOverviewBands[i] = apoOverviewBands[i];
6837 : }
6838 29 : apapoOverviewBands.push_back(papoOverviewBands);
6839 : }
6840 38 : const CPLErr eErr = GDALRegenerateOverviewsMultiBand(
6841 19 : static_cast<int>(apoSrcBands.size()), apoSrcBands.data(),
6842 19 : static_cast<int>(aapoOverviewBands[0].size()),
6843 19 : apapoOverviewBands.data(), pszResampling, pfnProgress, pProgressData,
6844 : papszOptions);
6845 48 : for (GDALRasterBand **papoOverviewBands : apapoOverviewBands)
6846 29 : CPLFree(papoOverviewBands);
6847 19 : return eErr;
6848 : }
6849 :
6850 : /************************************************************************/
6851 : /* GDALComputeBandStats() */
6852 : /************************************************************************/
6853 :
6854 : /** Undocumented
6855 : * @param hSrcBand undocumented.
6856 : * @param nSampleStep Step between scanlines used to compute statistics.
6857 : * When nSampleStep is equal to 1, all scanlines will
6858 : * be processed.
6859 : * @param pdfMean undocumented.
6860 : * @param pdfStdDev undocumented.
6861 : * @param pfnProgress undocumented.
6862 : * @param pProgressData undocumented.
6863 : * @return undocumented
6864 : */
6865 18 : CPLErr CPL_STDCALL GDALComputeBandStats(GDALRasterBandH hSrcBand,
6866 : int nSampleStep, double *pdfMean,
6867 : double *pdfStdDev,
6868 : GDALProgressFunc pfnProgress,
6869 : void *pProgressData)
6870 :
6871 : {
6872 18 : VALIDATE_POINTER1(hSrcBand, "GDALComputeBandStats", CE_Failure);
6873 :
6874 18 : GDALRasterBand *poSrcBand = GDALRasterBand::FromHandle(hSrcBand);
6875 :
6876 18 : if (pfnProgress == nullptr)
6877 18 : pfnProgress = GDALDummyProgress;
6878 :
6879 18 : const int nWidth = poSrcBand->GetXSize();
6880 18 : const int nHeight = poSrcBand->GetYSize();
6881 :
6882 18 : if (nSampleStep >= nHeight || nSampleStep < 1)
6883 5 : nSampleStep = 1;
6884 :
6885 18 : GDALDataType eWrkType = GDT_Unknown;
6886 18 : float *pafData = nullptr;
6887 18 : GDALDataType eType = poSrcBand->GetRasterDataType();
6888 18 : const bool bComplex = CPL_TO_BOOL(GDALDataTypeIsComplex(eType));
6889 18 : if (bComplex)
6890 : {
6891 : pafData = static_cast<float *>(
6892 0 : VSI_MALLOC2_VERBOSE(nWidth, 2 * sizeof(float)));
6893 0 : eWrkType = GDT_CFloat32;
6894 : }
6895 : else
6896 : {
6897 : pafData =
6898 18 : static_cast<float *>(VSI_MALLOC2_VERBOSE(nWidth, sizeof(float)));
6899 18 : eWrkType = GDT_Float32;
6900 : }
6901 :
6902 18 : if (nWidth == 0 || pafData == nullptr)
6903 : {
6904 0 : VSIFree(pafData);
6905 0 : return CE_Failure;
6906 : }
6907 :
6908 : /* -------------------------------------------------------------------- */
6909 : /* Loop over all sample lines. */
6910 : /* -------------------------------------------------------------------- */
6911 18 : double dfSum = 0.0;
6912 18 : double dfSum2 = 0.0;
6913 18 : int iLine = 0;
6914 18 : GIntBig nSamples = 0;
6915 :
6916 2143 : do
6917 : {
6918 2161 : if (!pfnProgress(iLine / static_cast<double>(nHeight), nullptr,
6919 : pProgressData))
6920 : {
6921 0 : CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
6922 0 : CPLFree(pafData);
6923 0 : return CE_Failure;
6924 : }
6925 :
6926 : const CPLErr eErr =
6927 2161 : poSrcBand->RasterIO(GF_Read, 0, iLine, nWidth, 1, pafData, nWidth,
6928 : 1, eWrkType, 0, 0, nullptr);
6929 2161 : if (eErr != CE_None)
6930 : {
6931 1 : CPLFree(pafData);
6932 1 : return eErr;
6933 : }
6934 :
6935 725208 : for (int iPixel = 0; iPixel < nWidth; ++iPixel)
6936 : {
6937 723048 : float fValue = 0.0f;
6938 :
6939 723048 : if (bComplex)
6940 : {
6941 : // Compute the magnitude of the complex value.
6942 : fValue =
6943 0 : std::hypot(pafData[static_cast<size_t>(iPixel) * 2],
6944 0 : pafData[static_cast<size_t>(iPixel) * 2 + 1]);
6945 : }
6946 : else
6947 : {
6948 723048 : fValue = pafData[iPixel];
6949 : }
6950 :
6951 723048 : dfSum += static_cast<double>(fValue);
6952 723048 : dfSum2 += static_cast<double>(fValue) * static_cast<double>(fValue);
6953 : }
6954 :
6955 2160 : nSamples += nWidth;
6956 2160 : iLine += nSampleStep;
6957 2160 : } while (iLine < nHeight);
6958 :
6959 17 : if (!pfnProgress(1.0, nullptr, pProgressData))
6960 : {
6961 0 : CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
6962 0 : CPLFree(pafData);
6963 0 : return CE_Failure;
6964 : }
6965 :
6966 : /* -------------------------------------------------------------------- */
6967 : /* Produce the result values. */
6968 : /* -------------------------------------------------------------------- */
6969 17 : if (pdfMean != nullptr)
6970 17 : *pdfMean = dfSum / nSamples;
6971 :
6972 17 : if (pdfStdDev != nullptr)
6973 : {
6974 17 : const double dfMean = dfSum / nSamples;
6975 :
6976 17 : *pdfStdDev = sqrt((dfSum2 / nSamples) - (dfMean * dfMean));
6977 : }
6978 :
6979 17 : CPLFree(pafData);
6980 :
6981 17 : return CE_None;
6982 : }
6983 :
6984 : /************************************************************************/
6985 : /* GDALOverviewMagnitudeCorrection() */
6986 : /* */
6987 : /* Correct the mean and standard deviation of the overviews of */
6988 : /* the given band to match the base layer approximately. */
6989 : /************************************************************************/
6990 :
6991 : /** Undocumented
6992 : * @param hBaseBand undocumented.
6993 : * @param nOverviewCount undocumented.
6994 : * @param pahOverviews undocumented.
6995 : * @param pfnProgress undocumented.
6996 : * @param pProgressData undocumented.
6997 : * @return undocumented
6998 : */
6999 0 : CPLErr GDALOverviewMagnitudeCorrection(GDALRasterBandH hBaseBand,
7000 : int nOverviewCount,
7001 : GDALRasterBandH *pahOverviews,
7002 : GDALProgressFunc pfnProgress,
7003 : void *pProgressData)
7004 :
7005 : {
7006 0 : VALIDATE_POINTER1(hBaseBand, "GDALOverviewMagnitudeCorrection", CE_Failure);
7007 :
7008 : /* -------------------------------------------------------------------- */
7009 : /* Compute mean/stddev for source raster. */
7010 : /* -------------------------------------------------------------------- */
7011 0 : double dfOrigMean = 0.0;
7012 0 : double dfOrigStdDev = 0.0;
7013 : {
7014 : const CPLErr eErr =
7015 0 : GDALComputeBandStats(hBaseBand, 2, &dfOrigMean, &dfOrigStdDev,
7016 : pfnProgress, pProgressData);
7017 :
7018 0 : if (eErr != CE_None)
7019 0 : return eErr;
7020 : }
7021 :
7022 : /* -------------------------------------------------------------------- */
7023 : /* Loop on overview bands. */
7024 : /* -------------------------------------------------------------------- */
7025 0 : for (int iOverview = 0; iOverview < nOverviewCount; ++iOverview)
7026 : {
7027 : GDALRasterBand *poOverview =
7028 0 : GDALRasterBand::FromHandle(pahOverviews[iOverview]);
7029 : double dfOverviewMean, dfOverviewStdDev;
7030 :
7031 : const CPLErr eErr =
7032 0 : GDALComputeBandStats(pahOverviews[iOverview], 1, &dfOverviewMean,
7033 : &dfOverviewStdDev, pfnProgress, pProgressData);
7034 :
7035 0 : if (eErr != CE_None)
7036 0 : return eErr;
7037 :
7038 0 : double dfGain = 1.0;
7039 0 : if (dfOrigStdDev >= 0.0001)
7040 0 : dfGain = dfOrigStdDev / dfOverviewStdDev;
7041 :
7042 : /* --------------------------------------------------------------------
7043 : */
7044 : /* Apply gain and offset. */
7045 : /* --------------------------------------------------------------------
7046 : */
7047 0 : const int nWidth = poOverview->GetXSize();
7048 0 : const int nHeight = poOverview->GetYSize();
7049 :
7050 0 : GDALDataType eWrkType = GDT_Unknown;
7051 0 : float *pafData = nullptr;
7052 0 : const GDALDataType eType = poOverview->GetRasterDataType();
7053 0 : const bool bComplex = CPL_TO_BOOL(GDALDataTypeIsComplex(eType));
7054 0 : if (bComplex)
7055 : {
7056 : pafData = static_cast<float *>(
7057 0 : VSI_MALLOC2_VERBOSE(nWidth, 2 * sizeof(float)));
7058 0 : eWrkType = GDT_CFloat32;
7059 : }
7060 : else
7061 : {
7062 : pafData = static_cast<float *>(
7063 0 : VSI_MALLOC2_VERBOSE(nWidth, sizeof(float)));
7064 0 : eWrkType = GDT_Float32;
7065 : }
7066 :
7067 0 : if (pafData == nullptr)
7068 : {
7069 0 : return CE_Failure;
7070 : }
7071 :
7072 0 : for (int iLine = 0; iLine < nHeight; ++iLine)
7073 : {
7074 0 : if (!pfnProgress(iLine / static_cast<double>(nHeight), nullptr,
7075 : pProgressData))
7076 : {
7077 0 : CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
7078 0 : CPLFree(pafData);
7079 0 : return CE_Failure;
7080 : }
7081 :
7082 0 : if (poOverview->RasterIO(GF_Read, 0, iLine, nWidth, 1, pafData,
7083 : nWidth, 1, eWrkType, 0, 0,
7084 0 : nullptr) != CE_None)
7085 : {
7086 0 : CPLFree(pafData);
7087 0 : return CE_Failure;
7088 : }
7089 :
7090 0 : for (int iPixel = 0; iPixel < nWidth; ++iPixel)
7091 : {
7092 0 : if (bComplex)
7093 : {
7094 0 : pafData[static_cast<size_t>(iPixel) * 2] *=
7095 0 : static_cast<float>(dfGain);
7096 0 : pafData[static_cast<size_t>(iPixel) * 2 + 1] *=
7097 0 : static_cast<float>(dfGain);
7098 : }
7099 : else
7100 : {
7101 0 : pafData[iPixel] = static_cast<float>(
7102 0 : (double(pafData[iPixel]) - dfOverviewMean) * dfGain +
7103 : dfOrigMean);
7104 : }
7105 : }
7106 :
7107 0 : if (poOverview->RasterIO(GF_Write, 0, iLine, nWidth, 1, pafData,
7108 : nWidth, 1, eWrkType, 0, 0,
7109 0 : nullptr) != CE_None)
7110 : {
7111 0 : CPLFree(pafData);
7112 0 : return CE_Failure;
7113 : }
7114 : }
7115 :
7116 0 : if (!pfnProgress(1.0, nullptr, pProgressData))
7117 : {
7118 0 : CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
7119 0 : CPLFree(pafData);
7120 0 : return CE_Failure;
7121 : }
7122 :
7123 0 : CPLFree(pafData);
7124 : }
7125 :
7126 0 : return CE_None;
7127 : }
|