-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
overview.cpp
5902 lines (5337 loc) · 233 KB
/
overview.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
*
* Project: GDAL Core
* Purpose: Helper code to implement overview support in different drivers.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2000, Frank Warmerdam
* Copyright (c) 2007-2010, Even Rouault <even dot rouault at spatialys.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "cpl_port.h"
#include "gdal_priv.h"
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <algorithm>
#include <complex>
#include <condition_variable>
#include <limits>
#include <list>
#include <memory>
#include <mutex>
#include <vector>
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_progress.h"
#include "cpl_vsi.h"
#include "gdal.h"
#include "gdal_thread_pool.h"
#include "gdalwarper.h"
// Restrict to 64bit processors because they are guaranteed to have SSE2,
// or if __AVX2__ is defined.
#if defined(__x86_64) || defined(_M_X64) || defined(__AVX2__)
#define USE_SSE2
#include "gdalsse_priv.h"
#ifdef __SSE3__
#include <pmmintrin.h>
#endif
#ifdef __SSSE3__
#include <tmmintrin.h>
#endif
#ifdef __SSE4_1__
#include <smmintrin.h>
#endif
#ifdef __AVX2__
#include <immintrin.h>
#endif
#endif
// To be included after above USE_SSE2 and include gdalsse_priv.h
// to avoid build issue on Windows x86
#include "gdal_priv_templates.hpp"
/************************************************************************/
/* GDALResampleChunk_Near() */
/************************************************************************/
template <class T>
static CPLErr GDALResampleChunk_NearT(
double dfXRatioDstToSrc, double dfYRatioDstToSrc, GDALDataType eWrkDataType,
const T *pChunk, int nChunkXOff, int nChunkXSize, int nChunkYOff,
int nDstXOff, int nDstXOff2, int nDstYOff, int nDstYOff2, T **ppDstBuffer)
{
const int nDstXWidth = nDstXOff2 - nDstXOff;
/* -------------------------------------------------------------------- */
/* Allocate buffers. */
/* -------------------------------------------------------------------- */
*ppDstBuffer = static_cast<T *>(
VSI_MALLOC3_VERBOSE(nDstXWidth, nDstYOff2 - nDstYOff,
GDALGetDataTypeSizeBytes(eWrkDataType)));
if (*ppDstBuffer == nullptr)
{
return CE_Failure;
}
T *const pDstBuffer = *ppDstBuffer;
int *panSrcXOff =
static_cast<int *>(VSI_MALLOC_VERBOSE(nDstXWidth * sizeof(int)));
if (panSrcXOff == nullptr)
{
VSIFree(panSrcXOff);
return CE_Failure;
}
/* ==================================================================== */
/* Precompute inner loop constants. */
/* ==================================================================== */
for (int iDstPixel = nDstXOff; iDstPixel < nDstXOff2; ++iDstPixel)
{
int nSrcXOff = static_cast<int>(0.5 + iDstPixel * dfXRatioDstToSrc);
if (nSrcXOff < nChunkXOff)
nSrcXOff = nChunkXOff;
panSrcXOff[iDstPixel - nDstXOff] = nSrcXOff;
}
/* ==================================================================== */
/* Loop over destination scanlines. */
/* ==================================================================== */
for (int iDstLine = nDstYOff; iDstLine < nDstYOff2; ++iDstLine)
{
int nSrcYOff = static_cast<int>(0.5 + iDstLine * dfYRatioDstToSrc);
if (nSrcYOff < nChunkYOff)
nSrcYOff = nChunkYOff;
const T *const pSrcScanline =
pChunk +
(static_cast<GPtrDiff_t>(nSrcYOff - nChunkYOff) * nChunkXSize) -
nChunkXOff;
/* --------------------------------------------------------------------
*/
/* Loop over destination pixels */
/* --------------------------------------------------------------------
*/
T *pDstScanline = pDstBuffer + (iDstLine - nDstYOff) * nDstXWidth;
for (int iDstPixel = 0; iDstPixel < nDstXWidth; ++iDstPixel)
{
pDstScanline[iDstPixel] = pSrcScanline[panSrcXOff[iDstPixel]];
}
}
CPLFree(panSrcXOff);
return CE_None;
}
static CPLErr GDALResampleChunk_Near(
double dfXRatioDstToSrc, double dfYRatioDstToSrc, double /* dfSrcXDelta */,
double /* dfSrcYDelta */, GDALDataType eWrkDataType, const void *pChunk,
const GByte * /* pabyChunkNodataMask_unused */, int nChunkXOff,
int nChunkXSize, int nChunkYOff, int /* nChunkYSize */, int nDstXOff,
int nDstXOff2, int nDstYOff, int nDstYOff2, GDALRasterBand * /*poOverview*/,
void **ppDstBuffer, GDALDataType *peDstBufferDataType,
const char * /* pszResampling_unused */, bool /* bHasNoData_unused */,
double /* fNoDataValue_unused */,
GDALColorTable * /* poColorTable_unused */, GDALDataType /* eSrcDataType */,
bool /* bPropagateNoData */)
{
*peDstBufferDataType = eWrkDataType;
if (eWrkDataType == GDT_Byte)
return GDALResampleChunk_NearT(
dfXRatioDstToSrc, dfYRatioDstToSrc, eWrkDataType,
static_cast<const GByte *>(pChunk), nChunkXOff, nChunkXSize,
nChunkYOff, nDstXOff, nDstXOff2, nDstYOff, nDstYOff2,
reinterpret_cast<GByte **>(ppDstBuffer));
else if (eWrkDataType == GDT_UInt16)
return GDALResampleChunk_NearT(
dfXRatioDstToSrc, dfYRatioDstToSrc, eWrkDataType,
static_cast<const GInt16 *>(pChunk), nChunkXOff, nChunkXSize,
nChunkYOff, nDstXOff, nDstXOff2, nDstYOff, nDstYOff2,
reinterpret_cast<GInt16 **>(ppDstBuffer));
else if (eWrkDataType == GDT_Float32)
return GDALResampleChunk_NearT(
dfXRatioDstToSrc, dfYRatioDstToSrc, eWrkDataType,
static_cast<const float *>(pChunk), nChunkXOff, nChunkXSize,
nChunkYOff, nDstXOff, nDstXOff2, nDstYOff, nDstYOff2,
reinterpret_cast<float **>(ppDstBuffer));
else if (eWrkDataType == GDT_Float64)
return GDALResampleChunk_NearT(
dfXRatioDstToSrc, dfYRatioDstToSrc, eWrkDataType,
static_cast<const double *>(pChunk), nChunkXOff, nChunkXSize,
nChunkYOff, nDstXOff, nDstXOff2, nDstYOff, nDstYOff2,
reinterpret_cast<double **>(ppDstBuffer));
CPLAssert(false);
return CE_Failure;
}
namespace
{
// Find in the color table the entry whose RGB value is the closest
// (using quadratic distance) to the test color, ignoring transparent entries.
int BestColorEntry(const std::vector<GDALColorEntry> &entries,
const GDALColorEntry &test)
{
int nMinDist = std::numeric_limits<int>::max();
size_t bestEntry = 0;
for (size_t i = 0; i < entries.size(); ++i)
{
const GDALColorEntry &entry = entries[i];
// Ignore transparent entries
if (entry.c4 == 0)
continue;
int nDist = ((test.c1 - entry.c1) * (test.c1 - entry.c1)) +
((test.c2 - entry.c2) * (test.c2 - entry.c2)) +
((test.c3 - entry.c3) * (test.c3 - entry.c3));
if (nDist < nMinDist)
{
nMinDist = nDist;
bestEntry = i;
}
}
return static_cast<int>(bestEntry);
}
std::vector<GDALColorEntry> ReadColorTable(const GDALColorTable &table,
int &transparentIdx)
{
std::vector<GDALColorEntry> entries(table.GetColorEntryCount());
transparentIdx = -1;
int i = 0;
for (auto &entry : entries)
{
table.GetColorEntryAsRGB(i, &entry);
if (transparentIdx < 0 && entry.c4 == 0)
transparentIdx = i;
++i;
}
return entries;
}
} // unnamed namespace
/************************************************************************/
/* GetReplacementValueIfNoData() */
/************************************************************************/
static double GetReplacementValueIfNoData(GDALDataType dt, bool bHasNoData,
double dfNoDataValue)
{
double dfReplacementVal = 0.0f;
if (bHasNoData)
{
if (dt == GDT_Byte)
{
if (dfNoDataValue == std::numeric_limits<unsigned char>::max())
dfReplacementVal =
std::numeric_limits<unsigned char>::max() - 1;
else
dfReplacementVal = dfNoDataValue + 1;
}
else if (dt == GDT_Int8)
{
if (dfNoDataValue == std::numeric_limits<GInt8>::max())
dfReplacementVal = std::numeric_limits<GInt8>::max() - 1;
else
dfReplacementVal = dfNoDataValue + 1;
}
else if (dt == GDT_UInt16)
{
if (dfNoDataValue == std::numeric_limits<GUInt16>::max())
dfReplacementVal = std::numeric_limits<GUInt16>::max() - 1;
else
dfReplacementVal = dfNoDataValue + 1;
}
else if (dt == GDT_Int16)
{
if (dfNoDataValue == std::numeric_limits<GInt16>::max())
dfReplacementVal = std::numeric_limits<GInt16>::max() - 1;
else
dfReplacementVal = dfNoDataValue + 1;
}
else if (dt == GDT_UInt32)
{
// Be careful to limited precision of float
dfReplacementVal = dfNoDataValue + 1;
double dfVal = dfNoDataValue;
if (dfReplacementVal >= std::numeric_limits<GUInt32>::max() - 128)
{
while (dfReplacementVal == dfNoDataValue)
{
dfVal -= 1.0;
dfReplacementVal = dfVal;
}
}
else
{
while (dfReplacementVal == dfNoDataValue)
{
dfVal += 1.0;
dfReplacementVal = dfVal;
}
}
}
else if (dt == GDT_Int32)
{
// Be careful to limited precision of float
dfReplacementVal = dfNoDataValue + 1;
double dfVal = dfNoDataValue;
if (dfReplacementVal >= std::numeric_limits<GInt32>::max() - 64)
{
while (dfReplacementVal == dfNoDataValue)
{
dfVal -= 1.0;
dfReplacementVal = dfVal;
}
}
else
{
while (dfReplacementVal == dfNoDataValue)
{
dfVal += 1.0;
dfReplacementVal = dfVal;
}
}
}
else if (dt == GDT_Float32 || dt == GDT_Float64)
{
if (dfNoDataValue == 0)
{
dfReplacementVal = std::numeric_limits<float>::min();
}
else
{
dfReplacementVal = dfNoDataValue + 1e-7 * dfNoDataValue;
}
}
}
return dfReplacementVal;
}
/************************************************************************/
/* SQUARE() */
/************************************************************************/
template <class T, class Tsquare = T> inline Tsquare SQUARE(T val)
{
return static_cast<Tsquare>(val) * val;
}
/************************************************************************/
/* ComputeIntegerRMS() */
/************************************************************************/
// Compute rms = sqrt(sumSquares / weight) in such a way that it is the
// integer that minimizes abs(rms**2 - sumSquares / weight)
template <class T, class Twork>
inline T ComputeIntegerRMS(double sumSquares, double weight)
{
const double sumDivWeight = sumSquares / weight;
T rms = static_cast<T>(sqrt(sumDivWeight));
// Is rms**2 or (rms+1)**2 closest to sumSquares / weight ?
// Naive version:
// if( weight * (rms+1)**2 - sumSquares < sumSquares - weight * rms**2 )
if (static_cast<double>(static_cast<Twork>(2) * rms * (rms + 1) + 1) <
2 * sumDivWeight)
rms += 1;
return rms;
}
template <class T, class Tsum> inline T ComputeIntegerRMS_4values(Tsum)
{
CPLAssert(false);
return 0;
}
template <> inline GByte ComputeIntegerRMS_4values<GByte, int>(int sumSquares)
{
// It has been verified that given the correction on rms below, using
// sqrt((float)((sumSquares + 1)/ 4)) or sqrt((float)sumSquares * 0.25f)
// is equivalent, so use the former as it is used twice.
const int sumSquaresPlusOneDiv4 = (sumSquares + 1) / 4;
const float sumDivWeight = static_cast<float>(sumSquaresPlusOneDiv4);
GByte rms = static_cast<GByte>(std::sqrt(sumDivWeight));
// Is rms**2 or (rms+1)**2 closest to sumSquares / weight ?
// Naive version:
// if( weight * (rms+1)**2 - sumSquares < sumSquares - weight * rms**2 )
// Optimized version for integer case and weight == 4
if (static_cast<int>(rms) * (rms + 1) < sumSquaresPlusOneDiv4)
rms += 1;
return rms;
}
template <>
inline GUInt16 ComputeIntegerRMS_4values<GUInt16, double>(double sumSquares)
{
const double sumDivWeight = sumSquares * 0.25;
GUInt16 rms = static_cast<GUInt16>(std::sqrt(sumDivWeight));
// Is rms**2 or (rms+1)**2 closest to sumSquares / weight ?
// Naive version:
// if( weight * (rms+1)**2 - sumSquares < sumSquares - weight * rms**2 )
// Optimized version for integer case and weight == 4
if (static_cast<GUInt32>(rms) * (rms + 1) <
static_cast<GUInt32>(sumDivWeight + 0.25))
rms += 1;
return rms;
}
#ifdef USE_SSE2
/************************************************************************/
/* QuadraticMeanByteSSE2OrAVX2() */
/************************************************************************/
#ifdef __SSE4_1__
#define sse2_packus_epi32 _mm_packus_epi32
#else
inline __m128i sse2_packus_epi32(__m128i a, __m128i b)
{
const auto minus32768_32 = _mm_set1_epi32(-32768);
const auto minus32768_16 = _mm_set1_epi16(-32768);
a = _mm_add_epi32(a, minus32768_32);
b = _mm_add_epi32(b, minus32768_32);
a = _mm_packs_epi32(a, b);
a = _mm_sub_epi16(a, minus32768_16);
return a;
}
#endif
#ifdef __SSSE3__
#define sse2_hadd_epi16 _mm_hadd_epi16
#else
inline __m128i sse2_hadd_epi16(__m128i a, __m128i b)
{
// Horizontal addition of adjacent pairs
const auto mask = _mm_set1_epi32(0xFFFF);
const auto horizLo =
_mm_add_epi32(_mm_and_si128(a, mask), _mm_srli_epi32(a, 16));
const auto horizHi =
_mm_add_epi32(_mm_and_si128(b, mask), _mm_srli_epi32(b, 16));
// Recombine low and high parts
return _mm_packs_epi32(horizLo, horizHi);
}
#endif
#ifdef __AVX2__
#define DEST_ELTS 16
#define set1_epi16 _mm256_set1_epi16
#define set1_epi32 _mm256_set1_epi32
#define setzero _mm256_setzero_si256
#define set1_ps _mm256_set1_ps
#define loadu_int(x) _mm256_loadu_si256(reinterpret_cast<__m256i const *>(x))
#define unpacklo_epi8 _mm256_unpacklo_epi8
#define unpackhi_epi8 _mm256_unpackhi_epi8
#define madd_epi16 _mm256_madd_epi16
#define add_epi32 _mm256_add_epi32
#define mul_ps _mm256_mul_ps
#define cvtepi32_ps _mm256_cvtepi32_ps
#define sqrt_ps _mm256_sqrt_ps
#define cvttps_epi32 _mm256_cvttps_epi32
#define packs_epi32 _mm256_packs_epi32
#define packus_epi32 _mm256_packus_epi32
#define srli_epi32 _mm256_srli_epi32
#define mullo_epi16 _mm256_mullo_epi16
#define srli_epi16 _mm256_srli_epi16
#define cmpgt_epi16 _mm256_cmpgt_epi16
#define add_epi16 _mm256_add_epi16
#define sub_epi16 _mm256_sub_epi16
#define packus_epi16 _mm256_packus_epi16
/* AVX2 operates on 2 separate 128-bit lanes, so we have to do shuffling */
/* to get the lower 128-bit bits of what would be a true 256-bit vector register
*/
#define store_lo(x, y) \
_mm_storeu_si128(reinterpret_cast<__m128i *>(x), \
_mm256_extracti128_si256( \
_mm256_permute4x64_epi64((y), 0 | (2 << 2)), 0))
#define hadd_epi16 _mm256_hadd_epi16
#define zeroupper() _mm256_zeroupper()
#else
#define DEST_ELTS 8
#define set1_epi16 _mm_set1_epi16
#define set1_epi32 _mm_set1_epi32
#define setzero _mm_setzero_si128
#define set1_ps _mm_set1_ps
#define loadu_int(x) _mm_loadu_si128(reinterpret_cast<__m128i const *>(x))
#define unpacklo_epi8 _mm_unpacklo_epi8
#define unpackhi_epi8 _mm_unpackhi_epi8
#define madd_epi16 _mm_madd_epi16
#define add_epi32 _mm_add_epi32
#define mul_ps _mm_mul_ps
#define cvtepi32_ps _mm_cvtepi32_ps
#define sqrt_ps _mm_sqrt_ps
#define cvttps_epi32 _mm_cvttps_epi32
#define packs_epi32 _mm_packs_epi32
#define packus_epi32 sse2_packus_epi32
#define srli_epi32 _mm_srli_epi32
#define mullo_epi16 _mm_mullo_epi16
#define srli_epi16 _mm_srli_epi16
#define cmpgt_epi16 _mm_cmpgt_epi16
#define add_epi16 _mm_add_epi16
#define sub_epi16 _mm_sub_epi16
#define packus_epi16 _mm_packus_epi16
#define store_lo(x, y) _mm_storel_epi64(reinterpret_cast<__m128i *>(x), (y))
#define hadd_epi16 sse2_hadd_epi16
#define zeroupper() (void)0
#endif
#if defined(__GNUC__) && defined(__AVX2__)
// Disabling inlining works around a bug with gcc 9.3 (Ubuntu 20.04) in
// -O2 -mavx2 mode in QuadraticMeanFloatSSE2(),
// where the registry that contains minus_zero is correctly
// loaded the first time the function is called (looking at the disassembly,
// one sees it is loaded much earlier than the function), but gets corrupted
// (zeroed) in following iterations.
// It appears the bug is due to the explicit zeroupper() call at the end of
// the function.
// The bug is at least solved in gcc 10.2.
// Inlining doesn't bring much here to performance.
// This is also needed with gcc 9.3 on QuadraticMeanByteSSE2OrAVX2() in
// -O3 -mavx2 mode
#define NOINLINE __attribute__((noinline))
#else
#define NOINLINE
#endif
template <class T>
static int NOINLINE
QuadraticMeanByteSSE2OrAVX2(int nDstXWidth, int nChunkXSize,
const T *&CPL_RESTRICT pSrcScanlineShiftedInOut,
T *CPL_RESTRICT pDstScanline)
{
// Optimized implementation for RMS on Byte by
// processing by group of 8 output pixels, so as to use
// a single _mm_sqrt_ps() call for 4 output pixels
const T *CPL_RESTRICT pSrcScanlineShifted = pSrcScanlineShiftedInOut;
int iDstPixel = 0;
const auto one16 = set1_epi16(1);
const auto one32 = set1_epi32(1);
const auto zero = setzero();
const auto minus32768 = set1_epi16(-32768);
for (; iDstPixel < nDstXWidth - (DEST_ELTS - 1); iDstPixel += DEST_ELTS)
{
// Load 2 * DEST_ELTS bytes from each line
auto firstLine = loadu_int(pSrcScanlineShifted);
auto secondLine = loadu_int(pSrcScanlineShifted + nChunkXSize);
// Extend those Bytes as UInt16s
auto firstLineLo = unpacklo_epi8(firstLine, zero);
auto firstLineHi = unpackhi_epi8(firstLine, zero);
auto secondLineLo = unpacklo_epi8(secondLine, zero);
auto secondLineHi = unpackhi_epi8(secondLine, zero);
// Multiplication of 16 bit values and horizontal
// addition of 32 bit results
// [ src[2*i+0]^2 + src[2*i+1]^2 for i in range(4) ]
firstLineLo = madd_epi16(firstLineLo, firstLineLo);
firstLineHi = madd_epi16(firstLineHi, firstLineHi);
secondLineLo = madd_epi16(secondLineLo, secondLineLo);
secondLineHi = madd_epi16(secondLineHi, secondLineHi);
// Vertical addition
const auto sumSquaresLo = add_epi32(firstLineLo, secondLineLo);
const auto sumSquaresHi = add_epi32(firstLineHi, secondLineHi);
const auto sumSquaresPlusOneDiv4Lo =
srli_epi32(add_epi32(sumSquaresLo, one32), 2);
const auto sumSquaresPlusOneDiv4Hi =
srli_epi32(add_epi32(sumSquaresHi, one32), 2);
// Take square root and truncate/floor to int32
const auto rmsLo =
cvttps_epi32(sqrt_ps(cvtepi32_ps(sumSquaresPlusOneDiv4Lo)));
const auto rmsHi =
cvttps_epi32(sqrt_ps(cvtepi32_ps(sumSquaresPlusOneDiv4Hi)));
// Merge back low and high registers with each RMS value
// as a 16 bit value.
auto rms = packs_epi32(rmsLo, rmsHi);
// Round to upper value if it minimizes the
// error |rms^2 - sumSquares/4|
// if( 2 * (2 * rms * (rms + 1) + 1) < sumSquares )
// rms += 1;
// which is equivalent to:
// if( rms * (rms + 1) < (sumSquares+1) / 4 )
// rms += 1;
// And both left and right parts fit on 16 (unsigned) bits
const auto sumSquaresPlusOneDiv4 =
packus_epi32(sumSquaresPlusOneDiv4Lo, sumSquaresPlusOneDiv4Hi);
// cmpgt_epi16 operates on signed int16, but here
// we have unsigned values, so shift them by -32768 before
auto mask = cmpgt_epi16(
add_epi16(sumSquaresPlusOneDiv4, minus32768),
add_epi16(mullo_epi16(rms, add_epi16(rms, one16)), minus32768));
// The value of the mask will be -1 when the correction needs to be
// applied
rms = sub_epi16(rms, mask);
// Pack each 16 bit RMS value to 8 bits
rms = packus_epi16(rms, rms /* could be anything */);
store_lo(&pDstScanline[iDstPixel], rms);
pSrcScanlineShifted += 2 * DEST_ELTS;
}
zeroupper();
pSrcScanlineShiftedInOut = pSrcScanlineShifted;
return iDstPixel;
}
/************************************************************************/
/* AverageByteSSE2OrAVX2() */
/************************************************************************/
template <class T>
static int
AverageByteSSE2OrAVX2(int nDstXWidth, int nChunkXSize,
const T *&CPL_RESTRICT pSrcScanlineShiftedInOut,
T *CPL_RESTRICT pDstScanline)
{
// Optimized implementation for average on Byte by
// processing by group of 8 output pixels.
const auto zero = setzero();
const auto two16 = set1_epi16(2);
const T *CPL_RESTRICT pSrcScanlineShifted = pSrcScanlineShiftedInOut;
int iDstPixel = 0;
for (; iDstPixel < nDstXWidth - (DEST_ELTS - 1); iDstPixel += DEST_ELTS)
{
// Load 2 * DEST_ELTS bytes from each line
const auto firstLine = loadu_int(pSrcScanlineShifted);
const auto secondLine = loadu_int(pSrcScanlineShifted + nChunkXSize);
// Extend those Bytes as UInt16s
const auto firstLineLo = unpacklo_epi8(firstLine, zero);
const auto firstLineHi = unpackhi_epi8(firstLine, zero);
const auto secondLineLo = unpacklo_epi8(secondLine, zero);
const auto secondLineHi = unpackhi_epi8(secondLine, zero);
// Vertical addition
const auto sumLo = add_epi16(firstLineLo, secondLineLo);
const auto sumHi = add_epi16(firstLineHi, secondLineHi);
// Horizontal addition of adjacent pairs, and recombine low and high
// parts
const auto sum = hadd_epi16(sumLo, sumHi);
// average = (sum + 2) / 4
auto average = srli_epi16(add_epi16(sum, two16), 2);
// Pack each 16 bit average value to 8 bits
average = packus_epi16(average, average /* could be anything */);
store_lo(&pDstScanline[iDstPixel], average);
pSrcScanlineShifted += 2 * DEST_ELTS;
}
zeroupper();
pSrcScanlineShiftedInOut = pSrcScanlineShifted;
return iDstPixel;
}
/************************************************************************/
/* QuadraticMeanUInt16SSE2() */
/************************************************************************/
#ifdef __SSE3__
#define sse2_hadd_pd _mm_hadd_pd
#else
inline __m128d sse2_hadd_pd(__m128d a, __m128d b)
{
auto aLo_bLo =
_mm_castps_pd(_mm_movelh_ps(_mm_castpd_ps(a), _mm_castpd_ps(b)));
auto aHi_bHi =
_mm_castps_pd(_mm_movehl_ps(_mm_castpd_ps(b), _mm_castpd_ps(a)));
return _mm_add_pd(aLo_bLo, aHi_bHi); // (aLo + aHi, bLo + bHi)
}
#endif
inline __m128d SQUARE(__m128d x)
{
return _mm_mul_pd(x, x);
}
#ifdef __AVX2__
inline __m256d SQUARE(__m256d x)
{
return _mm256_mul_pd(x, x);
}
inline __m256d FIXUP_LANES(__m256d x)
{
return _mm256_permute4x64_pd(x, _MM_SHUFFLE(3, 1, 2, 0));
}
inline __m256 FIXUP_LANES(__m256 x)
{
return _mm256_castpd_ps(FIXUP_LANES(_mm256_castps_pd(x)));
}
#endif
template <class T>
static int
QuadraticMeanUInt16SSE2(int nDstXWidth, int nChunkXSize,
const T *&CPL_RESTRICT pSrcScanlineShiftedInOut,
T *CPL_RESTRICT pDstScanline)
{
// Optimized implementation for RMS on UInt16 by
// processing by group of 4 output pixels.
const T *CPL_RESTRICT pSrcScanlineShifted = pSrcScanlineShiftedInOut;
int iDstPixel = 0;
const auto zero = _mm_setzero_si128();
#ifdef __AVX2__
const auto zeroDot25 = _mm256_set1_pd(0.25);
const auto zeroDot5 = _mm256_set1_pd(0.5);
// The first four 0's could be anything, as we only take the bottom
// 128 bits.
const auto permutation = _mm256_set_epi32(0, 0, 0, 0, 6, 4, 2, 0);
#else
const auto zeroDot25 = _mm_set1_pd(0.25);
const auto zeroDot5 = _mm_set1_pd(0.5);
#endif
for (; iDstPixel < nDstXWidth - 3; iDstPixel += 4)
{
// Load 8 UInt16 from each line
const auto firstLine = _mm_loadu_si128(
reinterpret_cast<__m128i const *>(pSrcScanlineShifted));
const auto secondLine =
_mm_loadu_si128(reinterpret_cast<__m128i const *>(
pSrcScanlineShifted + nChunkXSize));
// Detect if all of the source values fit in 14 bits.
// because if x < 2^14, then 4 * x^2 < 2^30 which fits in a signed int32
// and we can do a much faster implementation.
const auto maskTmp =
_mm_srli_epi16(_mm_or_si128(firstLine, secondLine), 14);
#if defined(__i386__) || defined(_M_IX86)
uint64_t nMaskFitsIn14Bits = 0;
_mm_storel_epi64(
reinterpret_cast<__m128i *>(&nMaskFitsIn14Bits),
_mm_packus_epi16(maskTmp, maskTmp /* could be anything */));
#else
const auto nMaskFitsIn14Bits = _mm_cvtsi128_si64(
_mm_packus_epi16(maskTmp, maskTmp /* could be anything */));
#endif
if (nMaskFitsIn14Bits == 0)
{
// Multiplication of 16 bit values and horizontal
// addition of 32 bit results
const auto firstLineHSumSquare =
_mm_madd_epi16(firstLine, firstLine);
const auto secondLineHSumSquare =
_mm_madd_epi16(secondLine, secondLine);
// Vertical addition
const auto sumSquares =
_mm_add_epi32(firstLineHSumSquare, secondLineHSumSquare);
// In theory we should take sqrt(sumSquares * 0.25f)
// but given the rounding we do, this is equivalent to
// sqrt((sumSquares + 1)/4). This has been verified exhaustively for
// sumSquares <= 4 * 16383^2
const auto one32 = _mm_set1_epi32(1);
const auto sumSquaresPlusOneDiv4 =
_mm_srli_epi32(_mm_add_epi32(sumSquares, one32), 2);
// Take square root and truncate/floor to int32
auto rms = _mm_cvttps_epi32(
_mm_sqrt_ps(_mm_cvtepi32_ps(sumSquaresPlusOneDiv4)));
// Round to upper value if it minimizes the
// error |rms^2 - sumSquares/4|
// if( 2 * (2 * rms * (rms + 1) + 1) < sumSquares )
// rms += 1;
// which is equivalent to:
// if( rms * rms + rms < (sumSquares+1) / 4 )
// rms += 1;
auto mask =
_mm_cmpgt_epi32(sumSquaresPlusOneDiv4,
_mm_add_epi32(_mm_madd_epi16(rms, rms), rms));
rms = _mm_sub_epi32(rms, mask);
// Pack each 32 bit RMS value to 16 bits
rms = _mm_packs_epi32(rms, rms /* could be anything */);
_mm_storel_epi64(
reinterpret_cast<__m128i *>(&pDstScanline[iDstPixel]), rms);
pSrcScanlineShifted += 8;
continue;
}
// An approach using _mm_mullo_epi16, _mm_mulhi_epu16 before extending
// to 32 bit would result in 4 multiplications instead of 8, but
// mullo/mulhi have a worse throughput than mul_pd.
// Extend those UInt16s as UInt32s
const auto firstLineLo = _mm_unpacklo_epi16(firstLine, zero);
const auto firstLineHi = _mm_unpackhi_epi16(firstLine, zero);
const auto secondLineLo = _mm_unpacklo_epi16(secondLine, zero);
const auto secondLineHi = _mm_unpackhi_epi16(secondLine, zero);
#ifdef __AVX2__
// Multiplication of 32 bit values previously converted to 64 bit double
const auto firstLineLoDbl = SQUARE(_mm256_cvtepi32_pd(firstLineLo));
const auto firstLineHiDbl = SQUARE(_mm256_cvtepi32_pd(firstLineHi));
const auto secondLineLoDbl = SQUARE(_mm256_cvtepi32_pd(secondLineLo));
const auto secondLineHiDbl = SQUARE(_mm256_cvtepi32_pd(secondLineHi));
// Vertical addition of squares
const auto sumSquaresLo =
_mm256_add_pd(firstLineLoDbl, secondLineLoDbl);
const auto sumSquaresHi =
_mm256_add_pd(firstLineHiDbl, secondLineHiDbl);
// Horizontal addition of squares
const auto sumSquares =
FIXUP_LANES(_mm256_hadd_pd(sumSquaresLo, sumSquaresHi));
const auto sumDivWeight = _mm256_mul_pd(sumSquares, zeroDot25);
// Take square root and truncate/floor to int32
auto rms = _mm256_cvttpd_epi32(_mm256_sqrt_pd(sumDivWeight));
const auto rmsDouble = _mm256_cvtepi32_pd(rms);
const auto right = _mm256_sub_pd(
sumDivWeight, _mm256_add_pd(SQUARE(rmsDouble), rmsDouble));
auto mask =
_mm256_castpd_ps(_mm256_cmp_pd(zeroDot5, right, _CMP_LT_OS));
// Extract 32-bit from each of the 4 64-bit masks
// mask = FIXUP_LANES(_mm256_shuffle_ps(mask, mask,
// _MM_SHUFFLE(2,0,2,0)));
mask = _mm256_permutevar8x32_ps(mask, permutation);
const auto maskI = _mm_castps_si128(_mm256_extractf128_ps(mask, 0));
// Apply the correction
rms = _mm_sub_epi32(rms, maskI);
// Pack each 32 bit RMS value to 16 bits
rms = _mm_packus_epi32(rms, rms /* could be anything */);
#else
// Multiplication of 32 bit values previously converted to 64 bit double
const auto firstLineLoLo = SQUARE(_mm_cvtepi32_pd(firstLineLo));
const auto firstLineLoHi =
SQUARE(_mm_cvtepi32_pd(_mm_srli_si128(firstLineLo, 8)));
const auto firstLineHiLo = SQUARE(_mm_cvtepi32_pd(firstLineHi));
const auto firstLineHiHi =
SQUARE(_mm_cvtepi32_pd(_mm_srli_si128(firstLineHi, 8)));
const auto secondLineLoLo = SQUARE(_mm_cvtepi32_pd(secondLineLo));
const auto secondLineLoHi =
SQUARE(_mm_cvtepi32_pd(_mm_srli_si128(secondLineLo, 8)));
const auto secondLineHiLo = SQUARE(_mm_cvtepi32_pd(secondLineHi));
const auto secondLineHiHi =
SQUARE(_mm_cvtepi32_pd(_mm_srli_si128(secondLineHi, 8)));
// Vertical addition of squares
const auto sumSquaresLoLo = _mm_add_pd(firstLineLoLo, secondLineLoLo);
const auto sumSquaresLoHi = _mm_add_pd(firstLineLoHi, secondLineLoHi);
const auto sumSquaresHiLo = _mm_add_pd(firstLineHiLo, secondLineHiLo);
const auto sumSquaresHiHi = _mm_add_pd(firstLineHiHi, secondLineHiHi);
// Horizontal addition of squares
const auto sumSquaresLo = sse2_hadd_pd(sumSquaresLoLo, sumSquaresLoHi);
const auto sumSquaresHi = sse2_hadd_pd(sumSquaresHiLo, sumSquaresHiHi);
const auto sumDivWeightLo = _mm_mul_pd(sumSquaresLo, zeroDot25);
const auto sumDivWeightHi = _mm_mul_pd(sumSquaresHi, zeroDot25);
// Take square root and truncate/floor to int32
const auto rmsLo = _mm_cvttpd_epi32(_mm_sqrt_pd(sumDivWeightLo));
const auto rmsHi = _mm_cvttpd_epi32(_mm_sqrt_pd(sumDivWeightHi));
// Correctly round rms to minimize | rms^2 - sumSquares / 4 |
// if( 0.5 < sumDivWeight - (rms * rms + rms) )
// rms += 1;
const auto rmsLoDouble = _mm_cvtepi32_pd(rmsLo);
const auto rmsHiDouble = _mm_cvtepi32_pd(rmsHi);
const auto rightLo = _mm_sub_pd(
sumDivWeightLo, _mm_add_pd(SQUARE(rmsLoDouble), rmsLoDouble));
const auto rightHi = _mm_sub_pd(
sumDivWeightHi, _mm_add_pd(SQUARE(rmsHiDouble), rmsHiDouble));
const auto maskLo = _mm_castpd_ps(_mm_cmplt_pd(zeroDot5, rightLo));
const auto maskHi = _mm_castpd_ps(_mm_cmplt_pd(zeroDot5, rightHi));
// The value of the mask will be -1 when the correction needs to be
// applied
const auto mask = _mm_castps_si128(_mm_shuffle_ps(
maskLo, maskHi, (0 << 0) | (2 << 2) | (0 << 4) | (2 << 6)));
auto rms = _mm_castps_si128(
_mm_movelh_ps(_mm_castsi128_ps(rmsLo), _mm_castsi128_ps(rmsHi)));
// Apply the correction
rms = _mm_sub_epi32(rms, mask);
// Pack each 32 bit RMS value to 16 bits
rms = sse2_packus_epi32(rms, rms /* could be anything */);
#endif
_mm_storel_epi64(reinterpret_cast<__m128i *>(&pDstScanline[iDstPixel]),
rms);
pSrcScanlineShifted += 8;
}
zeroupper();
pSrcScanlineShiftedInOut = pSrcScanlineShifted;
return iDstPixel;
}
/************************************************************************/
/* AverageUInt16SSE2() */
/************************************************************************/
template <class T>
static int AverageUInt16SSE2(int nDstXWidth, int nChunkXSize,
const T *&CPL_RESTRICT pSrcScanlineShiftedInOut,
T *CPL_RESTRICT pDstScanline)
{
// Optimized implementation for average on UInt16 by
// processing by group of 8 output pixels.
const auto mask = _mm_set1_epi32(0xFFFF);
const auto two = _mm_set1_epi32(2);
const T *CPL_RESTRICT pSrcScanlineShifted = pSrcScanlineShiftedInOut;
int iDstPixel = 0;
for (; iDstPixel < nDstXWidth - 7; iDstPixel += 8)
{
__m128i averageLow;
// Load 8 UInt16 from each line
{
const auto firstLine = _mm_loadu_si128(
reinterpret_cast<__m128i const *>(pSrcScanlineShifted));
const auto secondLine =
_mm_loadu_si128(reinterpret_cast<__m128i const *>(
pSrcScanlineShifted + nChunkXSize));
// Horizontal addition and extension to 32 bit
const auto horizAddFirstLine = _mm_add_epi32(
_mm_and_si128(firstLine, mask), _mm_srli_epi32(firstLine, 16));
const auto horizAddSecondLine =
_mm_add_epi32(_mm_and_si128(secondLine, mask),
_mm_srli_epi32(secondLine, 16));
// Vertical addition and average computation
// average = (sum + 2) >> 2
const auto sum = _mm_add_epi32(
_mm_add_epi32(horizAddFirstLine, horizAddSecondLine), two);
averageLow = _mm_srli_epi32(sum, 2);
}
// Load 8 UInt16 from each line
__m128i averageHigh;
{
const auto firstLine = _mm_loadu_si128(
reinterpret_cast<__m128i const *>(pSrcScanlineShifted + 8));
const auto secondLine =
_mm_loadu_si128(reinterpret_cast<__m128i const *>(
pSrcScanlineShifted + 8 + nChunkXSize));
// Horizontal addition and extension to 32 bit
const auto horizAddFirstLine = _mm_add_epi32(
_mm_and_si128(firstLine, mask), _mm_srli_epi32(firstLine, 16));
const auto horizAddSecondLine =
_mm_add_epi32(_mm_and_si128(secondLine, mask),
_mm_srli_epi32(secondLine, 16));
// Vertical addition and average computation
// average = (sum + 2) >> 2
const auto sum = _mm_add_epi32(
_mm_add_epi32(horizAddFirstLine, horizAddSecondLine), two);
averageHigh = _mm_srli_epi32(sum, 2);
}
// Pack each 32 bit average value to 16 bits
auto average = sse2_packus_epi32(averageLow, averageHigh);
_mm_storeu_si128(reinterpret_cast<__m128i *>(&pDstScanline[iDstPixel]),
average);
pSrcScanlineShifted += 16;
}
pSrcScanlineShiftedInOut = pSrcScanlineShifted;
return iDstPixel;
}
/************************************************************************/
/* QuadraticMeanFloatSSE2() */
/************************************************************************/
#ifdef __AVX2__
#define RMS_FLOAT_ELTS 8
#define set1_ps _mm256_set1_ps
#define loadu_ps _mm256_loadu_ps
#define andnot_ps _mm256_andnot_ps