1 /** 2 * Copyright 2017 Cut Through Recordings 3 * License: MIT License 4 * Author(s): Ethan Reker 5 */ 6 module ddsp.filter.biquad; 7 8 import ddsp.effect.effect; 9 10 const float pi = 3.14159265; 11 12 enum FilterType 13 { 14 lowpass, 15 highpass, 16 bandpass, 17 allpass, 18 peak, 19 lowshelf, 20 highshelf, 21 } 22 23 /** 24 This class implements a generic biquad filter. Should be inherited by all filters. 25 */ 26 class BiQuad(T) : AudioEffect!T 27 { 28 public: 29 30 this() nothrow @nogc 31 { 32 33 } 34 35 void initialize(T a0, 36 T a1, 37 T a2, 38 T b1, 39 T b2, 40 T c0 = 1, 41 T d0 = 0) nothrow @nogc 42 { 43 _a0 = a0; 44 _a1 = a1; 45 _a2 = a2; 46 _b1 = b1; 47 _b2 = b2; 48 _c0 = c0; 49 _d0 = d0; 50 } 51 52 void setFrequency(float frequency) nothrow @nogc 53 { 54 if(_frequency != frequency) 55 { 56 _frequency = frequency; 57 calcCoefficients(); 58 } 59 } 60 61 override void setSampleRate(float sampleRate) nothrow @nogc 62 { 63 _sampleRate = sampleRate; 64 calcCoefficients(); 65 reset(); 66 } 67 68 override T getNextSample(const T input) nothrow @nogc 69 { 70 _w = input - _b1 * _w1 - _b2 * _w2; 71 _yn = (_a0 * _w + _a1 *_w1 + _a2 * _w2) * _c0 + (input * _d0); 72 73 _w2 = _w1; 74 _w1 = _w; 75 76 return _yn; 77 } 78 79 override void reset() 80 { 81 _w = 0; 82 _w1 = 0; 83 _w2 = 0; 84 85 _yn = 0; 86 } 87 88 abstract void calcCoefficients() nothrow @nogc; 89 90 protected: 91 92 //Delay samples 93 float _w = 0; 94 float _w1 = 0; 95 float _w2 = 0; 96 float _yn = 0; 97 98 //Biquad Coeffecients 99 T _a0=0, _a1=0, _a2=0; 100 T _b1=0, _b2=0; 101 T _c0=1, _d0=0; 102 103 float _sampleRate; 104 float _qFactor; 105 float _frequency; 106 }