DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
CabinetModel.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
44#include "AudioBuffer.h"
45#include "Biquad.h"
46#include "BiquadCascade.h"
47#include "DspMath.h"
48#include "FilterDesign.h"
49#include "StateBlob.h"
50
51#include <algorithm>
52#include <array>
53#include <atomic>
54#include <cmath>
55#include <cstddef>
56#include <cstdio>
57#include <memory>
58#include <new>
59#include <vector>
60
61namespace dspark {
62
71template <FloatType T, int MaxChannels = 16>
73{
74public:
75 static constexpr int kTaps = 6;
76 static constexpr int kSections = 5;
77
82 void prepare(double sampleRate, int numChannels)
83 {
84 if (!std::isfinite(sampleRate) || !(sampleRate > 0.0) || numChannels <= 0) return;
85 fs_ = sampleRate;
86 channels_ = std::min(numChannels, MaxChannels);
87 if (!cascade_) cascade_.reset(new (std::nothrow) Cascade());
88 if (!cascade_) return;
89 cascade_->setNumSections(kSections);
90 fit_.prepare(sampleRate);
91
92 for (int k = 0; k < kTaps; ++k)
93 tapDelay_[static_cast<size_t>(k)] = std::max(1, static_cast<int>(std::lround(kTapMs[k] * 0.001 * fs_)));
94 diffuserDelay_[0] = std::max(1, static_cast<int>(std::lround(kDiffuserMs[0] * 0.001 * fs_)));
95 diffuserDelay_[1] = std::max(1, static_cast<int>(std::lround(kDiffuserMs[1] * 0.001 * fs_)));
96 size_ = 1;
97 while (size_ <= tapDelay_[kTaps - 1] + 1 || size_ <= diffuserDelay_[1] + 1) size_ <<= 1;
98 lines_.assign(static_cast<size_t>(channels_) * 3u * static_cast<size_t>(size_), T(0));
99 rampSamples_ = std::max(1, static_cast<int>(0.02 * fs_));
100 settled_ = false;
101 distanceNow_ = static_cast<double>(distance_.load(std::memory_order_relaxed));
102 dirty_.store(true, std::memory_order_release);
103 reset();
104 }
105
107 void reset() noexcept
108 {
109 if (cascade_) cascade_->reset();
110 std::fill(lines_.begin(), lines_.end(), T(0));
111 pos_ = 0;
112 distanceNow_ = static_cast<double>(distance_.load(std::memory_order_relaxed));
113 }
114
119 void setSize(T size) noexcept
120 {
121 if (!std::isfinite(size)) return;
122 sizeParam_.store(std::clamp(size, T(0), T(1)), std::memory_order_relaxed);
123 dirty_.store(true, std::memory_order_release);
124 }
129 void setBrightness(T brightness) noexcept
130 {
131 if (!std::isfinite(brightness)) return;
132 brightness_.store(std::clamp(brightness, T(0), T(1)), std::memory_order_relaxed);
133 dirty_.store(true, std::memory_order_release);
134 }
139 void setDistance(T distance) noexcept
140 {
141 if (!std::isfinite(distance)) return;
142 distance_.store(std::clamp(distance, T(0), T(1)), std::memory_order_relaxed);
143 }
144
145 [[nodiscard]] T getSize() const noexcept { return sizeParam_.load(std::memory_order_relaxed); }
146 [[nodiscard]] T getBrightness() const noexcept { return brightness_.load(std::memory_order_relaxed); }
147 [[nodiscard]] T getDistance() const noexcept { return distance_.load(std::memory_order_relaxed); }
148
150 [[nodiscard]] double getResonanceHz() const noexcept { return 140.0 * std::exp2(-static_cast<double>(getSize())); }
152 [[nodiscard]] double getRollOffHz() const noexcept
153 {
154 return 3000.0 * std::pow(7.0 / 3.0, static_cast<double>(getBrightness()));
155 }
156
158 void writeState(StateWriter& w, const char* prefix) const
159 {
160 char key[48];
161 std::snprintf(key, sizeof(key), "%ssize", prefix);
162 w.write(key, static_cast<float>(getSize()));
163 std::snprintf(key, sizeof(key), "%sbrightness", prefix);
164 w.write(key, static_cast<float>(getBrightness()));
165 std::snprintf(key, sizeof(key), "%sdistance", prefix);
166 w.write(key, static_cast<float>(getDistance()));
167 }
168
170 void readState(const StateReader& r, const char* prefix) noexcept
171 {
172 char key[48];
173 std::snprintf(key, sizeof(key), "%ssize", prefix);
174 setSize(static_cast<T>(r.read(key, 0.5f)));
175 std::snprintf(key, sizeof(key), "%sbrightness", prefix);
176 setBrightness(static_cast<T>(r.read(key, 0.5f)));
177 std::snprintf(key, sizeof(key), "%sdistance", prefix);
178 setDistance(static_cast<T>(r.read(key, 0.3f)));
179 }
180
182 void processBlock(AudioBufferView<T> buffer) noexcept
183 {
184 if (!cascade_ || lines_.empty()) return;
185 if (dirty_.load(std::memory_order_relaxed) && dirty_.exchange(false, std::memory_order_acquire))
186 design();
187 const int nCh = std::min(buffer.getNumChannels(), channels_);
188 const int nS = buffer.getNumSamples();
189 const double distance = static_cast<double>(distance_.load(std::memory_order_relaxed));
190 const double distanceStep = (distance - distanceNow_) / static_cast<double>(std::max(nS, 1));
191 const int mask = size_ - 1;
192 for (int i = 0; i < nS; ++i)
193 {
194 const double d = distanceNow_ + distanceStep * static_cast<double>(i + 1);
195 // Energy of the reflections, so the level stays as they come in.
196 const double norm = 1.0 / std::sqrt(1.0 + d * d * kTapEnergy);
197 for (int ch = 0; ch < nCh; ++ch)
198 {
199 T* data = buffer.getChannel(ch);
200 T* direct = lines_.data() + static_cast<size_t>(ch) * 3u * static_cast<size_t>(size_);
201 T* first = direct + size_;
202 T* second = first + size_;
203 const double x = static_cast<double>(data[i]);
204 const double y = cascade_->processSample(std::isfinite(x) ? x : 0.0, ch);
205 direct[pos_] = static_cast<T>(y);
206
207 double reflections = 0.0;
208 for (int k = 0; k < kTaps; ++k)
209 reflections += kTapGain[k] * static_cast<double>(direct[(pos_ - tapDelay_[static_cast<size_t>(k)]) & mask]);
210
211 // Two Schroeder allpasses: v = x + g w(n - D); out = w(n - D) - g v.
212 const double late1 = static_cast<double>(first[(pos_ - diffuserDelay_[0]) & mask]);
213 const double v1 = reflections + kDiffuserGain[0] * late1;
214 first[pos_] = static_cast<T>(v1);
215 const double a1 = late1 - kDiffuserGain[0] * v1;
216 const double late2 = static_cast<double>(second[(pos_ - diffuserDelay_[1]) & mask]);
217 const double v2 = a1 + kDiffuserGain[1] * late2;
218 second[pos_] = static_cast<T>(v2);
219 const double a2 = late2 - kDiffuserGain[1] * v2;
220
221 data[i] = static_cast<T>((y + d * a2) * norm);
222 }
223 cascade_->advanceRamps(1);
224 pos_ = (pos_ + 1) & mask;
225 }
226 distanceNow_ = distance;
227 }
228
229private:
231
232 // Reflections of the box: times (ms) and gains, alternating in sign.
233 static constexpr double kTapMs[kTaps] = { 0.29, 0.71, 1.13, 1.87, 2.63, 3.41 };
234 static constexpr double kTapGain[kTaps] = { 0.45, -0.32, 0.25, -0.18, 0.12, -0.08 };
235 static constexpr double kTapEnergy = 0.45 * 0.45 + 0.32 * 0.32 + 0.25 * 0.25 + 0.18 * 0.18 + 0.12 * 0.12 + 0.08 * 0.08;
236 static constexpr double kDiffuserMs[2] = { 1.31, 2.27 };
237 static constexpr double kDiffuserGain[2] = { 0.5, 0.4 };
238
240 void design() noexcept
241 {
242 const double resonance = getResonanceHz();
243 const double rollOff = std::min(getRollOffHz(), 0.45 * fs_);
244 AnalogCascade parts[4] = {
245 FilterDesign::lowCut(resonance, 12.0, 1.4),
246 FilterDesign::bell(450.0, 1.0, -2.0, 1),
247 FilterDesign::bell(0.62 * rollOff, 1.5, 4.0, 1),
248 FilterDesign::highCut(rollOff, 24.0),
249 };
250 BiquadCoeffs sections[kSections];
251 int count = 0;
252 for (const AnalogCascade& part : parts)
253 count += FilterDesign::digital(part, fit_, sections + count, kSections - count);
254 const int ramp = settled_ ? rampSamples_ : 0;
255 for (int s = 0; s < kSections; ++s)
256 cascade_->rampCoeffs(s, s < count ? sections[s] : BiquadCoeffs {}, ramp);
257 settled_ = true;
258 }
259
260 std::atomic<T> sizeParam_ { T(0.5) };
261 std::atomic<T> brightness_ { T(0.5) };
262 std::atomic<T> distance_ { T(0.3) };
263 std::atomic<bool> dirty_ { true };
264
265 // Audio thread.
266 std::unique_ptr<Cascade> cascade_;
267 FilterDesign::Band fit_;
268 std::array<int, kTaps> tapDelay_ {};
269 std::array<int, 2> diffuserDelay_ {};
270 std::vector<T> lines_;
271 double fs_ = 48000.0;
272 double distanceNow_ = 0.3;
273 int channels_ = 0;
274 int size_ = 1;
275 int pos_ = 0;
276 int rampSamples_ = 960;
277 bool settled_ = false;
278};
279
280} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Up to MaxSections second-order sections in series, run in one pass.
A loudspeaker cabinet: colour filters, sparse reflections and two diffusers, with no latency.
void reset() noexcept
Clears the filters and the reflections (settings are kept).
void writeState(StateWriter &w, const char *prefix) const
Writes the settings under keys that start with a prefix.
void prepare(double sampleRate, int numChannels)
Prepares the model for a sample rate and a channel count, and clears it. Invalid values are ignored....
void setBrightness(T brightness) noexcept
Brightness of the speaker, 0 to 1: the roll-off from 3 kHz (0) up to 7 kHz (1), with the breakup peak...
void readState(const StateReader &r, const char *prefix) noexcept
Reads what writeState() wrote (missing keys read as the defaults).
double getResonanceHz() const noexcept
The cone's resonance for the size set, in hertz.
void processBlock(AudioBufferView< T > buffer) noexcept
Runs a block in place. Channels beyond the prepared count pass through.
static constexpr int kTaps
Reflections of the box.
double getRollOffHz() const noexcept
The roll-off corner for the brightness set, in hertz.
void setSize(T size) noexcept
Size of the box, 0 to 1: the cone's resonance from 140 Hz (0) down to 70 Hz (1). Default 0....
T getSize() const noexcept
static constexpr int kSections
Sections of the colour filters.
void setDistance(T distance) noexcept
Distance of the microphone, 0 to 1: how much of the box's reflections comes with the direct sound (0:...
T getBrightness() const noexcept
T getDistance() const noexcept
void prepare(double sampleRate) noexcept
Sets the sample rate (an invalid one leaves 48 kHz).
static AnalogCascade bell(double hz, double q, double gainDb, double order) noexcept
Bell of any order: the higher the order, the flatter the top and the steeper the sides (6 dB per octa...
static AnalogCascade highCut(double hz, double slopeDbPerOctave, double q=kButterworthQ) noexcept
High cut (low-pass) of any slope from 0 to 96 dB per octave.
static AnalogCascade lowCut(double hz, double slopeDbPerOctave, double q=kButterworthQ) noexcept
Low cut (high-pass) of any slope from 0 to 96 dB per octave: highCut() mirrored about the corner.
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
Serializes key/value parameters into a versioned blob.
Definition StateBlob.h:53
void write(const char *key, float value)
Writes a float parameter.
Definition StateBlob.h:71
Main namespace for the DSPark framework.