forked from avaneev/r8brain-free-src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
r8bbase.h
1240 lines (1046 loc) · 30.2 KB
/
r8bbase.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
/**
* @file r8bbase.h
*
* @brief The "base" inclusion file with basic classes and functions.
*
* This is the "base" inclusion file for the "r8brain-free-src" sample rate
* converter. This inclusion file contains implementations of several small
* utility classes and functions used by the library.
*
* r8brain-free-src Copyright (c) 2013-2019 Aleksey Vaneev
* See the "License.txt" file for license.
*
* @mainpage
*
* @section intro_sec Introduction
*
* Open source (under the MIT license) high-quality professional audio sample
* rate converter (SRC) (resampling) library. Features routines for SRC, both
* up- and downsampling, to/from any sample rate, including non-integer sample
* rates: it can be also used for conversion to/from SACD sample rate and even
* go beyond that. SRC routines were implemented in multi-platform C++ code,
* and have a high level of optimality.
*
* For more information, please visit
* https://github.com/avaneev/r8brain-free-src
*
* @section license License
*
* The MIT License (MIT)
*
* r8brain-free-src Copyright (c) 2013-2019 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.
*
* Please credit the creator of this library in your documentation in the
* following way: "Sample rate converter designed by Aleksey Vaneev of
* Voxengo"
*
* @version 4.6
*/
#ifndef R8BBASE_INCLUDED
#define R8BBASE_INCLUDED
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#include "r8bconf.h"
#if defined( R8B_WIN )
#include <windows.h>
#else // R8B_WIN
#include <pthread.h>
#endif // R8B_WIN
/**
* @brief The "r8brain-free-src" library namespace.
*
* The "r8brain-free-src" sample rate converter library namespace.
*/
namespace r8b {
/**
* Macro defines r8brain-free-src version string.
*/
#define R8B_VERSION "4.6"
#if !defined( M_PI )
/**
* The macro equals to "pi" constant, fits 53-bit floating point mantissa.
*/
#define M_PI 3.14159265358979324
#endif // M_PI
#if !defined( M_2PI )
/**
* The M_2PI macro equals to "2 * pi" constant, fits 53-bit floating point
* mantissa.
*/
#define M_2PI 6.28318530717958648
#endif // M_2PI
#if !defined( M_3PI )
/**
* The M_3PI macro equals to "3 * pi" constant, fits 53-bit floating point
* mantissa.
*/
#define M_3PI 9.42477796076937972
#endif // M_3PI
#if !defined( M_4PI )
/**
* The M_4PI macro equals to "4 * pi" constant, fits 53-bit floating point
* mantissa.
*/
#define M_4PI 12.56637061435917295
#endif // M_4PI
#if !defined( M_PId2 )
/**
* The macro equals to "pi divided by 2" constant, fits 53-bit floating
* point mantissa.
*/
#define M_PId2 1.57079632679489662
#endif // M_PId2
/**
* A special macro that defines empty copy-constructor and copy operator with
* the "private:" prefix. This macro should be used in classes that cannot be
* copied in a standard C++ way.
*
* This macro does not need to be defined in classes derived from a class
* where such macro was already used.
*
* @param ClassName The name of the class which uses this macro.
*/
#define R8BNOCTOR( ClassName ) \
private: \
ClassName( const ClassName& ) { } \
ClassName& operator = ( const ClassName& ) { return( *this ); }
/**
* @brief The default base class for objects created on heap.
*
* Class that implements "new" and "delete" operators that use standard
* malloc() and free() functions.
*/
class CStdClassAllocator
{
public:
/**
* @param n The size of the object, in bytes.
* @param p Pointer to object's pre-allocated memory block.
* @return Pointer to object.
*/
void* operator new( size_t, void* p )
{
return( p );
}
/**
* @param n The size of the object, in bytes.
* @return Pointer to the allocated memory block for the object.
*/
void* operator new( size_t n )
{
return( :: malloc( n ));
}
/**
* @param n The size of the object, in bytes.
* @return Pointer to the allocated memory block for the object.
*/
void* operator new[]( size_t n )
{
return( :: malloc( n ));
}
/**
* Operator frees a previously allocated memory block for the object.
*
* @param p Pointer to the allocated memory block for the object.
*/
void operator delete( void* p )
{
:: free( p );
}
/**
* Operator frees a previously allocated memory block for the object.
*
* @param p Pointer to the allocated memory block for the object.
*/
void operator delete[]( void* p )
{
:: free( p );
}
};
/**
* @brief The default base class for objects that allocate blocks of memory.
*
* Memory buffer allocator that uses "stdlib" standard memory functions.
*/
class CStdMemAllocator : public CStdClassAllocator
{
public:
/**
* Function allocates memory block.
*
* @param Size The size of the block, in bytes.
* @result The pointer to the allocated block.
*/
static void* allocmem( const size_t Size )
{
return( :: malloc( Size ));
}
/**
* Function reallocates a previously allocated memory block.
*
* @param p Pointer to the allocated block, can be NULL.
* @param Size The new size of the block, in bytes.
* @result The pointer to the (re)allocated block.
*/
static void* reallocmem( void* p, const size_t Size )
{
return( :: realloc( p, Size ));
}
/**
* Function frees a previously allocated memory block.
*
* @param p Pointer to the allocated block, can be NULL.
*/
static void freemem( void* p )
{
:: free( p );
}
};
/**
* @brief Templated memory buffer class for element buffers of fixed capacity.
*
* Fixed memory buffer object. Supports allocation of a fixed amount of
* memory. Does not store buffer's capacity - the user should know the actual
* capacity of the buffer. Does not feature "internal" storage, memory is
* always allocated via the R8B_MEMALLOCCLASS class's functions. Thus the
* object of this class can be moved in memory.
*
* This class manages memory space only - it does not perform element class
* construction nor destruction operations.
*
* This class applies 256-bit memory address alignment to the allocated data
* block.
*
* @param T The class of the stored elements (e.g. "double").
*/
template< class T >
class CFixedBuffer : public R8B_MEMALLOCCLASS
{
R8BNOCTOR( CFixedBuffer );
public:
CFixedBuffer()
: Data0( NULL )
, Data( NULL )
{
}
/**
* Constructor allocates memory so that the specified number of elements
* of type T can be stored in *this buffer object.
*
* @param Capacity Storage for this number of elements to allocate.
*/
CFixedBuffer( const int Capacity )
{
R8BASSERT( Capacity > 0 || Capacity == 0 );
Data0 = allocmem( Capacity * sizeof( T ) + Alignment );
Data = (T*) alignptr( Data0, Alignment );
R8BASSERT( Data0 != NULL || Capacity == 0 );
}
~CFixedBuffer()
{
freemem( Data0 );
}
/**
* Function allocates memory so that the specified number of elements of
* type T can be stored in *this buffer object.
*
* @param Capacity Storage for this number of elements to allocate.
*/
void alloc( const int Capacity )
{
R8BASSERT( Capacity > 0 || Capacity == 0 );
freemem( Data0 );
Data0 = allocmem( Capacity * sizeof( T ) + Alignment );
Data = (T*) alignptr( Data0, Alignment );
R8BASSERT( Data0 != NULL || Capacity == 0 );
}
/**
* Function reallocates memory so that the specified number of elements of
* type T can be stored in *this buffer object. Previously allocated data
* is copied to the new memory buffer.
*
* @param PrevCapacity Previous capacity of *this buffer.
* @param NewCapacity Storage for this number of elements to allocate.
*/
void realloc( const int PrevCapacity, const int NewCapacity )
{
R8BASSERT( PrevCapacity >= 0 );
R8BASSERT( NewCapacity >= 0 );
void* const NewData0 = allocmem( NewCapacity * sizeof( T ) +
Alignment );
T* const NewData = (T*) alignptr( NewData0, Alignment );
const size_t CopySize = ( PrevCapacity > NewCapacity ?
NewCapacity : PrevCapacity ) * sizeof( T );
if( CopySize > 0 )
{
memcpy( NewData, Data, CopySize );
}
freemem( Data0 );
Data0 = NewData0;
Data = NewData;
R8BASSERT( Data0 != NULL || NewCapacity == 0 );
}
/**
* Function deallocates a previously allocated buffer.
*/
void free()
{
freemem( Data0 );
Data0 = NULL;
Data = NULL;
}
/**
* @return Pointer to the first element of the allocated buffer, NULL if
* not allocated.
*/
T* getPtr() const
{
return( Data );
}
/**
* @return Pointer to the first element of the allocated buffer, NULL if
* not allocated.
*/
operator T* () const
{
return( Data );
}
private:
static const size_t Alignment = 32; ///< Data buffer alignment, in bytes.
///<
void* Data0; ///< Buffer pointer, original unaligned.
///<
T* Data; ///< Element buffer pointer, aligned.
///<
/**
* This macro forces provided pointer ptr to be aligned to align bytes.
* Works with power-of-2 alignments only. If no alignment is necessary,
* "align" bytes will be added to the pointer value.
*
* @tparam Tp Pointer type.
*/
template< class Tp >
inline Tp alignptr( const Tp ptr, const uintptr_t align )
{
return( (Tp) ( (uintptr_t) ptr + align -
( (uintptr_t) ptr & ( align - 1 ))) );
}
};
/**
* @brief Pointer-to-object "keeper" class with automatic deletion.
*
* An auxiliary class that can be used for keeping a pointer to object that
* should be deleted together with the "keeper" by calling object's "delete"
* operator.
*
* @param T Pointer type to operate with, must include the asterisk (e.g.
* "CDSPFIRFilter*").
*/
template< class T >
class CPtrKeeper
{
R8BNOCTOR( CPtrKeeper );
public:
CPtrKeeper()
: Object( NULL )
{
}
/**
* Constructor assigns a pointer to object to *this keeper.
*
* @param aObject Pointer to object to keep, can be NULL.
*/
template< class T2 >
CPtrKeeper( T2 const aObject )
: Object( aObject )
{
}
~CPtrKeeper()
{
delete Object;
}
/**
* Function assigns a pointer to object to *this keeper. A previously
* keeped pointer will be reset and object deleted.
*
* @param aObject Pointer to object to keep, can be NULL.
*/
template< class T2 >
void operator = ( T2 const aObject )
{
reset();
Object = aObject;
}
/**
* @return Pointer to keeped object, NULL if no object is being kept.
*/
T operator -> () const
{
return( Object );
}
/**
* @return Pointer to keeped object, NULL if no object is being kept.
*/
operator T () const
{
return( Object );
}
/**
* Function resets the keeped pointer and deletes the keeped object.
*/
void reset()
{
T DelObj = Object;
Object = NULL;
delete DelObj;
}
/**
* @return Function returns the keeped pointer and resets it in *this
* keeper without object deletion.
*/
T unkeep()
{
T ResObject = Object;
Object = NULL;
return( ResObject );
}
private:
T Object; ///< Pointer to keeped object.
///<
};
/**
* @brief Multi-threaded synchronization object class.
*
* This class uses standard OS thread-locking (mutex) mechanism which is
* fairly efficient in most cases.
*
* The acquire() function can be called recursively, in the same thread, for
* this kind of thread-locking mechanism. This will not produce a dead-lock.
*/
class CSyncObject
{
R8BNOCTOR( CSyncObject );
public:
CSyncObject()
{
#if defined( R8B_WIN )
InitializeCriticalSectionAndSpinCount( &CritSec, 4000 );
#else // R8B_WIN
pthread_mutexattr_t MutexAttrs;
pthread_mutexattr_init( &MutexAttrs );
pthread_mutexattr_settype( &MutexAttrs, PTHREAD_MUTEX_RECURSIVE );
pthread_mutex_init( &Mutex, &MutexAttrs );
pthread_mutexattr_destroy( &MutexAttrs );
#endif // R8B_WIN
}
~CSyncObject()
{
#if defined( R8B_WIN )
DeleteCriticalSection( &CritSec );
#else // R8B_WIN
pthread_mutex_destroy( &Mutex );
#endif // R8B_WIN
}
/**
* Function "acquires" *this thread synchronizer object immediately or
* waits until another thread releases it.
*/
void acquire()
{
#if defined( R8B_WIN )
EnterCriticalSection( &CritSec );
#else // R8B_WIN
pthread_mutex_lock( &Mutex );
#endif // R8B_WIN
}
/**
* Function "releases" *this previously acquired thread synchronizer
* object.
*/
void release()
{
#if defined( R8B_WIN )
LeaveCriticalSection( &CritSec );
#else // R8B_WIN
pthread_mutex_unlock( &Mutex );
#endif // R8B_WIN
}
private:
#if defined( R8B_WIN )
CRITICAL_SECTION CritSec; ///< Standard Windows critical section
///< structure.
///<
#else // R8B_WIN
pthread_mutex_t Mutex; ///< pthread.h mutex object.
///<
#endif // R8B_WIN
};
/**
* @brief A "keeper" class for CSyncObject-based synchronization.
*
* Sync keeper class. The object of this class can be used as auto-init and
* auto-deinit object for calling the acquire() and release() functions of an
* object of the CSyncObject class. This "keeper" object is best used in
* functions as an "automatic" object allocated on the stack, possibly via the
* R8BSYNC() macro.
*/
class CSyncKeeper
{
R8BNOCTOR( CSyncKeeper );
public:
CSyncKeeper()
: SyncObj( NULL )
{
}
/**
* @param aSyncObj Pointer to the sync object which should be used for
* sync'ing, can be NULL.
*/
CSyncKeeper( CSyncObject* const aSyncObj )
: SyncObj( aSyncObj )
{
if( SyncObj != NULL )
{
SyncObj -> acquire();
}
}
/**
* @param aSyncObj Reference to the sync object which should be used for
* sync'ing.
*/
CSyncKeeper( CSyncObject& aSyncObj )
: SyncObj( &aSyncObj )
{
SyncObj -> acquire();
}
~CSyncKeeper()
{
if( SyncObj != NULL )
{
SyncObj -> release();
}
}
protected:
CSyncObject* SyncObj; ///< Sync object in use (can be NULL).
///<
};
/**
* The synchronization macro. The R8BSYNC( obj ) macro, which creates and
* object of the r8b::CSyncKeeper class on stack, should be put before
* sections of the code that may potentially change data asynchronously with
* other threads at the same time. The R8BSYNC( obj ) macro "acquires" the
* synchronization object thus blocking execution of other threads that also
* use the same R8BSYNC( obj ) macro. The blocked section begins with the
* R8BSYNC( obj ) macro and finishes at the end of the current C++ code block.
* Multiple R8BSYNC() macros may be defined from within the same code block.
*
* @param SyncObject An object of the CSyncObject type that is used for
* synchronization.
*/
#define R8BSYNC( SyncObject ) R8BSYNC_( SyncObject, __LINE__ )
#define R8BSYNC_( SyncObject, id ) R8BSYNC__( SyncObject, id )
#define R8BSYNC__( SyncObject, id ) CSyncKeeper SyncKeeper##id( SyncObject )
/**
* @brief Sine signal generator class.
*
* Class implements sine signal generator without biasing.
*/
class CSineGen
{
public:
CSineGen()
{
}
/**
* Constructor initializes *this sine signal generator.
*
* @param si Sine function increment, in radians.
* @param ph Starting phase, in radians. Add 0.5 * M_PI for cosine
* function.
*/
CSineGen( const double si, const double ph )
: svalue1( sin( ph ))
, svalue2( sin( ph - si ))
, sincr( 2.0 * cos( si ))
{
}
/**
* Constructor initializes *this sine signal generator.
*
* @param si Sine function increment, in radians.
* @param ph Starting phase, in radians. Add 0.5 * M_PI for cosine
* function.
* @param g The overall gain factor, 1.0 for unity gain (-1.0 to 1.0
* amplitude).
*/
CSineGen( const double si, const double ph, const double g )
: svalue1( sin( ph ) * g )
, svalue2( sin( ph - si ) * g )
, sincr( 2.0 * cos( si ))
{
}
/**
* Function initializes *this sine signal generator.
*
* @param si Sine function increment, in radians.
* @param ph Starting phase, in radians. Add 0.5 * M_PI for cosine
* function.
*/
void init( const double si, const double ph )
{
svalue1 = sin( ph );
svalue2 = sin( ph - si );
sincr = 2.0 * cos( si );
}
/**
* Function initializes *this sine signal generator.
*
* @param si Sine function increment, in radians.
* @param ph Starting phase, in radians. Add 0.5 * M_PI for cosine
* function.
* @param g The overall gain factor, 1.0 for unity gain (-1.0 to 1.0
* amplitude).
*/
void init( const double si, const double ph, const double g )
{
svalue1 = sin( ph ) * g;
svalue2 = sin( ph - si ) * g;
sincr = 2.0 * cos( si );
}
/**
* @return Next value of the sine function, 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.
///<
};
/**
* @param v Input value.
* @return Calculated bit occupancy of the specified input value. Bit
* occupancy means how many significant lower bits are necessary to store a
* specified value. Function treats the input value as unsigned.
*/
inline int getBitOccupancy( const int v )
{
static const char OccupancyTable[] =
{
1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8
};
const int tt = v >> 16;
if( tt != 0 )
{
const int t = v >> 24;
return( t != 0 ? 24 + OccupancyTable[ t & 0xFF ] :
16 + OccupancyTable[ tt ]);
}
else
{
const int t = v >> 8;
return( t != 0 ? 8 + OccupancyTable[ t ] : OccupancyTable[ v ]);
}
}
/**
* Function calculates frequency response of the specified FIR filter at the
* specified circular frequency. Phase can be calculated as atan2( im, re ).
*
* @param flt FIR filter's coefficients.
* @param fltlen Number of coefficients (taps) in the filter.
* @param th Circular frequency [0; pi].
* @param[out] re0 Resulting real part of the complex frequency response.
* @param[out] im0 Resulting imaginary part of the complex frequency response.
* @param fltlat Filter's latency in samples.
*/
inline void calcFIRFilterResponse( const double* flt, int fltlen,
const double th, double& re0, double& im0, const int fltlat = 0 )
{
const double sincr = 2.0 * cos( th );
double cvalue1;
double svalue1;
if( fltlat == 0 )
{
cvalue1 = 1.0;
svalue1 = 0.0;
}
else
{
cvalue1 = cos( -fltlat * th );
svalue1 = sin( -fltlat * th );
}
double cvalue2 = cos( -( fltlat + 1 ) * th );
double svalue2 = sin( -( fltlat + 1 ) * th );
double re = 0.0;
double im = 0.0;
while( fltlen > 0 )
{
re += cvalue1 * flt[ 0 ];
im += svalue1 * flt[ 0 ];
flt++;
fltlen--;
double tmp = cvalue1;
cvalue1 = sincr * cvalue1 - cvalue2;
cvalue2 = tmp;
tmp = svalue1;
svalue1 = sincr * svalue1 - svalue2;
svalue2 = tmp;
}
re0 = re;
im0 = im;
}
/**
* Function calculates frequency response and group delay of the specified FIR
* filter at the specified circular frequency. The group delay is calculated
* by evaluating the filter's response at close side-band frequencies of "th".
*
* @param flt FIR filter's coefficients.
* @param fltlen Number of coefficients (taps) in the filter.
* @param th Circular frequency [0; pi].
* @param[out] re Resulting real part of the complex frequency response.
* @param[out] im Resulting imaginary part of the complex frequency response.
* @param[out] gd Resulting group delay at the specified frequency, in
* samples.
*/
inline void calcFIRFilterResponseAndGroupDelay( const double* const flt,
const int fltlen, const double th, double& re, double& im, double& gd )
{
// Calculate response at "th".
calcFIRFilterResponse( flt, fltlen, th, re, im );
// Calculate response at close sideband frequencies.
const int Count = 2;
const double thd2 = 1e-9;
double ths[ Count ] = { th - thd2, th + thd2 };
if( ths[ 0 ] < 0.0 )
{
ths[ 0 ] = 0.0;
}
if( ths[ 1 ] > M_PI )
{
ths[ 1 ] = M_PI;
}
double ph1[ Count ];
int i;
for( i = 0; i < Count; i++ )
{
double re1;
double im1;
calcFIRFilterResponse( flt, fltlen, ths[ i ], re1, im1 );
ph1[ i ] = atan2( im1, re1 );
}
if( fabs( ph1[ 1 ] - ph1[ 0 ]) > M_PI )
{
if( ph1[ 1 ] > ph1[ 0 ])
{
ph1[ 1 ] -= M_2PI;
}
else
{
ph1[ 1 ] += M_2PI;
}
}
const double thd = ths[ 1 ] - ths[ 0 ];
gd = ( ph1[ 1 ] - ph1[ 0 ]) / thd;
}
/**
* Function normalizes FIR filter so that its frequency response at DC is
* equal to DCGain.
*
* @param[in,out] p Filter coefficients.
* @param l Filter length.
* @param DCGain Filter's gain at DC (linear, non-decibel value).
* @param pstep "p" array step.
*/
inline void normalizeFIRFilter( double* const p, const int l,
const double DCGain, const int pstep = 1 )
{
R8BASSERT( l > 0 );
R8BASSERT( pstep != 0 );
double s = 0.0;
double* pp = p;
int i = l;
while( i > 0 )
{
s += *pp;
pp += pstep;
i--;
}
s = DCGain / s;
pp = p;
i = l;
while( i > 0 )
{
*pp *= s;
pp += pstep;
i--;
}
}
/**
* Function calculates coefficients used to calculate 3rd order spline
* (polynomial) on the equidistant lattice, using 8 points.
*
* @param[out] c Output coefficients buffer, length = 4.
* @param xm3 Point at x-3 position.
* @param xm2 Point at x-2 position.
* @param xm1 Point at x-1 position.
* @param x0 Point at x position.
* @param x1 Point at x+1 position.
* @param x2 Point at x+2 position.
* @param x3 Point at x+3 position.
* @param x4 Point at x+4 position.
*/
inline void calcSpline3p8Coeffs( double* c, const double xm3,
const double xm2, const double xm1, const double x0, const double x1,
const double x2, const double x3, const double x4 )
{
c[ 0 ] = x0;
c[ 1 ] = ( 61.0 * ( x1 - xm1 ) + 16.0 * ( xm2 - x2 ) +
3.0 * ( x3 - xm3 )) / 76.0;
c[ 2 ] = ( 106.0 * ( xm1 + x1 ) + 10.0 * x3 + 6.0 * xm3 - 3.0 * x4 -
29.0 * ( xm2 + x2 ) - 167.0 * x0 ) / 76.0;
c[ 3 ] = ( 91.0 * ( x0 - x1 ) + 45.0 * ( x2 - xm1 ) +
13.0 * ( xm2 - x3 ) + 3.0 * ( x4 - xm3 )) / 76.0;
}