DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Convolver.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
48#include "AudioBuffer.h"
49#include "AudioSpec.h"
50#include "FFT.h"
51#include "SimdOps.h"
52
53#include <algorithm>
54#include <cassert>
55#include <cmath>
56#include <cstdint>
57#include <memory>
58#include <vector>
59
60namespace dspark {
61
76template <typename T>
78{
79public:
81 enum class Partitioning
82 {
83 Uniform,
85 };
86
103 void prepare(int blockSize, const T* irData, int irLength,
104 Partitioning partitioning = Partitioning::Uniform)
105 {
106 assert(blockSize >= 2 && (blockSize & (blockSize - 1)) == 0);
107 assert(irLength > 0);
108 assert(irData != nullptr);
109 if (irData == nullptr || irLength <= 0) return;
110
111 // Release-safe normalisation: the FFT needs a power of two >= 4, so
112 // the block needs a power of two >= 2. Round up (never down: rounding
113 // down would shrink the valid overlap-save region below the block).
114 int bs = 2;
115 while (bs < blockSize) bs <<= 1;
116
117 blockSize_ = bs;
118 fftSize_ = bs * 2;
119 numBins_ = fftSize_ + 2; // (N/2 + 1) complex bins, interleaved = N+2 scalars
120
121 // NonUniform: the head takes h[0, 2 x tail - bs), the tail the rest.
122 tailBlock_ = partitioning == Partitioning::NonUniform ? chooseTailBlock(bs, irLength) : 0;
123 const int headLength = tailBlock_ > 0 ? 2 * tailBlock_ - bs : irLength;
124
125 // Create FFT processor
126 fft_ = std::make_unique<FFTReal<T>>(fftSize_);
127
128 // Partition the IR into blocks
129 numPartitions_ = (headLength + bs - 1) / bs;
130
131 // Pre-transform each IR partition
132 irPartitions_.resize(static_cast<size_t>(numPartitions_));
133 std::vector<T> paddedBlock(static_cast<size_t>(fftSize_), T(0));
134
135 for (int p = 0; p < numPartitions_; ++p)
136 {
137 int offset = p * bs;
138 int remaining = std::min(bs, headLength - offset);
139
140 // Zero-pad the block to fftSize
141 std::fill(paddedBlock.begin(), paddedBlock.end(), T(0));
142 std::copy_n(irData + offset, remaining, paddedBlock.begin());
143
144 // Forward FFT and store
145 irPartitions_[static_cast<size_t>(p)].resize(static_cast<size_t>(numBins_));
146 fft_->forward(paddedBlock.data(), irPartitions_[static_cast<size_t>(p)].data());
147 }
148
149 // Allocate working buffers
150 inputBuffer_.assign(static_cast<size_t>(fftSize_), T(0));
151 outputBuffer_.assign(static_cast<size_t>(fftSize_), T(0));
152 overlapBuffer_.assign(static_cast<size_t>(blockSize_), T(0));
153 fftAccum_.assign(static_cast<size_t>(numBins_), T(0));
154
155 // Frequency-domain delay line (stores past input FFTs)
156 fdlBuffer_.resize(static_cast<size_t>(numPartitions_));
157 for (auto& fdl : fdlBuffer_)
158 fdl.assign(static_cast<size_t>(numBins_), T(0));
159
160 prepareTail(irData + headLength, irLength - headLength);
161
162 fdlIndex_ = 0;
163 inputPos_ = 0;
164 resetTail();
165 }
166
168 void reset() noexcept
169 {
170 std::fill(inputBuffer_.begin(), inputBuffer_.end(), T(0));
171 std::fill(outputBuffer_.begin(), outputBuffer_.end(), T(0));
172 std::fill(overlapBuffer_.begin(), overlapBuffer_.end(), T(0));
173 for (auto& fdl : fdlBuffer_)
174 std::fill(fdl.begin(), fdl.end(), T(0));
175 fdlIndex_ = 0;
176 inputPos_ = 0;
177 resetTail();
178 }
179
192 void process(const T* input, T* output, int numSamples) noexcept
193 {
194 if (blockSize_ == 0) // not prepared: honest pass-through
195 {
196 if (output != input)
197 std::copy_n(input, numSamples, output);
198 return;
199 }
200
201 // Copy in contiguous runs up to the next block boundary instead of
202 // sample-by-sample (this is the per-channel hot path of Reverb).
203 int i = 0;
204 while (i < numSamples)
205 {
206 const int run = std::min(numSamples - i, blockSize_ - inputPos_);
207
208 // Stage the input run first, then overwrite the caller's samples
209 // with the previous block's result -- this ordering is what makes
210 // full in-place (input == output) legal.
211 std::copy_n(input + i, run,
212 inputBuffer_.begin() + blockSize_ + inputPos_);
213 if (tailBlock_ > 0)
214 for (int k = 0; k < run; ++k)
215 inRing_[static_cast<size_t>((absPos_ + k) & inMask_)] = input[i + k];
216 std::copy_n(overlapBuffer_.begin() + inputPos_, run, output + i);
217 if (tailBlock_ > 0)
218 addTail(output + i, run);
219
220 inputPos_ += run;
221 i += run;
222
223 if (inputPos_ >= blockSize_)
224 {
225 processPartitionBlock();
226 inputPos_ = 0;
227
228 std::copy_n(outputBuffer_.begin() + blockSize_, static_cast<size_t>(blockSize_),
229 overlapBuffer_.begin());
230 }
231 }
232 }
233
240 void processInPlace(T* data, int numSamples) noexcept
241 {
242 process(data, data, numSamples);
243 }
244
259 void prepare(const AudioSpec& spec, const T* irData, int irLength)
260 {
261 prepare(spec.maxBlockSize, irData, irLength);
262 }
263
273 void processBlock(AudioBufferView<T> buffer) noexcept
274 {
275 if (buffer.getNumChannels() > 0 && buffer.getNumSamples() > 0)
276 processInPlace(buffer.getChannel(0), buffer.getNumSamples());
277 }
278
280 [[nodiscard]] int getLatency() const noexcept { return blockSize_; }
281
283 [[nodiscard]] int getBlockSize() const noexcept { return blockSize_; }
284
287 [[nodiscard]] int getNumPartitions() const noexcept { return numPartitions_ + numTailParts_; }
288
291 [[nodiscard]] int getTailBlockSize() const noexcept { return tailBlock_; }
292
293private:
304 static int chooseTailBlock(int bs, int irLength) noexcept
305 {
306 const double uniform = static_cast<double>(irLength) / bs;
307 double best = 0.8 * uniform; // only split where it clearly pays
308 int choice = 0;
309 for (int t = 4 * bs; t <= kMaxTailBlock; t <<= 1)
310 {
311 const int head = 2 * t - bs;
312 if (irLength <= head + t) break; // fewer than two tail partitions
313 const double tailParts = std::ceil(static_cast<double>(irLength - head) / t);
314 const double cost = static_cast<double>(head) / bs + tailParts
315 + 1.5 * std::log2(2.0 * t);
316 if (cost < best) { best = cost; choice = t; }
317 }
318 return choice;
319 }
320
322 void prepareTail(const T* tailIr, int tailLength)
323 {
324 numTailParts_ = 0;
325 totalUnits_ = 0;
326 if (tailBlock_ == 0 || tailLength <= 0)
327 {
328 tailBlock_ = 0;
329 tailFft_.reset();
330 tailIR_.clear(); tailFdl_.clear(); tailAccum_.clear();
331 tailScratch_.clear(); tailOut_.clear(); inRing_.clear();
332 return;
333 }
334 const int tb = tailBlock_;
335 const std::size_t spec = static_cast<std::size_t>(2 * tb + 2);
336 numTailParts_ = (tailLength + tb - 1) / tb;
337 totalUnits_ = numTailParts_ + 3; // FFT + K MACs + IFFT + scatter
338
339 tailFft_ = std::make_unique<FFTReal<T>>(2 * tb);
340 tailIR_.assign(static_cast<std::size_t>(numTailParts_) * spec, T(0));
341 tailFdl_.assign(static_cast<std::size_t>(numTailParts_) * spec, T(0));
342 tailAccum_.assign(spec, T(0));
343 tailScratch_.assign(static_cast<std::size_t>(2 * tb), T(0));
344 tailOut_.assign(static_cast<std::size_t>(8 * tb), T(0));
345 inRing_.assign(static_cast<std::size_t>(4 * tb), T(0));
346 outMask_ = 8 * tb - 1;
347 inMask_ = 4 * tb - 1;
348
349 std::vector<T> padded(static_cast<std::size_t>(2 * tb), T(0));
350 for (int p = 0; p < numTailParts_; ++p)
351 {
352 const int len = std::min(tb, tailLength - p * tb);
353 std::fill(padded.begin(), padded.end(), T(0));
354 std::copy_n(tailIr + static_cast<std::size_t>(p) * tb, len, padded.begin());
355 tailFft_->forward(padded.data(), &tailIR_[static_cast<std::size_t>(p) * spec]);
356 }
357 }
358
359 void resetTail() noexcept
360 {
361 std::fill(tailFdl_.begin(), tailFdl_.end(), T(0));
362 std::fill(tailOut_.begin(), tailOut_.end(), T(0));
363 std::fill(inRing_.begin(), inRing_.end(), T(0));
364 absPos_ = static_cast<std::int64_t>(inRing_.size()); // keep indices positive
365 cyclePos_ = 0;
366 tailFdlIndex_ = 0;
367 taskPhase_ = totalUnits_; // idle until the first tail block is in
368 taskStart_ = 0;
369 }
370
381 void addTail(T* out, int count) noexcept
382 {
383 for (int k = 0; k < count; ++k)
384 {
385 T& slot = tailOut_[static_cast<size_t>((absPos_ + k) & outMask_)];
386 out[k] += slot;
387 slot = T(0); // clear-on-read keeps the ring self-cleaning
388 }
389 absPos_ += count;
390 cyclePos_ += count;
391 // This cycle's proportional share of the task (64-bit product).
392 runTaskUnits(static_cast<int>((static_cast<std::int64_t>(totalUnits_) * cyclePos_
393 + tailBlock_ - 1) / tailBlock_));
394 if (cyclePos_ >= tailBlock_)
395 {
396 cyclePos_ = 0; // the task is fully drained (quota == total)
397 taskStart_ = absPos_;
398 tailFdlIndex_ = (tailFdlIndex_ + 1) % numTailParts_;
399 taskPhase_ = 0;
400 }
401 }
402
409 void runTaskUnits(int target) noexcept
410 {
411 const int tb = tailBlock_;
412 const std::size_t spec = static_cast<std::size_t>(2 * tb + 2);
413 target = std::min(target, totalUnits_);
414 while (taskPhase_ < target)
415 {
416 const int unit = taskPhase_++;
417 if (unit == 0)
418 {
419 const std::int64_t blockStart = taskStart_ - tb;
420 const int s0 = static_cast<int>(blockStart & inMask_);
421 const int first = std::min(tb, inMask_ + 1 - s0);
422 std::copy_n(&inRing_[static_cast<size_t>(s0)], first, tailScratch_.begin());
423 if (first < tb)
424 std::copy_n(inRing_.data(), tb - first, tailScratch_.begin() + first);
425 std::fill(tailScratch_.begin() + tb, tailScratch_.end(), T(0));
426 tailFft_->forward(tailScratch_.data(),
427 &tailFdl_[static_cast<size_t>(tailFdlIndex_) * spec]);
428 std::fill(tailAccum_.begin(), tailAccum_.end(), T(0));
429 }
430 else if (unit <= numTailParts_)
431 {
432 const int p = unit - 1;
433 const int slot = (tailFdlIndex_ - p + numTailParts_) % numTailParts_;
434 simd::complexMulAccum(tailAccum_.data(), &tailFdl_[static_cast<size_t>(slot) * spec],
435 &tailIR_[static_cast<size_t>(p) * spec], tb + 1);
436 }
437 else if (unit == numTailParts_ + 1)
438 {
439 tailFft_->inverse(tailAccum_.data(), tailScratch_.data());
440 }
441 else
442 {
443 const std::int64_t dst = taskStart_ + tb;
444 for (int m = 0; m < 2 * tb; ++m)
445 tailOut_[static_cast<size_t>((dst + m) & outMask_)] += tailScratch_[static_cast<size_t>(m)];
446 }
447 }
448 }
449
459 void processPartitionBlock() noexcept
460 {
461 // Forward FFT of the input buffer [previous block | current block],
462 // directly into this block's FDL slot (no intermediate copy).
463 fft_->forward(inputBuffer_.data(),
464 fdlBuffer_[static_cast<size_t>(fdlIndex_)].data());
465
466 // Complex multiply-accumulate: sum over all partitions
467 std::fill(fftAccum_.begin(), fftAccum_.end(), T(0));
468
469 for (int p = 0; p < numPartitions_; ++p)
470 {
471 int fdlIdx = (fdlIndex_ - p + numPartitions_) % numPartitions_;
472 const auto& irPart = irPartitions_[static_cast<size_t>(p)];
473 const auto& fdlPart = fdlBuffer_[static_cast<size_t>(fdlIdx)];
474
475 // Complex multiplication and accumulation (SIMD-accelerated)
476 int bins = numBins_ / 2;
477 simd::complexMulAccum(fftAccum_.data(), fdlPart.data(), irPart.data(), bins);
478 }
479
480 // Inverse FFT
481 fft_->inverse(fftAccum_.data(), outputBuffer_.data());
482
483 // Shift input buffer: move current block to previous position
484 std::copy_n(inputBuffer_.begin() + blockSize_, static_cast<size_t>(blockSize_),
485 inputBuffer_.begin());
486 std::fill(inputBuffer_.begin() + blockSize_, inputBuffer_.end(), T(0));
487
488 // Advance delay line index
489 fdlIndex_ = (fdlIndex_ + 1) % numPartitions_;
490 }
491
492 static constexpr int kMaxTailBlock = 65536;
493
494 int blockSize_ = 0;
495 int fftSize_ = 0;
496 int numBins_ = 0;
497 int numPartitions_ = 0;
498 int inputPos_ = 0;
499 int fdlIndex_ = 0;
500
501 std::unique_ptr<FFTReal<T>> fft_;
502
503 // Pre-transformed IR partitions (frequency domain)
504 std::vector<std::vector<T>> irPartitions_;
505
506 // Frequency-domain delay line (past input FFTs)
507 std::vector<std::vector<T>> fdlBuffer_;
508
509 // Working buffers
510 std::vector<T> inputBuffer_;
511 std::vector<T> outputBuffer_;
512 std::vector<T> overlapBuffer_;
513 std::vector<T> fftAccum_;
514
515 // NonUniform tail (empty in Uniform mode)
516 int tailBlock_ = 0;
517 int numTailParts_ = 0;
518 int totalUnits_ = 0;
519 std::unique_ptr<FFTReal<T>> tailFft_;
520 std::vector<T> tailIR_;
521 std::vector<T> tailFdl_;
522 std::vector<T> tailAccum_;
523 std::vector<T> tailScratch_;
524 std::vector<T> tailOut_;
525 std::vector<T> inRing_;
526 int outMask_ = 0;
527 int inMask_ = 0;
528 std::int64_t absPos_ = 0;
529 std::int64_t taskStart_ = 0;
530 int cyclePos_ = 0;
531 int tailFdlIndex_ = 0;
532 int taskPhase_ = 0;
533};
534
535} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Real-time partitioned convolution using overlap-save with FFT.
Definition Convolver.h:78
Partitioning
How the impulse response is partitioned (see the file notes).
Definition Convolver.h:82
@ Uniform
Every partition the block size (default).
@ NonUniform
Block-size head, larger time-distributed tail partitions.
int getNumPartitions() const noexcept
Returns the number of IR partitions: the block-size head partitions, plus the larger tail partitions ...
Definition Convolver.h:287
void prepare(const AudioSpec &spec, const T *irData, int irLength)
Prepares with AudioSpec and IR data (unified API).
Definition Convolver.h:259
void process(const T *input, T *output, int numSamples) noexcept
Processes a block of audio through the convolver.
Definition Convolver.h:192
int getBlockSize() const noexcept
Returns the block size.
Definition Convolver.h:283
void prepare(int blockSize, const T *irData, int irLength, Partitioning partitioning=Partitioning::Uniform)
Prepares the convolver with an impulse response.
Definition Convolver.h:103
void reset() noexcept
Resets the convolution state (clears delay lines and buffers).
Definition Convolver.h:168
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an audio buffer in-place (unified API).
Definition Convolver.h:273
int getLatency() const noexcept
Returns the processing latency in samples (= block size).
Definition Convolver.h:280
int getTailBlockSize() const noexcept
Tail partition size in NonUniform mode, 0 when the IR is convolved in block-size partitions only.
Definition Convolver.h:291
void processInPlace(T *data, int numSamples) noexcept
Processes audio in-place (output overwrites input).
Definition Convolver.h:240
void complexMulAccum(float *DSPARK_RESTRICT accum, const float *DSPARK_RESTRICT a, const float *DSPARK_RESTRICT b, int bins) noexcept
Complex multiply-accumulate over interleaved [re, im, ...] spectra.
Definition SimdOps.h:1234
constexpr ParamInfo choice(Param p, const char *id, const char *name, const char *const (&labels)[N], int def) noexcept
Main namespace for the DSPark framework.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
int maxBlockSize
Maximum number of samples per processing block.
Definition AudioSpec.h:53