Bela
Real-time, ultra-low-latency audio and sensor processing system for BeagleBone Black
Loading...
Searching...
No Matches
Biquad.h
1// This code is based on the code credited below, but it has been modified
2// further by Adan L Benito Temprano and Giulio Moro
3//
4// Created by Nigel Redmon on 11/24/12
5// EarLevel Engineering: earlevel.com
6// Copyright 2012 Nigel Redmon
7//
8// For a complete explanation of the code:
9// http://www.earlevel.com/main/2012/11/25/biquad-c-source-code/
10//
11// License:
12//
13// This source code is provided as is, without warranty.
14// You may copy and distribute verbatim copies of this document.
15// You may modify and use this source code to create binary code
16// for your own purposes, free or commercial.
17//
18
19#pragma once
20
22{
23public:
24 typedef enum
25 {
26 lowpass,
27 highpass,
28 bandpass,
29 notch,
30 peak,
31 lowshelf,
32 highshelf
33 } Type;
34 struct Settings {
35 double fs;
36 Type type;
37 double cutoff;
38 double q;
39 double peakGainDb;
40 };
41};
42
46template <typename T>
47class BiquadCoeffT : public BiquadCoeff
48{
49public:
50 typedef T sample_t;
51 BiquadCoeffT() {}
52 BiquadCoeffT(const Settings& settings) { setup(settings); }
53 int setup(const Settings& settings)
54 {
55 type = settings.type;
56 Fs = settings.fs;
57 Fc = settings.cutoff / Fs;
58 Q = settings.q;
59 peakGain = settings.peakGainDb;
60 calc();
61 return 0;
62 }
63
64 void setType(Type type) {
65 this->type = type;
66 calc();
67 }
68 void setQ(sample_t Q) {
69 this->Q = Q;
70 calc();
71 }
72 void setFc(sample_t Fc) {
73 this->Fc = Fc/this->Fs;
74 calc();
75 }
76 void setPeakGain(sample_t peakGainDB) {
77 this->peakGain = peakGainDB;
78 calc();
79 }
80
81 Type getType() { return type; }
82 sample_t getQ() { return Q; }
83 sample_t getFc() { return Fc; }
84 sample_t getPeakGain() { return peakGain; }
85
86 sample_t a0, a1, a2, b1, b2;
87private:
88 sample_t Fc, Q, peakGain;
89 sample_t Fs;
90 Type type;
91 void calc(void);
92};
93
99class Biquad : public BiquadCoeffT<double> {
100public:
101 Biquad() {};
102 Biquad(const Settings& s) {
103 setup(s);
104 }
108 sample_t process(sample_t in)
109 {
110 sample_t out = in * a0 + z1;
111 z1 = in * a1 + z2 - b1 * out;
112 z2 = in * a2 - b2 * out;
113 return out;
114 }
115
119 void clean()
120 {
121 z1 = z2 = 0.0;
122 }
123protected:
124 sample_t z1 = 0;
125 sample_t z2 = 0;
126};
127extern template class BiquadCoeffT<double>;
Definition Biquad.h:48
Definition Biquad.h:22
sample_t process(sample_t in)
Definition Biquad.h:108
void clean()
Definition Biquad.h:119
Definition Biquad.h:34
double fs
Sample rate in Hz.
Definition Biquad.h:35
double q
Quality factor.
Definition Biquad.h:38
double cutoff
Cutoff in Hz.
Definition Biquad.h:37
Type type
Filter type.
Definition Biquad.h:36
double peakGainDb
Maximum filter gain.
Definition Biquad.h:39