r8brain-free-src
High-quality pro audio sample rate converter library
 
Loading...
Searching...
No Matches
CDSPFIRFilter.h
Go to the documentation of this file.
1//$ nobt
2//$ nocpp
3
15
16#ifndef R8B_CDSPFIRFILTER_INCLUDED
17#define R8B_CDSPFIRFILTER_INCLUDED
18
19#include "CDSPSincFilterGen.h"
20#include "CDSPRealFFT.h"
21
22namespace r8b {
23
27
48
57
58class CDSPFIRFilter : public R8B_BASECLASS,
59 private CSinglyLinkedListItem< CDSPFIRFilter >
60{
61 R8BNOCTOR( CDSPFIRFilter )
62
63 friend class CSinglyLinkedListItem< CDSPFIRFilter >;
64 friend class CDSPFIRFilterCache;
65
66public:
71
72 static double getLPMinTransBand()
73 {
74 return( 0.5 );
75 }
76
81
82 static double getLPMaxTransBand()
83 {
84 return( 45.0 );
85 }
86
91
92 static double getLPMinAtten()
93 {
94 return( 49.0 );
95 }
96
101
102 static double getLPMaxAtten()
103 {
104 return( 218.0 );
105 }
106
111
112 bool isZeroPhase() const
113 {
114 return( IsZeroPhase );
115 }
116
120
121 int getLatency() const
122 {
123 return( Latency );
124 }
125
130
131 double getLatencyFrac() const
132 {
133 return( LatencyFrac );
134 }
135
140
141 int getKernelLen() const
142 {
143 return( KernelLen );
144 }
145
152
153 int getBlockLenBits() const
154 {
155 return( BlockLenBits );
156 }
157
170
172 {
173 return( KernelBlockFFT );
174 }
175
187
189 const realfft_t im ) const
190 {
191 return( dsnRe * re - dsnIm * im );
192 }
193
200
201 void unref();
202
203private:
204 double ReqNormFreq;
205 double ReqTransBand;
207 double ReqAtten;
209 EDSPFilterPhaseResponse ReqPhase;
210 double ReqGain;
211 int ReqDownShift;
212 int RefCount;
213 bool IsZeroPhase;
215 int Latency;
216 double LatencyFrac;
217 int KernelLen;
218 int BlockLenBits;
221 CFixedBuffer< double > KernelBlock;
225 realfft_t* KernelBlockFFT;
227 realfft_t dsnRe;
228 realfft_t dsnIm;
229
231 : RefCount( 1 )
232 {
233 }
234
243
244 static double hpoly( const double* const c, const int n, const double x )
245 {
246 double r = c[ n - 1 ];
247 int i;
248
249 for( i = n - 2; i >= 0; i-- )
250 {
251 r = r * x + c[ i ];
252 }
253
254 return( r );
255 }
256
315
316 static void calcDesignParams( const double T, const double ReqAtten,
317 double& pwr, double& hl, double& fo1 )
318 {
319 // b0(a): effective Kaiser beta vs attenuation, deg-9 in
320 // a = (A-133.5)/84.5
321 static const double LPF_CB[ 10 ] = {
322 14.409935832973984, 9.6626843693138884, -0.17435120318333536,
323 0.47264599329014079, 0.4940426137302133, -1.5662364718692721,
324 -0.71006021971136335, 2.0294051576357957, 0.22363464796569277,
325 -0.78254591651630068 };
326
327 // log(delta) = D0(u) + s^2*D2(u) + s^3*D3(u) + s^4*D4(u),
328 // s = (T/0.45)^2
329 static const double LPF_D0[ 7 ] = {
330 -1.0753246533566314, -0.75662395688736628, -0.0047894065672392377,
331 0.08577566962378394, -0.17001888073403126, -0.013628259555023822,
332 0.093950306915379783 };
333 static const double LPF_D2[ 3 ] = {
334 1.1482209047708865, -0.052152189285352819, -0.020187508756994623 };
335 static const double LPF_D3[ 3 ] = {
336 -1.4201039645189557, 0.1242900889796041, -0.028854770456694875 };
337 static const double LPF_D4[ 3 ] = {
338 0.55500996383110457, -0.062635292370927881, 0.023661985245151548 };
339
340 // log(Y) = Y0(u) + s^2*Y2(u) + s^3*Y3(u)
341 static const double LPF_Y0[ 5 ] = {
342 0.8399122624879678, 0.39839640583388353, 0.015028625919905413,
343 -0.005569192458538463, 0.001494097359614131 };
344 static const double LPF_Y2[ 3 ] = {
345 0.00069542490312080887, -0.00062890127106954123,
346 -0.00071460219184551251 };
347 static const double LPF_Y3[ 2 ] = {
348 -0.00065713366734133005, 0.0011106064299533634 };
349
350 const double a = ( ReqAtten - 133.5 ) / 84.5;
351 const double b = hpoly( LPF_CB, 10, a ) +
352 0.0523 + 4.07 * T * T;
353
354 const double u = ( log( b ) - 2.3555 ) / 0.8585;
355
356 const double s = ( T / 0.45 ) * ( T / 0.45 );
357 const double s2 = s * s;
358 const double s3 = s2 * s;
359 const double s4 = s2 * s2;
360
361 const double D = exp( hpoly( LPF_D0, 7, u ) +
362 s2 * hpoly( LPF_D2, 3, u ) +
363 s3 * hpoly( LPF_D3, 3, u ) +
364 s4 * hpoly( LPF_D4, 3, u ));
365
366 const double Y = exp( hpoly( LPF_Y0, 5, u ) +
367 s2 * hpoly( LPF_Y2, 3, u ) +
368 s3 * hpoly( LPF_Y3, 2, u ));
369
370 const double X = ( 4.0 / R8B_PI ) *
371 ( sqrt( b * b + R8B_PI * R8B_PI ) - D );
372
373 hl = ( X + Y ) / T;
374 fo1 = X * T / ( X + Y );
375 pwr = b / 125.0;
376 }
377
381
382 void buildLPFilter()
383 {
384 double pwr, fo1, hl;
385
386 calcDesignParams( ReqTransBand * 0.01, ReqAtten, pwr, hl, fo1 );
387
388 double WinParams[ 2 ];
389 WinParams[ 0 ] = 125.0;
390 WinParams[ 1 ] = pwr;
391
392 CDSPSincFilterGen sinc;
393 sinc.Len2 = 0.25 * hl / ReqNormFreq;
394 sinc.Freq1 = 0.0;
395 sinc.Freq2 = R8B_PI * ( 1.0 - fo1 ) * ReqNormFreq;
396 sinc.initBand( CDSPSincFilterGen :: wftKaiser, WinParams, true );
397
398 KernelLen = sinc.KernelLen;
399 BlockLenBits = getBitOccupancy( KernelLen - 1 ) + R8B_EXTFFT;
400 const int BlockLen = 1 << BlockLenBits;
401
402 KernelBlock.alloc( BlockLen * 2 );
403 sinc.generateBand( &KernelBlock[ 0 ],
404 &CDSPSincFilterGen :: calcWindowKaiser );
405
406 if( ReqPhase == fprLinearPhase )
407 {
408 IsZeroPhase = true;
409 Latency = sinc.fl2;
410 LatencyFrac = 0.0;
411 }
412 else
413 {
414 IsZeroPhase = false;
415 double DCGroupDelay;
416
417 calcMinPhaseTransform( &KernelBlock[ 0 ], KernelLen, 16, false,
418 &DCGroupDelay );
419
420 Latency = (int) DCGroupDelay;
421 LatencyFrac = DCGroupDelay - Latency;
422 }
423
424 CDSPRealFFTKeeper ffto( BlockLenBits + 1 );
425
426 dsnRe = 0;
427 dsnIm = 0;
428
429 if( IsZeroPhase )
430 {
431 // Calculate DC gain.
432
433 double s = 0.0;
434 int i;
435
436 for( i = 0; i < KernelLen; i++ )
437 {
438 s += KernelBlock[ i ];
439 }
440
441 s = ffto -> getInvMulConst() * ReqGain / s;
442
443 // Time-shift the filter so that zero-phase response is produced.
444 // Simultaneously multiply by "s".
445
446 for( i = 0; i <= sinc.fl2; i++ )
447 {
448 KernelBlock[ i ] = KernelBlock[ sinc.fl2 + i ] * s;
449 }
450
451 for( i = 1; i <= sinc.fl2; i++ )
452 {
453 KernelBlock[ BlockLen * 2 - i ] = KernelBlock[ i ];
454 }
455
456 memset( &KernelBlock[ sinc.fl2 + 1 ], 0,
457 (size_t) ( BlockLen * 2 - KernelLen ) *
458 sizeof( KernelBlock[ 0 ]));
459
460 KernelBlockFFT = ffto -> forward( KernelBlock );
461
462 if( ReqDownShift > 0 )
463 {
464 KernelBlockFFT = ffto -> reorderForward( KernelBlockFFT,
465 ffto -> getWorkBuf() );
466
467 const int z = ( 2 << BlockLenBits ) >> ReqDownShift;
468 dsnRe = KernelBlockFFT[ z ];
469 dsnIm = KernelBlockFFT[ z + 1 ];
470
471 CDSPRealFFTKeeper ffto2( BlockLenBits + 1 - ReqDownShift );
472 CFixedBuffer< double > NewBlock( ffto2 -> getLen() *
473 (int) sizeof( realfft_t ) / (int) sizeof( double ));
474
475 KernelBlockFFT = ffto2 -> reorderInverse( KernelBlockFFT,
476 NewBlock );
477
478 ffto2 -> convertToZP( KernelBlockFFT );
479
480 KernelBlock.moveFrom( NewBlock );
481 }
482 else
483 {
484 ffto -> convertToZP( KernelBlockFFT );
485 }
486 }
487 else
488 {
489 normalizeFIRFilter( &KernelBlock[ 0 ], KernelLen,
490 ffto -> getInvMulConst() * ReqGain );
491
492 memset( &KernelBlock[ KernelLen ], 0,
493 (size_t) ( BlockLen * 2 - KernelLen ) *
494 sizeof( KernelBlock[ 0 ]));
495
496 KernelBlockFFT = ffto -> forward( KernelBlock );
497
498 if( ReqDownShift > 0 )
499 {
500 KernelBlockFFT = ffto -> reorderForward( KernelBlockFFT,
501 ffto -> getWorkBuf() );
502
503 const int z = ( 2 << BlockLenBits ) >> ReqDownShift;
504 dsnRe = KernelBlockFFT[ z ];
505 dsnIm = KernelBlockFFT[ z + 1 ];
506
507 CDSPRealFFTKeeper ffto2( BlockLenBits + 1 - ReqDownShift );
508 CFixedBuffer< double > NewBlock( ffto2 -> getLen() *
509 (int) sizeof( realfft_t ) / (int) sizeof( double ));
510
511 KernelBlockFFT = ffto2 -> reorderInverse( KernelBlockFFT,
512 NewBlock );
513
514 KernelBlock.moveFrom( NewBlock );
515 }
516 }
517
518 R8BCONSOLE( "CDSPFIRFilter: flt_len=%i latency=%i nfreq=%.4f "
519 "tb=%.1f att=%.1f gain=%.3f dsh=%i\n", KernelLen, Latency,
520 ReqNormFreq, ReqTransBand, ReqAtten, ReqGain, ReqDownShift );
521 }
522};
523
530
532{
534
535 friend class CDSPFIRFilter;
536
537public:
542
543 static int getObjCount()
544 {
546
547 return( getObjCountStatic() );
548 }
549
582
583 static CDSPFIRFilter& getLPFilter( const double ReqNormFreq,
584 const double ReqTransBand, const double ReqAtten,
585 const EDSPFilterPhaseResponse ReqPhase, const double ReqGain,
586 const int ReqDownFactor )
587 {
588 R8BASSERT( ReqNormFreq > 0.0 && ReqNormFreq <= 1.0 );
589 R8BASSERT( ReqTransBand >= CDSPFIRFilter :: getLPMinTransBand() );
590 R8BASSERT( ReqTransBand <= CDSPFIRFilter :: getLPMaxTransBand() );
591 R8BASSERT( ReqAtten >= CDSPFIRFilter :: getLPMinAtten() );
592 R8BASSERT( ReqAtten <= CDSPFIRFilter :: getLPMaxAtten() );
593 R8BASSERT( ReqGain > 0.0 );
594 R8BASSERT( ReqDownFactor > 0 );
595
596 R8B_EXITDTOR static CPtrKeeper< CDSPFIRFilter > Objects; // The chain
597 // of cached objects.
598
599 int ReqDownShift = getBitOccupancy( ReqDownFactor ) - 1;
600
601 if(( 1 << ReqDownShift ) != ReqDownFactor )
602 {
603 ReqDownShift = 0;
604 }
605
607
608 int& ObjCount = getObjCountStatic();
609 CDSPFIRFilter* PrevObj = R8B_NULL;
610 CDSPFIRFilter* CurObj = Objects;
611
612 while( CurObj != R8B_NULL )
613 {
614 if( CurObj -> ReqNormFreq == ReqNormFreq &&
615 CurObj -> ReqTransBand == ReqTransBand &&
616 CurObj -> ReqGain == ReqGain &&
617 CurObj -> ReqDownShift == ReqDownShift &&
618 CurObj -> ReqAtten == ReqAtten &&
619 CurObj -> ReqPhase == ReqPhase )
620 {
621 break;
622 }
623
624 if( CurObj -> Next == R8B_NULL &&
625 ObjCount >= R8B_FILTER_CACHE_MAX )
626 {
627 if( CurObj -> RefCount == 0 )
628 {
629 // Delete the last filter which is not used.
630
631 PrevObj -> Next = R8B_NULL;
632 delete CurObj;
633 ObjCount--;
634 }
635 else
636 {
637 // Move the last filter to the top of the list since it
638 // seems to be in use for a long time.
639
640 PrevObj -> Next = R8B_NULL;
641 CurObj -> Next = Objects.unkeep();
642 Objects = CurObj;
643 }
644
645 CurObj = R8B_NULL;
646 break;
647 }
648
649 PrevObj = CurObj;
650 CurObj = CurObj -> Next;
651 }
652
653 if( CurObj != R8B_NULL )
654 {
655 CurObj -> RefCount++;
656
657 if( PrevObj == R8B_NULL )
658 {
659 return( *CurObj );
660 }
661
662 // Remove the filter from the list temporarily.
663
664 PrevObj -> Next = CurObj -> Next;
665 }
666 else
667 {
668 // Create a new filter object (with RefCount == 1) and build the
669 // filter kernel.
670
671 CPtrKeeper< CDSPFIRFilter > f( new CDSPFIRFilter() );
672
673 f -> ReqNormFreq = ReqNormFreq;
674 f -> ReqTransBand = ReqTransBand;
675 f -> ReqAtten = ReqAtten;
676 f -> ReqPhase = ReqPhase;
677 f -> ReqGain = ReqGain;
678 f -> ReqDownShift = ReqDownShift;
679
680 f -> buildLPFilter();
681
682 CurObj = f.unkeep();
683 ObjCount++;
684 }
685
686 // Insert the filter at the start of the list.
687
688 CurObj -> Next = Objects.unkeep();
689 Objects = CurObj;
690
691 return( *CurObj );
692 }
693
694protected:
698
700 {
701 R8B_EXITDTOR static CSyncObject StateSync;
702
703 return( StateSync );
704 }
705
709
710 static int& getObjCountStatic()
711 {
712 R8B_EXITDTOR static int ObjCount = 0; // The number of objects
713 // currently preset in the cache.
714
715 return( ObjCount );
716 }
717};
718
719// ---------------------------------------------------------------------------
720// CDSPFIRFilter PUBLIC
721// ---------------------------------------------------------------------------
722
723inline void CDSPFIRFilter :: unref()
724{
725 R8BSYNC( CDSPFIRFilterCache :: getStateSync() );
726
727 RefCount--;
728}
729
730// ---------------------------------------------------------------------------
731
732} // namespace r8b
733
734#endif // R8B_CDSPFIRFILTER_INCLUDED
Real-valued FFT transform class.
Sinc function-based FIR filter generator class.
#define R8BSYNC(SyncObject)
Thread synchronization macro.
Definition r8bbase.h:845
#define R8B_EXITDTOR
Macro that defines the attribute specifying that the exit-time destructor should be called for a stat...
Definition r8bbase.h:162
#define R8B_NULL
The "null pointer" value, portable between C++11 and earlier C++ versions.
Definition r8bbase.h:101
#define R8BNOCTOR(ClassName)
Macro that defines empty copy-constructor and copy operator.
Definition r8bbase.h:225
#define R8B_EXTFFT
This macro, when equal to 1, extends length of low-pass filters' FFT block by a factor of 2,...
Definition r8bconf.h:129
#define R8BASSERT(e)
Assertion macro used to check for certain run-time conditions. By default, no action is taken if asse...
Definition r8bconf.h:28
#define R8B_BASECLASS
Macro defines the name of the class from which all classes that are designed to be created on heap ar...
Definition r8bconf.h:56
#define R8BCONSOLE(...)
Console output macro, used to output various resampler status strings, including filter design parame...
Definition r8bconf.h:41
#define R8B_FILTER_CACHE_MAX
Macro specifies the number of filters kept in the cache at most.
Definition r8bconf.h:90
The "r8brain-free-src" library namespace.
Definition CDSPBlockConvolver.h:22
double realfft_t
Forward transform's native type.
Definition CDSPRealFFT.h:37
R8B_CONST double R8B_PI
Equals pi.
Definition r8bbase.h:197
EDSPFilterPhaseResponse
Enumeration of filter's phase responses.
Definition CDSPFIRFilter.h:29
@ fprMinPhase
Minimum-phase response. Features a minimal-latency response, but the response's phase is non-linear....
Definition CDSPFIRFilter.h:33
@ fprLinearPhase
Linear-phase response. Features a linear-phase, high-latency response, with the latency expressed as ...
Definition CDSPFIRFilter.h:30
int getBitOccupancy(const int v)
Calculate the exact number of bits a value needs for representation.
Definition r8bbase.h:956
void calcMinPhaseTransform(double *const Kernel, const int KernelLen, const int LenMult=2, const bool DoFinalMul=true, double *const DCGroupDelay=R8B_NULL)
Calculates the minimum-phase transform of the filter kernel, using a discrete Hilbert transform in ce...
Definition CDSPRealFFT.h:993
void normalizeFIRFilter(double *const p, const int l, const double DCGain, const int pstep=1)
FIR filter's gain normalization.
Definition r8bbase.h:1124
Calculation and storage class for FIR filters.
Definition CDSPFIRFilter.h:60
int getBlockLenBits() const
Returns filter's block length, expressed as Nth power of 2.
Definition CDSPFIRFilter.h:153
int getLatency() const
Returns filter's latency, in samples (integer part).
Definition CDSPFIRFilter.h:121
const realfft_t * getKernelBlock() const
Returns pointer to filter's kernel block, in complex-numbered form obtained via the CDSPRealFFT::forw...
Definition CDSPFIRFilter.h:171
static double getLPMaxTransBand()
Returns the maximal allowed low-pass filter's transition band, in percent.
Definition CDSPFIRFilter.h:82
void unref()
Reduces reference count to this object.
Definition CDSPFIRFilter.h:723
double getLatencyFrac() const
Returns filter's latency, in samples (fractional part). Always zero for linear-phase filters.
Definition CDSPFIRFilter.h:131
static double getLPMinAtten()
Returns the minimal allowed low-pass filter's stop-band attenuation, in decibel.
Definition CDSPFIRFilter.h:92
int getKernelLen() const
Returns filter kernel length, in samples. Not to be confused with the block length.
Definition CDSPFIRFilter.h:141
realfft_t calcDownShiftNyquist(const realfft_t re, const realfft_t im) const
Calculates Nyquist bin value for downsampling using power-of-2 down-shifting.
Definition CDSPFIRFilter.h:188
static double getLPMaxAtten()
Returns the maximal allowed low-pass filter's stop-band attenuation, in decibel.
Definition CDSPFIRFilter.h:102
static double getLPMinTransBand()
Returns the minimal allowed low-pass filter's transition band, in percent.
Definition CDSPFIRFilter.h:72
bool isZeroPhase() const
Returns true if kernel block of this filter has zero-phase response.
Definition CDSPFIRFilter.h:112
FIR filter cache class.
Definition CDSPFIRFilter.h:532
static int getObjCount()
Returns the number of filters present in the cache now. This value can be monitored for debugging "fo...
Definition CDSPFIRFilter.h:543
static int & getObjCountStatic()
Returns reference to variable containing cache object count.
Definition CDSPFIRFilter.h:710
static CDSPFIRFilter & getLPFilter(const double ReqNormFreq, const double ReqTransBand, const double ReqAtten, const EDSPFilterPhaseResponse ReqPhase, const double ReqGain, const int ReqDownFactor)
Calculates or returns reference to a previously calculated (cached) low-pass FIR filter.
Definition CDSPFIRFilter.h:583
static CSyncObject & getStateSync()
Returns reference to filter cache sync object.
Definition CDSPFIRFilter.h:699
Pointer-to-object "keeper" class with automatic deletion.
Definition r8bbase.h:469
T * unkeep()
Returns the keeped pointer and resets it in this keeper without object deletion.
Definition r8bbase.h:547
Multi-threaded synchronization object class.
Definition r8bbase.h:703