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 : AudioEffect
27 {
28     public:
29 
30         this() nothrow @nogc
31         {
32 
33         }
34 
35         void initialize(float a0,
36                         float a1,
37                         float a2,
38                         float b1,
39                         float b2,
40                         float c0 = 1,
41                         float 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             reset();
60         }
61     
62         override void setSampleRate(float sampleRate) nothrow @nogc
63         {
64             _sampleRate = sampleRate;
65             calcCoefficients();
66             reset();
67         }
68 
69         override float getNextSample(const float input)  nothrow @nogc
70         {
71             float output = (_a0 * input + _a1 * _xn1 + _a2 * _xn2 - _b1 * _yn1 - _b2 * _yn2) * _c0 + (input * _d0);
72 
73             _xn2 = _xn1;
74             _xn1 = input;
75             _yn2 = _yn1;
76             _yn1 = output;
77 
78             return output;
79         }
80 
81         override void reset()
82         {
83             _xn1 = 0;
84             _xn2 = 0;
85             _yn1 = 0;
86             _yn2 = 0;
87         }
88 
89         abstract void calcCoefficients() nothrow @nogc;
90 
91     protected:
92 
93         //Delay samples
94         float _xn1=0, _xn2=0;
95         float _yn1=0, _yn2=0;
96 
97         //Biquad Coeffecients
98         float _a0=0, _a1=0, _a2=0;
99         float _b1=0, _b2=0;
100         float _c0=1, _d0=0;
101 
102         float _sampleRate;
103         float _qFactor;
104         float _frequency;
105 }
106 
107 unittest
108 {
109     import dplug.core.nogc;
110 
111     //BiQuad f = mallocNew!BiQuad();
112     //f.setSampleRate(44100);
113     //f.initialize(0.1, 0.3, 0.5, 0,5, 0.1);
114     //testEffect(f, "BiQuad", 44100 * 2, false);
115 }