DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
SpectralProcessor.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
43#include "FFT.h"
44#include "WindowFunctions.h"
45#include "AudioSpec.h"
46#include "AudioBuffer.h"
47#include "DenormalGuard.h"
48
49#include <algorithm>
50#include <cassert>
51#include <cmath>
52#include <cstddef>
53#include <memory>
54#include <vector>
55
56namespace dspark {
57
84template <typename T>
86{
87public:
88 // -- Lifecycle -----------------------------------------------------------
89
107 void prepare(const AudioSpec& spec, int fftSize = 2048, int hopSize = 0)
108 {
109 if (!(spec.sampleRate > 0.0) || spec.numChannels < 1) return;
110
111 // Disarm first: if an allocation below throws, the processor is a
112 // safe no-op instead of running half-mutated state (basic guarantee).
113 prepared_ = false;
114 spec_ = spec;
115
116 assert((fftSize & (fftSize - 1)) == 0 && fftSize >= kMinFftSize
117 && "FFT size must be a power of 2");
118 // Release-safe: clamp, then round UP to a power of two (never down,
119 // so a requested resolution is always met). The clamp bounds the
120 // loop; kMaxFftSize is itself a power of two, so no overflow.
121 fftSize = std::clamp(fftSize, kMinFftSize, kMaxFftSize);
122 int pow2 = kMinFftSize;
123 while (pow2 < fftSize) pow2 <<= 1;
124 fftSize_ = pow2;
125 mask_ = fftSize_ - 1;
126
127 hopSize_ = (hopSize > 0) ? hopSize : fftSize_ / 2;
128 hopSize_ = std::clamp(hopSize_, 1, fftSize_ / 2);
129 if (fftSize_ % hopSize_ != 0) hopSize_ = fftSize_ / 2;
130 numBins_ = fftSize_ / 2 + 1;
131
132 fft_ = std::make_unique<FFTReal<T>>(fftSize_);
133
134 // WOLA window: periodic sqrt-Hann (analysis and synthesis).
135 window_.resize(static_cast<std::size_t>(fftSize_));
136 WindowFunctions<T>::hann(window_.data(), fftSize_, true);
137 for (auto& w : window_) w = std::sqrt(w);
138
139 computeWolaNorm();
140
141 const int nCh = spec.numChannels;
142 inputRing_.resize(static_cast<std::size_t>(nCh));
143 outputAccum_.resize(static_cast<std::size_t>(nCh));
144 inputPos_.assign(static_cast<std::size_t>(nCh), 0);
145 outputReadPos_.assign(static_cast<std::size_t>(nCh), 0);
146 spectra_.assign(static_cast<std::size_t>(nCh),
147 std::vector<T>(static_cast<std::size_t>(fftSize_ + 2), T(0)));
148
149 // The overlap-add accumulator holds twice the FFT size (also pow2).
150 accumMask_ = (fftSize_ * 2) - 1;
151
152 for (int ch = 0; ch < nCh; ++ch)
153 {
154 inputRing_[static_cast<std::size_t>(ch)]
155 .assign(static_cast<std::size_t>(fftSize_), T(0));
156 outputAccum_[static_cast<std::size_t>(ch)]
157 .assign(static_cast<std::size_t>(fftSize_ * 2), T(0));
158 }
159
160 // Plain vectors are fine here: the FFT kernels are unaligned-safe
161 // by design, so no aligned allocator is required.
162 fftIn_.resize(static_cast<std::size_t>(fftSize_));
163 fftOut_.resize(static_cast<std::size_t>(fftSize_ + 2));
164 fftResult_.resize(static_cast<std::size_t>(fftSize_));
165
166 hopCounter_ = 0;
167 prepared_ = true;
168 }
169
183 template <typename Func>
184 void processBlock(AudioBufferView<T> buffer, Func&& processFunc) noexcept
185 {
186 processHops(buffer, [&](int nCh) noexcept
187 {
188 for (int ch = 0; ch < nCh; ++ch)
189 {
190 analyse(ch, fftOut_.data());
191 processFunc(fftOut_.data(), numBins_);
192 synthesise(ch, fftOut_.data());
193 }
194 });
195 }
196
211 template <typename Observe, typename Func>
212 void processBlock(AudioBufferView<T> buffer, Observe&& observe, Func&& processFunc) noexcept
213 {
214 processHops(buffer, [&](int nCh) noexcept
215 {
216 for (int ch = 0; ch < nCh; ++ch)
217 {
218 T* spectrum = spectra_[static_cast<std::size_t>(ch)].data();
219 analyse(ch, spectrum);
220 observe(ch, static_cast<const T*>(spectrum), numBins_);
221 }
222 for (int ch = 0; ch < nCh; ++ch)
223 {
224 T* spectrum = spectra_[static_cast<std::size_t>(ch)].data();
225 processFunc(ch, spectrum, numBins_);
226 synthesise(ch, spectrum);
227 }
228 });
229 }
230
231private:
233 template <typename Hop>
234 void processHops(AudioBufferView<T> buffer, Hop&& hop) noexcept
235 {
236 if (!prepared_) return;
237 DenormalGuard guard;
238
239 const int nCh = std::min(buffer.getNumChannels(),
240 static_cast<int>(inputRing_.size()));
241 const int nS = buffer.getNumSamples();
242
243 // Chunked processing between hop boundaries. Order per chunk:
244 // push input, drain output, then fire the hop. Draining BEFORE the
245 // hop is what anchors every frame to its absolute stream position
246 // (the accumulator write position equals sample index m*hop at the
247 // m-th hop no matter how the caller chops the stream); it is also
248 // what makes the pipeline in-place safe (input is read into the
249 // ring before the drain overwrites it).
250 int i = 0;
251 while (i < nS)
252 {
253 const int chunk = std::min(nS - i, hopSize_ - hopCounter_);
254
255 // 1. Push the input chunk into the ring buffers (two contiguous
256 // spans instead of a per-sample masked loop).
257 for (int ch = 0; ch < nCh; ++ch)
258 {
259 const T* data = buffer.getChannel(ch) + i;
260 auto& ring = inputRing_[static_cast<std::size_t>(ch)];
261 const int wp = inputPos_[static_cast<std::size_t>(ch)];
262 const int first = std::min(chunk, fftSize_ - wp);
263 std::copy_n(data, first, ring.data() + wp);
264 std::copy_n(data + first, chunk - first, ring.data());
265 inputPos_[static_cast<std::size_t>(ch)] = (wp + chunk) & mask_;
266 }
267
268 // 2. Drain the overlap-add accumulator for the chunk (read and
269 // clear in one pass, two contiguous spans).
270 for (int ch = 0; ch < nCh; ++ch)
271 {
272 T* data = buffer.getChannel(ch) + i;
273 T* acc = outputAccum_[static_cast<std::size_t>(ch)].data();
274 const int rp = outputReadPos_[static_cast<std::size_t>(ch)];
275 const int first = std::min(chunk, fftSize_ * 2 - rp);
276 for (int k = 0; k < first; ++k)
277 {
278 data[k] = acc[rp + k];
279 acc[rp + k] = T(0);
280 }
281 for (int k = first; k < chunk; ++k)
282 {
283 data[k] = acc[k - first];
284 acc[k - first] = T(0);
285 }
286 outputReadPos_[static_cast<std::size_t>(ch)] = (rp + chunk) & accumMask_;
287 }
288
289 // 3. Fire the STFT hop at the boundary.
290 hopCounter_ += chunk;
291 if (hopCounter_ >= hopSize_)
292 {
293 hopCounter_ = 0;
294 hop(nCh);
295 }
296
297 i += chunk;
298 }
299 }
300
301public:
302 // -- Queries -------------------------------------------------------------
303
309 [[nodiscard]] int getLatency() const noexcept { return fftSize_; }
310 [[nodiscard]] int getFFTSize() const noexcept { return fftSize_; }
311 [[nodiscard]] int getNumBins() const noexcept { return numBins_; }
312 [[nodiscard]] int getHopSize() const noexcept { return hopSize_; }
313
315 void reset() noexcept
316 {
317 for (auto& ring : inputRing_) std::fill(ring.begin(), ring.end(), T(0));
318 for (auto& acc : outputAccum_) std::fill(acc.begin(), acc.end(), T(0));
319 std::fill(inputPos_.begin(), inputPos_.end(), 0);
320 std::fill(outputReadPos_.begin(), outputReadPos_.end(), 0);
321 hopCounter_ = 0;
322 }
323
324private:
333 void analyse(int ch, T* spectrum) noexcept
334 {
335 // 1. Copy from ring buffer with the analysis window, as two
336 // contiguous multiply spans (auto-vectorizable).
337 const T* ring = inputRing_[static_cast<std::size_t>(ch)].data();
338 const T* win = window_.data();
339 const int readPos = inputPos_[static_cast<std::size_t>(ch)];
340 const int head = fftSize_ - readPos;
341 for (int k = 0; k < head; ++k)
342 fftIn_[static_cast<std::size_t>(k)] = ring[readPos + k] * win[k];
343 for (int k = head; k < fftSize_; ++k)
344 fftIn_[static_cast<std::size_t>(k)] = ring[k - head] * win[k];
345
346 // 2. Forward FFT
347 fft_->forward(fftIn_.data(), spectrum);
348 }
349
351 void synthesise(int ch, T* spectrum) noexcept
352 {
353 const T* win = window_.data();
354 // 4. Inverse FFT (FFTReal::inverse already applies the 1/N
355 // normalization, so the analysis->synthesis round-trip is unity
356 // before windowing).
357 fft_->inverse(spectrum, fftResult_.data());
358
359 // 5. Synthesis window and overlap-add, two contiguous spans.
360 T* acc = outputAccum_[static_cast<std::size_t>(ch)].data();
361 const T* res = fftResult_.data();
362 const int writePos = outputReadPos_[static_cast<std::size_t>(ch)];
363 const int headOut = std::min(fftSize_, fftSize_ * 2 - writePos);
364 for (int k = 0; k < headOut; ++k)
365 acc[writePos + k] += res[k] * win[k] * wolaNorm_;
366 for (int k = headOut; k < fftSize_; ++k)
367 acc[k - headOut] += res[k] * win[k] * wolaNorm_;
368 }
369
378 void computeWolaNorm() noexcept
379 {
380 const int numOverlaps = fftSize_ / hopSize_;
381 T maxSum = T(0);
382 for (int pos = 0; pos < hopSize_; ++pos)
383 {
384 T sumSq = T(0);
385 for (int hop = 0; hop < numOverlaps; ++hop)
386 {
387 const int idx = pos + hop * hopSize_;
388 if (idx < fftSize_)
389 {
390 const T w = window_[static_cast<std::size_t>(idx)];
391 sumSq += w * w;
392 }
393 }
394 if (sumSq > maxSum) maxSum = sumSq;
395 }
396 wolaNorm_ = (maxSum > T(1e-10)) ? (T(1) / maxSum) : T(1);
397 }
398
399 // -- Members -------------------------------------------------------------
400 static constexpr int kMinFftSize = 4;
401 static constexpr int kMaxFftSize = 1 << 20;
402
403 AudioSpec spec_ {};
404 bool prepared_ = false;
405
406 int fftSize_ = 2048;
407 int hopSize_ = 1024;
408 int numBins_ = 1025;
409 int mask_ = 2047; // Bitwise mask for fftSize_ bounds
410 int accumMask_ = 4095; // Bitwise mask for fftSize_*2 bounds
411
412 std::unique_ptr<FFTReal<T>> fft_;
413 std::vector<T> window_;
414 T wolaNorm_ = T(1);
415
416 std::vector<std::vector<T>> inputRing_;
417 std::vector<std::vector<T>> outputAccum_;
418 std::vector<int> inputPos_;
419 std::vector<int> outputReadPos_;
420 std::vector<std::vector<T>> spectra_;
421 int hopCounter_ = 0;
422
423 // Shared work buffers for sequential channel processing
424 std::vector<T> fftIn_, fftOut_, fftResult_;
425};
426
427} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
High-performance STFT analysis-modification-synthesis pipeline.
int getNumBins() const noexcept
void processBlock(AudioBufferView< T > buffer, Observe &&observe, Func &&processFunc) noexcept
Processes a block with every channel of a hop analysed before the first is processed,...
int getLatency() const noexcept
I/O latency in samples: exactly one FFT frame.
void prepare(const AudioSpec &spec, int fftSize=2048, int hopSize=0)
Allocates buffers and prepares the WOLA processing state.
int getFFTSize() const noexcept
void processBlock(AudioBufferView< T > buffer, Func &&processFunc) noexcept
Processes a block of audio through the STFT pipeline.
void reset() noexcept
Clears all internal delay lines and state variables.
int getHopSize() const noexcept
Main namespace for the DSPark framework.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
static void hann(T *output, int size, bool periodic=true) noexcept
Hann (raised cosine) window.