DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
ZeroLatencyConvolver.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
56#include "AudioBuffer.h"
57#include "Convolver.h"
58#include "FFT.h"
59#include "SimdOps.h"
60
61#include <algorithm>
62#include <cmath>
63#include <cstdint>
64#include <cstring>
65#include <memory>
66#include <vector>
67
68namespace dspark {
69
76template <typename T>
78{
79public:
89 void prepare(const T* irData, int irLength, int headSize = 128)
90 {
91 prepared_ = false;
92 if (irData == nullptr || irLength <= 0) return;
93
94 headSize_ = 32;
95 while (headSize_ < std::clamp(headSize, 32, 512)) headSize_ <<= 1;
96
97 // --- head: ir[0, headLen) stored reversed for a linear dot product ---
98 headLen_ = std::min(irLength, headSize_);
99 headRev_.assign(static_cast<size_t>(headLen_), T(0));
100 for (int i = 0; i < headLen_; ++i)
101 headRev_[static_cast<size_t>(i)] = irData[headLen_ - 1 - i];
102
103 // --- mid: uniform partitioned convolver, block == headSize ----------
104 // Its block latency equals this region's offset, so its (delayed)
105 // output is exactly the contribution of ir[headSize, tailStart).
106 const int midEnd = std::min(irLength, kTailStart);
107 hasMid_ = irLength > headSize_;
108 if (hasMid_)
109 {
110 mid_.prepare(headSize_, irData + headSize_, midEnd - headSize_);
111 midScratch_.assign(static_cast<size_t>(headSize_), T(0));
112 }
113
114 // --- tail: time-distributed levels of growing partitions -------------
115 // Level j has block B = kTailBlock * 2^j and starts at 2 B; every
116 // level but the last holds two partitions, so the next one starts at
117 // 4 B = 2 (2 B). The last level (block kMaxTailBlock, or wherever
118 // the IR ends) takes all remaining partitions.
119 hasTail_ = irLength > kTailStart;
120 numTailParts_ = 0;
121 levels_.clear();
122 int topBlock = kTailBlock;
123 if (hasTail_)
124 {
125 const int topLevel = chooseTopLevel(irLength);
126 int offset = kTailStart;
127 int block = kTailBlock;
128 while (offset < irLength)
129 {
130 const int remaining = irLength - offset;
131 const bool top = static_cast<int>(levels_.size()) >= topLevel;
132 TailLevel lv;
133 lv.block = block;
134 lv.numParts = std::max(1, (remaining + block - 1) / block);
135 if (!top) lv.numParts = std::min(lv.numParts, 2);
136 lv.totalUnits = lv.numParts + 3; // FFT + K MACs + IFFT + scatter
137 lv.spec = 2 * block + 2;
138 lv.delay = std::min(static_cast<int>(levels_.size()) * (kTailBlock / 8), block / 4);
139
140 lv.fft = std::make_unique<FFTReal<T>>(static_cast<size_t>(2 * block));
141 lv.ir.assign(static_cast<size_t>(lv.numParts) * static_cast<size_t>(lv.spec), T(0));
142 lv.fdl.assign(static_cast<size_t>(lv.numParts) * static_cast<size_t>(lv.spec), T(0));
143 lv.accum.assign(static_cast<size_t>(lv.spec), T(0));
144 lv.scratch.assign(static_cast<size_t>(2 * block), T(0));
145
146 for (int p = 0; p < lv.numParts; ++p)
147 {
148 const int start = offset + p * block;
149 const int len = std::min(block, irLength - start);
150 std::fill(lv.scratch.begin(), lv.scratch.end(), T(0));
151 std::copy_n(irData + start, len, lv.scratch.begin());
152 lv.fft->forward(lv.scratch.data(), &lv.ir[static_cast<size_t>(p) * static_cast<size_t>(lv.spec)]);
153 }
154
155 numTailParts_ += lv.numParts;
156 topBlock = block;
157 offset += lv.numParts * block;
158 levels_.push_back(std::move(lv));
159 block *= 2;
160 }
161
162 // Output ring: a level scatters [taskStart + B, taskStart + 3 B)
163 // while the read position is at least taskStart, so 4 B of the
164 // largest level never wrap onto unread samples.
165 int outSize = 1;
166 while (outSize < 4 * topBlock) outSize <<= 1;
167 tailOut_.assign(static_cast<size_t>(outSize), T(0));
168 outMask_ = outSize - 1;
169 }
170
171 // --- shared input history ring ---------------------------------------
172 int ringSize = 2 * headSize_;
173 if (hasTail_) ringSize = std::max(ringSize, 4 * topBlock);
174 int pow2 = 1;
175 while (pow2 < ringSize) pow2 <<= 1;
176 inRing_.assign(static_cast<size_t>(pow2), T(0));
177 inMask_ = pow2 - 1;
178
179 prepared_ = true;
180 reset();
181 }
182
184 void reset() noexcept
185 {
186 if (!prepared_) return;
187 std::fill(inRing_.begin(), inRing_.end(), T(0));
188 std::fill(tailOut_.begin(), tailOut_.end(), T(0));
189 if (hasMid_) mid_.reset();
190 absPos_ = static_cast<int64_t>(inRing_.size()); // keep indices positive
191 for (auto& lv : levels_)
192 {
193 std::fill(lv.fdl.begin(), lv.fdl.end(), T(0));
194 lv.cyclePos = 0;
195 lv.fdlIndex = 0;
196 lv.taskPhase = lv.totalUnits; // idle
197 lv.taskStart = 0;
198 }
199 }
200
207 void process(const T* input, T* output, int numSamples) noexcept
208 {
209 if (!prepared_)
210 {
211 if (output != input)
212 std::memmove(output, input, static_cast<size_t>(numSamples) * sizeof(T));
213 return;
214 }
215
216 int i = 0;
217 while (i < numSamples)
218 {
219 int chunk = std::min(numSamples - i, headSize_);
220 // Every level's block is a multiple of the first level's, so a
221 // chunk that stops at its boundary stops at all of them.
222 if (hasTail_)
223 chunk = std::min(chunk, levels_[0].block - levels_[0].cyclePos);
224
225 // Mid level reads the pristine input before output overwrites it.
226 if (hasMid_)
227 mid_.process(input + i, midScratch_.data(), chunk);
228
229 for (int k = 0; k < chunk; ++k)
230 {
231 inRing_[static_cast<size_t>(absPos_ & inMask_)] = input[i + k];
232
233 T y = headDot();
234 if (hasMid_) y += midScratch_[static_cast<size_t>(k)];
235 if (hasTail_)
236 {
237 auto& slot = tailOut_[static_cast<size_t>(absPos_ & outMask_)];
238 y += slot;
239 slot = T(0); // clear-on-read keeps the ring self-cleaning
240 }
241 output[i + k] = y;
242 ++absPos_;
243 }
244
245 if (hasTail_)
246 {
247 for (auto& lv : levels_)
248 {
249 lv.cyclePos += chunk;
250 // Execute this cycle's proportional share of the pending
251 // task. 64-bit product: totalUnits grows with the
252 // partition count and would wrap int for hours-long IRs.
253 // Each level starts its share a little later than the one
254 // before (lv.delay), so the levels that launch on the same
255 // boundary do not run their transforms in the same callback.
256 const int64_t span = lv.block - lv.delay;
257 const int64_t done = std::max<int64_t>(0, lv.cyclePos - lv.delay);
258 runTaskUnits(lv, static_cast<int>(
259 (static_cast<int64_t>(lv.totalUnits) * done + span - 1) / span));
260 if (lv.cyclePos >= lv.block)
261 {
262 lv.cyclePos = 0; // task is fully drained (quota == total)
263 launchTask(lv);
264 }
265 }
266 }
267 i += chunk;
268 }
269 }
270
272 void processInPlace(T* data, int numSamples) noexcept
273 {
274 process(data, data, numSamples);
275 }
276
281 void processBlock(AudioBufferView<T> buffer) noexcept
282 {
283 if (buffer.getNumChannels() > 0 && buffer.getNumSamples() > 0)
284 processInPlace(buffer.getChannel(0), buffer.getNumSamples());
285 }
286
288 [[nodiscard]] static constexpr int getLatency() noexcept { return 0; }
289
291 [[nodiscard]] int getHeadSize() const noexcept { return headSize_; }
292
294 [[nodiscard]] int getNumTailPartitions() const noexcept { return numTailParts_; }
295
297 [[nodiscard]] int getNumTailLevels() const noexcept { return static_cast<int>(levels_.size()); }
298
299private:
300 static constexpr int kTailBlock = 1024;
301 static constexpr int kTailStart = 2 * kTailBlock;
302 static constexpr int kMaxTailBlock = 8192;
303
305 struct TailLevel
306 {
307 int block = 0;
308 int numParts = 0;
309 int totalUnits = 0;
310 int spec = 0;
311 int delay = 0;
312 std::unique_ptr<FFTReal<T>> fft;
313 std::vector<T> ir;
314 std::vector<T> fdl;
315 std::vector<T> accum;
316 std::vector<T> scratch;
317 int cyclePos = 0;
318 int fdlIndex = 0;
319 int taskPhase = 0;
320 int64_t taskStart = 0;
321 };
322
324 [[nodiscard]] T headDot() const noexcept
325 {
326 const int64_t start = absPos_ - headLen_ + 1;
327 const int s0 = static_cast<int>(start & inMask_);
328 const int ringSize = inMask_ + 1;
329 const int first = std::min(headLen_, ringSize - s0);
330
331 T y = simd::dotProduct(headRev_.data(), &inRing_[static_cast<size_t>(s0)], first);
332 if (first < headLen_)
333 y += simd::dotProduct(headRev_.data() + first, inRing_.data(), headLen_ - first);
334 return y;
335 }
336
348 [[nodiscard]] static int chooseTopLevel(int irLength) noexcept
349 {
350 double below = 0.0; // cost of the full levels under the candidate top
351 double best = 1e300;
352 int bestLevel = 0;
353 int offset = kTailStart;
354 int level = 0;
355 for (int block = kTailBlock; block <= kMaxTailBlock && offset < irLength; block *= 2, ++level)
356 {
357 const double fft = 1.5 * std::log2(2.0 * block);
358 const double parts = std::ceil(static_cast<double>(irLength - offset) / block);
359 const double cost = below + parts + fft;
360 if (cost < best) { best = cost; bestLevel = level; }
361 if (irLength - offset <= 2 * block) break; // nothing would remain above
362 below += 2.0 + fft;
363 offset += 2 * block;
364 }
365 return bestLevel;
366 }
367
369 void launchTask(TailLevel& lv) noexcept
370 {
371 lv.taskStart = absPos_;
372 lv.fdlIndex = (lv.fdlIndex + 1) % lv.numParts;
373 lv.taskPhase = 0;
374 }
375
384 void runTaskUnits(TailLevel& lv, int target) noexcept
385 {
386 const int B = lv.block;
387 const size_t spec = static_cast<size_t>(lv.spec);
388 target = std::min(target, lv.totalUnits);
389 while (lv.taskPhase < target)
390 {
391 const int unit = lv.taskPhase++;
392 if (unit == 0)
393 {
394 const int64_t blockStart = lv.taskStart - B;
395 const int s0 = static_cast<int>(blockStart & inMask_);
396 const int ringSize = inMask_ + 1;
397 const int first = std::min(B, ringSize - s0);
398 std::copy_n(&inRing_[static_cast<size_t>(s0)], first, lv.scratch.begin());
399 if (first < B)
400 std::copy_n(inRing_.data(), B - first, lv.scratch.begin() + first);
401 std::fill(lv.scratch.begin() + B, lv.scratch.end(), T(0));
402
403 lv.fft->forward(lv.scratch.data(), &lv.fdl[static_cast<size_t>(lv.fdlIndex) * spec]);
404 std::fill(lv.accum.begin(), lv.accum.end(), T(0));
405 }
406 else if (unit <= lv.numParts)
407 {
408 const int p = unit - 1;
409 const int slot = (lv.fdlIndex - p + lv.numParts) % lv.numParts;
410 simd::complexMulAccum(lv.accum.data(), &lv.fdl[static_cast<size_t>(slot) * spec],
411 &lv.ir[static_cast<size_t>(p) * spec], B + 1);
412 }
413 else if (unit == lv.numParts + 1)
414 {
415 lv.fft->inverse(lv.accum.data(), lv.scratch.data());
416 }
417 else
418 {
419 // Overlap-add in at most two contiguous runs of the ring.
420 const int ringSize = outMask_ + 1;
421 const int d0 = static_cast<int>((lv.taskStart + B) & outMask_);
422 const int first = std::min(2 * B, ringSize - d0);
423 T* out = tailOut_.data();
424 const T* src = lv.scratch.data();
425 for (int m = 0; m < first; ++m) out[d0 + m] += src[m];
426 for (int m = first; m < 2 * B; ++m) out[m - first] += src[m];
427 }
428 }
429 }
430
431 // -- Members -----------------------------------------------------------------
432 bool prepared_ = false;
433
434 int headSize_ = 128;
435 int headLen_ = 0;
436 std::vector<T> headRev_;
437
438 bool hasMid_ = false;
439 Convolver<T> mid_;
440 std::vector<T> midScratch_;
441
442 bool hasTail_ = false;
443 int numTailParts_ = 0;
444 std::vector<TailLevel> levels_;
445 std::vector<T> tailOut_;
446 int outMask_ = 0;
447
448 std::vector<T> inRing_;
449 int inMask_ = 0;
450 int64_t absPos_ = 0;
451};
452
453} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Gardner-style non-uniform partitioned convolver (zero latency, flat CPU).
int getNumTailLevels() const noexcept
Number of tail levels (partition sizes 1024, 2048, ...).
void processBlock(AudioBufferView< T > buffer) noexcept
Processes channel 0 of a buffer in-place (unified API). Mono engine – use one instance per channel fo...
int getHeadSize() const noexcept
Resolved direct-head length in samples.
void process(const T *input, T *output, int numSamples) noexcept
Convolves out-of-place. Works with any numSamples, even 1.
int getNumTailPartitions() const noexcept
Number of FFT partitions in the time-distributed tail (all levels).
void prepare(const T *irData, int irLength, int headSize=128)
Prepares the convolver with an impulse response (allocates).
static constexpr int getLatency() noexcept
Zero – that is the point.
void processInPlace(T *data, int numSamples) noexcept
Convolves in-place.
void reset() noexcept
Clears all signal state (keeps the IR). Safe on the audio thread.
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
float dotProduct(const float *DSPARK_RESTRICT a, const float *DSPARK_RESTRICT b, int count) noexcept
Computes the dot product of two arrays.
Definition SimdOps.h:644
Main namespace for the DSPark framework.