DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
GraphicBank.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
49#include "AudioBuffer.h"
50#include "AuditoryBands.h"
51#include "Biquad.h"
52#include "BiquadCascade.h"
53#include "DspMath.h"
54#include "LaneCascade.h"
55
56#include <algorithm>
57#include <cmath>
58#include <complex>
59#include <vector>
60
61namespace dspark {
62
70template <FloatType T, int Lanes = 8>
72{
73public:
74 static constexpr int kMaxBands = 256;
76 static constexpr int kCarryRefinement = -1;
77
91 void prepare(double sampleRate, const double* centresHz, int bands, int channels, double qScale = 1.0,
92 const double* widthsHz = nullptr)
93 {
94 if (!std::isfinite(sampleRate) || !(sampleRate > 0.0) || centresHz == nullptr || bands < 2) return;
95 fs_ = sampleRate;
96 nb_ = std::min(bands, kMaxBands);
97 const double qs = std::clamp(qScale, 0.25, 8.0);
98 cw_.resize(static_cast<size_t>(nb_));
99 alpha_.resize(static_cast<size_t>(nb_));
100 centre_.resize(static_cast<size_t>(nb_));
101 for (int s = 0; s < nb_; ++s)
102 {
103 const double f = std::clamp(centresHz[s], 10.0, 0.49 * fs_);
104 centre_[static_cast<size_t>(s)] = f;
105 const double w = 2.0 * 3.141592653589793 * f / fs_;
106 cw_[static_cast<size_t>(s)] = std::cos(w);
107 const double width = widthsHz != nullptr && std::isfinite(widthsHz[s]) && widthsHz[s] > 0.0
108 ? widthsHz[s] : AuditoryScale::criticalBandwidth(f);
109 const double q = s == 0 || s == nb_ - 1 ? 0.0 : qs * f / width;
110 alpha_[static_cast<size_t>(s)] = (s == 0 || s == nb_ - 1) ? std::sin(w) * 0.7071067811865476
111 : std::sin(w) / (2.0 * q);
112 }
113 // The grid: the centres and the points half way between them (in log).
114 grid_ = 2 * nb_ - 1;
115 z1_.resize(static_cast<size_t>(grid_));
116 for (int g = 0; g < grid_; ++g)
117 {
118 const double f = g % 2 == 0 ? centre_[static_cast<size_t>(g / 2)]
119 : std::sqrt(centre_[static_cast<size_t>(g / 2)] * centre_[static_cast<size_t>(g / 2 + 1)]);
120 z1_[static_cast<size_t>(g)] = std::polar(1.0, -2.0 * 3.141592653589793 * f / fs_);
121 }
122 // Response in dB of each section at +1 dB on the grid, and the
123 // regularized least-squares solution P = (A'A + l I)^-1 A'.
124 std::vector<double> a(static_cast<size_t>(grid_ * nb_));
125 for (int s = 0; s < nb_; ++s)
126 {
127 const BiquadCoeffs c = sectionAt(s, 1.0);
128 for (int g = 0; g < grid_; ++g) a[static_cast<size_t>(g * nb_ + s)] = dbAt(c, g);
129 }
130 std::vector<double> m(static_cast<size_t>(nb_ * nb_), 0.0);
131 for (int i = 0; i < nb_; ++i)
132 for (int j = 0; j < nb_; ++j)
133 {
134 double acc = 0.0;
135 for (int g = 0; g < grid_; ++g) acc += weightOf(g) * a[static_cast<size_t>(g * nb_ + i)] * a[static_cast<size_t>(g * nb_ + j)];
136 m[static_cast<size_t>(i * nb_ + j)] = acc;
137 }
138 double trace = 0.0;
139 for (int i = 0; i < nb_; ++i) trace += m[static_cast<size_t>(i * nb_ + i)];
140 const double lambda = kRegularization * trace / nb_;
141 for (int i = 0; i < nb_; ++i) m[static_cast<size_t>(i * nb_ + i)] += lambda;
142 // Cholesky: m = L L'.
143 for (int j = 0; j < nb_; ++j)
144 {
145 double d = m[static_cast<size_t>(j * nb_ + j)];
146 for (int k = 0; k < j; ++k) d -= m[static_cast<size_t>(j * nb_ + k)] * m[static_cast<size_t>(j * nb_ + k)];
147 const double l = std::sqrt(std::max(d, 1e-30));
148 m[static_cast<size_t>(j * nb_ + j)] = l;
149 for (int i = j + 1; i < nb_; ++i)
150 {
151 double v = m[static_cast<size_t>(i * nb_ + j)];
152 for (int k = 0; k < j; ++k) v -= m[static_cast<size_t>(i * nb_ + k)] * m[static_cast<size_t>(j * nb_ + k)];
153 m[static_cast<size_t>(i * nb_ + j)] = v / l;
154 }
155 }
156 p_.assign(static_cast<size_t>(nb_ * grid_), 0.0);
157 std::vector<double> col(static_cast<size_t>(nb_));
158 for (int g = 0; g < grid_; ++g)
159 {
160 for (int i = 0; i < nb_; ++i) col[static_cast<size_t>(i)] = weightOf(g) * a[static_cast<size_t>(g * nb_ + i)];
161 for (int i = 0; i < nb_; ++i) // forward: L y = col
162 {
163 double v = col[static_cast<size_t>(i)];
164 for (int k = 0; k < i; ++k) v -= m[static_cast<size_t>(i * nb_ + k)] * col[static_cast<size_t>(k)];
165 col[static_cast<size_t>(i)] = v / m[static_cast<size_t>(i * nb_ + i)];
166 }
167 for (int i = nb_ - 1; i >= 0; --i) // back: L' x = y
168 {
169 double v = col[static_cast<size_t>(i)];
170 for (int k = i + 1; k < nb_; ++k) v -= m[static_cast<size_t>(k * nb_ + i)] * col[static_cast<size_t>(k)];
171 col[static_cast<size_t>(i)] = v / m[static_cast<size_t>(i * nb_ + i)];
172 }
173 for (int i = 0; i < nb_; ++i) p_[static_cast<size_t>(i * grid_ + g)] = col[static_cast<size_t>(i)];
174 }
175 target_.assign(static_cast<size_t>(grid_), 0.0);
176 response_.assign(static_cast<size_t>(grid_), 0.0);
177 gains_.assign(static_cast<size_t>(nb_), 0.0);
178 candidate_.assign(static_cast<size_t>(nb_), 0.0);
179 correction_.assign(static_cast<size_t>(nb_), 0.0);
180 useLanes_ = channels <= 1;
181 if (useLanes_)
182 {
183 lanes_.prepare(nb_, 1);
184 for (int s = 0; s < nb_; ++s) lanes_.setCoeffs(s, sectionAt(s, 0.0));
185 }
186 else
187 {
188 serial_.setNumSections(nb_);
189 for (int s = 0; s < nb_; ++s) serial_.setCoeffs(s, sectionAt(s, 0.0));
190 serial_.reset();
191 }
192 }
193
194 [[nodiscard]] int getNumBands() const noexcept { return nb_; }
195 [[nodiscard]] double getCentre(int band) const noexcept { return centre_[static_cast<size_t>(std::clamp(band, 0, nb_ - 1))]; }
197 [[nodiscard]] int getLatency() const noexcept { return useLanes_ ? Lanes - 1 : 0; }
199 [[nodiscard]] double getSectionGain(int section) const noexcept { return gains_[static_cast<size_t>(std::clamp(section, 0, nb_ - 1))]; }
200
208 void setGains(const T* gainsDb, int rampSamples, int refine = 1) noexcept
209 {
210 if (nb_ < 2) return;
211 for (int g = 0; g < grid_; ++g)
212 {
213 const double v = g % 2 == 0 ? static_cast<double>(gainsDb[g / 2])
214 : 0.5 * (static_cast<double>(gainsDb[g / 2]) + static_cast<double>(gainsDb[g / 2 + 1]));
215 target_[static_cast<size_t>(g)] = std::isfinite(v) ? std::clamp(v, -24.0, 24.0) : 0.0;
216 }
217 solve(target_.data(), gains_.data(), false);
218 for (auto& g : gains_) g = std::clamp(g, -kMaxSectionDb, kMaxSectionDb);
219 if (refine == kCarryRefinement)
220 {
221 for (int s = 0; s < nb_; ++s)
222 gains_[static_cast<size_t>(s)] = std::clamp(gains_[static_cast<size_t>(s)] + correction_[static_cast<size_t>(s)], -kMaxSectionDb, kMaxSectionDb);
223 }
224 else
225 {
226 correction_ = gains_; // the plain solution, until the refinement is known
227 }
228 // Refining: a step on what the real response misses, kept only if it
229 // brings the response nearer (a shape the sections cannot follow,
230 // such as a zigzag from band to band, keeps the first solution).
231 const int steps = std::clamp(refine, 0, 3);
232 if (steps > 0)
233 {
234 double err = missing(gains_.data());
235 for (int r = 0; r < steps; ++r)
236 {
237 candidate_ = gains_;
238 solve(response_.data(), candidate_.data(), true);
239 for (auto& g : candidate_) g = std::clamp(g, -kMaxSectionDb, kMaxSectionDb);
240 const double next = missing(candidate_.data());
241 if (!(next < err)) break;
242 gains_ = candidate_;
243 err = next;
244 }
245 }
246 // What the refinement added to the plain solution (nothing without it).
247 if (refine != kCarryRefinement)
248 for (int s = 0; s < nb_; ++s)
249 correction_[static_cast<size_t>(s)] = gains_[static_cast<size_t>(s)] - correction_[static_cast<size_t>(s)];
250 if (useLanes_)
251 {
252 for (int s = 0; s < nb_; ++s)
253 lanes_.setTargetCoeffs(s, sectionAt(s, gains_[static_cast<size_t>(s)]));
254 lanes_.startRamp(rampSamples);
255 }
256 else
257 {
258 for (int s = 0; s < nb_; ++s)
259 serial_.rampCoeffs(s, sectionAt(s, gains_[static_cast<size_t>(s)]), rampSamples);
260 }
261 }
262
264 [[nodiscard]] double responseDb(double hz) const noexcept
265 {
266 const std::complex<double> z = std::polar(1.0, -2.0 * 3.141592653589793 * hz / fs_);
267 double db = 0.0;
268 for (int s = 0; s < nb_; ++s) db += dbOf(sectionAt(s, gains_[static_cast<size_t>(s)]), z);
269 return db;
270 }
271
273 void reset() noexcept { if (useLanes_) lanes_.reset(); else serial_.reset(); }
274
276 void processBlock(AudioBufferView<T> buffer) noexcept
277 {
278 if (useLanes_) lanes_.processBlock(buffer);
279 else serial_.processBlock(buffer);
280 // A sample that is not a number would stay in the sections for good:
281 // it leaves as silence and the sections start again from rest.
282 bool broken = false;
283 for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
284 {
285 T* d = buffer.getChannel(ch);
286 for (int i = 0; i < buffer.getNumSamples(); ++i)
287 if (!std::isfinite(d[i])) { d[i] = T(0); broken = true; }
288 }
289 if (broken) reset();
290 }
291
292private:
294 [[nodiscard]] static double weightOf(int g) noexcept { return g % 2 == 0 ? 1.0 : kMidWeight; }
295 static constexpr double kMidWeight = 0.1;
296 static constexpr double kRegularization = 1e-2;
297 static constexpr double kMaxSectionDb = 30.0;
298
300 [[nodiscard]] BiquadCoeffs sectionAt(int s, double gainDb) const noexcept
301 {
302 const double A = std::pow(10.0, gainDb / 40.0);
303 const double cw = cw_[static_cast<size_t>(s)], al = alpha_[static_cast<size_t>(s)];
304 BiquadCoeffs c;
305 if (s == 0 || s == nb_ - 1)
306 {
307 const double t = 2.0 * std::sqrt(A) * al;
308 const double sign = s == 0 ? 1.0 : -1.0; // low shelf / high shelf
309 const double a0 = (A + 1.0) + sign * (A - 1.0) * cw + t;
310 c.b0 = A * ((A + 1.0) - sign * (A - 1.0) * cw + t) / a0;
311 c.b1 = sign * 2.0 * A * ((A - 1.0) - sign * (A + 1.0) * cw) / a0;
312 c.b2 = A * ((A + 1.0) - sign * (A - 1.0) * cw - t) / a0;
313 c.a1 = -sign * 2.0 * ((A - 1.0) + sign * (A + 1.0) * cw) / a0;
314 c.a2 = ((A + 1.0) + sign * (A - 1.0) * cw - t) / a0;
315 return c;
316 }
317 const double ia = A / (A + al); // 1 / a0, a0 = 1 + alpha / A
318 c.b0 = (1.0 + al * A) * ia;
319 c.b1 = -2.0 * cw * ia;
320 c.b2 = (1.0 - al * A) * ia;
321 c.a1 = c.b1;
322 c.a2 = (A - al) / (A + al);
323 return c;
324 }
325
326 [[nodiscard]] static double dbOf(const BiquadCoeffs& c, std::complex<double> z1) noexcept
327 {
328 const std::complex<double> z2 = z1 * z1;
329 const std::complex<double> num = c.b0 + c.b1 * z1 + c.b2 * z2;
330 const std::complex<double> den = 1.0 + c.a1 * z1 + c.a2 * z2;
331 return 10.0 * std::log10(std::max(std::norm(num), 1e-30) / std::max(std::norm(den), 1e-30));
332 }
333
334 [[nodiscard]] double dbAt(const BiquadCoeffs& c, int g) const noexcept { return dbOf(c, z1_[static_cast<size_t>(g)]); }
335
340 double missing(const double* gains) noexcept
341 {
342 for (int g = 0; g < grid_; ++g) response_[static_cast<size_t>(g)] = 0.0;
343 for (int s = 0; s < nb_; ++s)
344 {
345 const BiquadCoeffs c = sectionAt(s, gains[s]);
346 for (int g = 0; g < grid_; ++g) response_[static_cast<size_t>(g)] += dbAt(c, g);
347 }
348 double err = 0.0;
349 for (int g = 0; g < grid_; ++g)
350 {
351 const double d = target_[static_cast<size_t>(g)] - response_[static_cast<size_t>(g)];
352 response_[static_cast<size_t>(g)] = d;
353 err += weightOf(g) * d * d;
354 }
355 return err;
356 }
357
359 void solve(const double* v, double* x, bool add) const noexcept
360 {
361 for (int s = 0; s < nb_; ++s)
362 {
363 double acc = 0.0;
364 const double* row = p_.data() + static_cast<size_t>(s * grid_);
365 for (int g = 0; g < grid_; ++g) acc += row[g] * v[g];
366 x[s] = add ? x[s] + acc : acc;
367 }
368 }
369
370 double fs_ = 48000.0;
371 int nb_ = 0, grid_ = 0;
372 std::vector<double> cw_, alpha_, centre_, p_, target_, response_, gains_, candidate_, correction_;
373 std::vector<std::complex<double>> z1_;
374 bool useLanes_ = true;
375 LaneCascade<T, Lanes> lanes_;
376 BiquadCascade<T, kMaxBands, 8> serial_;
377};
378
379} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
void reset() noexcept
Clears the memory of every node. Coefficients and ramps are kept.
void setCoeffs(int section, const BiquadCoeffs &c) noexcept
Makes a coefficient set a section's own from the next sample.
void setNumSections(int count) noexcept
Sets how many sections the cascade has.
void processBlock(AudioBufferView< T > buffer) noexcept
Runs a block through the cascade, in place.
void rampCoeffs(int section, const BiquadCoeffs &target, int samples) noexcept
Moves a section's five coefficients linearly to a set.
A bank of overlapping sections driven by least squares.
Definition GraphicBank.h:72
int getLatency() const noexcept
void reset() noexcept
Clears the history (the gains stay).
static constexpr int kCarryRefinement
setGains(): no refining step; the correction of the last refining call is added instead.
Definition GraphicBank.h:76
double getCentre(int band) const noexcept
void prepare(double sampleRate, const double *centresHz, int bands, int channels, double qScale=1.0, const double *widthsHz=nullptr)
Lays the bank out (allocates).
Definition GraphicBank.h:91
static constexpr int kMaxBands
Definition GraphicBank.h:74
void setGains(const T *gainsDb, int rampSamples, int refine=1) noexcept
The gains asked of the bands.
void processBlock(AudioBufferView< T > buffer) noexcept
Runs a block in place.
double responseDb(double hz) const noexcept
double getSectionGain(int section) const noexcept
int getNumBands() const noexcept
void add(float *DSPARK_RESTRICT dst, const float *DSPARK_RESTRICT src, int count) noexcept
Adds source samples into a destination buffer (no scaling).
Definition SimdOps.h:829
Main namespace for the DSPark framework.
static double criticalBandwidth(double hz) noexcept
Stores normalised biquad coefficients (b0, b1, b2, a1, a2), always double.
Definition Biquad.h:107