DSPark 1.6.1
Header-only audio DSP framework in pure C++20 — zero dependencies
Loading...
Searching...
No Matches
SpectrumAnalyzer.h File Reference

Real-time FFT-based spectrum analyser for audio visualisation. More...

#include "../Core/DspMath.h"
#include "../Core/FFT.h"
#include "../Core/WindowFunctions.h"
#include <algorithm>
#include <array>
#include <atomic>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <memory>
#include <vector>
Include dependency graph for SpectrumAnalyzer.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

class  dspark::SpectrumAnalyzer< T >
 Real-time FFT spectrum analyser with per-bin smoothing and peak hold. More...
 

Namespaces

namespace  dspark
 Main namespace for the DSPark framework.
 

Detailed Description

Real-time FFT-based spectrum analyser for audio visualisation.

Handles the complete pipeline: windowing -> FFT -> single-sided magnitude (amplitude-calibrated: a full-scale sine reads 0 dB) -> per-bin exponential smoothing -> dB conversion -> optional peak hold with dB/s decay.

Note
Performance: the FFT and transcendental math run synchronously inside pushSamples() whenever a hop completes. For large FFT sizes (>2048) on tight audio callbacks, consider a lock-free queue architecture where the GUI thread pulls samples and computes the FFT independently.

Threading:

  • prepare() / reset(): setup thread (not concurrent with the audio or reader threads; reset() rewrites the reader-visible slots).
  • pushSamples(): audio thread (stream owner). No-op before prepare().
  • getMagnitudesDb() / getPeakHoldDb() / isNewDataReady(): ONE reader thread (GUI). Wait-free triple-buffer hand-off; never blocks the writer. The two arrays are acquired independently, so a pair of consecutive calls may straddle a frame boundary (benign for metering).
  • setSmoothing() / setPeakDecay() / setPeakHoldEnabled() / setFloorDb(): any thread (relaxed atomics, picked up once per analysis frame). Non-finite values are ignored.

Dependencies: DspMath.h, FFT.h, WindowFunctions.h.

analyzer.prepare(48000.0, 2048); // 48 kHz, 2048-point FFT
// In audio callback:
analyzer.pushSamples(buffer.getChannel(0), numSamples);
// In GUI paint (Timer at 60Hz):
if (analyzer.isNewDataReady()) {
const float* spectrum = analyzer.getMagnitudesDb();
// Draw spectrum...
}
Real-time FFT spectrum analyser with per-bin smoothing and peak hold.
void prepare(double sampleRate, int fftSize=2048, WindowType windowType=WindowType::Hann)
Prepares the analyser and allocates all necessary buffers.
void pushSamples(const T *samples, int numSamples) noexcept
Pushes audio samples into the analyser's internal ring buffer.
const T * getMagnitudesDb() const noexcept
Returns the current magnitude spectrum in decibels.
bool isNewDataReady() noexcept
Consumes and returns the new data flag. True if updated since last call.

Definition in file SpectrumAnalyzer.h.