DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
BucketBrigade.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
71#include "DspMath.h"
72
73#include <algorithm>
74#include <array>
75#include <cmath>
76#include <vector>
77
78namespace dspark {
79
87template <FloatType T>
89{
90public:
91 static constexpr int kMinStages = 64;
92 static constexpr int kMaxStages = 8192;
93
95 enum class Precision
96 {
97 Standard,
98 High
99 };
100
109 void prepare(double sampleRate, int stages, double cornerHz, int factor = 1)
110 {
111 if (!std::isfinite(sampleRate) || !(sampleRate > 0.0)) return;
112 fs_ = sampleRate;
113 factor_ = factor == 2 ? 2 : 1;
114 rate_ = fs_ * static_cast<double>(factor_);
115 stages_ = std::clamp(stages / 2 * 2, kMinStages, kMaxStages);
116 buckets_.assign(static_cast<size_t>(stages_ / 2), 0.0);
117 snap_ = true;
118 setShape(shape_);
119 setCorner(cornerHz);
120 reset();
121 }
122
124 enum class Shape
125 {
127 Chorus
128 };
129
131 void setShape(Shape shape) noexcept
132 {
133 shape_ = shape == Shape::Chorus ? Shape::Chorus : Shape::Butterworth;
134 const bool chorus = shape_ == Shape::Chorus;
135 in_.count = 2;
136 in_.k = chorus ? std::array<double, 2> { 1.0 / 0.8, 1.0 / 0.8 } : kButterworthK;
137 in_.mean = false;
138 out_.count = chorus ? 1 : 2;
139 out_.k = chorus ? std::array<double, 2> { 1.0 / 0.6, 0.0 } : kButterworthK;
140 out_.mean = chorus;
141 snap_ = true;
142 setCorners(inCorner_, outCorner_);
143 }
145 [[nodiscard]] Shape getShape() const noexcept { return shape_; }
146
148 void reset() noexcept
149 {
150 std::fill(buckets_.begin(), buckets_.end(), 0.0);
151 head_ = 0;
152 phase_ = 0.0;
153 previousIn_ = 0.0;
154 held_ = 0.0;
155 lastInput_ = 0.0;
156 rise1_ = rise2_ = middle1_ = 0.0;
157 history_ = {};
158 in_.clear();
159 out_.clear();
160 }
161
163 void setCorner(double hz) noexcept { setCorners(hz, hz); }
164
171 void setCorners(double inputHz, double outputHz) noexcept
172 {
173 if (!std::isfinite(inputHz) || !std::isfinite(outputHz)) return;
174 inCorner_ = std::clamp(inputHz, 200.0, 0.45 * fs_);
175 outCorner_ = std::clamp(outputHz, 200.0, 0.45 * fs_);
176 in_.aim(std::tan(3.141592653589793 * inCorner_ / rate_), inCorner_, snap_ ? 0 : kCornerRampSteps);
177 out_.aim(std::tan(3.141592653589793 * outCorner_ / rate_), outCorner_, snap_ ? 0 : kCornerRampSteps);
178 }
179
184 void setCornersNow(double inputHz, double outputHz) noexcept
185 {
186 snap_ = true;
187 setCorners(inputHz, outputHz);
188 }
189
190 [[nodiscard]] int getStages() const noexcept { return stages_; }
192 [[nodiscard]] double getCorner() const noexcept { return inCorner_; }
194 [[nodiscard]] double getOutputCorner() const noexcept { return outCorner_; }
196 [[nodiscard]] int getFactor() const noexcept { return factor_; }
197
199 void setPrecision(Precision precision) noexcept
200 {
201 precision_ = precision == Precision::High ? Precision::High : Precision::Standard;
202 }
204 [[nodiscard]] Precision getPrecision() const noexcept { return precision_; }
205
207 [[nodiscard]] double clockFor(double delaySeconds) const noexcept
208 {
209 return static_cast<double>(stages_) / (2.0 * std::max(delaySeconds, 1e-5));
210 }
211
227 [[nodiscard]] double delayFor(double wantedSeconds) const noexcept
228 {
229 // Group delay at low frequencies of the low-passes: one over the Q of
230 // each section over its corner in radians per second, and half a
231 // step for a mean of two.
232 const double filters = in_.delay(rate_) + out_.delay(rate_);
233 const double steps = (precision_ == Precision::High ? 3.5 : 0.5) / rate_;
234 const double chainOnly = (wantedSeconds - filters - steps) / (1.0 + 1.0 / static_cast<double>(stages_));
235 return std::max(chainOnly, 1e-5);
236 }
237
245 [[nodiscard]] T processSample(T input, double delaySeconds) noexcept
246 {
247 const double x = std::isfinite(input) ? static_cast<double>(input) : 0.0;
248 if (factor_ == 2) (void)chain(lowPass(0.5 * (lastInput_ + x)), delaySeconds);
249 lastInput_ = x;
250 return static_cast<T>(chain(lowPass(x), delaySeconds));
251 }
252
268 void processPair(BucketBrigade& twin, T input, double delayThis, double delayTwin,
269 double& outThis, double& outTwin) noexcept
270 {
271 const double x = std::isfinite(input) ? static_cast<double>(input) : 0.0;
272 if (factor_ == 2)
273 {
274 const double mid = lowPass(0.5 * (lastInput_ + x));
275 (void)chain(mid, delayThis);
276 (void)twin.chain(mid, delayTwin);
277 }
278 lastInput_ = x;
279 const double filtered = lowPass(x);
280 outThis = static_cast<double>(static_cast<T>(chain(filtered, delayThis)));
281 outTwin = static_cast<double>(static_cast<T>(twin.chain(filtered, delayTwin)));
282 }
283
284private:
286 double lowPass(double x) noexcept { return in_.run(x); }
287
293 [[nodiscard]] double quintic(double t, double x) const noexcept
294 {
295 const double a = t + 2.0, b = t + 1.0, e = t - 1.0, f = t - 2.0, g = t - 3.0;
296 const double ab = a * b, efg = e * f * g;
297 return history_[0] * (b * t * efg) * (-1.0 / 120.0)
298 + history_[1] * (a * t * efg) * (1.0 / 24.0)
299 + history_[2] * (ab * efg) * (-1.0 / 12.0)
300 + history_[3] * (ab * t * f * g) * (1.0 / 12.0)
301 + history_[4] * (ab * t * e * g) * (-1.0 / 24.0)
302 + x * (ab * t * e * f) * (1.0 / 120.0);
303 }
304
306 double chain(double x, double delaySeconds) noexcept
307 {
308 snap_ = false;
309 const double step = std::min(clockFor(delaySeconds) / rate_, 64.0);
310 const double start = phase_;
311 phase_ += step;
312 const int size = static_cast<int>(buckets_.size());
313 // Each tick between the previous step and this one takes the input at
314 // its own time, hands the oldest bucket to the output and moves on.
315 // The output is the held value averaged over the step (the integral
316 // of the steps): sampled at the step's instants, the steps' images
317 // around the clock rate would fold into the band.
318 // High precision: the ticks of this step read the input of the step
319 // two before, by a quintic through the six steps around it, and the
320 // output is the held value weighted by a quadratic B-spline over the
321 // last three steps: each stretch of this step adds to the spline's
322 // falling piece now ((1 - u)^2 / 2), its middle piece one step later
323 // (1/2 + u - u^2) and its rising piece two steps later (u^2 / 2).
324 const bool high = precision_ == Precision::High;
325 double area = 0.0, last = 0.0, rise = 0.0, middle = 0.0, fall = 0.0;
326 const auto weigh = [&](double from, double to) noexcept {
327 const double d1 = to - from, d2 = 0.5 * (to * to - from * from),
328 d3 = (to * to * to - from * from * from) * (1.0 / 3.0);
329 rise += held_ * (0.5 * d3);
330 middle += held_ * (0.5 * d1 + d2 - d3);
331 fall += held_ * (0.5 * (d1 - 2.0 * d2 + d3));
332 };
333 for (double tick = std::floor(start) + 1.0; tick <= phase_ && size > 0; tick += 1.0)
334 {
335 const double t = step > 0.0 ? (tick - start) / step : 1.0;
336 const double sampled = high ? quintic(t, x) : previousIn_ + t * (x - previousIn_);
337 area += held_ * (t - last);
338 if (high) weigh(last, t);
339 last = t;
340 held_ = buckets_[static_cast<size_t>(head_)];
341 buckets_[static_cast<size_t>(head_)] = sampled;
342 head_ = head_ + 1 == size ? 0 : head_ + 1;
343 }
344 area += held_ * (1.0 - last);
345 if (phase_ >= 1.0) phase_ -= std::floor(phase_);
346 previousIn_ = x;
347 double y = area;
348 if (high)
349 {
350 weigh(last, 1.0);
351 y = rise2_ + middle1_ + fall;
352 rise2_ = rise1_;
353 rise1_ = rise;
354 middle1_ = middle;
355 history_ = { history_[1], history_[2], history_[3], history_[4], x };
356 }
357 return out_.run(y);
358 }
359
360 static constexpr std::array<double, 2> kButterworthK = { 1.0 / 0.5411961001461970, 1.0 / 1.3065629648763764 };
361 static constexpr int kCornerRampSteps = 32;
362
365 struct LowPass
366 {
367 int count = 2;
368 std::array<double, 2> k = kButterworthK;
369 bool mean = false;
370 double g = 0.1, target = 0.1, step = 0.0;
371 double hz = 4000.0, hzTarget = 4000.0, hzStep = 0.0;
372 int left = 0;
373 std::array<double, 2> a1 {};
374 std::array<double, 2> s1 {}, s2 {};
375 double last = 0.0;
376
377 void solve() noexcept
378 {
379 for (int i = 0; i < count; ++i) a1[static_cast<size_t>(i)] = 1.0 / (1.0 + g * (g + k[static_cast<size_t>(i)]));
380 }
381 void aim(double to, double toHz, int steps) noexcept
382 {
383 target = to;
384 hzTarget = toHz;
385 if (steps <= 0) { g = to; hz = toHz; left = 0; solve(); return; }
386 left = steps;
387 step = (to - g) / static_cast<double>(steps);
388 hzStep = (toHz - hz) / static_cast<double>(steps);
389 }
390 void clear() noexcept
391 {
392 s1 = {};
393 s2 = {};
394 last = 0.0;
395 }
396 double run(double x) noexcept
397 {
398 if (left > 0)
399 {
400 const bool landed = --left == 0;
401 g = landed ? target : g + step;
402 hz = landed ? hzTarget : hz + hzStep;
403 solve();
404 }
405 if (mean)
406 {
407 const double m = 0.5 * (x + last);
408 last = x;
409 x = m;
410 }
411 for (int i = 0; i < count; ++i)
412 {
413 const auto j = static_cast<size_t>(i);
414 const double v1 = a1[j] * (s1[j] + g * (x - s2[j]));
415 const double v2 = s2[j] + g * v1;
416 s1[j] = 2.0 * v1 - s1[j];
417 s2[j] = 2.0 * v2 - s2[j];
418 x = v2;
419 }
420 return x;
421 }
423 [[nodiscard]] double delay(double rate) const noexcept
424 {
425 double sum = 0.0;
426 for (int i = 0; i < count; ++i) sum += k[static_cast<size_t>(i)];
427 return sum / (2.0 * 3.141592653589793 * hz) + (mean ? 0.5 / rate : 0.0);
428 }
429 };
430
431 double fs_ = 48000.0, rate_ = 48000.0, inCorner_ = 4000.0, outCorner_ = 4000.0;
432 int stages_ = 1024, factor_ = 1;
433 std::vector<double> buckets_;
434 int head_ = 0;
435 double phase_ = 0.0, previousIn_ = 0.0, held_ = 0.0, lastInput_ = 0.0;
436 double rise1_ = 0.0, rise2_ = 0.0, middle1_ = 0.0;
437 std::array<double, 5> history_ {};
438 Precision precision_ = Precision::Standard;
439 Shape shape_ = Shape::Butterworth;
440 LowPass in_ {}, out_ {};
441 bool snap_ = true;
442};
443
444} // namespace dspark
One bucket-brigade delay line (one channel).
static constexpr int kMinStages
Smallest chain.
double getOutputCorner() const noexcept
int getStages() const noexcept
void setCornersNow(double inputHz, double outputHz) noexcept
The corners taken at once, without the glide: for an owner that moves them every sample itself....
void setShape(Shape shape) noexcept
The pair of filters around the chain; takes effect from the next corner set.
void processPair(BucketBrigade &twin, T input, double delayThis, double delayTwin, double &outThis, double &outTwin) noexcept
One host sample through this line and a twin, sharing this line's input low-pass (the twin's own is n...
Precision getPrecision() const noexcept
void setCorners(double inputHz, double outputHz) noexcept
Corners of the input and the output low-passes, each 200 Hz to 0.45 of the host's rate (non-finite va...
void setCorner(double hz) noexcept
Corner of the input and output low-passes, 200 Hz to 0.45 of the host's rate.
int getFactor() const noexcept
void prepare(double sampleRate, int stages, double cornerHz, int factor=1)
Allocates the chain and designs the filters.
Shape
The pair of filters around the chain (setShape()).
@ Chorus
Two sections of Q 0.8 at the input; a mean of two steps and a section of Q 0.6 at the output.
@ Butterworth
Fourth-order Butterworth low-passes at the input and the output (default).
void reset() noexcept
Empties the chain and the filters.
static constexpr int kMaxStages
Largest chain.
void setPrecision(Precision precision) noexcept
How the line reads its input and its output (out-of-range values read as Standard); call reset() afte...
double clockFor(double delaySeconds) const noexcept
The clock rate a delay needs, in hertz.
double delayFor(double wantedSeconds) const noexcept
The delay to ask of processSample() for the whole device to be late by wantedSeconds.
Shape getShape() const noexcept
Precision
How the line reads its input and its output (setPrecision()).
@ High
Input by a quintic through six steps, output by a quadratic B-spline over three (see the file notes).
@ Standard
Input by a straight line between steps, output by its average over the step (default).
double getCorner() const noexcept
T processSample(T input, double delaySeconds) noexcept
One host sample through the device.
Multi-voice chorus/flanger with true stereo spread and smooth parameter handling.
Definition Chorus.h:104
constexpr int delay
Delay of the projected output behind the newest input, in samples.
Main namespace for the DSPark framework.