111#include "../Core/AudioSpec.h"
112#include "../Core/AudioBuffer.h"
113#include "../Core/Biquad.h"
114#include "../Core/BiquadCascade.h"
115#include "../Core/DenormalGuard.h"
116#include "../Core/DspMath.h"
117#include "../Core/FFT.h"
118#include "../Core/FilterDesign.h"
119#include "../Core/StateBlob.h"
143template <FloatType T,
int MaxBands = 16>
202 static_assert(std::atomic<T>::is_always_lock_free,
203 "audio-thread stores must not lock");
204 static_assert(MaxBands > 0,
"an equalizer needs at least one band");
224 for (
int i = 0; i < MaxBands; ++i)
244 analog_ = std::make_unique<std::array<AnalogBand, MaxBands>>();
245 for (
int i = 0; i < MaxBands; ++i)
258 auto engine = std::make_unique<PrototypeEngine>();
268 const auto at =
static_cast<size_t>(k);
270 e.
omega[at] = 2.0 * std::numbers::pi * hz;
271 e.
cosOne[at] = std::cos(theta);
272 e.
sinOne[at] = std::sin(theta);
273 e.
cosTwo[at] = std::cos(2.0 * theta);
274 e.
sinTwo[at] = std::sin(2.0 * theta);
275 const double past = std::clamp((hz - top) / (nyquist - top), 0.0, 1.0);
276 const double fall = std::cos(0.5 * std::numbers::pi * past);
277 e.
taper[at] = fall * fall;
283 const double fall = std::cos(0.5 * std::numbers::pi * std::clamp(2.0 * away - 1.0, 0.0, 1.0));
284 e.
window[
static_cast<size_t>(m)] = fall * fall;
306 const int parts = kernel / part;
307 const size_t specLen =
static_cast<size_t>(2 * part + 2);
308 const size_t channels =
static_cast<size_t>(
lpChannels_);
311 set.assign(
static_cast<size_t>(
lpSlots_) *
static_cast<size_t>(parts) * specLen, T(0));
312 lpFdl_.assign(channels *
static_cast<size_t>(parts) * specLen, T(0));
313 lpInput_.assign(channels *
static_cast<size_t>(2 * part), T(0));
314 lpOutput_.assign(channels *
static_cast<size_t>(part), T(0));
316 lpWarm_.assign(channels *
static_cast<size_t>(2 * part), T(0));
318 lpBlockTime_.assign(
static_cast<size_t>(2 * part), T(0));
321 const int design = 2 * kernel;
322 lpWindow_.resize(
static_cast<size_t>(kernel));
323 for (
int i = 0; i < kernel; ++i)
327 const double t = 2.0 * pi<double> *
static_cast<double>(i) /
static_cast<double>(kernel);
328 lpWindow_[
static_cast<size_t>(i)] =
static_cast<T
>(
329 0.35875 - 0.48829 * std::cos(t) + 0.14128 * std::cos(2.0 * t) - 0.01168 * std::cos(3.0 * t));
331 lpMag_.assign(
static_cast<size_t>(
lpSlots_) *
static_cast<size_t>(kernel + 1), T(1));
332 lpBandPower_.assign(
static_cast<size_t>(MaxBands) *
static_cast<size_t>(kernel + 1), 1.0f);
339 lpDesignFft_ = std::make_unique<FFTReal<T>>(
static_cast<size_t>(design));
340 auto partitionFft = std::make_unique<FFTReal<T>>(
static_cast<size_t>(2 * part));
345 lpFft_ = std::move(partitionFft);
349 lpDirty_.store(
false, std::memory_order_relaxed);
384 const int gN = buffer.getNumSamples();
385 for (
int ch = 0; ch < buffer.getNumChannels(); ++ch)
387 T* d = buffer.getChannel(ch);
388 for (
int i = 0; i < gN; ++i)
389 if (!std::isfinite(d[i])) d[i] = T(0);
394 if (
configDirty_.exchange(
false, std::memory_order_acquire))
398 lpDirty_.store(
true, std::memory_order_release);
459 &&
configDirty_.exchange(
false, std::memory_order_acquire))
463 const int n =
numBands_.load(std::memory_order_relaxed);
464 for (
int i = 0; i < n; ++i)
465 bands_[i].applyParametersNow();
466 lpDirty_.store(
true, std::memory_order_release);
470 const int activeBands =
numBands_.load(std::memory_order_relaxed);
472 for (
int i = 0; i < activeBands; ++i)
474 if (!
bandEnabled_[i].load(std::memory_order_relaxed))
continue;
478 const int scope =
bandScope_[
static_cast<size_t>(i)];
479 if (scope >=
static_cast<int>(
Scope::Mid))
continue;
481 && channel != (scope ==
static_cast<int>(
Scope::Left) ? 0 : 1))
continue;
482 const int slot = scope ==
static_cast<int>(
Scope::Stereo) ? channel : 0;
486 AnalogBand& band = (*analog_)[
static_cast<size_t>(i)];
498 sample =
bands_[i].processSample(sample, slot);
510 for (
int i = 0; i < MaxBands; ++i)
515 for (
auto& band : *
analog_) band.cascade.reset();
531 void setBand(
int index, T frequency, T gainDb)
533 setBand(index, frequency, gainDb, T(0.707));
543 void setBand(
int index, T frequency, T gainDb, T q)
568 if (index < 0 || index >= MaxBands)
return;
577 if (!std::isfinite(cfg.
q)) cfg.
q = prev.
q;
583 cfg.
slope = std::clamp(cfg.
slope, T(0), T(96));
590 int currentBands =
numBands_.load(std::memory_order_relaxed);
591 if (index >= currentBands)
592 numBands_.store(index + 1, std::memory_order_relaxed);
604 int validCount = std::clamp(count, 1, MaxBands);
605 numBands_.store(validCount, std::memory_order_relaxed);
607 const T logMin = std::log(T(80));
608 const T logMax = std::log(T(16000));
610 for (
int i = 0; i < validCount; ++i)
612 T t = (validCount > 1) ?
static_cast<T
>(i) /
static_cast<T
>(validCount - 1) : T(0.5);
615 cfg.
frequency = std::exp(logMin + t * (logMax - logMin));
632 return numBands_.load(std::memory_order_relaxed);
695 structure =
static_cast<Structure>(std::clamp(
static_cast<int>(structure), 0, 1));
696 structure_.store(structure, std::memory_order_relaxed);
697 for (
auto& band :
bands_) band.setStructure(structure);
784 if (index < 0 || index >= MaxBands)
return {};
795 if (index >= 0 && index < MaxBands)
799 bandEnabled_[index].store(enabled, std::memory_order_release);
823 const int m = std::clamp(
static_cast<int>(mode), 0,
828 lpDirty_.store(
true, std::memory_order_release);
831 if (prototype != wasPrototype)
838 return filterMode_.load(std::memory_order_relaxed);
872 if (index < 0 || index >= MaxBands || !
analog_ || !
bandAnalog_[
static_cast<size_t>(index)]
874 const AnalogBand& band = (*analog_)[
static_cast<size_t>(index)];
877 const double c1 = std::cos(w), s1 = std::sin(w), c2 = std::cos(2.0 * w), s2 = std::sin(2.0 * w);
883 const double nRe = c.
b0 + c.
b1 * c1 + c.
b2 * c2, nIm = -(c.
b1 * s1 + c.
b2 * s2);
884 const double dRe = 1.0 + c.
a1 * c1 + c.
a2 * c2, dIm = -(c.
a1 * s1 + c.
a2 * s2);
885 power *= (nRe * nRe + nIm * nIm) / std::max(dRe * dRe + dIm * dIm, 1e-300);
887 return static_cast<T
>(10.0 * std::log10(std::max(power, 1e-30)));
903 std::memory_order_relaxed);
916 softMode_.store(enabled, std::memory_order_relaxed);
923 return softMode_.load(std::memory_order_relaxed);
954 magnitudeOfBands(frequencies, magnitudes, numPoints,
static_cast<int>(where));
959 void magnitudeOfBands(
const T* frequencies, T* magnitudes,
int numPoints,
int where)
const noexcept
961 for (
int i = 0; i < numPoints; ++i)
962 magnitudes[i] = T(1);
964 const int activeBands =
numBands_.load(std::memory_order_relaxed);
965 for (
int b = 0; b < activeBands; ++b)
974 for (
int i = 0; i < numPoints; ++i)
977 for (
int s = 0; s < ns; ++s)
978 mag *= st[s].getMagnitude(
static_cast<double>(frequencies[i]),
spec_.
sampleRate);
979 magnitudes[i] =
static_cast<T
>(
static_cast<double>(magnitudes[i]) * mag);
999 assert(index >= 0 && index < MaxBands);
1000 return bands_[
static_cast<std::size_t
>(std::clamp(index, 0, MaxBands - 1))];
1006 assert(index >= 0 && index < MaxBands);
1007 return bands_[
static_cast<std::size_t
>(std::clamp(index, 0, MaxBands - 1))];
1015 const int n =
numBands_.load(std::memory_order_relaxed);
1016 w.
write(
"numBands", n);
1020 w.
write(
"filterMode",
static_cast<int32_t
>(
filterMode_.load(std::memory_order_relaxed)));
1026 for (
int i = 0; i < n; ++i)
1029 std::snprintf(key,
sizeof(key),
"b%d.freq", i);
1031 std::snprintf(key,
sizeof(key),
"b%d.gain", i);
1032 w.
write(key,
static_cast<float>(cfg.
gain));
1033 std::snprintf(key,
sizeof(key),
"b%d.q", i);
1034 w.
write(key,
static_cast<float>(cfg.
q));
1035 std::snprintf(key,
sizeof(key),
"b%d.type", i);
1036 w.
write(key,
static_cast<int32_t
>(cfg.
type));
1037 std::snprintf(key,
sizeof(key),
"b%d.slope", i);
1038 w.
write(key,
static_cast<int32_t
>(std::lround(
static_cast<double>(cfg.
slope))));
1039 std::snprintf(key,
sizeof(key),
"b%d.slopeDb", i);
1041 std::snprintf(key,
sizeof(key),
"b%d.order", i);
1042 w.
write(key,
static_cast<int32_t
>(std::lround(
static_cast<double>(cfg.
order))));
1043 std::snprintf(key,
sizeof(key),
"b%d.orderReal", i);
1045 std::snprintf(key,
sizeof(key),
"b%d.on", i);
1047 std::snprintf(key,
sizeof(key),
"b%d.scope", i);
1048 w.
write(key,
static_cast<int32_t
>(cfg.
scope));
1058 const int n = std::clamp(r.
read(
"numBands", 0), 0, MaxBands);
1064 r.
read(
"filterMode",
static_cast<int32_t
>(
filterMode_.load(std::memory_order_relaxed)))));
1070 for (
int i = 0; i < n; ++i)
1073 std::snprintf(key,
sizeof(key),
"b%d.freq", i);
1075 std::snprintf(key,
sizeof(key),
"b%d.gain", i);
1076 cfg.
gain =
static_cast<T
>(r.
read(key, 0.0f));
1077 std::snprintf(key,
sizeof(key),
"b%d.q", i);
1078 cfg.
q =
static_cast<T
>(r.
read(key, 0.707f));
1079 std::snprintf(key,
sizeof(key),
"b%d.type", i);
1081 std::snprintf(key,
sizeof(key),
"b%d.slope", i);
1082 const int wholeSlope = r.
read(key, 12);
1083 std::snprintf(key,
sizeof(key),
"b%d.slopeDb", i);
1084 cfg.
slope =
static_cast<T
>(r.
read(key,
static_cast<float>(wholeSlope)));
1085 std::snprintf(key,
sizeof(key),
"b%d.order", i);
1086 const int wholeOrder = r.
read(key, 1);
1087 std::snprintf(key,
sizeof(key),
"b%d.orderReal", i);
1088 cfg.
order =
static_cast<T
>(r.
read(key,
static_cast<float>(wholeOrder)));
1089 std::snprintf(key,
sizeof(key),
"b%d.on", i);
1091 std::snprintf(key,
sizeof(key),
"b%d.scope", i);
1095 numBands_.store(n, std::memory_order_relaxed);
1108 if (
softMode_.load(std::memory_order_relaxed))
1110 const T absGain = std::abs(cfg.gain);
1111 const T maxQ = T(1) + T(8) / (absGain + T(1));
1112 q = std::min(q, maxQ);
1140 double target = 1.0;
1143 constexpr int kPoints = 96;
1145 T f[kPoints], m[kPoints];
1146 for (
int i = 0; i < kPoints; ++i)
1147 f[i] =
static_cast<T
>(20.0 * std::pow(top / 20.0,
static_cast<double>(i) / (kPoints - 1)));
1149 double num = 0.0, den = 0.0;
1150 for (
int i = 0; i < kPoints; ++i)
1152 const double hz =
static_cast<double>(f[i]);
1154 const double w = k * k, g =
static_cast<double>(m[i]);
1158 if (num > 0.0 && den > 0.0) target = std::sqrt(den / num);
1160 compensationDb_.store(
static_cast<T
>(20.0 * std::log10(target)), std::memory_order_relaxed);
1171 const int nS = buffer.getNumSamples(), nCh = buffer.getNumChannels();
1172 for (
int i = 0; i < nS; ++i)
1176 const T g =
static_cast<T
>(
compNow_);
1177 for (
int ch = 0; ch < nCh; ++ch) buffer.getChannel(ch)[i] *= g;
1183 const bool matched =
matchedBells_.load(std::memory_order_relaxed);
1184 const bool matchedOthers =
matchedFilters_.load(std::memory_order_relaxed);
1185 int activeBands =
numBands_.load(std::memory_order_relaxed);
1187 for (
int i = 0; i < activeBands; ++i)
1189 auto& filter =
bands_[i];
1200 if (
static_cast<int>(cfg.
scope) !=
bandScope_[
static_cast<size_t>(i)])
1203 bandMix_[
static_cast<size_t>(i)] = T(0);
1209 if (analog !=
bandAnalog_[
static_cast<size_t>(i)])
1212 bandMix_[
static_cast<size_t>(i)] = T(0);
1213 if (analog) (*analog_)[
static_cast<size_t>(i)].configured =
false;
1221 float freq =
static_cast<float>(cfg.
frequency);
1222 float gain =
static_cast<float>(cfg.
gain);
1223 float q =
static_cast<float>(
effectiveQ(cfg));
1225 filter.setMatchedPeak(matched);
1226 filter.setMatchedFilters(matchedOthers);
1256 q = std::max(q, 0.05);
1257 const double A = std::pow(10.0, std::abs(gainDb) / 40.0);
1258 const double denom = A + 1.0 / A;
1259 const double invS = (1.0 / (q * q) - 2.0) / denom + 1.0;
1260 if (invS <= 1.0)
return 1.0;
1261 return std::clamp(1.0 / invS, 0.0001, 1.0);
1272 double f =
static_cast<double>(cfg.frequency);
1273 double g =
static_cast<double>(cfg.gain);
1274 double q =
static_cast<double>(cfg.q);
1288 if (mf && slope >= 1.0)
1323 const double f = std::clamp(
static_cast<double>(cfg.frequency), 10.0, sr * 0.499);
1324 const T q = std::max(
effectiveQ(cfg), T(0.1));
1332 if (casc.hasFirstOrder)
1336 for (
int s = 0; s < casc.numSecondOrder; ++s)
1338 const double stageQ =
static_cast<double>(casc.qValues[s]);
1375 for (
int i = 0; i < n; ++i) sections[i] = stages[i];
1411 return static_cast<int>(std::lround(std::clamp(
static_cast<double>(cfg.slope), 6.0, 48.0)));
1429 const double f = std::clamp(
static_cast<double>(cfg.frequency), 1.0, 80000.0);
1430 const double g = std::clamp(
static_cast<double>(cfg.gain), -96.0, 96.0);
1431 const double q = std::max(
static_cast<double>(
effectiveQ(cfg)), 0.025);
1432 const double order = std::clamp(
static_cast<double>(cfg.order), 1.0,
static_cast<double>(
kMaxBandSections));
1433 const double slope =
static_cast<double>(cfg.slope);
1489 const int n = std::min(proto.
count, capacity);
1490 const double corner = std::clamp(
static_cast<double>(cfg.frequency), 1.0, 80000.0);
1491 for (
int i = 0; i < n; ++i)
1499 const double gain = std::abs(
static_cast<double>(cfg.gain));
1507 default:
return false;
1517 double distance = 1.0;
1518 if (from.type == to.type)
1520 const double f0 = std::max(
static_cast<double>(from.frequency), 1.0), f1 = std::max(
static_cast<double>(to.frequency), 1.0);
1521 const double q0 = std::max(
static_cast<double>(from.q), 0.025), q1 = std::max(
static_cast<double>(to.q), 0.025);
1522 distance = std::max({ std::abs(
static_cast<double>(to.gain) -
static_cast<double>(from.gain)) / 24.0,
1523 std::abs(
static_cast<double>(to.order) -
static_cast<double>(from.order)) / 2.0,
1524 std::abs(std::log2(f1 / f0)) / 4.0,
1525 std::abs(std::log2(q1 / q0)) / 4.0,
1526 std::abs(
static_cast<double>(to.slope) -
static_cast<double>(from.slope)) / 48.0 });
1528 const double closeness = std::max(0.0, 1.0 - distance);
1547 AnalogBand& band = (*analog_)[
static_cast<size_t>(index)];
1548 const bool soft =
softMode_.load(std::memory_order_relaxed);
1558 const int had = band.
configured ? cascade.getNumSections() : 0;
1559 const int count = std::max(had, n);
1562 const int ramp = fresh ? 0 :
rampSamples(origin, cfg);
1563 const int stretches = !fresh && !rest && !band.
resting && !band.
idle && n == had && n == band.
wanted
1579 if (!band.
configured) cascade.setNumSections(0);
1580 for (
int s = had; s < count; ++s)
1582 cascade.setSectionEnabled(s,
true);
1583 cascade.setCoeffs(s, target[s].bypassed());
1585 cascade.setNumSections(count);
1587 for (
int s = 0; s < count; ++s) cascade.setSectionEnabled(s,
true);
1588 for (
int s = 0; s < count; ++s)
1590 if (s >= n) cascade.rampToBypass(s, ramp);
1591 else cascade.rampCoeffs(s, rest ? target[s].bypassed() : target[s], ramp);
1612 if (from.type != to.type || from.order != to.order || from.slope != to.slope)
return 1;
1620 const double f0 = std::max(
static_cast<double>(from.frequency), 1.0), f1 = std::max(
static_cast<double>(to.frequency), 1.0);
1621 const double q0 = std::max(
static_cast<double>(from.q), 0.025), q1 = std::max(
static_cast<double>(to.q), 0.025);
1622 const double way = std::max({ 4.0 * std::abs(std::log2(f1 / f0)),
1623 std::abs(
static_cast<double>(to.gain) -
static_cast<double>(from.gain)) / 12.0,
1624 std::abs(std::log2(q1 / q0)) });
1625 if (!(way > 1.0))
return 1;
1626 const int count =
static_cast<int>(std::ceil(std::min(way,
static_cast<double>(
kMaxStretches))));
1634 const double f0 = std::max(
static_cast<double>(from.frequency), 1.0), f1 = std::max(
static_cast<double>(to.frequency), 1.0);
1635 const double q0 = std::max(
static_cast<double>(from.q), 0.025), q1 = std::max(
static_cast<double>(to.q), 0.025);
1636 point.
frequency =
static_cast<T
>(f0 * std::pow(f1 / f0, share));
1637 point.
q =
static_cast<T
>(q0 * std::pow(q1 / q0, share));
1638 point.
gain =
static_cast<T
>(
static_cast<double>(from.gain) + share * (
static_cast<double>(to.gain) -
static_cast<double>(from.gain)));
1646 bool last = band.stretch >= band.stretches;
1648 :
between(band.origin, band.config,
static_cast<double>(band.stretch) / band.stretches);
1651 if (n != band.wanted && !last)
1655 point = band.config;
1658 auto& cascade = band.cascade;
1659 for (
int s = 0; s < std::min(n, cascade.getNumSections()); ++s)
1660 cascade.rampCoeffs(s, target[s], band.stretchLength);
1661 band.heading = point;
1662 band.stretchLeft = band.stretchLength;
1663 if (last) band.stretches = 0;
1669 if (band.stretches <= 0)
return;
1670 band.stretchLeft -= samples;
1677 return a.frequency == b.frequency && a.gain == b.gain && a.q == b.q && a.type == b.type
1678 && a.slope == b.slope && a.order == b.order;
1684 auto& cascade = band.cascade;
1685 if (cascade.isRamping())
return;
1686 if (cascade.getNumSections() > band.wanted) cascade.setNumSections(band.wanted);
1687 if (band.resting && !band.idle)
1689 for (
int s = 0; s < band.wanted; ++s) cascade.setSectionEnabled(s,
false);
1699 AnalogBand& band = (*analog_)[
static_cast<size_t>(index)];
1701 const int total = view.getNumSamples();
1703 while (done < total)
1705 const int n = band.
stretches > 0 ? std::min(total - done, std::max(1, band.
stretchLeft)) : total - done;
1713 bands_[index].processBlock(view);
1719 (*analog_)[
static_cast<size_t>(index)].cascade.reset();
1728 return from < to ? std::min(to, from + delta) : std::max(to, from - delta);
1743 const int activeBands =
numBands_.load(std::memory_order_relaxed);
1744 const int total = buffer.getNumSamples();
1746 const bool pair = buffer.getNumChannels() >= 2;
1747 const int firstOfThePair =
static_cast<int>(
Scope::Mid);
1750 bool second =
false;
1751 for (
int i = 0; i < MaxBands; ++i)
1752 if (
bandScope_[
static_cast<size_t>(i)] >= firstOfThePair
1753 && ((i < activeBands &&
bandEnabled_[i].load(std::memory_order_relaxed))
1754 ||
bandMix_[
static_cast<size_t>(i)] != T(0)))
1757 for (
int offset = 0; offset < total; offset += slice)
1759 const int n = std::min(slice, total - offset);
1761 for (
int i = 0; i < MaxBands; ++i)
1766 for (
int i = 0; i < MaxBands; ++i)
1781 const bool on = i < activeBands &&
bandEnabled_[i].load(std::memory_order_relaxed);
1782 const T target = on ? T(1) : T(0);
1783 T& mix =
bandMix_[
static_cast<size_t>(i)];
1786 T* single[1] = {
nullptr };
1788 const int scope =
bandScope_[
static_cast<size_t>(i)];
1791 const int channel = (scope ==
static_cast<int>(
Scope::Left)
1792 || scope ==
static_cast<int>(
Scope::Mid)) ? 0 : 1;
1793 if (channel >= view.getNumChannels())
1798 single[0] = view.getChannel(channel);
1811 for (
int ch = 0; ch < nCh; ++ch)
1815 const T start = mix;
1816 for (
int ch = 0; ch < nCh; ++ch)
1820 for (
int k = 0; k < n; ++k)
1823 wet[k] = dry[k] + (wet[k] - dry[k]) * m;
1852 using Curve = std::array<double, kPrototypeBins + 1>;
1853 using Taps = std::array<T, kPrototypeTaps>;
1856 std::array<PrototypeSeen, MaxBands>
seen {};
1864 std::array<double, kPrototypeTaps>
window {};
1893 const AnalogBand& band = (*analog_)[
static_cast<size_t>(index)];
1894 auto& level = e.
bandLog[
static_cast<size_t>(index)];
1895 auto& phase = e.
bandArg[
static_cast<size_t>(index)];
1901 for (
int s = 0; s < sections; ++s)
1907 const auto at =
static_cast<size_t>(k);
1908 const double w = e.
omega[at], w2 = w * w;
1910 const double anr = a.
b0 - a.
b2 * w2, ani = a.
b1 * w;
1911 const double adr = a.
a0 - a.
a2 * w2, adi = a.
a1 * w;
1914 const double dnr = d.
b0 + d.
b1 * c1 + d.
b2 * c2, dni = -(d.
b1 * s1 + d.
b2 * s2);
1915 const double ddr = 1.0 + d.
a1 * c1 + d.
a2 * c2, ddi = -(d.
a1 * s1 + d.
a2 * s2);
1917 const double nr = anr * ddr - ani * ddi, ni = anr * ddi + ani * ddr;
1918 const double dr = adr * dnr - adi * dni, di = adr * dni + adi * dnr;
1919 const double nn = nr * nr + ni * ni, dd = dr * dr + di * di;
1922 if (!(nn > 1e-300) || !(dd > 1e-300) || !std::isfinite(nn) || !std::isfinite(dd))
continue;
1923 level[at] += 0.5 * std::log(nn / dd);
1924 phase[at] += std::atan2(ni * dr - nr * di, nr * dr + ni * di);
1941 const int activeBands =
numBands_.load(std::memory_order_relaxed);
1942 bool changed = snap;
1944 for (
int b = 0; b < MaxBands; ++b)
1946 const auto at =
static_cast<size_t>(b);
1957 want.
group =
static_cast<int>(where);
1969 if (same && !snap)
continue;
1985 e.
groupLog[
static_cast<size_t>(g)].fill(0.0);
1986 e.
groupArg[
static_cast<size_t>(g)].fill(0.0);
1987 e.
groupUsed[
static_cast<size_t>(g)] =
false;
1989 for (
int b = 0; b < MaxBands; ++b)
1993 const auto g =
static_cast<size_t>(seen.
group);
1997 e.
groupLog[g][
static_cast<size_t>(k)] += e.
bandLog[
static_cast<size_t>(b)][
static_cast<size_t>(k)];
1998 e.
groupArg[g][
static_cast<size_t>(k)] += e.
bandArg[
static_cast<size_t>(b)][
static_cast<size_t>(k)];
2010 const auto group = [&](
int g,
int k)
noexcept {
2013 const double t = e.
taper[
static_cast<size_t>(k)];
2015 return std::polar(std::exp(t * level), t * e.
groupArg[
static_cast<size_t>(g)][
static_cast<size_t>(k)]);
2017 const auto slot = [&](
int index,
bool used,
bool unity,
const auto& response)
noexcept {
2018 auto& taps = e.
to[
static_cast<size_t>(index)];
2028 const std::complex<double> c = response(k);
2029 e.
spectrum[
static_cast<size_t>(2 * k)] = c.real();
2046 taps[
static_cast<size_t>(
kPrototypeTaps - 1 - m)] =
static_cast<T
>(h[m]);
2051 slot(0, e.
groupUsed[0],
true, [&](
int k)
noexcept { return group(0, k); });
2062 const auto sum = [&](
int k)
noexcept {
return 0.5 * (group(3, k) + group(4, k)); };
2063 const auto difference = [&](
int k)
noexcept {
return 0.5 * (group(3, k) - group(4, k)); };
2065 slot(0, e.
groupUsed[0] || e.
groupUsed[1] || across,
true, [&](
int k)
noexcept { return group(0, k) * group(1, k) * sum(k); });
2066 slot(1, e.
groupUsed[0] || e.
groupUsed[2] || across,
true, [&](
int k)
noexcept { return group(0, k) * group(2, k) * sum(k); });
2067 slot(2, across,
false, [&](
int k)
noexcept {
return group(0, k) * group(2, k) * difference(k); });
2068 slot(3, across,
false, [&](
int k)
noexcept {
return group(0, k) * group(1, k) * difference(k); });
2069 slot(4, e.
groupUsed[0],
true, [&](
int k)
noexcept { return group(0, k); });
2102 const int nCh = std::min(buffer.getNumChannels(), e.
channels);
2103 const int total = buffer.getNumSamples();
2108 while (offset < total)
2115 const T share =
static_cast<T
>(1.0 -
static_cast<double>(e.
fadeLeft) /
static_cast<double>(e.
fadeLength));
2119 const auto si =
static_cast<size_t>(s), mi =
static_cast<size_t>(m);
2121 : e.
from[si][mi] + (e.
to[si][mi] - e.
from[si][mi]) * share;
2127 for (
int ch = 0; ch < nCh; ++ch)
2128 std::copy_n(buffer.getChannel(ch) + offset, n, e.
work.data() +
static_cast<size_t>(ch) * stride + history);
2130 for (
int ch = 0; ch < nCh; ++ch)
2132 const T* own = e.
work.data() +
static_cast<size_t>(ch) * stride;
2133 const T* taps = e.
now[
static_cast<size_t>(ch == 0 ? 0 : (ch == 1 ? 1 : 4))].data();
2134 T* out = buffer.getChannel(ch) + offset;
2135 for (
int j = 0; j < n; ++j)
2137 if (cross && ch < 2)
2139 const T* other = e.
work.data() +
static_cast<size_t>(1 - ch) * stride;
2140 const T* across = e.
now[
static_cast<size_t>(ch == 0 ? 2 : 3)].data();
2141 for (
int j = 0; j < n; ++j)
2146 for (
int ch = 0; ch < nCh; ++ch)
2148 T* line = e.
work.data() +
static_cast<size_t>(ch) * stride;
2149 std::copy(line + n, line + n + history, line);
2151 e.
clock +=
static_cast<unsigned>(n);
2188 const double target = 32768.0 * sampleRate / 48000.0;
2189 while (n <
kLpMaxKernel &&
static_cast<double>(n) * 1.4142135623730951 < target) n <<= 1;
2220 const int design = 2 * kernel;
2228 const int activeBands =
numBands_.load(std::memory_order_relaxed);
2229 for (
int b = 0; b < activeBands; ++b)
2236 else if (!
staged_[b].tryRead(cfg))
2241 lpDirty_.store(
true, std::memory_order_release);
2245 const auto at =
static_cast<size_t>(b);
2261 int stageCount = 0, analogCount = 0;
2266 analogCount = proto.
count;
2275 for (
int s = 0; same && s < stageCount; ++s)
2281 for (
int s = 0; same && s < analogCount; ++s)
2289 for (
int s = 0; s < stageCount; ++s) keptStages[s] = stages[s];
2290 for (
int s = 0; s < analogCount; ++s) keptProto[s] = proto.
sections[
static_cast<size_t>(s)];
2303 for (
int b = 0; b < activeBands; ++b)
2305 const auto at =
static_cast<size_t>(b);
2321 const int bins = kernel + 1;
2329 last = std::min(bins, first + perSlice);
2333 const double dw = pi<double> /
static_cast<double>(kernel);
2334 const double rc = std::cos(dw), rs = std::sin(dw);
2335 double c1 = std::cos(dw *
static_cast<double>(first));
2336 double s1 = std::sin(dw *
static_cast<double>(first));
2337 for (
int k = first; k < last; ++k)
2339 const double c2 = 2.0 * c1 * c1 - 1.0;
2340 const double s2 = 2.0 * s1 * c1;
2344 const auto at =
static_cast<size_t>(b);
2351 const double nRe = c.
b0 + c.
b1 * c1 + c.
b2 * c2;
2352 const double nIm = -(c.
b1 * s1 + c.
b2 * s2);
2353 const double dRe = 1.0 + c.
a1 * c1 + c.
a2 * c2;
2354 const double dIm = -(c.
a1 * s1 + c.
a2 * s2);
2355 const double den = dRe * dRe + dIm * dIm;
2356 power *= (den > 1e-300) ? (nRe * nRe + nIm * nIm) / den : 0.0;
2360 power *= sections[s].magnitudeSquared(omega);
2362 lpBandPower_[at *
static_cast<size_t>(bins) +
static_cast<size_t>(k)] =
2363 power > 1e-30 ?
static_cast<float>(std::min(power, 1e30)) : 0.0f;
2365 const double cn = c1 * rc - s1 * rs;
2366 s1 = s1 * rc + c1 * rs;
2377 const auto at =
static_cast<size_t>(b);
2396 const int bins = kernel + 1;
2401 const int last = std::min(bins, first + perSlice);
2402 for (
int k = first; k < last; ++k)
2405 double powers[5] = { 1.0, 1.0, 1.0, 1.0, 1.0 };
2408 const auto at =
static_cast<size_t>(b);
2411 static_cast<double>(
lpBandPower_[at *
static_cast<size_t>(bins) +
static_cast<size_t>(k)]);
2415 lpMag_[
static_cast<size_t>(k)] =
static_cast<T
>(std::sqrt(powers[0]));
2421 const double both = std::sqrt(powers[0]), left = std::sqrt(powers[1]), right = std::sqrt(powers[2]);
2422 const double sum = 0.5 * (std::sqrt(powers[3]) + std::sqrt(powers[4]));
2423 const double difference = 0.5 * (std::sqrt(powers[3]) - std::sqrt(powers[4]));
2424 const size_t stride =
static_cast<size_t>(kernel + 1), at =
static_cast<size_t>(k);
2425 lpMag_[at] =
static_cast<T
>(both * left * sum);
2426 lpMag_[stride + at] =
static_cast<T
>(both * right * sum);
2427 lpMag_[2 * stride + at] =
static_cast<T
>(both * right * difference);
2428 lpMag_[3 * stride + at] =
static_cast<T
>(both * left * difference);
2429 if (
lpSlots_ > 4)
lpMag_[4 * stride + at] =
static_cast<T
>(both);
2441 const T* response =
lpMag_.data() +
static_cast<size_t>(
lpSlot_) *
static_cast<size_t>(kernel + 1);
2442 for (
int k = 0; k <= kernel; ++k)
2443 lpDesignSpec_[
static_cast<size_t>(2 * k)] = response[
static_cast<size_t>(k)];
2449 for (
int i = 1; i < kernel; ++i)
2451 const int src = (i - kernel / 2 + design) % design;
2463 const size_t specLen =
static_cast<size_t>(2 * part + 2);
2468 const int first =
lpStep_ * perSlice;
2470 for (
int p = first; p < last; ++p)
2472 std::copy_n(
lpKernelTime_.data() +
static_cast<size_t>(p) *
static_cast<size_t>(part),
2512 if (!
lpFft_ || part <= 0 || channels <= 0
2513 ||
lpWarm_.size() <
static_cast<size_t>(channels) *
static_cast<size_t>(2 * part))
return;
2514 for (
int i = 0; i < MaxBands; ++i)
resetBand(i);
2515 for (
int ch = 0; ch < channels; ++ch)
2516 std::copy_n(
lpInput_.data() +
static_cast<size_t>(ch) *
static_cast<size_t>(2 * part), held,
2517 lpWarm_.data() +
static_cast<size_t>(ch) *
static_cast<size_t>(2 * part));
2519 for (
int at = 0; at < held; at += step)
2521 const int n = std::min(step, held - at);
2522 for (
int ch = 0; ch < channels; ++ch)
2524 lpWarm_.data() +
static_cast<size_t>(ch) *
static_cast<size_t>(2 * part) +
static_cast<size_t>(at);
2533 if (
lpDirty_.exchange(
false, std::memory_order_acquire))
2553 if (
lpDirty_.load(std::memory_order_relaxed)
2554 &&
lpDirty_.exchange(
false, std::memory_order_acquire))
2560 bool crossfade =
false;
2573 const size_t specLen =
static_cast<size_t>(2 * part + 2);
2574 const int bins = part + 1;
2576 const T invPart = T(1) /
static_cast<T
>(part);
2580 const size_t lineLen =
static_cast<size_t>(parts) * specLen;
2582 lpFft_->forward(
lpInput_.data() +
static_cast<size_t>(ch) *
static_cast<size_t>(2 * part),
2583 lpFdl_.data() +
static_cast<size_t>(ch) * lineLen +
static_cast<size_t>(
lpFdlPos_) * specLen);
2587 T* input =
lpInput_.data() +
static_cast<size_t>(ch) *
static_cast<size_t>(2 * part);
2588 T* output =
lpOutput_.data() +
static_cast<size_t>(ch) *
static_cast<size_t>(part);
2590 auto convolve = [&](
int setIndex, T* time)
noexcept {
2592 const bool placed =
lpPlaced_[
static_cast<size_t>(setIndex)];
2593 const T* kernels =
lpKernelSet_[
static_cast<size_t>(setIndex)].data();
2594 const auto add = [&](
int slot,
int from)
noexcept {
2595 const T* kernel = kernels +
static_cast<size_t>(slot) * lineLen;
2596 const T* line =
lpFdl_.data() +
static_cast<size_t>(from) * lineLen;
2597 for (
int p = 0; p < parts; ++p)
2599 const int at = (
lpFdlPos_ - p + parts) % parts;
2601 kernel +
static_cast<size_t>(p) * specLen, bins);
2606 add(!placed ? 0 : (ch == 0 ? 0 : (ch == 1 ? 1 : 4)), ch);
2607 if (placed && ch < 2) add(ch == 0 ? 2 : 3, 1 - ch);
2615 for (
int i = 0; i < part; ++i)
2618 const T newY =
lpBlockTime_[
static_cast<size_t>(part + i)];
2619 output[i] = oldY + (newY - oldY) * (
static_cast<T
>(i + 1) * invPart);
2628 std::copy_n(input + part, part, input);
2649 const int nCh = std::min(buffer.getNumChannels(),
lpChannels_);
2650 const int total = buffer.getNumSamples();
2653 while (done < total)
2655 const int seg = std::min(total - done, part -
lpFifoPos_);
2658 T* in =
lpInput_.data() +
static_cast<size_t>(ch) *
static_cast<size_t>(2 * part)
2660 const T* out =
lpOutput_.data() +
static_cast<size_t>(ch) *
static_cast<size_t>(part)
2664 T* data = buffer.getChannel(ch) + done;
2665 std::copy_n(data, seg, in);
2666 std::copy_n(out, seg, data);
2670 std::fill_n(in, seg, T(0));
2686 std::array<FilterEngine<T>, MaxBands>
bands_ {};
2713 std::atomic<unsigned>
seq { 0 };
2729 seq.fetch_add(1, std::memory_order_acq_rel);
2730 std::atomic_thread_fence(std::memory_order_release);
2731 frequency.store(c.frequency, std::memory_order_relaxed);
2732 gain.store(c.gain, std::memory_order_relaxed);
2733 q.store(c.q, std::memory_order_relaxed);
2734 type.store(
static_cast<int>(c.type), std::memory_order_relaxed);
2735 slope.store(c.slope, std::memory_order_relaxed);
2736 order.store(c.order, std::memory_order_relaxed);
2737 enabled.store(c.enabled, std::memory_order_relaxed);
2738 scope.store(
static_cast<int>(c.scope), std::memory_order_relaxed);
2739 seq.fetch_add(1, std::memory_order_release);
2757 c.frequency =
frequency.load(std::memory_order_relaxed);
2758 c.gain =
gain.load(std::memory_order_relaxed);
2759 c.q =
q.load(std::memory_order_relaxed);
2760 c.type =
static_cast<BandType>(
type.load(std::memory_order_relaxed));
2761 c.slope =
slope.load(std::memory_order_relaxed);
2762 c.order =
order.load(std::memory_order_relaxed);
2763 c.enabled =
enabled.load(std::memory_order_relaxed);
2764 c.scope =
static_cast<Scope>(
scope.load(std::memory_order_relaxed));
2791 const unsigned s0 =
seq.load(std::memory_order_acquire);
2792 if ((s0 & 1u) != 0u)
continue;
2795 std::atomic_thread_fence(std::memory_order_acquire);
2796 if (s0 ==
seq.load(std::memory_order_relaxed))
2826 s0 =
seq.load(std::memory_order_acquire);
2828 std::atomic_thread_fence(std::memory_order_acquire);
2829 s1 =
seq.load(std::memory_order_relaxed);
2830 }
while ((s0 & 1u) != 0u || s0 != s1);
2863 std::unique_ptr<std::array<AnalogBand, MaxBands>>
analog_;
2918 std::array<AnalogSection, MaxBands * AnalogCascade::kMaxSections>
lpAnalog_ {};
Non-owning view over audio channel data.
int getNumChannels() const noexcept
Returns the number of channels in this view.
T * getChannel(int ch) const noexcept
Returns a pointer to the sample data for the given channel.
AudioBufferView getSubView(int startSample, int length) const noexcept
Returns a zero-copy sub-view starting at an offset.
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).
int getNumSections() const noexcept
Number of sections in the cascade.
void processBlock(AudioBufferView< T > buffer) noexcept
Runs a block through the cascade, in place.
BiquadCoeffs getCoeffs(int section) const noexcept
The coefficients a section is using now (mid ramp, where the ramp is).
double processSample(double input, int channel) noexcept
One sample of one channel through the cascade, in double.
BiquadCoeffs getTargetCoeffs(int section) const noexcept
The coefficients a section is heading to (its own when it is not ramping).
bool isSectionEnabled(int section) const noexcept
Whether a section is computed.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Parametric multi-band EQ using cascaded biquads or FFT overlap-save convolution.
std::vector< T > lpBlockTime_
static constexpr int kPrototypeGrid
Samples between two steps of a fade of the correction.
typename FilterEngine< T >::Structure Structure
How the sections of the bands are realised (FilterEngine::Structure).
bool setState(const uint8_t *data, size_t size)
Restores bands and modes from a blob (tolerant; rejects foreign ids).
BandType
Filter type for each EQ band.
@ LowShelf
Shelf: boosts/cuts below frequency.
@ BandPass
Bandpass around frequency.
@ AllPass
Turns the phase around frequency, 180 degrees per order; the level stays.
@ Tilt
Tilt EQ: pivots spectrum around frequency.
@ LowPass
Removes frequencies above cutoff.
@ HighPassWall
Elliptic cut below frequency.
@ Peak
Parametric bell (boost/cut around frequency).
@ Notch
Narrow rejection at frequency.
@ HighShelf
Shelf: boosts/cuts above frequency.
@ HighPass
Removes frequencies below cutoff.
@ LowPassWall
Elliptic cut above frequency: flat to it, 100 dB down a quarter of an octave later.
void conditionBandsAfterLinearPhase() noexcept
Leaving LinearPhase: clears the bands and runs them over the input the engine still holds (the last w...
void processLinearPhase(AudioBufferView< T > buffer) noexcept
LinearPhase processing: any block length streams through a partition-sized FIFO, so the output is ide...
void setBand(int index, const BandConfig &config)
Configures a band with full control over all parameters. Thread-safe.
void setAnalogResponse(bool enabled) noexcept
Designs every band from its analog prototype (see the file notes).
std::array< AnalogSection, MaxBands *AnalogCascade::kMaxSections > lpAnalog_
Prototypes of the analog bands.
bool getSoftMode() const noexcept
Returns whether soft mode is enabled.
static constexpr int kLpMinPartition
static constexpr int kLpPartitionSlices
Hops spent on partition FFTs.
std::atomic< bool > configDirty_
DesignPace
How much of a design one advanceDesign() call may do.
@ Immediate
Audio thread, whole stages at once (bounded seqlock reads).
@ Setup
Setup thread, whole stages, unbounded seqlock reads.
@ Sliced
Audio thread, one bounded slice per partition hop.
static constexpr double kTiltCeilingDb
Most a constant tilt lifts its rising end (20 Hz or 20 kHz).
FilterDesign::Band designBand_
std::array< bool, MaxBands > bandAnalog_
Which engine runs each band.
void refreshPrototype(bool snap) noexcept
Brings the correction up to date with the bands as they are now, and starts its fade if anything chan...
std::atomic< bool > loudnessComp_
void settleAnalogBand(AnalogBand &band) noexcept
Once a glide has landed: dropped sections leave, and a resting band stops computing.
int lpDesignLive_
Bands that act in this design.
bool isMatchedBells() const noexcept
Returns whether Peak bands use the matched design (setMatchedBells()).
std::vector< float > lpBandPower_
Per band: its squared magnitude on the design grid.
static constexpr int kMaxBandSections
Most sections a band has.
T processSample(T input, int channel) noexcept
Processes a single sample through all enabled bands (IIR mode only).
int getLinearPhaseKernelLength() const noexcept
The prepared linear-phase kernel length in taps (0 before prepare()). Read it from the setup thread o...
std::vector< uint8_t > getState() const
Serializes bands and modes (setup/UI threads; allocates).
void setBand(int index, T frequency, T gainDb)
Configures a band with frequency and gain (Peak filter).
std::atomic< bool > lpDirty_
bool prototypeWasActive_
The last block ran in that mode.
void advanceGlide(AnalogBand &band, int samples) noexcept
Counts the samples a gliding band has played and starts its next stretch when one ends.
void reset() noexcept
Resets all filter states to zero to prevent ringing on playback start.
std::vector< T > lpInput_
static constexpr int kStretchSamples
Shortest stretch between two of them.
std::vector< T > lpWarm_
The held input the bands are run over on leaving the mode.
bool isResonantShelves() const noexcept
Returns whether the Q of a shelf can go above 0.7071 (setResonantShelves()).
std::atomic< bool > matchedBells_
Matched (de-cramped) bells by default.
std::vector< T > lpBlockTimeOld_
static BandConfig between(const BandConfig &from, const BandConfig &to, double share) noexcept
The configuration a share of the way between two: frequency and Q in octaves, gain in decibels.
void setLinearPhaseKernelLength(int taps) noexcept
Requests the linear-phase kernel length in taps.
static constexpr int kPrototypeDelay
Its centre: the latency of the mode.
std::vector< T > lpFdl_
Per channel: partitions x spectrum.
T effectiveQ(const BandConfig &cfg) const noexcept
The band Q the audio path actually uses (soft mode caps it by gain).
void runBand(int index, AudioBufferView< T > view) noexcept
One block through a band, in the engine that runs it.
static constexpr int kLpPartitionCount
Partitions per kernel.
std::array< StagedBand, MaxBands > staged_
Published band configurations. The ONLY band storage both threads reach.
void designAnalogBand(int index, const BandConfig &cfg, bool snap) noexcept
Designs a band of the analog response and starts its cascade towards the design (audio thread,...
T getAnalogBandResponse(int index, T hz) const noexcept
The response of a band of the analog response as its sections are at this moment, a glide in flight i...
std::vector< T > lpDesignSpec_
static T moveTowards(T from, T to, T delta) noexcept
bool isAnalogResponse() const noexcept
Returns whether bands are designed from their analog prototypes (setAnalogResponse()).
void prepare(const AudioSpec &spec)
Prepares all bands and allocates necessary resources for processing.
std::array< bool, 2 > lpPlaced_
Whether each kernel set is one.
static constexpr int kLpProductBudget
Products of kept curves per hop (< 1 ms).
int buildBandStages(const BandConfig &cfg, BiquadCoeffs *stages) const noexcept
Fills stages with the ACTUAL biquad cascade for a band (per-stage Butterworth Q for multi-stage LP/HP...
int buildBandSections(const BandConfig &cfg, BiquadCoeffs *sections, int capacity) const noexcept
Fills sections with the biquads a band runs, whichever engine runs it, and returns how many (up to 16...
std::vector< T > bandDry_
std::array< int, MaxBands > lpAnalogCount_
static constexpr int kLpBinBudget
Stage evaluations per hop (< 1 ms).
std::vector< T > lpOutput_
Per channel FIFOs.
static constexpr int kLpMaxKernel
std::array< bool, MaxBands > lpBandDirty_
This design computes the band's curve.
std::vector< T > lpAccum_
std::array< BiquadCoeffs, MaxBands *5 > lpStages_
FilterMode getFilterMode() const noexcept
Returns the current filter mode.
std::array< bool, MaxBands > lpBandKept_
The band's curve is that of its stored design.
bool lpDesignPlaced_
The design in flight is a matrix.
std::array< BandConfig, MaxBands > masterConfigs_
std::atomic< Structure > structure_
setStructure().
std::atomic< int > numBands_
AnalogCascade bandPrototype(const BandConfig &cfg) const noexcept
The analog prototype of a band.
void setResonantShelves(bool enabled) noexcept
Lets the Q of a shelf go above 0.7071 (off by default, where a Q above it is read as 0....
std::array< bool, MaxBands > lpBandLive_
The band acts in this design.
int getNumBands() const noexcept
Returns the number of active bands.
static constexpr double kRampSlowMs
Glide of a small move of a band of the analog response.
void getMagnitudeForFrequencyArray(const T *frequencies, T *magnitudes, int numPoints, Scope where) const noexcept
The magnitude response at one place of the stereo pair: the stereo bands and the bands placed there.
void clearLinearPhaseStream() noexcept
Clears the engine's audio history (not the kernels).
int lpDesignStages_
Sections of the bands whose curve this design computes.
FilterEngine< T > & getBandFilter(int index) noexcept
Direct access to a band's underlying FilterEngine.
static bool sameDesign(const BandConfig &a, const BandConfig &b) noexcept
Whether two configurations give the same sections (the enabled flag is not part of the design).
void setMatchedBells(bool enabled) noexcept
Switches Peak bands to the analog-matched (de-cramped) design.
static constexpr int kPrototypeGroups
One per Scope.
bool isMatchedFilters() const noexcept
Returns whether non-bell bands use the matched designs (setMatchedFilters()).
void setNumBands(int count)
Sets the number of active bands with auto-logarithmic spacing.
static constexpr double kPrototypeFadeSeconds
std::unique_ptr< FFTReal< T > > lpFft_
Partition FFT (2 x partition); gates the engine.
static constexpr int kPrototypeTaps
Length of the correction.
void processPrototype(AudioBufferView< T > buffer) noexcept
The correction over one block: every channel through its filter, and with placed bands the other chan...
void setBandEnabled(int index, bool enabled) noexcept
Enables or disables a band without changing its parameters.
static bool restsAtUnity(const BandConfig &cfg) noexcept
Whether a band does nothing as configured: a gain band within kRestDb of 0 dB.
void processMinimumPhase(AudioBufferView< T > buffer) noexcept
MinimumPhase processing, with each band's on/off state crossfaded over kBandFadeSeconds.
static constexpr int kLpSyncSteps
Bound of a synchronous design.
void advanceDesign(DesignPace pace) noexcept
Runs one bounded slice of a kernel design into the inactive set.
void setMatchedFilters(bool enabled) noexcept
Switches LowPass/HighPass, BandPass and slope-1 shelf bands to the analog-matched designs.
static constexpr double kRampFastMs
Glide of a jump.
void applyCompensation(AudioBufferView< T > &buffer) noexcept
The compensation's gain on a block (nothing at rest at unity).
static constexpr int kLpMinKernel
void designPrototype(bool snap) noexcept
Designs the correction filters from the curves of the bands and fades to them.
void prototypeBandCurves(int index) noexcept
The analog response of a band over its digital one, on the grid.
FilterMode
Filter processing mode.
@ LinearPhase
Partitioned FFT convolution (fixed latency, see getLatency()).
@ PrototypePhase
The bands from their analog prototypes plus a short correction: the phase of the analog curve,...
@ MinimumPhase
IIR biquads (zero latency, minimum phase shift). Default.
void magnitudeOfBands(const T *frequencies, T *magnitudes, int numPoints, int where) const noexcept
The product of the enabled bands: all of them (where < 0), or the stereo ones and those placed at whe...
std::unique_ptr< PrototypeEngine > prototype_
The correction of the prototype-phase mode.
bool getLoudnessCompensation() const noexcept
void setFilterMode(FilterMode mode) noexcept
Sets the filter processing mode (minimum, linear or prototype phase).
~Equalizer()=default
Non-virtual destructor to prevent vtable instantiation (zero virtual dispatch).
void resetBand(int index) noexcept
static constexpr double kBandFadeSeconds
std::atomic< bool > softMode_
void setBand(int index, T frequency, T gainDb, T q)
Configures a band with frequency, gain, and Q.
void refreshCompensation() noexcept
Translates BandConfigs into internal FilterEngine parameters safely.
std::vector< T > lpWindow_
std::vector< T > lpKernelTime_
int lpSlot_
Kernel of the design being transformed.
void setStructure(Structure structure) noexcept
Chooses how the bands' sections are realised in minimum phase.
BandConfig getBandConfig(int index) const noexcept
Returns the current configuration of a band.
static int legacySlope(const BandConfig &cfg) noexcept
The slope the cookbook engine runs: 6 to 48 dB per octave, whole.
std::array< int, MaxBands > bandScope_
Where each band acts (audio thread's copy).
static constexpr double kRestDb
A gain band closer to 0 dB than this leaves the path.
std::array< std::atomic< bool >, MaxBands > bandEnabled_
Structure getStructure() const noexcept
int resolveKernelLength(double sampleRate) const noexcept
Kernel length for a sample rate (see setLinearPhaseKernelLength()).
std::atomic< int > lpKernelRequest_
0 = automatic length.
std::unique_ptr< FFTReal< T > > lpDesignFft_
Design FFT (2 x kernel).
std::atomic< T > compensationDb_
static double shelfSlopeFromQ(double q, double gainDb) noexcept
Converts a user-facing shelf Q into the RBJ shelf slope S.
void clearPrototypeStream() noexcept
Clears what the correction remembers of the signal.
void runLinearPhaseHop() noexcept
One partition hop: schedule the design, then convolve every prepared channel (uniformly partitioned o...
static constexpr int kMaxStretches
Most designs a glide goes through.
std::vector< T * > lpWarmChannels_
void setLoudnessCompensation(bool on) noexcept
Keeps the loudness (off by default): the bands' change of the K-weighted level of pink noise (as BS....
std::array< int, MaxBands > lpStageCount_
void updateActiveFilters() noexcept
int designSections(const BandConfig &cfg, BiquadCoeffs *sections, int capacity) const noexcept
The biquads of a band of the analog response.
std::unique_ptr< std::array< AnalogBand, MaxBands > > analog_
int getLatency() const noexcept
Returns the latency in samples.
std::array< int, MaxBands > lpBandGroup_
Where each band of the design acts (0 when it acts on every channel).
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an audio buffer in-place.
static constexpr int kPrototypeSlots
Left to left, right to right, right to left, left to right, further channels.
std::array< std::vector< T >, 2 > lpKernelSet_
Partition spectra, active + incoming.
std::array< T, MaxBands > bandMix_
std::atomic< bool > analogResponse_
Every band from its analog prototype: opt-in.
int rampSamples(const BandConfig &from, const BandConfig &to) const noexcept
How long the coefficients of a band take to reach a new design: long for a small move,...
static constexpr double kPrototypeReach
Most the correction changes a level: 12 dB, in nepers.
T getCompensationDb() const noexcept
std::atomic< FilterMode > filterMode_
void processBandSlice(int i, AudioBufferView< T > view, int n, int activeBands) noexcept
One band over one slice, on the channels of its scope, with its on/off fade. For a band of the middle...
void setSoftMode(bool enabled) noexcept
Enables soft mode (anti-ringing Q reduction dynamically based on gain).
BiquadCoeffs computeBandCoeffs(const BandConfig &cfg) const noexcept
Computes single-biquad coefficients for a band (analysis/kernel).
std::vector< T > lpDesignTime_
std::atomic< bool > resonantShelves_
The Q of a shelf can go above 0.7071: opt-in.
std::atomic< bool > matchedFilters_
Matched LP/HP/BP/shelves: opt-in.
static constexpr int kPrototypeBins
The correction is designed on 129 frequencies up to Nyquist.
int lpSlots_
Kernels a set holds: 1, or the matrix of a pair (and one more for further channels).
void getMagnitudeForFrequencyArray(const T *frequencies, T *magnitudes, int numPoints) const noexcept
Computes the combined magnitude response of all enabled bands.
void finishDesignNow() noexcept
Completes a pending design now and adopts it without a crossfade (first block after prepare/reset/mod...
bool usesAnalog(const BandConfig &cfg) const noexcept
Whether a band runs with the analog response (the switch, or a band only it can make).
std::array< FilterEngine< T >, MaxBands > bands_
Scope
Where in a stereo pair a band acts.
@ Mid
The middle of the first two channels: what they share.
@ Right
The second channel only.
@ Left
The first channel only.
@ Stereo
Every channel. Default.
@ Side
Their sides: what sets them apart.
static bool prototypeCovers(const BandConfig &cfg) noexcept
Whether a band is one the correction covers: an elliptic wall is not (its digital form is itself).
const FilterEngine< T > & getBandFilter(int index) const noexcept
Const overload. Same clamping contract.
void nextStretch(AnalogBand &band) noexcept
Starts the next stretch of a glide: designs where it ends and sends the coefficients there.
static int glideStretches(const BandConfig &from, const BandConfig &to, int ramp) noexcept
In how many designs a band goes from one configuration to another: one for every quarter of an octave...
static constexpr int kEngineChannels
Channels the band engines hold.
FFT optimised for real-valued input signals (the common audio case).
void inverse(const T *freqData, T *timeData) noexcept
Inverse transform: complex frequency-domain -> real time-domain.
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).
double getHighHz() const noexcept
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 bandStop(double hz, double q, double order) noexcept
Butterworth band-stop: a null at the centre, -3 dB at the two edges hz / q apart, and a floor that wi...
static AnalogCascade allPass(double hz, double q, double order) noexcept
All-pass of any order: the magnitude stays at 1 and the phase turns 180 degrees per order around the ...
static constexpr double kButterworthQ
The Q that leaves a cut maximally flat.
static BiquadCoeffs digital(const AnalogSection §ion, const Band &band) noexcept
The biquad whose magnitude follows an analog section up to Nyquist.
static double tiltSlopeWithin(double pivotHz, double slopeDbPerOctave, double ceilingDb) noexcept
The slope a tilt can have at a pivot without lifting the end that rises (20 kHz for a positive slope,...
static AnalogCascade bandPass(double hz, double q, double order) noexcept
Butterworth band-pass: 0 dB at the centre, -3 dB at the two edges hz / q apart, 6 dB per octave on ea...
static AnalogCascade ellipticHighCut(double hz, int order=12, double rippleDb=0.05, double stopDb=100.0) noexcept
Elliptic high cut: flat to the corner within the ripple, then a wall down to the stop level.
static AnalogCascade highShelf(double hz, double gainDb, double order, double q=kButterworthQ) noexcept
High shelf of any order: lowShelf() mirrored about the corner.
static BiquadCoeffs bilinear(const AnalogSection §ion, double sampleRate, double exactHz) noexcept
The bilinear transform of a section, with one frequency mapped exactly.
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 ellipticLowCut(double hz, int order=12, double rippleDb=0.05, double stopDb=100.0) noexcept
Elliptic low cut: ellipticHighCut() 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 AnalogCascade tilt(double pivotHz, double slopeDbPerOctave) noexcept
Tilt: the same slope across the whole band, 0 dB at the pivot.
Professional multi-mode filter with cascaded biquad stages.
static CascadeInfo cascadeForSlope(int slopeDb, float userQ=0.707f) noexcept
Returns the exact Butterworth cascade (first-order flag + per-stage Q values) used internally for a g...
Structure
How each second-order section is realised (see setStructure()).
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
bool isValid() const noexcept
uint32_t processorId() const noexcept
Serializes key/value parameters into a versioned blob.
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
void write(const char *key, float value)
Writes a float parameter.
void complexMulAccum(float *DSPARK_RESTRICT accum, const float *DSPARK_RESTRICT a, const float *DSPARK_RESTRICT b, int bins) noexcept
Complex multiply-accumulate over interleaved [re, im, ...] spectra.
float dotProduct(const float *DSPARK_RESTRICT a, const float *DSPARK_RESTRICT b, int count) noexcept
Computes the dot product of two arrays.
Main namespace for the DSPark framework.
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Up to kMaxSections analog sections in series.
std::array< AnalogSection, kMaxSections > sections
void add(const AnalogSection §ion) noexcept
Appends a section (ignored once the cascade is full).
static constexpr int kMaxSections
A first or second order analog section, in radians per second: (b2 s^2 + b1 s + b0) / (a2 s^2 + a1 s ...
static AnalogSection lowShelfQ(double hz, double gainDb, double q) noexcept
Second-order low shelf by its Q: gainDb below the corner, half of it (in decibels) at the corner what...
static AnalogSection peak(double hz, double q, double gainDb) noexcept
Bell: gainDb at the centre, bandwidth hz / Q at half that gain in decibels.
static AnalogSection bandPass(double hz, double q=0.7071067811865476) noexcept
Band-pass, 0 dB at the centre.
static AnalogSection tilt(double hz, double gainDb) noexcept
First-order tilt: 0 dB at the pivot, half of gainDb down far below it and half of it up far above.
static AnalogSection notch(double hz, double q=0.7071067811865476) noexcept
Notch at the centre, 0 dB away from it.
static AnalogSection highShelfQ(double hz, double gainDb, double q) noexcept
Second-order high shelf by its Q: lowShelfQ() mirrored about the corner.
static AnalogSection lowShelf(double hz, double gainDb, double slope=1.0) noexcept
Second-order low shelf: gainDb below the corner, half of it (in decibels) at the corner.
static AnalogSection tiltSecondOrder(double hz, double gainDb, double q=0.7071067811865476) noexcept
Second-order tilt: 0 dB at the pivot, half of gainDb down far below it and half of it up far above,...
static AnalogSection highShelf(double hz, double gainDb, double slope=1.0) noexcept
Second-order high shelf: gainDb above the corner, half of it (in decibels) at the corner.
Describes the audio environment for a DSP processor.
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
int maxBlockSize
Maximum number of samples per processing block.
double sampleRate
Sample rate in Hz.
Stores normalised biquad coefficients (b0, b1, b2, a1, a2), always double.
static BiquadCoeffs makeFirstOrderHighPass(double sampleRate, double frequency) noexcept
First-order (6 dB/oct) high-pass filter.
static BiquadCoeffs makePeakMatched(double sampleRate, double freq, double Q, double gainDb) noexcept
Analog-matched ("de-cramped") peaking filter (Vicanek design).
static BiquadCoeffs makeHighPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
High-pass filter.
static BiquadCoeffs makeHighShelfMatched(double sampleRate, double freq, double gainDb) noexcept
Analog-matched Butterworth high shelf (see makeLowShelfMatched()).
static BiquadCoeffs makeBandPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Band-pass filter (constant 0 dB peak gain).
static BiquadCoeffs makeLowShelfMatched(double sampleRate, double freq, double gainDb) noexcept
Analog-matched Butterworth low shelf (Vicanek, "Matched Two-Pole Digital Shelving Filters",...
static BiquadCoeffs makePeak(double sampleRate, double freq, double Q, double gainDb) noexcept
Peak (parametric EQ) filter.
double getMagnitude(double frequency, double sampleRate) const noexcept
Evaluates magnitude response |H(f)| at a single frequency.
static BiquadCoeffs makeFirstOrderLowPass(double sampleRate, double frequency) noexcept
First-order (6 dB/oct) low-pass filter.
static BiquadCoeffs makeTilt(double sampleRate, double pivotFreq, double gainDb) noexcept
Creates a first-order tilt filter.
static BiquadCoeffs makeLowPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Low-pass filter.
static BiquadCoeffs makeBandPassMatched(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Analog-matched band-pass, 0 dB at the centre (Vicanek 2016).
static BiquadCoeffs makeLowShelf(double sampleRate, double freq, double gainDb, double slope=1.0) noexcept
Low-shelf filter.
static BiquadCoeffs makeLowPassMatched(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Analog-matched second-order low-pass (Vicanek, "Matched Second Order Digital Filters",...
static BiquadCoeffs makeHighShelf(double sampleRate, double freq, double gainDb, double slope=1.0) noexcept
High-shelf filter.
static BiquadCoeffs makeHighPassMatched(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Analog-matched second-order high-pass (Vicanek 2016).
static BiquadCoeffs makeNotch(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Notch (band-reject) filter.
One band of the analog response.
bool resting
The design is transparent (a gain band at 0 dB).
BandConfig heading
Where the coefficients are going now: config, or a design on the way to it.
int stretchLength
Samples of each.
BiquadCascade< T, kMaxBandSections, kEngineChannels > cascade
int stretches
Designs the glide in flight goes through (0: none, or its last one).
int stretch
The one being approached, from 1.
bool idle
Resting and landed: no section is computed.
bool resonant
setResonantShelves() when it was designed (it changes a shelf).
int wanted
Sections of that design (a glide can still carry more).
bool soft
Soft mode when it was designed (it changes the Q).
BandConfig origin
Where a glide in stretches set out from.
BandConfig config
What the cascade is on, or gliding to.
int stretchLeft
Samples to the one being approached.
Full configuration for a single EQ band.
Scope scope
The channels the band acts on.
T q
Q factor (0.1 = wide, 10 = narrow).
T gain
Gain in dB (Peak, Shelf, Tilt).
bool enabled
False to bypass this band.
BandType type
Filter type for this band.
T slope
Slope in dB/oct (LP/HP only): 6 to 48 in steps of 6, or any value from 0 to 96 with the analog respon...
T order
Order of a bell, shelf, notch, band-pass or all-pass, 1 to 16, whole or not (6 dB/oct each; a shelf i...
T frequency
Center/cutoff frequency in Hz.
The state of the prototype-phase mode, allocated in prepare().
std::array< Curve, MaxBands > bandArg
Analog over digital per band: level in nepers, phase in radians.
std::vector< double > spectrum
Curve sinTwo
... and z^-2.
std::array< T, kPrototypeTaps > Taps
std::array< Curve, MaxBands > bandLog
std::vector< double > time
std::array< Taps, kPrototypeSlots > to
std::array< Taps, kPrototypeSlots > now
Reversed, ready for a dot product.
std::array< bool, kPrototypeGroups > groupUsed
Curve taper
1 up to the top of the fitted band, down to 0 at Nyquist.
std::vector< T > work
Per channel: the last taps - 1 samples, then the chunk.
std::array< Taps, kPrototypeSlots > from
Curve sinOne
z^-1 on the grid ...
std::array< double, kPrototypeTaps > window
std::array< Curve, kPrototypeGroups > groupLog
std::array< Curve, kPrototypeGroups > groupArg
std::array< PrototypeSeen, MaxBands > seen
std::array< double, kPrototypeBins+1 > Curve
Curve omega
The grid, in rad/s.
unsigned clock
Free-running, so a fade does not depend on the host's blocks.
bool crossTo
Whether the matrix has terms between the channels.
What the correction of one band was designed from.
bool present
The band has a correction at all.
One band's published configuration: a seqlock over atomic words.
std::atomic< T > frequency
BandConfig read() const noexcept
Reads the band into a caller-private plain copy (readouts).
void loadWordsRelaxed(BandConfig &c) const noexcept
Relaxed copy of the six published words (no ordering of its own; the caller's fences and counter chec...
static constexpr int kSeqlockMaxAttempts
std::atomic< unsigned > seq
void publish(const BandConfig &c) noexcept
Publishes a whole band configuration (control thread only).
std::atomic< bool > enabled
bool tryRead(BandConfig &out) const noexcept
The bounded seqlock read for the AUDIO thread.
static void encode(AudioBufferView< T > buffer) noexcept
Encodes an entire stereo buffer from Left/Right to Mid/Side.
static void decode(AudioBufferView< T > buffer) noexcept
Decodes an entire stereo buffer from Mid/Side back to Left/Right.