-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathIIRFilter.java
89 lines (73 loc) · 2.26 KB
/
IIRFilter.java
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
//
// Copyright 2012 Jeff Bush
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
// Infinite Impulse Response filter, with a variable number of poles
//
class IIRFilter
{
static IIRFilter makeBandpassFilter(double centerFrequency, double bandwidth,
double sampleRate)
{
double normFreq = 2 * Math.PI * (centerFrequency / sampleRate);
double normBandwidth = bandwidth / sampleRate;
double r = 1.0 - 3.0 * normBandwidth;
double k = (1.0 - 2.0 * r * Math.cos(normFreq) + Math.pow(r, 2.0))
/ (2.0 - 2.0 * Math.cos(normFreq));
double[] aValues = new double[3];
double[] bValues = new double[2];
aValues[0] = 1.0 - 3.0 * normBandwidth;
aValues[1] = 2.0 * (k - r) * Math.cos(normFreq);
aValues[2] = Math.pow(r, 2.0) - k;
bValues[0] = 2.0 * r * Math.cos(normFreq);
bValues[1] = -Math.pow(r, 2.0);
return new IIRFilter(aValues, bValues);
}
static IIRFilter makeLowPassFilter(double cutoffFrequency, double sampleRate)
{
double x = Math.pow(Math.E, -2 * Math.E * cutoffFrequency / sampleRate);
double[] aValues = new double[1];
double[] bValues = new double[1];
aValues[0] = 1.0 - x;
bValues[0] = x;
return new IIRFilter(aValues, bValues);
}
protected IIRFilter(double[] aValues, double[] bValues)
{
fA = aValues;
fB = bValues;
fX = new double[aValues.length];
fY = new double[bValues.length];
}
double processSample(double sample)
{
for (int i = fX.length - 1; i > 0; i--)
fX[i] = fX[i - 1];
fX[0] = sample;
double y = 0.0;
for (int i = 0; i < fX.length; i++)
y += fA[i] * fX[i];
for (int i = 0; i < fY.length; i++)
y += fB[i] * fY[i];
for (int i = fY.length - 1; i > 0; i--)
fY[i] = fY[i - 1];
fY[0] = y;
return y;
}
double[] fX;
double[] fY;
double[] fA;
double[] fB;
}