-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathlancir.h
2446 lines (2015 loc) · 55.6 KB
/
lancir.h
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
//$ nobt
//$ nocpp
/**
* @file lancir.h
*
* @version 3.0.11
*
* @brief The self-contained header-only "LANCIR" image resizing algorithm.
*
* This is the self-contained inclusion file for the "LANCIR" image resizer,
* a part of the AVIR library. Features scalar, AVX, SSE2, and NEON
* optimizations as well as batched resizing technique which provides a better
* CPU cache performance.
*
* AVIR Copyright (c) 2015-2024 Aleksey Vaneev
*
* @mainpage
*
* @section intro_sec Introduction
*
* Description is available at https://github.com/avaneev/avir
*
* @section license License
*
* LICENSE:
*
* Copyright (c) 2015-2024 Aleksey Vaneev
*
* 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.
*/
#ifndef AVIR_CLANCIR_INCLUDED
#define AVIR_CLANCIR_INCLUDED
#include <stdint.h>
#include <string.h>
#include <math.h>
#if defined( __AVX__ ) || defined( __AVX2__ )
#include <immintrin.h>
#define LANCIR_AVX
#define LANCIR_SSE2 // Some functions use SSE2; AVX has a higher priority.
#define LANCIR_ALIGN 32
#elif defined( __SSE4_2__ ) || defined( __SSE4_1__ ) || \
defined( __SSSE3__ ) || defined( __SSE3__ ) || defined( __SSE2__ ) || \
defined( __x86_64__ ) || defined( __amd64 ) || defined( _M_X64 ) || \
defined( _M_AMD64 ) || ( defined( _M_IX86_FP ) && _M_IX86_FP == 2 )
#if defined( _MSC_VER )
#include <intrin.h>
#else // defined( _MSC_VER )
#include <emmintrin.h>
#endif // defined( _MSC_VER )
#define LANCIR_SSE2
#define LANCIR_ALIGN 16
#elif defined( __aarch64__ ) || defined( __arm64 ) || defined( __ARM_NEON )
#include <arm_neon.h>
#define LANCIR_NEON
#define LANCIR_ALIGN 16
#else // NEON
#define LANCIR_ALIGN 4
#endif // NEON
namespace avir {
/**
* @brief LANCIR resizing parameters class.
*
* An object of this class, which can be allocated on stack, can be used to
* pass non-default parameters to the resizing algorithm. See the constructor
* for the default values.
*/
class CLancIRParams
{
public:
int SrcSSize; ///< Physical size of the source scanline, in elements (not
///< bytes). If this value is below 1, SrcWidth * ElCount will be
///< used.
int NewSSize; ///< Physical size of the destination scanline, in elements
///< (not bytes). If this value is below 1, NewWidth * ElCount will be
///< used.
double kx; ///< Resizing step - horizontal (one output pixel corresponds
///< to `k` input pixels). A downsizing factor if greater than 1.0;
///< upsizing factor if below or equal to 1.0. Multiply by -1 if you
///< would like to bypass `ox` and `oy` adjustment which is done by
///< default to produce a centered image. If this step value equals 0,
///< the step value will be chosen automatically.
double ky; ///< Resizing step - vertical. Same as `kx`.
double ox; ///< Start X pixel offset within the source image, can be
///< negative. A positive offset moves the image to the left.
///<
double oy; ///< Start Y pixel offset within the source image, can be
///< negative. A positive offset moves the image to the top.
///<
double la; ///< Lanczos window function's `a` parameter, greater or equal
///< to 2.0.
///<
/**
* Default constructor, with optional arguments that correspond to class
* variables.
*
* @param aSrcSSize Physical size of the source scanline.
* @param aNewSSize Physical size of the destination scanline.
* @param akx Resizing step - horizontal.
* @param aky Resizing step - vertical.
* @param aox Start X pixel offset.
* @param aoy Start Y pixel offset.
*/
CLancIRParams( const int aSrcSSize = 0, const int aNewSSize = 0,
const double akx = 0.0, const double aky = 0.0,
const double aox = 0.0, const double aoy = 0.0 )
: SrcSSize( aSrcSSize )
, NewSSize( aNewSSize )
, kx( akx )
, ky( aky )
, ox( aox )
, oy( aoy )
, la( 3.0 )
{
}
};
/**
* @brief LANCIR image resizer class.
*
* The object of this class can be used to resize 1-4 channel images to any
* required size. Resizing is performed by utilizing Lanczos filters, with
* 8-bit precision. This class offers a kind of "optimal" Lanczos resampling
* implementation.
*
* Object of this class can be allocated on stack.
*
* Note that object of this class does not free temporary buffers and
* variables after the resizeImage() function call (until object's
* destruction): these buffers are reused (or reallocated) on subsequent
* calls, thus making batch resizing of images faster. This means resizing is
* not thread-safe: a separate object should be created for each thread.
*/
class CLancIR
{
private:
CLancIR( const CLancIR& )
{
// Unsupported.
}
CLancIR& operator = ( const CLancIR& )
{
// Unsupported.
return( *this );
}
public:
CLancIR()
: FltBuf0( NULL )
, FltBuf0Len( 0 )
, spv0( NULL )
, spv0len( 0 )
, spv( NULL )
{
}
~CLancIR()
{
delete[] FltBuf0;
delete[] spv0;
}
/**
* @brief Function resizes an image.
*
* Performs input-to-output type conversion, if necessary.
*
* @param[in] SrcBuf Source image buffer.
* @param SrcWidth Source image width, in pixels.
* @param SrcHeight Source image height, in pixels.
* @param[out] NewBuf Buffer to accept the resized image. Cannot be equal
* to SrcBuf.
* @param NewWidth New image width, in pixels.
* @param NewHeight New image height, in pixels.
* @param ElCount The number of elements (channels) used to store each
* source and destination pixel (1-4).
* @tparam Tin Input buffer's element type. Can be uint8_t (0-255 value
* range), uint16_t (0-65535 value range), float (0-1 value range), double
* (0-1 value range). uint32_t type is treated as uint16_t. Signed integer
* types and larger integer types are unsupported.
* @tparam Tout Output buffer's element type, treated like `Tin`. If `Tin`
* and `Tout` types do not match, an output value scaling will be applied.
* Floating-point output will not clamped/clipped/saturated, integer
* output is always rounded and clamped.
* @return The number of available output scanlines. Equals to NewHeight,
* or 0 on function parameters error.
*/
template< typename Tin, typename Tout >
int resizeImage( const Tin* const SrcBuf, const int SrcWidth,
const int SrcHeight, Tout* const NewBuf, const int NewWidth,
const int NewHeight, const int ElCount,
const CLancIRParams* const aParams = NULL )
{
if(( SrcWidth < 0 ) | ( SrcHeight < 0 ) | ( NewWidth <= 0 ) |
( NewHeight <= 0 ) | ( SrcBuf == NULL ) | ( NewBuf == NULL ) |
( (const void*) SrcBuf == (const void*) NewBuf ))
{
return( 0 );
}
static const CLancIRParams DefParams;
const CLancIRParams& Params = ( aParams != NULL ?
*aParams : DefParams );
if( Params.la < 2.0 )
{
return( 0 );
}
const int OutSSize = NewWidth * ElCount;
const size_t NewScanlineSize = ( Params.NewSSize < 1 ?
OutSSize : Params.NewSSize );
if(( SrcWidth == 0 ) | ( SrcHeight == 0 ))
{
Tout* op = NewBuf;
int i;
for( i = 0; i < NewHeight; i++ )
{
memset( op, 0, OutSSize * sizeof( Tout ));
op += NewScanlineSize;
}
return( NewHeight );
}
const size_t SrcScanlineSize = ( Params.SrcSSize < 1 ?
SrcWidth * ElCount : Params.SrcSSize );
double ox = Params.ox;
double oy = Params.oy;
double kx;
double ky;
if( Params.kx >= 0.0 )
{
kx = ( Params.kx == 0.0 ?
(double) SrcWidth / NewWidth : Params.kx );
ox += ( kx - 1.0 ) * 0.5;
}
else
{
kx = -Params.kx;
}
if( Params.ky >= 0.0 )
{
ky = ( Params.ky == 0.0 ?
(double) SrcHeight / NewHeight : Params.ky );
oy += ( ky - 1.0 ) * 0.5;
}
else
{
ky = -Params.ky;
}
if( rfv.update( Params.la, ky, ElCount ))
{
rsv.reset();
rsh.reset();
}
CResizeFilters* rfh; // Pointer to resizing filters for horizontal
// resizing, may equal to `rfv` if the same stepping is in use.
if( kx == ky )
{
rfh = &rfv;
}
else
{
rfh = &rfh0;
if( rfh0.update( Params.la, kx, ElCount ))
{
rsh.reset();
}
}
rsv.update( SrcHeight, NewHeight, oy, rfv, spv );
rsh.update( SrcWidth, NewWidth, ox, *rfh );
// Calculate vertical progressive resizing's batch size. Progressive
// batching is used to try to keep addressing within the cache
// capacity. This technique definitely works well for single-threaded
// resizing on most CPUs, but may not provide an additional benefit
// for multi-threaded resizing, or in a system-wide high-load
// situations.
const size_t FltWidthE = ( rsh.padl + SrcWidth + rsh.padr ) * ElCount;
const double CacheSize = 5500000.0; // Tuned for various CPUs.
const double OpSize = (double) SrcScanlineSize * SrcHeight *
sizeof( Tin ) + (double) FltWidthE * NewHeight * sizeof( float );
int BatchSize = (int) ( NewHeight * CacheSize / ( OpSize + 1.0 ));
if( BatchSize < 8 )
{
BatchSize = 8;
}
if( BatchSize > NewHeight )
{
BatchSize = NewHeight;
}
// Allocate/resize intermediate buffers.
const int svs = ( rsv.padl + SrcHeight + rsv.padr ) * ElCount;
float* const pspv0 = spv0;
reallocBuf( spv0, spv, spv0len, ( svs > OutSSize ? svs : OutSSize ));
reallocBuf( FltBuf0, FltBuf, FltBuf0Len, FltWidthE * BatchSize );
if( spv0 != pspv0 )
{
rsv.updateSPO( rfv, spv );
}
// Prepare output-related constants.
const bool IsOutFloat = ( (Tout) 0.25 != 0 );
const int Clamp = ( sizeof( Tout ) == 1 ? 255 : 65535 );
const float OutMul = ( IsOutFloat ? 1.0f : (float) Clamp ) /
( (Tin) 0.25 != 0 ? 1 : ( sizeof( Tin ) == 1 ? 255 : 65535 ));
// Perform batched resizing.
const CResizePos* rpv = rsv.pos;
Tout* opn = NewBuf;
int bl = NewHeight;
while( bl > 0 )
{
const int bc = ( bl > BatchSize ? BatchSize : bl );
int kl = rfv.KernelLen;
const Tin* ip = SrcBuf;
float* op = FltBuf + rsh.padl * ElCount;
const int so = (int) rpv[ 0 ].so;
float* const sp = spv + so * ElCount;
int cc = (int) rpv[ bc - 1 ].so - so + kl; // Pixel copy count.
int rl = 0; // Leftmost pixel's replication count.
int rr = 0; // Rightmost pixel's replication count.
const int socc = so + cc;
const int spe = rsv.padl + SrcHeight;
// Calculate scanline copying and padding parameters, depending on
// the batch's size and its vertical offset.
if( so < rsv.padl )
{
if( socc <= rsv.padl )
{
rl = cc;
cc = 0;
}
else
{
if( socc > spe )
{
rr = socc - spe;
cc -= rr;
}
rl = rsv.padl - so;
cc -= rl;
}
}
else
{
if( so >= spe )
{
rr = cc;
cc = 0;
ip += SrcHeight * SrcScanlineSize;
}
else
{
if( socc > spe )
{
rr = socc - spe;
cc -= rr;
}
ip += ( so - rsv.padl ) * SrcScanlineSize;
}
}
// Batched vertical resizing.
int i;
if( ElCount == 1 )
{
for( i = 0; i < SrcWidth; i++ )
{
copyScanline1v( ip, SrcScanlineSize, sp, cc, rl, rr );
resize1< false >( NULL, op, FltWidthE, rpv, kl, bc );
ip += 1;
op += 1;
}
}
else
if( ElCount == 2 )
{
for( i = 0; i < SrcWidth; i++ )
{
copyScanline2v( ip, SrcScanlineSize, sp, cc, rl, rr );
resize2< false >( NULL, op, FltWidthE, rpv, kl, bc );
ip += 2;
op += 2;
}
}
else
if( ElCount == 3 )
{
for( i = 0; i < SrcWidth; i++ )
{
copyScanline3v( ip, SrcScanlineSize, sp, cc, rl, rr );
resize3< false >( NULL, op, FltWidthE, rpv, kl, bc );
ip += 3;
op += 3;
}
}
else // ElCount == 4
{
for( i = 0; i < SrcWidth; i++ )
{
copyScanline4v( ip, SrcScanlineSize, sp, cc, rl, rr );
resize4< false >( NULL, op, FltWidthE, rpv, kl, bc );
ip += 4;
op += 4;
}
}
// Perform horizontal resizing batch, and produce final output.
float* ipf = FltBuf;
kl = rfh -> KernelLen;
if( ElCount == 1 )
{
for( i = 0; i < bc; i++ )
{
padScanline1h( ipf, rsh, SrcWidth );
resize1< true >( ipf, spv, 1, rsh.pos, kl, NewWidth );
copyToOutput( spv, opn, OutSSize, Clamp, IsOutFloat,
OutMul );
ipf += FltWidthE;
opn += NewScanlineSize;
}
}
else
if( ElCount == 2 )
{
for( i = 0; i < bc; i++ )
{
padScanline2h( ipf, rsh, SrcWidth );
resize2< true >( ipf, spv, 2, rsh.pos, kl, NewWidth );
copyToOutput( spv, opn, OutSSize, Clamp, IsOutFloat,
OutMul );
ipf += FltWidthE;
opn += NewScanlineSize;
}
}
else
if( ElCount == 3 )
{
for( i = 0; i < bc; i++ )
{
padScanline3h( ipf, rsh, SrcWidth );
resize3< true >( ipf, spv, 3, rsh.pos, kl, NewWidth );
copyToOutput( spv, opn, OutSSize, Clamp, IsOutFloat,
OutMul );
ipf += FltWidthE;
opn += NewScanlineSize;
}
}
else // ElCount == 4
{
for( i = 0; i < bc; i++ )
{
padScanline4h( ipf, rsh, SrcWidth );
resize4< true >( ipf, spv, 4, rsh.pos, kl, NewWidth );
copyToOutput( spv, opn, OutSSize, Clamp, IsOutFloat,
OutMul );
ipf += FltWidthE;
opn += NewScanlineSize;
}
}
rpv += bc;
bl -= bc;
}
return( NewHeight );
}
/**
* @brief Legacy resizing function. Not recommended for new projects.
*
* See the prior resizeImage() function and CLancIRParams class for
* details.
*
* @param[in] SrcBuf Source image buffer.
* @param SrcWidth Source image width, in pixels.
* @param SrcHeight Source image height, in pixels.
* @param SrcSSize Physical size of the source scanline, in elements (not
* bytes).
* @param[out] NewBuf Buffer to accept the resized image. Cannot be equal
* to SrcBuf.
* @param NewWidth New image width, in pixels.
* @param NewHeight New image height, in pixels.
* @param NewSSize Physical size of the destination scanline, in elements
* (not bytes).
* @param ElCount The number of elements (channels) used to store each
* source and destination pixel (1-4).
* @param kx0 Resizing step - horizontal.
* @param ky0 Resizing step - vertical. Same as `kx0`.
* @param ox Start X pixel offset within the source image.
* @param oy Start Y pixel offset within the source image.
* @tparam Tin Input buffer's element type.
* @tparam Tout Output buffer's element type.
* @return The number of available output scanlines. Equals to NewHeight,
* or 0 on function parameters error.
*/
template< typename Tin, typename Tout >
int resizeImage( const Tin* const SrcBuf, const int SrcWidth,
const int SrcHeight, const int SrcSSize, Tout* const NewBuf,
const int NewWidth, const int NewHeight, const int NewSSize,
const int ElCount, const double kx0 = 0.0, const double ky0 = 0.0,
double ox = 0.0, double oy = 0.0 )
{
const CLancIRParams Params( SrcSSize, NewSSize, kx0, ky0, ox, oy );
return( resizeImage( SrcBuf, SrcWidth, SrcHeight, NewBuf, NewWidth,
NewHeight, ElCount, &Params ));
}
protected:
float* FltBuf0; ///< Intermediate resizing buffer.
size_t FltBuf0Len; ///< Length of `FltBuf0`.
float* FltBuf; ///< Address-aligned `FltBuf0`.
float* spv0; ///< Scanline buffer for vertical resizing, also used at the
///< output stage.
///<
int spv0len; ///< Length of `spv0`.
float* spv; ///< Address-aligned `spv0`.
/**
* Function reallocates a typed buffer if its current length is smaller
* than the required length.
*
* @param buf0 Reference to the pointer of the previously allocated
* buffer.
* @param buf Reference to address-aligned `buf0` pointer.
* @param len The current length of the `buf0`.
* @param newlen A new required length.
* @tparam Tb Buffer element type.
* @tparam Tl Length variable type.
*/
template< typename Tb, typename Tl >
static void reallocBuf( Tb*& buf0, Tb*& buf, Tl& len, Tl newlen )
{
newlen += LANCIR_ALIGN;
if( newlen > len )
{
if( buf0 != NULL )
{
delete[] buf0;
buf0 = NULL;
len = 0;
}
buf0 = new Tb[ newlen ];
len = newlen;
buf = (Tb*) (( (uintptr_t) buf0 + LANCIR_ALIGN - 1 ) &
~(uintptr_t) ( LANCIR_ALIGN - 1 ));
}
}
/**
* Function reallocates a typed buffer if its current length is smaller
* than the required length.
*
* @param buf Reference to the pointer of the previously allocated buffer;
* address alignment will not be applied.
* @param len The current length of the `buf0`.
* @param newlen A new required length.
* @tparam Tb Buffer element type.
* @tparam Tl Length variable type.
*/
template< typename Tb, typename Tl >
static void reallocBuf( Tb*& buf, Tl& len, const Tl newlen )
{
if( newlen > len )
{
if( buf != NULL )
{
delete[] buf;
buf = NULL;
len = 0;
}
buf = new Tb[ newlen ];
len = newlen;
}
}
class CResizeScanline;
/**
* Class implements fractional delay filter bank calculation.
*/
class CResizeFilters
{
friend class CResizeScanline;
public:
int KernelLen; ///< Resampling filter kernel's length, taps. Available
///< after the update() function call. Always an even value,
///< should not be lesser than 4.
CResizeFilters()
: Filters( NULL )
, FiltersLen( 0 )
, la( 0.0 )
{
memset( Bufs0, 0, sizeof( Bufs0 ));
memset( Bufs0Len, 0, sizeof( Bufs0Len ));
}
~CResizeFilters()
{
int i;
for( i = 0; i < BufCount; i++ )
{
delete[] Bufs0[ i ];
}
delete[] Filters;
}
/**
* Function updates the resizing filter bank.
*
* @param la0 Lanczos `a` parameter value (greater or equal to 2.0),
* can be fractional.
* @param k0 Resizing step.
* @param ElCount0 Image's element count, may be used for SIMD filter
* tap replication.
* @return `true` if an update occured and scanline resizing positions
* should be updated unconditionally.
*/
bool update( const double la0, const double k0, const int ElCount0 )
{
if( la0 == la && k0 == k && ElCount0 == ElCount )
{
return( false );
}
const double NormFreq = ( k0 <= 1.0 ? 1.0 : 1.0 / k0 );
Freq = 3.1415926535897932 * NormFreq;
FreqA = Freq / la0;
Len2 = la0 / NormFreq;
fl2 = (int) ceil( Len2 );
KernelLen = fl2 + fl2;
#if LANCIR_ALIGN > 4
ElRepl = ElCount0;
KernelLenA = KernelLen * ElRepl;
const int elalign =
(int) ( LANCIR_ALIGN / sizeof( float )) - 1;
KernelLenA = ( KernelLenA + elalign ) & ~elalign;
#else // LANCIR_ALIGN > 4
ElRepl = 1;
KernelLenA = KernelLen;
#endif // LANCIR_ALIGN > 4
FracCount = 1000; // Enough for Lanczos implicit 8-bit precision.
la = 0.0;
reallocBuf( Filters, FiltersLen, FracCount + 1 );
memset( Filters, 0, FiltersLen * sizeof( Filters[ 0 ]));
setBuf( 0 );
la = la0;
k = k0;
ElCount = ElCount0;
return( true );
}
/**
* Function returns filter at the specified fractional offset. This
* function can only be called after a prior update() function call.
*
* @param x Fractional offset, [0; 1].
*/
const float* getFilter( const double x )
{
const int Frac = (int) ( x * FracCount + 0.5 );
float* flt = Filters[ Frac ];
if( flt != NULL )
{
return( flt );
}
flt = Bufs[ CurBuf ] + CurBufFill * KernelLenA;
Filters[ Frac ] = flt;
CurBufFill++;
if( CurBufFill == BufLen )
{
setBuf( CurBuf + 1 );
}
makeFilterNorm( flt, 1.0 - (double) Frac / FracCount );
if( ElRepl > 1 )
{
replicateFilter( flt, KernelLen, ElRepl );
}
return( flt );
}
protected:
double Freq; ///< Circular frequency of the filter.
double FreqA; ///< Circular frequency of the window function.
double Len2; ///< Half resampling filter's length, unrounded.
int fl2; ///< Half resampling filter's length, integer.
int FracCount; ///< The number of fractional positions for which
///< filters can be created.
///<
int KernelLenA; ///< SIMD-aligned and replicated filter kernel's
///< length.
///<
int ElRepl; ///< The number of repetitions of each filter tap.
static const int BufCount = 4; ///< The maximal number of buffers that
///< can be in use.
///<
static const int BufLen = 256; ///< The number of fractional filters
///< a single buffer may contain. Both `BufLen` and `BufCount`
///< should correspond to the `FracCount` used.
float* Bufs0[ BufCount ]; ///< Buffers that hold all filters,
///< original.
///<
int Bufs0Len[ BufCount ]; ///< Allocated lengthes in `Bufs0`, in
///< `float` elements.
///<
float* Bufs[ BufCount ]; ///< Address-aligned `Bufs0`.
int CurBuf; ///< Filter buffer currently being filled.
int CurBufFill; ///< The number of fractional positions filled in the
///< current filter buffer.
///<
float** Filters; ///< Fractional delay filters for all positions.
///< A particular pointer equals NULL if a filter for such
///< position has not been created yet.
int FiltersLen; ///< Allocated length of Filters, in elements.
double la; ///< Current `la`.
double k; ///< Current `k`.
int ElCount; ///< Current `ElCount`.
/**
* Function changes the buffer currently being filled, check its
* size and reallocates it if necessary, then resets its fill counter.
*
* @param bi New current buffer index.
*/
void setBuf( const int bi )
{
reallocBuf( Bufs0[ bi ], Bufs[ bi ], Bufs0Len[ bi ],
BufLen * KernelLenA );
CurBuf = bi;
CurBufFill = 0;
}
/**
* @brief Sine-wave signal generator class.
*
* Class implements sine-wave signal generator without biasing, with
* constructor-based initialization only. This generator uses an
* oscillator instead of the `sin` function.
*/
class CSineGen
{
public:
/**
* Constructor initializes `this` sine-wave signal generator.
*
* @param si Sine function increment, in radians.
* @param ph Starting phase, in radians. Add `0.5 x PI` for a
* cosine function.
*/
CSineGen( const double si, const double ph )
: svalue1( sin( ph ))
, svalue2( sin( ph - si ))
, sincr( 2.0 * cos( si ))
{
}
/**
* @return The next value of the sine-wave, without biasing.
*/
double generate()
{
const double res = svalue1;
svalue1 = sincr * res - svalue2;
svalue2 = res;
return( res );
}
private:
double svalue1; ///< Current sine value.
double svalue2; ///< Previous sine value.
double sincr; ///< Sine value increment.
};
/**
* Function creates a filter for the specified fractional delay. The
* update() function should be called prior to calling this function.
* The created filter is normalized (DC gain=1).
*
* @param[out] op Output filter buffer.
* @param FracDelay Fractional delay, 0 to 1, inclusive.
*/
void makeFilterNorm( float* op, const double FracDelay ) const
{
CSineGen f( Freq, Freq * ( FracDelay - fl2 ));
CSineGen fw( FreqA, FreqA * ( FracDelay - fl2 ));
float* op0 = op;
double s = 0.0;
double ut;
int t = -fl2;
if( t + FracDelay < -Len2 )
{
f.generate();
fw.generate();
*op = (float) 0;
op++;
t++;
}
int IsZeroX = ( fabs( FracDelay - 1.0 ) < 2.3e-13 );
int mt = 0 - IsZeroX;
IsZeroX |= ( fabs( FracDelay ) < 2.3e-13 );
while( t < mt )
{
ut = t + FracDelay;
*op = (float) ( f.generate() * fw.generate() / ( ut * ut ));
s += *op;
op++;
t++;
}
if( IsZeroX ) // t+FracDelay==0
{
*op = (float) ( Freq * FreqA );
s += *op;
f.generate();
fw.generate();
}
else
{
ut = FracDelay; // t==0
*op = (float) ( f.generate() * fw.generate() / ( ut * ut ));
s += *op;
}
mt = fl2 - 2;
while( t < mt )
{
op++;
t++;
ut = t + FracDelay;
*op = (float) ( f.generate() * fw.generate() / ( ut * ut ));
s += *op;
}
op++;
ut = t + 1 + FracDelay;
if( ut > Len2 )
{
*op = (float) 0;
}
else
{
*op = (float) ( f.generate() * fw.generate() / ( ut * ut ));
s += *op;
}
s = 1.0 / s;
t = (int) ( op - op0 + 1 );
while( t != 0 )
{
*op0 = (float) ( *op0 * s );
op0++;
t--;
}
}
/**
* Function replicates taps of the specified filter so that it can
* be used with SIMD loading instructions. This function works
* "in-place".
*
* @param[in,out] p Filter buffer pointer, should be sized to contain
* `kl * erp` elements.
* @param kl Filter kernel's length, in taps.
* @param erp The number of repetitions to apply.
*/
static void replicateFilter( float* const p, const int kl,
const int erp )
{
const float* ip = p + kl - 1;
float* op = p + ( kl - 1 ) * erp;
int c = kl;