DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Goertzel.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
43#include "../Core/DspMath.h"
44
45#include <algorithm>
46#include <cassert>
47#include <cmath>
48#include <numbers>
49
50namespace dspark {
51
66template <FloatType T>
68{
69public:
89 void prepare(double sampleRate, double targetFreqHz, int blockSize) noexcept
90 {
91 assert(sampleRate > 0.0 && "Sample rate must be positive");
92 assert(blockSize > 0 && "Block size must be strictly positive");
93 assert(targetFreqHz >= 0.0 && targetFreqHz <= (sampleRate * 0.5) && "Frequency must be within Nyquist limit");
94
95 if (!std::isfinite(sampleRate) || sampleRate <= 0.0
96 || !std::isfinite(targetFreqHz) || blockSize <= 0)
97 return;
98
99 sampleRate_ = sampleRate;
100 targetFreq_ = std::clamp(targetFreqHz, 0.0, sampleRate * 0.5);
101 blockSize_ = blockSize;
102
103 // Exact target frequency omega calculation (Generalized Goertzel)
104 double omega = 2.0 * std::numbers::pi * targetFreq_ / sampleRate_;
105
106 coeff_ = 2.0 * std::cos(omega);
107 cosOmega_ = std::cos(omega);
108 sinOmega_ = std::sin(omega);
109
110 // Magnitude normalization: 2/N for interior bins, 1/N for DC and for
111 // exact Nyquist (neither has a mirrored bin; the old 2/N at Nyquist
112 // read a full-scale alternating signal 2x / +6 dB high).
113 const bool isDc = targetFreq_ <= 0.001;
114 const bool isNyquist = targetFreq_ >= sampleRate_ * 0.5 * (1.0 - 1e-12);
115 normalisationFactor_ = (isDc || isNyquist) ? 1.0 / blockSize_ : 2.0 / blockSize_;
116
117 reset();
118 }
119
129 void processBlock(const T* data, int numSamples) noexcept
130 {
131 if (data == nullptr || numSamples <= 0) return;
132
133 // Bring state to local variables for compiler optimization (register allocation)
134 double s1 = s1_;
135 double s2 = s2_;
136 const double coeff = coeff_;
137
138 for (int i = 0; i < numSamples; ++i)
139 {
140 double s0 = static_cast<double>(data[i]) + coeff * s1 - s2;
141 s2 = s1;
142 s1 = s0;
143
144 if (++sampleCount_ >= blockSize_)
145 {
146 computeResult(s1, s2);
147 s1 = 0.0;
148 s2 = 0.0;
149 sampleCount_ = 0;
150 }
151 }
152
153 // Save local state back to member variables
154 s1_ = s1;
155 s2_ = s2;
156 }
157
164 bool pushSample(T sample) noexcept
165 {
166 double s0 = static_cast<double>(sample) + coeff_ * s1_ - s2_;
167 s2_ = s1_;
168 s1_ = s0;
169
170 if (++sampleCount_ >= blockSize_)
171 {
172 computeResult(s1_, s2_);
173 s1_ = 0.0;
174 s2_ = 0.0;
175 sampleCount_ = 0;
176 return true;
177 }
178 return false;
179 }
180
187 void forceCompute() noexcept
188 {
189 computeResult(s1_, s2_);
190 s1_ = 0.0;
191 s2_ = 0.0;
192 sampleCount_ = 0;
193 }
194
195 // -- Results ------------------------------------------------------------------
196
205 [[nodiscard]] bool checkNewResultAvailable() noexcept
206 {
207 if (hasNewResult_)
208 {
209 hasNewResult_ = false;
210 return true;
211 }
212 return false;
213 }
214
219 [[nodiscard]] T getMagnitude() const noexcept
220 {
221 return std::sqrt(real_ * real_ + imag_ * imag_);
222 }
223
228 [[nodiscard]] T getPower() const noexcept
229 {
230 return real_ * real_ + imag_ * imag_;
231 }
232
238 [[nodiscard]] T getMagnitudeDb() const noexcept
239 {
241 }
242
252 [[nodiscard]] T getPhase() const noexcept
253 {
254 return std::atan2(imag_, real_);
255 }
256
261 [[nodiscard]] double getTargetFrequency() const noexcept { return targetFreq_; }
262
264 [[nodiscard]] double getSampleRate() const noexcept { return sampleRate_; }
265
267 [[nodiscard]] int getBlockSize() const noexcept { return blockSize_; }
268
274 void reset() noexcept
275 {
276 s1_ = 0.0;
277 s2_ = 0.0;
278 sampleCount_ = 0;
279 real_ = T(0);
280 imag_ = T(0);
281 hasNewResult_ = false;
282 }
283
284private:
288 void computeResult(double s1, double s2) noexcept
289 {
290 real_ = static_cast<T>((s1 - s2 * cosOmega_) * normalisationFactor_);
291 imag_ = static_cast<T>((s2 * sinOmega_) * normalisationFactor_);
292 hasNewResult_ = true;
293 }
294
295 double sampleRate_ = 48000.0;
296 double targetFreq_ = 440.0;
297 int blockSize_ = 2048;
298
299 // Coefficients and resonator state in double (see the class comment).
300 double coeff_ = 0.0;
301 double cosOmega_ = 0.0;
302 double sinOmega_ = 0.0;
303 double normalisationFactor_ = 0.0;
304
305 // Streaming state
306 double s1_ = 0.0;
307 double s2_ = 0.0;
308 int sampleCount_ = 0;
309
310 // Results
311 T real_ = T(0);
312 T imag_ = T(0);
313 bool hasNewResult_ = false;
314};
315
316} // namespace dspark
Single-frequency magnitude detector using the Goertzel algorithm.
Definition Goertzel.h:68
double getSampleRate() const noexcept
Returns the configured sample rate in Hz.
Definition Goertzel.h:264
T getPower() const noexcept
Returns the power at the target frequency.
Definition Goertzel.h:228
void processBlock(const T *data, int numSamples) noexcept
Processes a block of audio samples, updating the internal state.
Definition Goertzel.h:129
double getTargetFrequency() const noexcept
Returns the currently configured target frequency.
Definition Goertzel.h:261
void reset() noexcept
Resets the internal IIR state and counters to zero.
Definition Goertzel.h:274
void forceCompute() noexcept
Manually forces the computation of the result before N samples are reached.
Definition Goertzel.h:187
T getPhase() const noexcept
Returns the phase angle at the target frequency.
Definition Goertzel.h:252
bool checkNewResultAvailable() noexcept
Checks if a new result has been computed.
Definition Goertzel.h:205
T getMagnitude() const noexcept
Returns the magnitude at the target frequency (linear scale).
Definition Goertzel.h:219
int getBlockSize() const noexcept
Returns the configured analysis block size in samples.
Definition Goertzel.h:267
bool pushSample(T sample) noexcept
Feeds a single sample into the running Goertzel computation.
Definition Goertzel.h:164
T getMagnitudeDb() const noexcept
Returns the magnitude in decibels.
Definition Goertzel.h:238
void prepare(double sampleRate, double targetFreqHz, int blockSize) noexcept
Prepares the detector for a specific frequency.
Definition Goertzel.h:89
Main namespace for the DSPark framework.
T gainToDecibels(T gain, T minusInfinityDb=T(-100)) noexcept
Converts a linear gain value to decibels.
Definition DspMath.h:92