DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
KeyEqualizer.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
62#include "Biquad.h"
63#include "BiquadCascade.h"
64#include "DspMath.h"
65#include "FilterDesign.h"
66#include "StateBlob.h"
67
68#include <algorithm>
69#include <array>
70#include <atomic>
71#include <cmath>
72#include <cstdint>
73#include <cstdio>
74#include <memory>
75#include <new>
76
77namespace dspark {
78
88template <FloatType T, int MaxChannels = 16>
90{
91public:
92 static constexpr int kBands = 6;
93 static constexpr int kBandSections = 5;
94 static constexpr int kSections = kBands * kBandSections;
95 static constexpr double kRampSeconds = 0.02;
96 static constexpr double kStretchSeconds = 1.0 / 1500.0;
97
99 enum class Shape
100 {
101 Off,
102 LowCut,
103 HighCut,
104 Bell,
105 LowShelf,
106 HighShelf,
107 Tilt
108 };
109
111 enum class Placement
112 {
113 Stereo,
114 Mid,
115 Side
116 };
117
119 struct Band
120 {
122 T frequency = T(1000);
123 T gainDb = T(0);
124 T q = T(0.7071);
125 T slope = T(12);
128 };
129
134 struct Response
135 {
136 std::array<BiquadCoeffs, kSections> sections {};
137 int count = 0;
138 double sampleRate = 48000.0;
139
141 [[nodiscard]] double magnitudeDb(double hz) const noexcept
142 {
144 }
145 };
146
147 // -- Setup ------------------------------------------------------------------
148
158 void prepare(double sampleRate) noexcept
159 {
160 if (!std::isfinite(sampleRate) || !(sampleRate > 0.0)) return;
161 for (Bank& bank : bank_)
162 if (!bank.cascade) bank.cascade.reset(new (std::nothrow) Cascade());
163 if (!bank_[0].cascade || !bank_[1].cascade) return;
164 for (Bank& bank : bank_) clear(bank);
165 fit_.prepare(sampleRate);
166 sampleRate_.store(sampleRate, std::memory_order_relaxed);
167 rampSamples_ = std::max(1, static_cast<int>(kRampSeconds * sampleRate));
168 stretch_ = std::max(8, static_cast<int>(std::lround(kStretchSeconds * sampleRate)));
169 fadeStep_ = 1.0 / static_cast<double>(rampSamples_);
170 for (Glide& g : glide_) g.moving = false;
171 count_.fill(0);
172 phase_.fill(0);
173 live_ = 0;
174 stretchLeft_ = stretch_;
175 fade_ = 0.0;
176 settled_ = false;
177 gliding_ = false;
178 changing_ = false;
179 waiting_ = false;
180 active_ = false;
181 placed_ = false;
182 inParts_ = false;
183 compSnap_ = true;
184 dirty_.store(true, std::memory_order_release);
185 }
186
193 void reset() noexcept
194 {
195 if (!bank_[0].cascade || !bank_[1].cascade) return;
196 if (changing_) finishChange();
197 for (Bank& bank : bank_) bank.cascade->reset();
198 compNow_ = compTarget_;
199 compLeft_ = 0;
200 }
201
202 // -- Settings (any thread) --------------------------------------------------
203
214 void setBand(int band, const Band& settings) noexcept
215 {
216 if (band < 0 || band >= kBands) return;
217 Published& p = published_[static_cast<size_t>(band)];
218 p.shape.store(std::clamp(static_cast<int>(settings.shape), 0, static_cast<int>(Shape::Tilt)),
219 std::memory_order_relaxed);
220 p.placement.store(std::clamp(static_cast<int>(settings.placement), 0, static_cast<int>(Placement::Side)),
221 std::memory_order_relaxed);
222 if (std::isfinite(settings.frequency) && settings.frequency > T(0))
223 p.frequency.store(std::clamp(settings.frequency, T(10), T(40000)), std::memory_order_relaxed);
224 if (std::isfinite(settings.gainDb))
225 p.gainDb.store(std::clamp(settings.gainDb, T(-24), T(24)), std::memory_order_relaxed);
226 if (std::isfinite(settings.q))
227 p.q.store(std::clamp(settings.q, T(0.1), T(20)), std::memory_order_relaxed);
228 if (std::isfinite(settings.slope))
229 p.slope.store(std::clamp(settings.slope, T(-48), T(48)), std::memory_order_relaxed);
230 dirty_.store(true, std::memory_order_release);
231 }
232
234 [[nodiscard]] Band getBand(int band) const noexcept
235 {
236 Band out;
237 if (band < 0 || band >= kBands) return out;
238 const Published& p = published_[static_cast<size_t>(band)];
239 out.shape = static_cast<Shape>(p.shape.load(std::memory_order_relaxed));
240 out.frequency = p.frequency.load(std::memory_order_relaxed);
241 out.gainDb = p.gainDb.load(std::memory_order_relaxed);
242 out.q = p.q.load(std::memory_order_relaxed);
243 out.slope = p.slope.load(std::memory_order_relaxed);
244 out.placement = static_cast<Placement>(p.placement.load(std::memory_order_relaxed));
245 return out;
246 }
247
249 [[nodiscard]] bool hasBands() const noexcept
250 {
251 for (const Published& p : published_)
252 if (p.shape.load(std::memory_order_relaxed) != static_cast<int>(Shape::Off)) return true;
253 return false;
254 }
255
267 [[nodiscard]] Response getResponse(Placement part = Placement::Stereo) const noexcept
268 {
269 Response out;
270 out.sampleRate = sampleRate_.load(std::memory_order_relaxed);
271 const FilterDesign::Band fit(out.sampleRate);
272 for (int b = 0; b < kBands; ++b)
273 {
274 const Band band = getBand(b);
275 if (part != Placement::Stereo && band.placement != Placement::Stereo && band.placement != part) continue;
276 out.count += design(band, fit, out.sections.data() + out.count, false);
277 }
278 return out;
279 }
280
287 void setLoudnessCompensation(bool on) noexcept
288 {
289 loudnessComp_.store(on, std::memory_order_relaxed);
290 dirty_.store(true, std::memory_order_release);
291 }
292
294 [[nodiscard]] bool getLoudnessCompensation() const noexcept { return loudnessComp_.load(std::memory_order_relaxed); }
295
297 [[nodiscard]] double getCompensationDb() const noexcept { return compensationDb_.load(std::memory_order_relaxed); }
298
304 void writeState(StateWriter& w, const char* prefix) const
305 {
306 char key[64];
307 for (int b = 0; b < kBands; ++b)
308 {
309 const Band band = getBand(b);
310 std::snprintf(key, sizeof(key), "%s%d.shape", prefix, b);
311 w.write(key, static_cast<int32_t>(band.shape));
312 std::snprintf(key, sizeof(key), "%s%d.freq", prefix, b);
313 w.write(key, static_cast<float>(band.frequency));
314 std::snprintf(key, sizeof(key), "%s%d.gain", prefix, b);
315 w.write(key, static_cast<float>(band.gainDb));
316 std::snprintf(key, sizeof(key), "%s%d.q", prefix, b);
317 w.write(key, static_cast<float>(band.q));
318 std::snprintf(key, sizeof(key), "%s%d.slope", prefix, b);
319 w.write(key, static_cast<float>(band.slope));
320 std::snprintf(key, sizeof(key), "%s%d.place", prefix, b);
321 w.write(key, static_cast<int32_t>(band.placement));
322 }
323 std::snprintf(key, sizeof(key), "%sloudness", prefix);
325 }
326
329 void readState(const StateReader& r, const char* prefix) noexcept
330 {
331 char key[64];
332 for (int b = 0; b < kBands; ++b)
333 {
334 Band band;
335 std::snprintf(key, sizeof(key), "%s%d.shape", prefix, b);
336 band.shape = static_cast<Shape>(std::clamp(static_cast<int>(r.read(key, int32_t(0))), 0,
337 static_cast<int>(Shape::Tilt)));
338 std::snprintf(key, sizeof(key), "%s%d.freq", prefix, b);
339 band.frequency = static_cast<T>(r.read(key, 1000.0f));
340 std::snprintf(key, sizeof(key), "%s%d.gain", prefix, b);
341 band.gainDb = static_cast<T>(r.read(key, 0.0f));
342 std::snprintf(key, sizeof(key), "%s%d.q", prefix, b);
343 band.q = static_cast<T>(r.read(key, 0.7071f));
344 std::snprintf(key, sizeof(key), "%s%d.slope", prefix, b);
345 band.slope = static_cast<T>(r.read(key, 12.0f));
346 std::snprintf(key, sizeof(key), "%s%d.place", prefix, b);
347 band.placement = static_cast<Placement>(std::clamp(static_cast<int>(r.read(key, int32_t(0))), 0,
348 static_cast<int>(Placement::Side)));
349 setBand(b, band);
350 }
351 std::snprintf(key, sizeof(key), "%sloudness", prefix);
352 setLoudnessCompensation(r.read(key, false));
353 }
354
355 // -- Audio thread -----------------------------------------------------------
356
361 bool sync() noexcept
362 {
363 if (!bank_[0].cascade || !bank_[1].cascade) return false;
364 if (dirty_.load(std::memory_order_relaxed) && dirty_.exchange(false, std::memory_order_acquire))
365 {
366 apply();
367 refreshCompensation();
368 }
369 return active_;
370 }
371
374 [[nodiscard]] bool isActive() const noexcept { return active_; }
375
378 [[nodiscard]] bool isPlaced() const noexcept { return placed_; }
379
382 [[nodiscard]] int getStretch() const noexcept { return stretch_; }
383
395 [[nodiscard]] T processSample(T input, int channel) noexcept
396 {
397 if (!active_) return input;
398 return static_cast<T>(run(static_cast<double>(input), channel, Placement::Stereo) * compNow_);
399 }
400
418 void processFrame(T* frame, int channels) noexcept
419 {
420 if (!active_) return;
421 const int nCh = std::min(channels, MaxChannels);
422 const bool parts = nCh == 2 && placed_;
423 if (parts != inParts_) turn(parts);
424 if (parts)
425 {
426 const double left = static_cast<double>(frame[0]), right = static_cast<double>(frame[1]);
427 const double mid = run(0.5 * (left + right), 0, Placement::Mid);
428 const double side = run(0.5 * (left - right), 1, Placement::Side);
429 frame[0] = static_cast<T>((mid + side) * compNow_);
430 frame[1] = static_cast<T>((mid - side) * compNow_);
431 return;
432 }
433 const Placement part = nCh == 1 ? Placement::Mid : Placement::Stereo;
434 for (int ch = 0; ch < nCh; ++ch)
435 frame[ch] = static_cast<T>(run(static_cast<double>(frame[ch]), ch, part) * compNow_);
436 }
437
444 void advance(int samples) noexcept
445 {
446 if (!active_ || samples <= 0) return;
447 if (compLeft_ > 0)
448 {
449 const int n = std::min(samples, compLeft_);
450 compLeft_ -= n;
451 compNow_ = compLeft_ == 0 ? compTarget_ : compNow_ + compStep_ * static_cast<double>(n);
452 }
453 Cascade& live = *bank_[static_cast<size_t>(live_)].cascade;
454 if (live.isRamping()) live.advanceRamps(samples);
455 if (gliding_)
456 {
457 stretchLeft_ -= samples;
458 if (stretchLeft_ <= 0) nextStretch();
459 }
460 if (changing_)
461 {
462 fade_ += fadeStep_ * static_cast<double>(samples);
463 phase_.fill(0);
464 if (fade_ >= 1.0) finishChange();
465 }
466 }
467
468private:
470
471 struct Published
472 {
473 std::atomic<int> shape { 0 };
474 std::atomic<int> placement { 0 };
475 std::atomic<T> frequency { T(1000) };
476 std::atomic<T> gainDb { T(0) };
477 std::atomic<T> q { T(0.7071) };
478 std::atomic<T> slope { T(12) };
479 };
480
482 struct Bank
483 {
484 std::unique_ptr<Cascade> cascade;
485 std::uint64_t midOnly = 0;
486 std::uint64_t sideOnly = 0;
487 bool any = false;
488 };
489
491 struct Glide
492 {
493 Band from {}, to {};
494 int left = 0;
495 bool moving = false;
496 };
497
505 [[nodiscard]] static int design(const Band& band, const FilterDesign::Band& fit, BiquadCoeffs* out,
506 bool keepFlat) noexcept
507 {
508 const double hz = std::clamp(static_cast<double>(band.frequency), 10.0, 0.45 * fit.getSampleRate());
509 const double gainDb = static_cast<double>(band.gainDb);
510 const double q = static_cast<double>(band.q);
511 const double slope = static_cast<double>(band.slope);
512 const double steep = std::clamp(std::abs(slope), 6.0, 48.0);
513 const int shelfOrder = std::clamp(static_cast<int>(std::lround(std::abs(slope) / 6.0)), 1, 4);
514 const bool shaped = keepFlat || std::abs(gainDb) >= 1e-6;
515
516 AnalogCascade proto;
517 switch (band.shape)
518 {
519 case Shape::LowCut: proto = FilterDesign::lowCut(hz, steep, q); break;
520 case Shape::HighCut: proto = FilterDesign::highCut(hz, steep, q); break;
521 case Shape::Bell: if (shaped) proto = FilterDesign::bell(hz, q, gainDb, 1); break;
522 case Shape::LowShelf: if (shaped) proto = FilterDesign::lowShelf(hz, gainDb, shelfOrder); break;
523 case Shape::HighShelf: if (shaped) proto = FilterDesign::highShelf(hz, gainDb, shelfOrder); break;
524 case Shape::Tilt: proto = FilterDesign::tilt(hz, std::clamp(slope, -6.0, 6.0)); break;
525 case Shape::Off: break;
526 }
527 return FilterDesign::digital(proto, fit, out, kBandSections);
528 }
529
531 [[nodiscard]] static bool same(const Band& a, const Band& b) noexcept
532 {
533 return a.shape == b.shape && a.placement == b.placement && a.frequency == b.frequency
534 && a.gainDb == b.gainDb && a.q == b.q && a.slope == b.slope;
535 }
536
542 [[nodiscard]] static Band between(const Band& from, const Band& to, double p) noexcept
543 {
544 if (p >= 1.0) return to;
545 const auto geometric = [p](T a, T b) {
546 const double la = std::log(static_cast<double>(a)), lb = std::log(static_cast<double>(b));
547 return static_cast<T>(std::exp(la + (lb - la) * p));
548 };
549 const auto linear = [p](T a, T b) {
550 return static_cast<T>(static_cast<double>(a) + (static_cast<double>(b) - static_cast<double>(a)) * p);
551 };
552 Band at = to;
553 at.frequency = geometric(from.frequency, to.frequency);
554 at.q = geometric(from.q, to.q);
555 at.gainDb = linear(from.gainDb, to.gainDb);
556 at.slope = linear(from.slope, to.slope);
557 return at;
558 }
559
561 static void clear(Bank& bank) noexcept
562 {
563 bank.cascade->setNumSections(kSections);
564 for (int s = 0; s < kSections; ++s)
565 {
566 bank.cascade->setCoeffs(s, BiquadCoeffs {});
567 bank.cascade->setSectionEnabled(s, false);
568 }
569 bank.cascade->reset();
570 bank.midOnly = 0;
571 bank.sideOnly = 0;
572 bank.any = false;
573 }
574
577 void build(Bank& bank, const std::array<Band, kBands>& bands, std::array<int, kBands>& counts) noexcept
578 {
579 bank.midOnly = 0;
580 bank.sideOnly = 0;
581 bank.any = false;
582 for (int b = 0; b < kBands; ++b)
583 {
584 const Band& band = bands[static_cast<size_t>(b)];
585 BiquadCoeffs sections[kBandSections];
586 const int count = design(band, fit_, sections, false);
587 counts[static_cast<size_t>(b)] = count;
588 for (int j = 0; j < kBandSections; ++j)
589 {
590 const int s = b * kBandSections + j;
591 if (j < count)
592 {
593 bank.cascade->setCoeffs(s, sections[j]);
594 bank.cascade->setSectionEnabled(s, true);
595 const std::uint64_t bit = std::uint64_t { 1 } << s;
596 if (band.placement == Placement::Mid) bank.midOnly |= bit;
597 if (band.placement == Placement::Side) bank.sideOnly |= bit;
598 bank.any = true;
599 }
600 else
601 {
602 bank.cascade->setSectionEnabled(s, false);
603 }
604 }
605 }
606 bank.cascade->reset();
607 }
608
623 void refreshCompensation() noexcept
624 {
625 double target = 1.0;
626 const double fs = sampleRate_.load(std::memory_order_relaxed);
627 if (loudnessComp_.load(std::memory_order_relaxed))
628 {
629 constexpr int kPoints = 96;
630 const Response r = getResponse(Placement::Stereo);
631 const BiquadCoeffs shelf = BiquadCoeffs::makeHighShelf(fs, 1681.974450955533, 3.999843853973347);
632 const BiquadCoeffs low = BiquadCoeffs::makeHighPass(fs, 38.13547087602444, 0.5003270373238773);
633 const double top = std::min(20000.0, 0.45 * fs);
634 double num = 0.0, den = 0.0;
635 for (int i = 0; i < kPoints; ++i)
636 {
637 const double hz = 20.0 * std::pow(top / 20.0, static_cast<double>(i) / (kPoints - 1));
638 const double k = shelf.getMagnitude(hz, fs) * low.getMagnitude(hz, fs);
639 const double w = k * k, g = std::pow(10.0, r.magnitudeDb(hz) / 10.0);
640 num += w * g;
641 den += w;
642 }
643 if (num > 0.0 && den > 0.0) target = std::sqrt(den / num);
644 }
645 compensationDb_.store(20.0 * std::log10(target), std::memory_order_relaxed);
646 if (compSnap_)
647 {
648 compSnap_ = false;
649 compTarget_ = compNow_ = target;
650 compLeft_ = 0;
651 return;
652 }
653 if (target == compTarget_) return;
654 compTarget_ = target;
655 const int ramp = std::max(1, static_cast<int>(0.05 * fs));
656 compStep_ = (compTarget_ - compNow_) / static_cast<double>(ramp);
657 compLeft_ = ramp;
658 }
659
660 void apply() noexcept
661 {
662 if (changing_) { waiting_ = true; return; }
663
664 std::array<Band, kBands> wanted;
665 for (int b = 0; b < kBands; ++b) wanted[static_cast<size_t>(b)] = getBand(b);
666
667 Bank& live = bank_[static_cast<size_t>(live_)];
668 if (!settled_)
669 {
670 build(live, wanted, count_);
671 goal_ = wanted;
672 settled_ = true;
673 refresh();
674 return;
675 }
676
677 bool sameForm = true;
678 for (int b = 0; b < kBands && sameForm; ++b)
679 {
680 const auto index = static_cast<size_t>(b);
681 const Band& now = goal_[index];
682 const Band& next = wanted[index];
683 if (same(now, next)) continue;
684 BiquadCoeffs sections[kBandSections];
685 sameForm = next.shape == now.shape && next.placement == now.placement
686 && design(next, fit_, sections, false) == count_[index];
687 }
688 if (!sameForm) { startChange(wanted); return; }
689
690 // Since the last design: a glide that starts now starts from here.
691 const int elapsed = stretch_ - stretchLeft_;
692 bool started = false;
693 for (int b = 0; b < kBands; ++b)
694 {
695 const auto index = static_cast<size_t>(b);
696 if (same(goal_[index], wanted[index]) || count_[index] == 0)
697 {
698 goal_[index] = wanted[index];
699 continue;
700 }
701 Glide& g = glide_[index];
702 g.from = g.moving ? between(g.from, g.to, progress(g, elapsed)) : goal_[index];
703 g.to = wanted[index];
704 g.left = rampSamples_ + elapsed;
705 g.moving = true;
706 goal_[index] = wanted[index];
707 started = true;
708 }
709 if (started)
710 {
711 gliding_ = true;
712 nextStretch();
713 }
714 }
715
717 [[nodiscard]] double progress(const Glide& g, int elapsed) const noexcept
718 {
719 return std::clamp(1.0 - static_cast<double>(g.left - elapsed) / static_cast<double>(rampSamples_), 0.0, 1.0);
720 }
721
727 void nextStretch() noexcept
728 {
729 const int elapsed = stretch_ - stretchLeft_;
730 stretchLeft_ = stretch_;
731 Cascade& live = *bank_[static_cast<size_t>(live_)].cascade;
732 bool any = false, lost = false;
733 for (int b = 0; b < kBands; ++b)
734 {
735 const auto index = static_cast<size_t>(b);
736 Glide& g = glide_[index];
737 if (!g.moving) continue;
738 g.left -= elapsed;
739 const int after = g.left - stretch_;
740 const double p = after > 0 ? 1.0 - static_cast<double>(after) / static_cast<double>(rampSamples_) : 1.0;
741 BiquadCoeffs sections[kBandSections];
742 const int count = design(between(g.from, g.to, p), fit_, sections, true);
743 if (count != count_[index])
744 {
745 // The form changed on the way (a tilt through 0 dB per octave).
746 g.moving = false;
747 lost = true;
748 continue;
749 }
750 const int length = std::max(1, std::min(stretch_, g.left));
751 for (int j = 0; j < count; ++j)
752 live.rampCoeffs(b * kBandSections + j, sections[j], length);
753 if (after > 0) any = true;
754 else g.moving = false;
755 }
756 gliding_ = any;
757 if (lost && !changing_) startChange(goal_);
758 }
759
768 void startChange(const std::array<Band, kBands>& wanted) noexcept
769 {
770 Bank& next = bank_[static_cast<size_t>(1 - live_)];
771 build(next, wanted, count_);
772 goal_ = wanted;
773 for (Glide& g : glide_) g.moving = false;
774 gliding_ = false;
775 phase_.fill(0);
776 fade_ = 0.0;
777 changing_ = true;
778 refresh();
779 }
780
782 void finishChange() noexcept
783 {
784 clear(bank_[static_cast<size_t>(live_)]);
785 live_ = 1 - live_;
786 changing_ = false;
787 fade_ = 0.0;
788 stretchLeft_ = stretch_;
789 refresh();
790 if (waiting_)
791 {
792 waiting_ = false;
793 dirty_.store(true, std::memory_order_release);
794 }
795 }
796
797 void refresh() noexcept
798 {
799 const Bank& live = bank_[static_cast<size_t>(live_)];
800 const Bank& next = bank_[static_cast<size_t>(1 - live_)];
801 active_ = live.any || changing_;
802 placed_ = (live.midOnly | live.sideOnly) != 0 || (changing_ && (next.midOnly | next.sideOnly) != 0);
803 }
804
810 void turn(bool parts) noexcept
811 {
812 for (Bank& bank : bank_) bank.cascade->turnPairMemory(0, 1, !parts);
813 inParts_ = parts;
814 }
815
817 [[nodiscard]] static std::uint64_t leftOut(const Bank& bank, Placement part) noexcept
818 {
819 return part == Placement::Mid ? bank.sideOnly : (part == Placement::Side ? bank.midOnly : 0);
820 }
821
824 [[nodiscard]] double run(double x, int channel, Placement part) noexcept
825 {
826 Bank& live = bank_[static_cast<size_t>(live_)];
827 const double out = live.any ? live.cascade->processSample(x, channel, leftOut(live, part)) : x;
828 if (!changing_) return out;
829
830 Bank& next = bank_[static_cast<size_t>(1 - live_)];
831 int& at = phase_[static_cast<size_t>(channel)];
832 const double w = std::min(1.0, fade_ + fadeStep_ * static_cast<double>(at));
833 ++at;
834 const double in = w * x;
835 const double entering = next.any ? next.cascade->processSample(in, channel, leftOut(next, part)) : in;
836 return (1.0 - w) * out + entering;
837 }
838
839 std::array<Published, kBands> published_ {};
840 std::atomic<bool> dirty_ { true };
841 std::atomic<double> sampleRate_ { 48000.0 };
842 std::atomic<bool> loudnessComp_ { false };
843 std::atomic<double> compensationDb_ { 0.0 };
844 double compTarget_ = 1.0, compNow_ = 1.0, compStep_ = 0.0;
845 int compLeft_ = 0;
846 bool compSnap_ = true;
847
848 // Audio thread.
849 std::array<Bank, 2> bank_ {};
850 FilterDesign::Band fit_;
851 std::array<Band, kBands> goal_ {};
852 std::array<int, kBands> count_ {};
853 std::array<Glide, kBands> glide_ {};
854 std::array<int, MaxChannels> phase_ {};
855 int live_ = 0;
856 int rampSamples_ = 960;
857 int stretch_ = 32;
858 int stretchLeft_ = 32;
859 double fade_ = 0.0, fadeStep_ = 1.0 / 960.0;
860 bool settled_ = false;
861 bool gliding_ = false;
862 bool changing_ = false;
863 bool waiting_ = false;
864 bool active_ = false;
865 bool placed_ = false;
866 bool inParts_ = false;
867};
868
890template <FloatType T, int MaxChannels = 16>
892{
893public:
894 static constexpr double kCeiling = 1.0;
895 static constexpr double kReleaseSeconds = 0.1;
896
902 void prepare(double sampleRate, int maxDelaySamples) noexcept
903 {
904 if (!std::isfinite(sampleRate) || !(sampleRate > 0.0)) return;
905 release_ = std::exp(-1.0 / (kReleaseSeconds * sampleRate));
906 int n = 1;
907 while (n < std::max(1, maxDelaySamples) + 1 && n < (1 << 24)) n <<= 1;
908 lines_.reset(new (std::nothrow) T[static_cast<size_t>(n) * static_cast<size_t>(MaxChannels)]);
909 size_ = lines_ ? n : 0;
910 reset();
911 }
912
914 void reset() noexcept
915 {
916 if (lines_) std::fill_n(lines_.get(), static_cast<size_t>(size_) * static_cast<size_t>(MaxChannels), T(0));
917 pos_ = 0;
918 peak_ = 0.0;
919 }
920
928 void processFrame(T* frame, int channels, int delay) noexcept
929 {
930 const int nCh = std::min(channels, MaxChannels);
931 double top = 0.0;
932 if (size_ > 0)
933 {
934 const int d = std::clamp(delay, 0, size_ - 1);
935 for (int ch = 0; ch < nCh; ++ch)
936 {
937 T* line = lines_.get() + static_cast<size_t>(ch) * static_cast<size_t>(size_);
938 line[pos_] = frame[ch];
939 frame[ch] = line[(pos_ - d) & (size_ - 1)];
940 }
941 pos_ = (pos_ + 1) & (size_ - 1);
942 }
943 for (int ch = 0; ch < nCh; ++ch) top = std::max(top, std::abs(static_cast<double>(frame[ch])));
944 peak_ = std::max(top, peak_ * release_);
945 if (peak_ > kCeiling)
946 {
947 const T gain = static_cast<T>(kCeiling / peak_);
948 for (int ch = 0; ch < nCh; ++ch) frame[ch] *= gain;
949 }
950 }
951
952private:
953 std::unique_ptr<T[]> lines_;
954 int size_ = 0, pos_ = 0;
955 double release_ = 0.999, peak_ = 0.0;
956};
957
958} // namespace dspark
Up to MaxSections second-order sections in series, run in one pass.
void advanceRamps(int samples) noexcept
Moves every ramp on by a number of samples (for processSample() callers).
bool isRamping(int section) const noexcept
Whether a section's coefficients are moving.
The frequencies a design is fitted over at one sample rate.
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 BiquadCoeffs digital(const AnalogSection &section, const Band &band) noexcept
The biquad whose magnitude follows an analog section up to Nyquist.
static AnalogCascade highShelf(double hz, double gainDb, double order, double q=kButterworthQ) noexcept
High shelf of any order: lowShelf() mirrored about the corner.
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.
static AnalogCascade lowShelf(double hz, double gainDb, double order, double q=kButterworthQ) noexcept
Low shelf of any order from 1, whole or not: gainDb below the corner, half of it (in decibels) at the...
static double magnitudeDb(const BiquadCoeffs *sections, int n, double hz, double sampleRate) noexcept
Magnitude in decibels of n digital sections in series at a frequency.
static AnalogCascade tilt(double pivotHz, double slopeDbPerOctave) noexcept
Tilt: the same slope across the whole band, 0 dB at the pivot.
Six bands of cuts, bells, shelves and tilts over the key of a dynamics processor.
void setLoudnessCompensation(bool on) noexcept
Keeps the loudness (off by default): the bands' change of the K-weighted level of pink noise (as BS....
bool getLoudnessCompensation() const noexcept
void writeState(StateWriter &w, const char *prefix) const
Writes the bands under keys that start with a prefix ("<prefix><band>.shape", ".freq",...
bool isActive() const noexcept
Whether any section is in the path: processSample() and processFrame() do nothing otherwise.
bool sync() noexcept
Takes the settings published since the last call.
void processFrame(T *frame, int channels) noexcept
One frame of the key, every channel of it, in place.
Placement
The part of a two-channel key a band acts on (see processFrame()).
@ Mid
The middle of the pair, (L + R) / 2, alone.
@ Stereo
Both channels (default).
@ Side
The sides of the pair, (L - R) / 2, alone.
void advance(int samples) noexcept
Moves the equalizer on in time: the coefficients between two designs, the bands on the move to their ...
void reset() noexcept
Clears the memory of the filters (settings and glides are kept).
static constexpr int kSections
Response getResponse(Placement part=Placement::Stereo) const noexcept
The sections of the published bands, designed as the audio thread designs them, for a display.
static constexpr int kBands
Bands of the equalizer.
void readState(const StateReader &r, const char *prefix) noexcept
Reads the bands writeState() wrote (a band that is missing reads as Off, a placement that is missing ...
Shape
What a band does to the key.
@ LowShelf
gainDb under the frequency; slope 6 to 24 is its transition.
@ LowCut
High-pass: frequency, slope and q.
@ Tilt
The same slope across the band, 0 dB at the frequency.
@ Bell
Peak or dip: frequency, gainDb and q.
@ HighShelf
gainDb over the frequency; slope 6 to 24 is its transition.
@ HighCut
Low-pass: frequency, slope and q.
int getStretch() const noexcept
Frames between two designs of a band on the move: advance() at least this often for a glide to be fol...
static constexpr double kRampSeconds
Time a new setting takes to arrive.
double getCompensationDb() const noexcept
Band getBand(int band) const noexcept
The published settings of a band (a band out of range reads as Off).
void setBand(int band, const Band &settings) noexcept
Publishes the settings of a band.
bool hasBands() const noexcept
Whether any published band is in the path.
T processSample(T input, int channel) noexcept
One sample of one channel of the key through the equalizer.
bool isPlaced() const noexcept
Whether a band in the path is placed on the middle or on the sides: only processFrame() gives those t...
static constexpr double kStretchSeconds
A band on the move is designed again this often.
static constexpr int kBandSections
Most sections one band takes (a 48 dB per octave cut).
void prepare(double sampleRate) noexcept
Prepares the equalizer for a sample rate and clears its memory.
The key of a dynamics processor as it is listened to: late by the processor's latency and held under ...
static constexpr double kCeiling
Largest sample that goes out.
void processFrame(T *frame, int channels, int delay) noexcept
One frame: the key of every channel goes in and comes out late and under the ceiling.
static constexpr double kReleaseSeconds
Time constant of the gain's return.
void prepare(double sampleRate, int maxDelaySamples) noexcept
Sets the rate and the longest delay (allocates).
void reset() noexcept
Clears the delay and lets the gain go.
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.
static BiquadCoeffs makeHighPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
High-pass filter.
Definition Biquad.h:143
static BiquadCoeffs makeHighShelf(double sampleRate, double freq, double gainDb, double slope=1.0) noexcept
High-shelf filter.
Definition Biquad.h:447
The settings of one band.
T gainDb
Bell and shelves, -24 to +24 dB.
Placement placement
Part of a two-channel key it acts on.
T frequency
Corner, centre or pivot, in hertz.
T q
Width of the bell; resonance of a cut (0.7071 is Butterworth).
The sections of a set of bands, to draw the curve they make.
double magnitudeDb(double hz) const noexcept
Magnitude of the whole equalizer at a frequency, in decibels.
std::array< BiquadCoeffs, kSections > sections