DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
SpectralDynamicEQ.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
51#include "../Core/AudioBuffer.h"
52#include "../Core/AudioSpec.h"
53#include "../Core/DetailAnalysis.h"
54#include "../Core/DetailFilter.h"
55#include "../Core/DspMath.h"
56#include "../Core/FilterDesign.h"
57#include "../Core/SpectralFilter.h"
58#include "../Core/StateBlob.h"
59
60#include <algorithm>
61#include <array>
62#include <atomic>
63#include <cmath>
64#include <cstdint>
65#include <cstdio>
66#include <numbers>
67#include <utility>
68#include <vector>
69
70namespace dspark {
71
78template <FloatType T>
80{
81public:
82 static constexpr int kBands = 4;
83
85 enum class Shape { Off, Bell, LowShelf, HighShelf };
86
88 struct Band
89 {
91 T frequency = T(1000);
92 T q = T(1);
93 T threshold = T(-12);
94 T ratio = T(3);
95 T range = T(-12);
96 T attack = T(10);
97 T release = T(150);
98 };
99
101 void prepare(const AudioSpec& spec)
102 {
103 if (!spec.isValid()) return;
104 prepared_ = false;
105 spec_ = spec;
106 channels_ = std::min(spec.numChannels, DetailFilter<T>::kMaxChannels);
107 filter_.prepare(spec);
108 filter_.setLinked(true);
109 analysis_.setLinked(true);
110 analysis_.prepare(spec);
111 hopSeconds_ = static_cast<double>(filter_.getHopSize()) / spec.sampleRate;
112 for (auto& s : state_)
113 {
114 for (auto* v : { &s.share, &s.shareDb, &s.action, &s.attack, &s.release }) v->assign(kSize, T(0));
115 s.peak = kSilent;
116 s.active = false;
117 s.first = s.end = 0;
118 }
119 for (auto* v : { &power_, &level_, &held_, &total_ }) v->assign(kSize, T(0));
120 sum_.assign(kSize + 1, 0.0);
121 queue_.assign(kSize, 0);
122 lastDetail_ = T(-1); // the detail is taken at the first block
123 shownCurve_ = 0;
124 for (auto& d : dirty_) d.store(true, std::memory_order_release);
125 prepared_ = true;
126 }
127
129 void reset() noexcept
130 {
131 filter_.reset();
132 analysis_.reset();
133 for (auto& s : state_)
134 {
135 std::fill(s.action.begin(), s.action.end(), T(0));
136 s.peak = kSilent;
137 s.watching = 0;
138 }
139 shownCurve_ = 0;
140 }
141
143 void setBand(int index, const Band& band) noexcept
144 {
145 if (index < 0 || index >= kBands) return;
146 auto& p = published_[static_cast<size_t>(index)];
147 p.shape.store(std::clamp(static_cast<int>(band.shape), 0, 3), std::memory_order_relaxed);
148 const auto put = [](std::atomic<T>& a, T v, T lo, T hi) { if (std::isfinite(v)) a.store(std::clamp(v, lo, hi), std::memory_order_relaxed); };
149 put(p.frequency, band.frequency, T(20), T(24000));
150 put(p.q, band.q, T(0.1), T(20));
151 put(p.threshold, band.threshold, T(-60), T(0));
152 put(p.ratio, band.ratio, T(1), T(20));
153 put(p.range, band.range, T(-24), T(24));
154 put(p.attack, band.attack, T(0.5), T(500));
155 put(p.release, band.release, T(5), T(2000));
156 dirty_[static_cast<size_t>(index)].store(true, std::memory_order_release);
157 }
158
160 [[nodiscard]] Band getBand(int index) const noexcept
161 {
162 Band b;
163 if (index < 0 || index >= kBands) return b;
164 const auto& p = published_[static_cast<size_t>(index)];
165 b.shape = static_cast<Shape>(p.shape.load(std::memory_order_relaxed));
166 b.frequency = p.frequency.load(std::memory_order_relaxed);
167 b.q = p.q.load(std::memory_order_relaxed);
168 b.threshold = p.threshold.load(std::memory_order_relaxed);
169 b.ratio = p.ratio.load(std::memory_order_relaxed);
170 b.range = p.range.load(std::memory_order_relaxed);
171 b.attack = p.attack.load(std::memory_order_relaxed);
172 b.release = p.release.load(std::memory_order_relaxed);
173 return b;
174 }
175
181 void setDetail(T octaves) noexcept
182 {
183 if (std::isfinite(octaves))
184 detail_.store(std::clamp(octaves, static_cast<T>(DetailAnalysis<T>::kFinest), static_cast<T>(DetailAnalysis<T>::kWidest)), std::memory_order_relaxed);
185 }
187 [[nodiscard]] T getDetail() const noexcept { return detail_.load(std::memory_order_relaxed); }
188
197 void setTimeFocus(bool on) noexcept { timeFocus_.store(on, std::memory_order_relaxed); }
199 [[nodiscard]] bool getTimeFocus() const noexcept { return timeFocus_.load(std::memory_order_relaxed); }
200
202 [[nodiscard]] int getLatency() const noexcept { return filter_.getLatency(); }
204 [[nodiscard]] double getGain(double hz) const noexcept
205 {
206 if (total_.empty() || !(hz > 0.0)) return 0.0;
207 const double at = (kPoints - 1) * std::log(hz / 20.0) / std::log(1000.0);
208 return static_cast<double>(total_[static_cast<size_t>(std::lround(std::clamp(at, 0.0, static_cast<double>(kPoints - 1))))]);
209 }
210
214 [[nodiscard]] static double getDisplayFrequency(int point) noexcept { return SpectralReadout<T>::frequency(point); }
220 [[nodiscard]] T getDisplayGain(int point) const noexcept { return filter_.playedValue(0, point); }
222 [[nodiscard]] T getPeakGain() const noexcept { return filter_.playedExtreme(); }
223
225 void processBlock(AudioBufferView<T> buffer) noexcept { run(buffer, nullptr); }
228 {
229 run(buffer, key.getNumChannels() > 0 && key.getNumSamples() >= buffer.getNumSamples() ? &key : nullptr);
230 }
231
232 [[nodiscard]] std::vector<uint8_t> getState() const
233 {
234 StateWriter w(stateId("SDEQ"), 2);
235 w.write("detail", static_cast<float>(getDetail()));
236 w.write("timeFocus", getTimeFocus());
237 char key[32];
238 for (int i = 0; i < kBands; ++i)
239 {
240 const Band b = getBand(i);
241 const auto put = [&](const char* name, float v) { std::snprintf(key, sizeof(key), "b%d.%s", i, name); w.write(key, v); };
242 std::snprintf(key, sizeof(key), "b%d.shape", i);
243 w.write(key, static_cast<int32_t>(b.shape));
244 put("freq", static_cast<float>(b.frequency));
245 put("q", static_cast<float>(b.q));
246 put("thr", static_cast<float>(b.threshold));
247 put("ratio", static_cast<float>(b.ratio));
248 put("range", static_cast<float>(b.range));
249 put("att", static_cast<float>(b.attack));
250 put("rel", static_cast<float>(b.release));
251 }
252 return w.blob();
253 }
254
260 bool setState(const uint8_t* data, size_t size)
261 {
262 StateReader r(data, size);
263 if (!r.isValid() || r.processorId() != stateId("SDEQ")) return false;
264 const bool first = r.processorVersion() < 2;
265 double finest = 0.0;
266 char key[32];
267 for (int i = 0; i < kBands; ++i)
268 {
269 Band b;
270 const auto get = [&](const char* name, float def) { std::snprintf(key, sizeof(key), "b%d.%s", i, name); return static_cast<T>(r.read(key, def)); };
271 std::snprintf(key, sizeof(key), "b%d.shape", i);
272 b.shape = static_cast<Shape>(std::clamp(r.read(key, 0), 0, 3));
273 b.frequency = get("freq", 1000.0f);
274 b.q = get("q", 1.0f);
275 b.threshold = get("thr", -12.0f);
276 b.ratio = get("ratio", 3.0f);
277 b.range = get("range", -12.0f);
278 b.attack = get("att", 10.0f);
279 b.release = get("rel", 150.0f);
280 setBand(i, b);
281 if (!first || b.shape == Shape::Off) continue;
282 std::snprintf(key, sizeof(key), "b%d.cells", i);
283 const int cells = std::clamp(r.read(key, 32), 1, 128);
284 const double q = std::clamp(static_cast<double>(getBand(i).q), 0.1, 20.0);
285 const double band = b.shape == Shape::Bell ? 2.0 * std::asinh(0.5 / q) / std::numbers::ln2 : kShelfOctaves;
286 const double width = 2.0 * band / cells;
287 if (finest == 0.0 || width < finest) finest = width;
288 }
289 setDetail(first && finest > 0.0 ? static_cast<T>(finest) : static_cast<T>(r.read("detail", 1.0f / 12.0f)));
290 setTimeFocus(r.read("timeFocus", false));
291 return true;
292 }
293
294private:
295 static constexpr int kPoints = SpectralReadout<T>::kPoints;
296 static constexpr size_t kSize = static_cast<size_t>(kPoints);
297 static constexpr double kSilent = -200.0;
298 static constexpr double kLeastLevel = -120.0;
299 static constexpr double kShelfOctaves = 2.0;
300
301 struct Published
302 {
303 std::atomic<int> shape { 0 };
304 std::atomic<T> frequency { T(1000) }, q { T(1) }, threshold { T(-12) }, ratio { T(3) };
305 std::atomic<T> range { T(-12) }, attack { T(10) }, release { T(150) };
306 };
307
308 struct State
309 {
310 Band band {};
311 bool active = false;
312 int first = 0, end = 0;
313 std::vector<T> share, shareDb;
314 std::vector<T> action, attack, release;
315 double peak = kSilent;
316 double candidate = kSilent;
317 int watching = 0;
318 };
319
321 void redesign(int index) noexcept
322 {
323 auto& s = state_[static_cast<size_t>(index)];
324 const bool wasActive = s.active;
325 const int oldFirst = s.first, oldEnd = s.end;
326 s.band = getBand(index);
327 const Band& b = s.band;
328 s.active = b.shape != Shape::Off && std::abs(static_cast<double>(b.range)) > 1e-3;
329 s.watching = 0;
330 s.first = s.end = 0;
331 std::fill(s.share.begin(), s.share.end(), T(0));
332 if (s.active)
333 {
334 const double f0 = std::clamp(static_cast<double>(b.frequency), 20.0, 0.45 * spec_.sampleRate);
335 const double range = static_cast<double>(b.range), q = std::max(static_cast<double>(b.q), 0.025);
336 // The band's shape from its analog prototype: a bilinear design
337 // narrows toward the top of the band.
338 const AnalogSection proto = b.shape == Shape::Bell ? AnalogSection::peak(f0, q, range)
339 : b.shape == Shape::LowShelf ? AnalogSection::lowShelf(f0, range)
340 : AnalogSection::highShelf(f0, range);
341 const double attack = 0.001 * static_cast<double>(b.attack), release = 0.001 * static_cast<double>(b.release);
342 int first = -1, last = -1;
343 for (int i = 0; i < kPoints; ++i)
344 {
345 const auto u = static_cast<size_t>(i);
346 const double hz = DetailFilter<T>::frequency(i);
347 const double share = std::clamp(proto.magnitudeDb(hz) / range, 0.0, 1.0);
348 if (!(share > 0.01)) continue;
349 if (first < 0) first = i;
350 last = i;
351 s.share[u] = static_cast<T>(share);
352 s.shareDb[u] = static_cast<T>(10.0 * std::log10(share));
353 const double scale = std::sqrt(1000.0 / hz);
354 s.attack[u] = static_cast<T>(std::exp(-hopSeconds_ / std::max(1e-4, attack * scale)));
355 s.release[u] = static_cast<T>(std::exp(-hopSeconds_ / std::max(1e-3, release * scale)));
356 }
357 s.active = first >= 0;
358 if (s.active)
359 {
360 s.first = first;
361 s.end = last + 1;
362 }
363 }
364 // Each frequency keeps what the band was doing there; outside, nothing.
365 for (int i = 0; i < kPoints; ++i)
366 if (i < s.first || i >= s.end || s.share[static_cast<size_t>(i)] == T(0)) s.action[static_cast<size_t>(i)] = T(0);
367 if (!s.active) return;
368 // A span that moved has another level: a second reference listens
369 // to it for half a second, then replaces the first.
370 if (wasActive && (std::abs(s.first - oldFirst) > 1 || std::abs(s.end - oldEnd) > 1))
371 {
372 s.candidate = kSilent;
373 s.watching = std::max(1, static_cast<int>(0.5 / hopSeconds_));
374 }
375 }
376
377 void run(AudioBufferView<T>& buffer, const AudioBufferView<T>* key) noexcept
378 {
379 if (!prepared_) return;
380 const int channels = std::min(buffer.getNumChannels(), channels_);
381 if (channels <= 0) return;
382 for (int i = 0; i < kBands; ++i)
383 if (dirty_[static_cast<size_t>(i)].exchange(false, std::memory_order_acquire)) redesign(i);
384 if (const T detail = detail_.load(std::memory_order_relaxed); detail != lastDetail_)
385 {
386 lastDetail_ = detail;
387 analysis_.setWidth(static_cast<double>(detail));
388 const double points = static_cast<double>(detail) * (kPoints - 1) * std::numbers::ln2 / std::log(1000.0);
389 hold_ = std::max(1, static_cast<int>(std::lround(points / 8.0)));
390 }
391 {
392 const bool focus = timeFocus_.load(std::memory_order_relaxed);
393 analysis_.setTimeFocus(focus);
394 filter_.setHold(focus ? DetailHold::None : DetailHold::Reach);
395 }
396 filter_.processBlock(
397 buffer,
398 [&](int offset, int count) noexcept {
399 for (int ch = 0; ch < channels; ++ch)
400 {
401 const T* from = key != nullptr ? key->getChannel(std::min(ch, key->getNumChannels() - 1)) : buffer.getChannel(ch);
402 analysis_.feed(ch, from + offset, count);
403 }
404 },
405 [&](int, T* curveDb) noexcept {
406 analysis_.update(channels);
407 design(curveDb);
408 });
409 if (!filter_.isDisplayDue(shownCurve_)) return;
410 shownCurve_ = filter_.getCurveCount();
411 filter_.publishPlayed(channels);
412 }
413
419 void readLevels(int first, int end) noexcept
420 {
421 analysis_.read(0, power_.data(), first, end);
422 std::fill(level_.begin(), level_.begin() + first, T(kSilent));
423 for (int i = first; i < end; ++i)
424 level_[static_cast<size_t>(i)] = T(4.3429448190325183) * std::log(power_[static_cast<size_t>(i)] + T(1e-20));
425 std::fill(level_.begin() + end, level_.end(), T(kSilent));
426 holdLargest();
427 const int half = hold_ / 2;
428 if (half == 0) return;
429 double sum = 0.0;
430 for (size_t i = 0; i < kSize; ++i)
431 {
432 sum_[i] = sum;
433 sum += static_cast<double>(held_[i]);
434 }
435 sum_[kSize] = sum;
436 for (int i = 0; i < kPoints; ++i)
437 {
438 const int from = std::max(0, i - half), to = std::min(kPoints, i + half + 1);
439 held_[static_cast<size_t>(i)] = static_cast<T>((sum_[static_cast<size_t>(to)] - sum_[static_cast<size_t>(from)]) / (to - from));
440 }
441 }
442
444 void holdLargest() noexcept
445 {
446 if (hold_ <= kFewPoints)
447 {
448 // A few points: as many passes of three, which compilers vectorise.
449 T* from = level_.data();
450 T* to = held_.data();
451 for (int pass = 0; pass < hold_; ++pass)
452 {
453 to[0] = std::max(from[0], from[1]);
454 for (int i = 1; i < kPoints - 1; ++i) to[i] = std::max(std::max(from[i - 1], from[i]), from[i + 1]);
455 to[kPoints - 1] = std::max(from[kPoints - 2], from[kPoints - 1]);
456 std::swap(from, to);
457 }
458 if (from != held_.data()) std::copy_n(from, kPoints, held_.data());
459 return;
460 }
461 int head = 0, tail = 0, next = 0;
462 for (int i = 0; i < kPoints; ++i)
463 {
464 for (; next < kPoints && next <= i + hold_; ++next)
465 {
466 const T v = level_[static_cast<size_t>(next)];
467 while (tail > head && level_[static_cast<size_t>(queue_[static_cast<size_t>(tail - 1)])] <= v) --tail;
468 queue_[static_cast<size_t>(tail++)] = next;
469 }
470 while (queue_[static_cast<size_t>(head)] < i - hold_) ++head;
471 held_[static_cast<size_t>(i)] = level_[static_cast<size_t>(queue_[static_cast<size_t>(head)])];
472 }
473 }
474
475 static constexpr int kFewPoints = 4;
476
477 void design(T* curve) noexcept
478 {
479 std::fill(total_.begin(), total_.end(), T(0));
480 // The points the bands reach, and as far again as the hold and its
481 // smoothing read around them.
482 int first = kPoints, end = 0;
483 for (const auto& s : state_)
484 if (s.active)
485 {
486 first = std::min(first, s.first);
487 end = std::max(end, s.end);
488 }
489 if (end > first)
490 {
491 const int reach = hold_ + hold_ / 2 + 1;
492 readLevels(std::max(0, first - reach), std::min(kPoints, end + reach));
493 }
494 for (auto& s : state_)
495 {
496 if (!s.active) continue;
497 const Band& b = s.band;
498 const T* held = held_.data();
499 T top = T(-300);
500 for (int i = s.first; i < s.end; ++i) top = std::max(top, held[i] + s.shareDb[static_cast<size_t>(i)]);
501 // The band's recent peak: up at once, down by 2 dB per second.
502 const double loudest = static_cast<double>(top);
503 s.peak = loudest > s.peak ? loudest : std::max(loudest, s.peak - 2.0 * hopSeconds_);
504 if (s.watching > 0)
505 {
506 s.candidate = loudest > s.candidate ? loudest : std::max(loudest, s.candidate - 2.0 * hopSeconds_);
507 if (--s.watching == 0) s.peak = s.candidate;
508 }
509 const T threshold = static_cast<T>(std::max(s.peak + static_cast<double>(b.threshold), kLeastLevel));
510 const T range = std::abs(b.range);
511 const T perDb = (T(1) - T(1) / b.ratio) / range;
512 for (int i = s.first; i < s.end; ++i)
513 {
514 const auto u = static_cast<size_t>(i);
515 const T target = std::min(T(1), std::max(T(0), held[i] + s.shareDb[u] - threshold) * perDb);
516 T& a = s.action[u];
517 a = target + (target > a ? s.attack[u] : s.release[u]) * (a - target);
518 if (target == T(0) && a < T(1e-5)) a = T(0);
519 total_[u] += b.range * a * s.share[u];
520 }
521 }
522 std::copy(total_.begin(), total_.end(), curve);
523 }
524
525 AudioSpec spec_ {};
526 int channels_ = 0, hold_ = 1, shownCurve_ = 0;
527 bool prepared_ = false;
528 double hopSeconds_ = 256.0 / 48000.0;
529 T lastDetail_ = T(-1);
530 DetailFilter<T> filter_;
531 DetailAnalysis<T> analysis_;
532 std::array<Published, kBands> published_ {};
533 std::array<std::atomic<bool>, kBands> dirty_ {};
534 std::atomic<T> detail_ { T(1.0 / 12.0) };
535 std::atomic<bool> timeFocus_ { false };
536 std::array<State, kBands> state_ {};
537 std::vector<T> power_, level_, held_, total_;
538 std::vector<double> sum_;
539 std::vector<int> queue_;
540};
541
542} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Multiresolution power spectrum on the grid of SpectralReadout.
Minimum-phase filtering by a curve on a log-frequency grid, fine in the low end.
static double frequency(int point) noexcept
Dynamic equalizer bands with a level at every frequency inside each band.
bool setState(const uint8_t *data, size_t size)
Restores the settings. A blob of the first version, with cells in each band, gives as detail the widt...
T getPeakGain() const noexcept
double getGain(double hz) const noexcept
Shape
The shape of a band.
void processBlock(AudioBufferView< T > buffer, AudioBufferView< T > key) noexcept
Processes the programme in place, a key's level driving the bands.
static double getDisplayFrequency(int point) noexcept
std::vector< uint8_t > getState() const
void processBlock(AudioBufferView< T > buffer) noexcept
Processes the programme in place, its own level driving the bands.
void setTimeFocus(bool on) noexcept
Reads the levels at the top through a window that shortens as frequency rises, centred where the curv...
void prepare(const AudioSpec &spec)
Allocates for a rate and a layout (an invalid spec is ignored).
void setDetail(T octaves) noexcept
The detail: how finely the bands move inside themselves, from an octave to 1/24 of one (default 1/12)...
int getLatency() const noexcept
Band getBand(int index) const noexcept
static constexpr int kDisplayPoints
Points of the display curve, evenly in log frequency from 20 Hz to 20 kHz.
void setBand(int index, const Band &band) noexcept
Sets a band (out-of-range indices are ignored; fields are clamped).
bool getTimeFocus() const noexcept
T getDisplayGain(int point) const noexcept
static constexpr int kBands
Bands.
void reset() noexcept
Clears the analysis, the actions and the filter.
A per-bin quantity of the last frame (a gain curve, a reduction), read at fixed points for a display ...
static double frequency(int point) noexcept
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
uint16_t processorVersion() const noexcept
Definition StateBlob.h:211
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
Definition StateBlob.h:214
bool isValid() const noexcept
Definition StateBlob.h:209
uint32_t processorId() const noexcept
Definition StateBlob.h:210
Serializes key/value parameters into a versioned blob.
Definition StateBlob.h:53
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
Definition StateBlob.h:112
void write(const char *key, float value)
Writes a float parameter.
Definition StateBlob.h:71
Main namespace for the DSPark framework.
DetailHold
How a DetailFilter by the frame holds the moves of each point of its curve, over the three curves tha...
@ None
The curve as drawn: a brief move plays at part of its depth.
@ Reach
A new move for the three, then the curve as drawn: a move ends when it is drawn.
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
static AnalogSection peak(double hz, double q, double gainDb) noexcept
Bell: gainDb at the centre, bandwidth hz / Q at half that gain in decibels.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
T frequency
Centre or corner, 20 Hz to 0.45 of the rate.
T release
At 1 kHz, 5 to 2000 ms.
T q
Width of the bell, 0.1 to 20.
T range
Most action, -24 (cut) to +24 dB.
T threshold
Under the band's recent peak, -60 to 0 dB.
T attack
At 1 kHz, 0.5 to 500 ms.