303 static constexpr double kTopShare = 20000.0 / 44100.0 + 1e-4;
306 explicit Band(
double sampleRate)
noexcept {
prepare(sampleRate); }
311 fs_ = (std::isfinite(sampleRate) && sampleRate > 0.0) ? sampleRate : 48000.0;
312 highHz_ = std::min(
kTopShare * fs_, std::max(20000.0, 0.42 * fs_));
313 lowHz_ = std::min(20.0, 0.01 * highHz_);
314 const double ratio = std::pow(highHz_ / lowHz_, 1.0 / (
kPoints - 1));
316 for (
int i = 0; i <
kPoints; ++i, hz *= ratio)
318 const double omega = 2.0 * std::numbers::pi * std::min(hz, highHz_);
319 omega2_[i] = omega * omega;
320 y_[i] = yOf(omega / fs_);
321 weight_[i] = weightOf(omega);
326 [[nodiscard]]
double getLowHz() const noexcept {
return lowHz_; }
327 [[nodiscard]]
double getHighHz() const noexcept {
return highHz_; }
331 double fs_ = 48000.0, lowHz_ = 20.0, highHz_ = 20000.0;
349 const double c = (exactHz > 0.0 && exactHz < 0.49 * sampleRate)
350 ? 2.0 * kPi * exactHz / std::tan(kPi * exactHz / sampleRate)
352 const double c2 = c * c;
353 const double a0 = section.a2 * c2 + section.a1 * c + section.a0;
355 if (!(std::abs(a0) > 0.0))
return out;
356 const double inverse = 1.0 / a0;
357 out.
b0 = (section.b2 * c2 + section.b1 * c + section.b0) * inverse;
358 out.
b1 = 2.0 * (section.b0 - section.b2 * c2) * inverse;
359 out.
b2 = (section.b2 * c2 - section.b1 * c + section.b0) * inverse;
360 out.
a1 = 2.0 * (section.a0 - section.a2 * c2) * inverse;
361 out.
a2 = (section.a2 * c2 - section.a1 * c + section.a0) * inverse;
387 static bool bilinearPolynomial(
const double* analogNum,
const double* analogDen,
int order,
double sampleRate,
388 double exactHz,
double* digitalNum,
double* digitalDen)
noexcept
390 if (order < 1 || order > 16 || !(sampleRate > 0.0))
return false;
391 const double c = (exactHz > 0.0 && exactHz < 0.49 * sampleRate)
392 ? 2.0 * kPi * exactHz / std::tan(kPi * exactHz / sampleRate)
394 double num[17] = {}, den[17] = {};
396 for (
int j = 0; j <= order; ++j)
399 double row[17] = { 1.0 };
400 for (
int r = 0; r < order; ++r)
402 const double sign = r < j ? -1.0 : 1.0;
403 for (
int i = r + 1; i >= 1; --i) row[i] += sign * row[i - 1];
405 for (
int i = 0; i <= order; ++i)
407 num[i] += analogNum[j] * power * row[i];
408 den[i] += analogDen[j] * power * row[i];
412 if (!(std::abs(den[0]) > 0.0))
return false;
413 const double inverse = 1.0 / den[0];
414 for (
int i = 0; i <= order; ++i)
416 digitalNum[i] = num[i] * inverse;
417 digitalDen[i] = den[i] * inverse;
436 const double fs = band.fs_;
438 if (!usable(section))
return bilinear(section, fs, section.poleFrequency());
440 const Shape shape = shapeOf(section, fs);
441 const Denominator start = invariantDenominator(section, fs);
445 if (shape.first) { out.
b0 = start.a1; out.
b1 = 1.0; out.
b2 = 0.0; }
446 else { out.
b0 = start.a2; out.
b1 = start.a1; out.
b2 = 1.0; }
447 out.
a1 = start.a1; out.
a2 = start.a2;
454 const double poleOmega = shape.first ? section.a0 / section.
a1 : std::sqrt(section.a0 / section.a2);
455 const double y0 = yOf(std::clamp(poleOmega / fs, 1e-9, kPi));
457 gather(section, shape, band, y0, x);
459 const int nN = shape.numeratorTerms(), nD = shape.denominatorTerms();
461 p[nN] = start.d1 * y0 / start.d0;
462 if (nD > 1) p[nN + 1] = start.d2 * y0 * y0 / start.d0;
466 double cost = 0.0, gap = 0.0;
469 pass(shape, x, p,
false, normal, cost, gap);
470 if (!advance(shape,
false, 1e-12, normal, p))
return bilinear(section, fs, section.poleFrequency());
471 clampNumerator(shape, x, p);
476 std::copy(p, p + 5, best);
477 double bestCost = 0.0;
478 pass(shape, x, p,
true,
nullptr, bestCost, gap);
482 for (
int i = 0; i < kFitSteps && gap > kClose; ++i)
484 pass(shape, x, p,
true, normal, cost, gap);
487 if (!(cost < bestCost))
break;
488 const bool settled = bestCost - cost < kSettled * bestCost;
489 std::copy(p, p + 5, best);
491 if (settled || !(gap > kClose))
break;
493 if (!advance(shape,
true, 1e-6, normal, p))
break;
494 if (!positive(p[nN], nD > 1 ? p[nN + 1] : 0.0, x.tMax))
break;
495 clampNumerator(shape, x, p);
498 pass(shape, x, p,
true,
nullptr, cost, gap);
499 if (cost < bestCost) std::copy(p, p + 5, best);
504 if (!assemble(shape, x, best, y0, out))
return bilinear(section, fs, section.poleFrequency());
525 const int n = std::min(cascade.count, capacity);
526 for (
int i = 0; i < n; ++i)
527 out[i] =
digital(cascade.sections[
static_cast<size_t>(i)], band);
534 return digital(cascade,
Band(sampleRate), out, capacity);
541 for (
int i = 0; i < n; ++i)
542 db += 20.0 * std::log10(std::max(sections[i].getMagnitude(hz, sampleRate), 1e-15));
576 const double omega = omegaOf(hz);
577 for (
int i = 0; i < out.
count; ++i) at(out, i) = scaled(at(out, i), omega);
585 const double omega = omegaOf(hz);
586 for (
int i = 0; i < out.
count; ++i) at(out, i) = mirrored(at(out, i), omega);
608 const double omega = omegaOf(hz);
609 for (
int i = 0; i < out.
count; ++i) at(out, i) = scaled(at(out, i), omega);
617 const double omega = omegaOf(hz);
618 for (
int i = 0; i < out.
count; ++i) at(out, i) = mirrored(at(out, i), omega);
631 [[nodiscard]]
static AnalogCascade bell(
double hz,
double q,
double gainDb,
double order)
noexcept
635 const double w0 = omegaOf(hz), width = w0 / std::clamp(q, 1e-3, 1e3);
636 for (
int i = 0; i < proto.
count; ++i)
644 const BandPair num = bandPair(s.
b1, s.
b0, width, w0), den = bandPair(s.
a1, s.
a0, width, w0);
660 return bandFilter(hz, q, order,
false);
670 return bandFilter(hz, q, order,
true);
684 const double nu = wholeOrPart(order);
685 const double w = omegaOf(hz), w2 = w * w;
686 if (nu != std::floor(nu))
694 const int pairs =
static_cast<int>(std::floor(0.5 * nu));
695 const double rest = nu - 2.0 * pairs;
696 const double sharpest =
kButterworthQ / std::clamp(q, 0.1, 100.0);
697 for (
int i = 0; i < pairs; ++i)
699 const double a1 = 2.0 * std::sin(kPi * (2 * i + 1) / (2.0 * nu)) * (i == 0 ? sharpest : 1.0) * w;
702 const double turn = std::tan(0.25 * kPi * rest);
709 const double part = rest - 1.0;
710 const double narrow = 2.0 * std::sin(kPi * (2 * pairs + 1) / (2.0 * (2 * pairs + 2)));
711 double damping = std::pow(narrow, part);
712 if (pairs == 0) damping *= std::pow(sharpest, part);
713 const double second = std::clamp(1.0 - damping / turn, 0.0, 1.0);
718 const int n =
static_cast<int>(nu);
719 for (
int i = 0; i < n / 2; ++i)
721 double damping = 2.0 * std::sin(kPi * (2 * i + 1) / (2.0 * n));
722 if (i == 0) damping *=
kButterworthQ / std::clamp(q, 0.1, 100.0);
723 const double a1 = damping * w;
743 if (!std::isfinite(slopeDbPerOctave))
return out;
744 const double order = std::clamp(slopeDbPerOctave / 6.020599913279624, -1.0, 1.0);
745 if (std::abs(order) < 1e-9)
return out;
746 const double toZero = std::pow(kLadderStep, 0.5 * (1.0 - order));
747 const double toPole = std::pow(kLadderStep, 0.5 * (1.0 + order));
748 double cell = 2.0 * kPi * 632.4555320336759 / (kLadderStep * kLadderStep * kLadderStep * kLadderStep);
749 for (
int i = 0; i < 4; ++i)
751 const double z1 = cell * toZero, p1 = cell * toPole, z2 = z1 * kLadderStep, p2 = p1 * kLadderStep;
753 1.0 / (p1 * p2), 1.0 / p1 + 1.0 / p2, 1.0));
754 cell *= kLadderStep * kLadderStep;
757 if (level > 0.0 && std::isfinite(level))
759 const double gain = 1.0 / std::sqrt(level);
761 first.
b2 *= gain; first.
b1 *= gain; first.
b0 *= gain;
776 [[nodiscard]]
static double tiltSlopeWithin(
double pivotHz,
double slopeDbPerOctave,
double ceilingDb)
noexcept
778 if (!std::isfinite(slopeDbPerOctave) || !std::isfinite(pivotHz) || !(ceilingDb > 0.0))
return slopeDbPerOctave;
779 const double pivot = std::clamp(pivotHz, 20.0, 20000.0);
780 const double octaves = slopeDbPerOctave > 0.0 ? std::log2(20000.0 / pivot) : std::log2(pivot / 20.0);
781 const double rise = std::abs(slopeDbPerOctave) * octaves;
782 return rise > ceilingDb ? slopeDbPerOctave * (ceilingDb / rise) : slopeDbPerOctave;
798 double stopDb = 100.0) noexcept
800 AnalogCascade out = ellipticPrototype(order, rippleDb, stopDb);
801 const double omega = omegaOf(hz);
802 for (
int i = 0; i < out.
count; ++i) at(out, i) = scaled(at(out, i), omega);
808 double stopDb = 100.0) noexcept
810 AnalogCascade out = ellipticPrototype(order, rippleDb, stopDb);
811 const double omega = omegaOf(hz);
812 for (
int i = 0; i < out.
count; ++i) at(out, i) = mirrored(at(out, i), omega);
821 [[nodiscard]]
static double ellipticStopRatio(
int order = 12,
double rippleDb = 0.05,
double stopDb = 100.0) noexcept
823 double ripple = 0.0, stop = 0.0;
824 return 1.0 / ellipticModulus(order, rippleDb, stopDb, ripple, stop);
828 static constexpr double kPi = std::numbers::pi;
829 static constexpr int kClusterPoints = 7;
830 static constexpr int kMaxPoints =
Band::kPoints + 2 * kClusterPoints;
831 static constexpr double kFloor = 1e-8;
832 static constexpr double kClose = 5.3e-6;
833 static constexpr double kUltrasonicHz = 3000.0;
834 static constexpr double kSettled = 0.05;
841 bool allPass =
false;
842 double cosNotch = 0.0;
846 [[nodiscard]]
int numeratorTerms() const noexcept
849 return kind == 3 ? 0 : (kind == 2 ? 1 : 2);
851 [[nodiscard]]
int denominatorTerms() const noexcept {
return first ? 1 : 2; }
857 double d0 = 1.0, d1 = 0.0, d2 = 0.0;
858 double a1 = 0.0, a2 = 0.0;
865 double t[kMaxPoints] {};
866 double m[kMaxPoints] {};
867 double weight[kMaxPoints] {};
879 [[nodiscard]]
static double weightOf(
double omega)
noexcept
881 const double over = std::max(0.0, omega * (0.5 / kPi) - 20000.0) * (1.0 / kUltrasonicHz);
882 return 1.0 / (1.0 + over * over);
886 [[nodiscard]]
static double yOf(
double w)
noexcept
888 const double s = std::sin(0.5 * w);
893 [[nodiscard]]
static double sine(
double x)
noexcept
895 constexpr double k3 = 1.0 / 6.0, k5 = 1.0 / 20.0, k7 = 1.0 / 42.0, k9 = 1.0 / 72.0;
896 constexpr double k11 = 1.0 / 110.0, k13 = 1.0 / 156.0, k15 = 1.0 / 210.0;
897 const double x2 = x * x;
898 return x * (1.0 - x2 * k3 * (1.0 - x2 * k5 * (1.0 - x2 * k7 * (1.0 - x2 * k9
899 * (1.0 - x2 * k11 * (1.0 - x2 * k13 * (1.0 - x2 * k15)))))));
902 [[nodiscard]]
static bool finite(
const AnalogSection& h)
noexcept
904 return std::isfinite(h.b2) && std::isfinite(h.b1) && std::isfinite(h.b0)
905 && std::isfinite(h.a2) && std::isfinite(h.a1) && std::isfinite(h.a0);
908 [[nodiscard]]
static bool usable(
const AnalogSection& h)
noexcept
910 if (h.b2 == 0.0 && h.b1 == 0.0 && h.b0 == 0.0)
return false;
911 if (h.isSecondOrder())
return h.a1 / h.a2 > 0.0 && h.a0 / h.a2 > 0.0;
912 return h.b2 == 0.0 && h.a1 != 0.0 && h.a0 / h.a1 > 0.0;
915 [[nodiscard]]
static Shape shapeOf(
const AnalogSection& h,
double fs)
noexcept
918 s.first = !h.isSecondOrder();
921 if (h.b0 == 0.0) s.kind = 1;
922 s.allPass = h.b1 != 0.0 && h.b1 == -h.a1 && h.b0 == h.a0;
925 if (h.b0 == 0.0) s.kind = (h.b1 == 0.0) ? 2 : 1;
926 else if (h.b1 == 0.0 && h.b2 != 0.0 && h.b0 / h.b2 > 0.0)
928 const double w = std::sqrt(h.b0 / h.b2) / fs;
933 s.cosNotch = 1.0 - s.yNotch;
936 s.allPass = h.b1 != 0.0 && h.b2 == h.a2 && h.b0 == h.a0 && h.b1 == -h.a1;
946 [[nodiscard]]
static Denominator invariantDenominator(
const AnalogSection& h,
double fs)
noexcept
949 if (!h.isSecondOrder())
951 const double x = -(h.a0 / h.a1) / fs;
952 const double p = std::exp(x), gap = -std::expm1(x);
953 d.d0 = gap * gap; d.d1 = 2.0 * p; d.d2 = 0.0;
954 d.a1 = -p; d.a2 = 0.0;
957 const double sigma = -0.5 * h.a1 / h.a2, det = sigma * sigma - h.a0 / h.a2;
958 double atNyquist = 0.0;
961 const double r = std::exp(sigma / fs), gap = -std::expm1(sigma / fs);
962 constexpr double kFree = 0.95 * kPi, kRoom = 0.04 * kPi;
963 double theta = std::sqrt(-det) / fs;
964 if (theta > kFree) theta = kFree + kRoom * (1.0 - std::exp(-(theta - kFree) / kRoom));
965 const double s = std::sin(0.5 * theta), bend = 4.0 * r * s * s;
966 const double atDc = gap * gap + bend, top = (1.0 + r) * (1.0 + r) - bend;
968 atNyquist = top * top;
970 d.a1 = -2.0 * r * std::cos(theta); d.a2 = r * r;
974 const double root = std::sqrt(det);
975 const double x1 = (sigma + root) / fs, x2 = (sigma - root) / fs;
976 const double p1 = std::exp(x1), p2 = std::exp(x2);
977 const double gap = std::expm1(x1) * std::expm1(x2), top = (1.0 + p1) * (1.0 + p2);
979 atNyquist = top * top;
980 d.d2 = 4.0 * p1 * p2;
981 d.a1 = -(p1 + p2); d.a2 = p1 * p2;
983 d.d1 = 0.5 * (atNyquist - d.d0) - 2.0 * d.d2;
988 [[nodiscard]]
static double power(
const AnalogSection& h,
double omega2)
noexcept
990 const double nr = h.b0 - h.b2 * omega2, dr = h.a0 - h.a2 * omega2;
991 return (nr * nr + h.b1 * h.b1 * omega2) / (dr * dr + h.a1 * h.a1 * omega2);
999 static void cluster(
const AnalogSection& h,
const Band& band,
double centre,
double q,
double y0, Samples& x)
noexcept
1001 const double half = 0.5 / std::max(q, 0.5);
1002 const double r = std::sqrt(1.0 + half * half) + half, s = std::sqrt(r);
1003 const double factors[kClusterPoints] = { 1.0 / (r * r), 1.0 / r, 1.0 / s, 1.0, s, r, r * r };
1004 const double low = 2.0 * kPi * band.lowHz_, high = 2.0 * kPi * band.highHz_;
1005 const double halfPeriod = 0.5 / band.fs_, scale = 1.0 / y0;
1006 for (
const double ratio : factors)
1008 const double omega = std::clamp(centre * ratio, low, high);
1009 const double sn = sine(omega * halfPeriod);
1010 x.t[x.n] = 2.0 * sn * sn * scale;
1011 x.m[x.n] = power(h, omega * omega);
1012 x.weight[x.n] = weightOf(omega);
1017 static void gather(
const AnalogSection& h,
const Shape& shape,
const Band& band,
double y0, Samples& x)
noexcept
1019 const double scale = 1.0 / y0;
1023 x.t[i] = band.y_[i] * scale;
1024 x.m[i] = power(h, band.omega2_[i]);
1025 x.weight[i] = band.weight_[i];
1029 cluster(h, band, h.a0 / h.a1, 0.5, y0, x);
1030 if (h.b1 != 0.0 && h.b0 != 0.0) cluster(h, band, std::abs(h.b0 / h.b1), 0.5, y0, x);
1034 cluster(h, band, std::sqrt(h.a0 / h.a2), std::sqrt(h.a0 * h.a2) / std::abs(h.a1), y0, x);
1035 if (shape.kind == 0)
1037 if (h.b2 != 0.0 && h.b0 / h.b2 > 0.0 && h.b1 != 0.0)
1038 cluster(h, band, std::sqrt(h.b0 / h.b2), std::sqrt(h.b0 * h.b2) / std::abs(h.b1), y0, x);
1039 else if (h.b2 == 0.0 && h.b1 != 0.0)
1040 cluster(h, band, std::abs(h.b0 / h.b1), 0.5, y0, x);
1043 double largest = 0.0;
1044 for (
int i = 0; i < x.n; ++i) largest = std::max(largest, x.m[i]);
1045 x.floor = kFloor * largest;
1046 x.tMax = 2.0 * scale;
1047 x.tz = shape.yNotch * scale;
1048 x.dc = (shape.kind == 0 || shape.kind == 3) ? (h.b0 / h.a0) * (h.b0 / h.a0) : 0.0;
1052 static void numeratorAt(
const Shape& s,
double t,
double* out)
noexcept
1054 if (s.first) out[0] = t;
1055 else if (s.kind == 2) out[0] = t * t;
1056 else if (s.kind != 3) { out[0] = t; out[1] = t * t; }
1060 [[nodiscard]]
static double heldAt(
const Shape& s,
const Samples& x,
double t)
noexcept
1062 if (s.kind == 0)
return x.dc;
1063 if (s.kind == 3)
return x.dc * (t - x.tz) * (t - x.tz) / (x.tz * x.tz);
1068 [[nodiscard]]
static bool solve(
int n,
double m[5][6])
noexcept
1070 for (
int c = 0; c < n; ++c)
1073 for (
int r = c + 1; r < n; ++r)
1074 if (std::abs(m[r][c]) > std::abs(m[pivot][c])) pivot = r;
1075 if (!(std::abs(m[pivot][c]) > 1e-300))
return false;
1077 for (
int k = 0; k <= n; ++k) std::swap(m[c][k], m[pivot][k]);
1078 for (
int r = 0; r < n; ++r)
1080 if (r == c)
continue;
1081 const double f = m[r][c] / m[c][c];
1082 for (
int k = c; k <= n; ++k) m[r][k] -= f * m[c][k];
1085 for (
int r = 0; r < n; ++r) m[r][n] /= m[r][r];
1104 static void pass(
const Shape& s,
const Samples& x,
const double* p,
bool together,
1105 double (*normal)[6],
double& cost,
double& worst)
noexcept
1107 const int nN = s.numeratorTerms(), nD = s.denominatorTerms();
1108 const int n = together ? nN + nD : nN;
1109 if (normal !=
nullptr)
1110 for (
int a = 0; a < 5; ++a)
1111 for (
int b = 0; b < 6; ++b) normal[a][b] = 0.0;
1114 for (
int i = 0; i < x.n; ++i)
1116 const double t = x.t[i], m = x.m[i], t2 = t * t;
1118 numeratorAt(s, t, row);
1119 double value = heldAt(s, x, t);
1120 for (
int j = 0; j < nN; ++j) value += p[j] * row[j];
1121 const double was = 1.0 + p[nN] * t + (nD > 1 ? p[nN + 1] * t2 : 0.0);
1122 const double want = (m + x.floor) * was, have = value + x.floor * was;
1123 const double u = x.weight[i] / want, off = (have - want) * u;
1124 const double apart = off * off * want / have;
1126 worst = std::max(worst, apart);
1127 if (normal ==
nullptr)
continue;
1129 for (
int j = 0; j < nN; ++j) row[j] *= u;
1132 row[nN] = -u * m * t;
1133 if (nD > 1) row[nN + 1] = -u * m * t2;
1135 for (
int a = 0; a < n; ++a)
1137 const double ra = row[a];
1138 for (
int b = a; b < n; ++b) normal[a][b] += ra * row[b];
1139 normal[a][n] -= ra * off;
1150 [[nodiscard]]
static bool advance(
const Shape& s,
bool together,
double damping,
1151 double (*normal)[6],
double* p)
noexcept
1153 const int n = together ? s.numeratorTerms() + s.denominatorTerms() : s.numeratorTerms();
1154 if (n == 0)
return true;
1156 for (
int a = 0; a < n; ++a)
1158 if (!(normal[a][a] > 0.0))
return false;
1159 scale[a] = 1.0 / std::sqrt(normal[a][a]);
1161 double system[5][6];
1162 for (
int a = 0; a < n; ++a)
1164 for (
int b = a; b < n; ++b) system[a][b] = system[b][a] = normal[a][b] * scale[a] * scale[b];
1165 system[a][a] = 1.0 + damping;
1166 system[a][n] = normal[a][n] * scale[a];
1168 if (!solve(n, system))
return false;
1169 for (
int a = 0; a < n; ++a)
1171 const double move = system[a][n] * scale[a];
1172 if (!std::isfinite(move))
return false;
1179 [[nodiscard]]
static bool positive(
double d1,
double d2,
double tMax)
noexcept
1181 constexpr double kMargin = 1e-9;
1182 const double end = 1.0 + tMax * (d1 + tMax * d2);
1183 if (!(end > kMargin * (1.0 + tMax * (std::abs(d1) + tMax * std::abs(d2)))))
return false;
1186 const double tv = -0.5 * d1 / d2;
1187 if (tv > 0.0 && tv < tMax)
1189 const double low = 1.0 + 0.5 * d1 * tv;
1190 if (!(low > kMargin * (1.0 + tv * (std::abs(d1) + tv * std::abs(d2)))))
return false;
1201 static void clampNumerator(
const Shape& s,
const Samples& x,
double* p)
noexcept
1203 if (s.kind == 0 && s.first)
1205 if (x.dc + p[0] * x.tMax < 0.0) p[0] = -x.dc / x.tMax;
1207 else if (s.kind == 0)
1209 if (x.dc + x.tMax * (p[0] + x.tMax * p[1]) < 0.0) p[1] = -(x.dc + p[0] * x.tMax) / (x.tMax * x.tMax);
1210 if (p[1] > 0.0 && p[0] < 0.0 && -0.5 * p[0] / p[1] < x.tMax && p[0] * p[0] > 4.0 * x.dc * p[1])
1211 p[0] = -2.0 * std::sqrt(x.dc * p[1]);
1213 else if (s.kind == 1 && !s.first)
1215 p[0] = std::max(p[0], 0.0);
1216 if (p[0] + p[1] * x.tMax < 0.0) p[1] = -p[0] / x.tMax;
1218 else if (s.kind != 3)
1220 p[0] = std::max(p[0], 0.0);
1225 [[nodiscard]]
static bool factor(
double k0,
double k1,
double k2,
double& c0,
double& c1,
double& c2)
noexcept
1229 const double slack = -1e-9 * (std::abs(k0) + 2.0 * std::abs(k1) + 4.0 * std::abs(k2));
1230 double atDc = k0, atNyquist = k0 + 2.0 * k1 + 4.0 * k2;
1231 if (!(atDc >= slack) || !(atNyquist >= slack))
return false;
1232 atDc = std::max(atDc, 0.0);
1233 atNyquist = std::max(atNyquist, 0.0);
1234 const double p = std::sqrt(atDc), m = std::sqrt(atNyquist);
1235 const double sum = 0.5 * (p + m);
1237 const double disc = sum * sum - k2;
1238 if (disc < -1e-9 * (sum * sum + std::abs(k2)))
return false;
1239 c0 = 0.5 * (sum + std::sqrt(std::max(0.0, disc)));
1240 if (!(c0 > 0.0))
return false;
1241 c2 = 0.25 * k2 / c0;
1246 [[nodiscard]]
static bool assemble(
const Shape& s,
const Samples& x,
const double* p,
double y0, BiquadCoeffs& out)
noexcept
1248 const int nN = s.numeratorTerms();
1249 const double scale = 1.0 / y0, scale2 = scale * scale;
1250 double c0 = 1.0, c1 = 0.0, c2 = 0.0;
1251 if (!factor(1.0, p[nN] * scale, s.first ? 0.0 : p[nN + 1] * scale2, c0, c1, c2)) return false;
1253 double e0 = 0.0, e1 = 0.0, e2 = 0.0;
1256 if (!factor(x.dc, p[0] * scale, s.first ? 0.0 : p[1] * scale2, e0, e1, e2)) return false;
1258 else if (s.kind == 1 && !s.first)
1261 double f0 = 0.0, f1 = 0.0, unused = 0.0;
1262 if (!factor(0.5 * p[0] * scale, 0.5 * p[1] * scale2, 0.0, f0, f1, unused))
return false;
1263 e0 = f0; e1 = f1 - f0; e2 = -f1;
1265 else if (s.kind == 1)
1267 const double g = std::sqrt(0.5 * std::max(p[0], 0.0) * scale);
1270 else if (s.kind == 2)
1273 const double g = 0.5 * std::sqrt(std::max(p[0], 0.0)) * scale;
1274 e0 = g; e1 = -2.0 * g; e2 = g;
1280 const double g = 0.5 * std::sqrt(x.dc) / s.yNotch;
1281 e0 = g; e1 = -2.0 * g * s.cosNotch; e2 = g;
1284 const double inverse = 1.0 / c0;
1285 out.b0 = e0 * inverse; out.b1 = e1 * inverse; out.b2 = e2 * inverse;
1286 out.a1 = c1 * inverse; out.a2 = c2 * inverse;
1287 return std::isfinite(out.b0) && std::isfinite(out.b1) && std::isfinite(out.b2)
1288 && std::isfinite(out.a1) && std::isfinite(out.a2);
1293 static constexpr double kLadderStep = 4.0;
1294 static constexpr double kDeep = 3981.0717055349733;
1295 static constexpr double kMiddle = 63.09573444801933;
1297 [[nodiscard]]
static AnalogSection& at(AnalogCascade& cascade,
int i)
noexcept
1299 return cascade.sections[
static_cast<size_t>(i)];
1302 [[nodiscard]]
static double omegaOf(
double hz)
noexcept
1304 return 2.0 * kPi * (std::isfinite(hz) ? std::max(hz, 1e-3) : 1000.0);
1308 [[nodiscard]]
static AnalogSection scaled(
const AnalogSection& n,
double omega)
noexcept
1310 if (!n.isSecondOrder())
1312 return AnalogSection::make(n.b2, n.b1 * omega, n.b0 * omega * omega, n.a2, n.a1 * omega, n.a0 * omega * omega);
1316 [[nodiscard]]
static AnalogSection mirrored(
const AnalogSection& n,
double omega)
noexcept
1318 if (!n.isSecondOrder())
1320 return AnalogSection::make(n.b0, n.b1 * omega, n.b2 * omega * omega, n.a0, n.a1 * omega, n.a2 * omega * omega);
1324 static void fractionalPole(
double order, AnalogCascade& out)
noexcept
1326 const double gap = std::pow(kLadderStep, order);
1327 const double leaving = 1.0 - order * order * order * order;
1328 double pole = std::pow(kLadderStep, 0.5 * (1.0 - order));
1329 for (
int i = 0; i < 3; ++i)
1331 const double p1 = pole, p2 = pole * kLadderStep;
1332 const double iz1 = 1.0 / (p1 * gap), iz2 = (i == 2 ? leaving : 1.0) / (p2 * gap);
1333 out.add(
AnalogSection::make(iz1 * iz2, iz1 + iz2, 1.0, 1.0 / (p1 * p2), 1.0 / p1 + 1.0 / p2, 1.0));
1334 pole = p2 * kLadderStep;
1339 [[nodiscard]]
static AnalogCascade cutPrototype(
double slopeDbPerOctave,
double q)
noexcept
1342 if (!std::isfinite(slopeDbPerOctave))
return out;
1343 const double order = std::clamp(slopeDbPerOctave, 0.0,
kMaxCutSlope) / 6.0;
1344 if (order < 1e-6)
return out;
1347 fractionalPole(order, out);
1355 const int whole =
static_cast<int>(std::floor(order));
1356 const int pairs =
static_cast<int>(std::floor(order + 1.0)) / 2;
1357 const bool onPair = (whole % 2) == 1;
1358 const int plain = onPair ? pairs - 1 : pairs;
1360 for (
int k = 0; k < pairs; ++k)
1361 damping[k] = 2.0 * std::sin(kPi * (2 * k + 1) / (2.0 * order));
1370 const double deep = std::pow(kDeep - 1.0, 1.0 / order);
1371 double atCorner = 1.0, atDeep = 1.0;
1372 for (
int k = 0; k < plain; ++k)
1374 atCorner *= damping[k] * damping[k];
1375 atDeep *= (1.0 - deep) * (1.0 - deep) + damping[k] * damping[k] * deep;
1377 const double lift = std::pow(std::clamp(q, 0.1, 100.0) /
kButterworthQ, std::clamp(order - 1.0, 0.0, 1.0));
1378 for (
int k = 0; k < plain; ++k)
1379 out.add(
AnalogSection::make(0.0, 0.0, 1.0, 1.0, damping[k] / (k == 0 ? lift : 1.0), 1.0));
1384 const double mid = std::pow(kMiddle - 1.0, 1.0 / order);
1386 for (
int k = 0; k < plain; ++k)
1387 atMid *= (1.0 - mid) * (1.0 - mid) + damping[k] * damping[k] * mid;
1388 const double points[3] = { 1.0, mid, deep };
1389 const double asked[3] = { 2.0 / atCorner, kMiddle / atMid, kDeep / atDeep };
1390 double system[5][6] = {};
1391 for (
int i = 0; i < 3; ++i)
1393 system[i][0] = points[i];
1394 system[i][1] = points[i] * points[i];
1395 system[i][2] = -asked[i] * points[i];
1396 system[i][3] = asked[i] - 1.0;
1398 double alpha = 0.0, beta = 0.0, zero2 = -1.0;
1399 if (solve(3, system))
1401 alpha = system[0][3]; beta = system[1][3]; zero2 = system[2][3];
1403 const double natural2 = beta > 0.0 ? 1.0 / std::sqrt(beta) : 0.0;
1404 const double damping2 = alpha * natural2 + 2.0;
1405 if (zero2 > -1e-9 && zero2 <= 1.0 + 1e-9 && natural2 > 0.0 && std::isfinite(natural2) && damping2 > 1e-6)
1407 const double a1 = std::sqrt(damping2 * natural2) / (plain == 0 ? lift : 1.0);
1408 out.add(
AnalogSection::make(0.0, std::sqrt(std::max(zero2, 0.0)) * natural2, natural2, 1.0, a1, natural2));
1413 const double c = 2.0 / atCorner;
1414 const double slope = deep * (atDeep * c - kDeep);
1416 if (std::abs(slope) > 1e-12 * deep * kDeep)
1417 z = std::clamp((kDeep - atDeep * ((1.0 - deep) * (1.0 - deep) + c * deep)) / slope, 0.0, 1.0);
1419 std::sqrt(c * (1.0 + z)) / (plain == 0 ? lift : 1.0), 1.0));
1425 const double c = 2.0 / atCorner;
1426 const double slope = deep * (atDeep * c - kDeep);
1428 if (std::abs(slope) > 1e-12 * deep * kDeep)
1429 z = std::clamp((kDeep - atDeep * (1.0 + (c - 1.0) * deep)) / slope, 0.0, 1.0);
1430 const double u = c * (1.0 + z) - 1.0;
1431 if (u > 1e-12) out.add(
AnalogSection::make(0.0, std::sqrt(z), 1.0, 0.0, std::sqrt(u), 1.0));
1441 [[nodiscard]]
static AnalogCascade shelfPrototype(
double gainDb,
double order,
double q =
kButterworthQ)
noexcept
1444 const double nu = wholeOrPart(order);
1445 const double db = std::isfinite(gainDb) ? std::clamp(gainDb, -120.0, 120.0) : 0.0;
1449 const double g = std::pow(10.0, db / (20.0 * nu)), beta = std::pow(10.0, -db / (40.0 * nu));
1450 if (nu == std::floor(nu))
1452 const int n =
static_cast<int>(nu);
1453 for (
int i = 0; i < n / 2; ++i)
1455 const double s = std::sin(kPi * (2 * i + 1) / (2.0 * n)) * (i == 0 ? sharpest : 1.0);
1456 out.add(
AnalogSection::make(1.0, 2.0 * g * s * beta, g * g * beta * beta, 1.0, 2.0 * s * beta, beta * beta));
1466 const int pairs =
static_cast<int>(std::floor(0.5 * nu));
1467 const double rest = nu - 2.0 * pairs;
1468 for (
int i = 0; i < pairs; ++i)
1470 const double s = std::sin(kPi * (2 * i + 1) / (2.0 * nu)) * (i == 0 ? sharpest : 1.0);
1471 out.add(
AnalogSection::make(1.0, 2.0 * g * s * beta, g * g * beta * beta, 1.0, 2.0 * s * beta, beta * beta));
1476 const double share = std::pow(g, rest), factor = 1.0 / std::sqrt(share);
1486 const double part = rest - 1.0;
1487 const double share = std::pow(g, 0.5 * rest), factor = 1.0 / std::sqrt(share);
1488 const double wide = std::pow(g, 0.25) + std::pow(g, -0.25);
1489 const double narrow = 2.0 * std::sin(kPi * (2 * pairs + 1) / (2.0 * (2 * pairs + 2)));
1490 double damping = std::exp((1.0 - part) * std::log(wide) + part * std::log(narrow));
1491 if (pairs == 0) damping *= std::pow(sharpest, part);
1492 out.add(
AnalogSection::make(1.0, damping * share * factor, share * share * factor * factor, 1.0, damping * factor, factor * factor));
1498 [[nodiscard]]
static double wholeOrPart(
double order)
noexcept
1500 return std::isfinite(order) ? std::clamp(order, 1.0,
static_cast<double>(
kMaxOrder)) : 1.0;
1506 double upper1 = 0.0, upper0 = 0.0;
1507 double lower1 = 0.0, lower0 = 0.0;
1515 [[nodiscard]]
static BandPair bandPair(
double c1,
double c0,
double width,
double w0)
noexcept
1518 if (c1 * c1 > 4.0 * c0)
1521 const double spread = std::sqrt(c1 * c1 - 4.0 * c0);
1522 pair.upper1 = 0.5 * (c1 + spread) * width; pair.upper0 = w0 * w0;
1523 pair.lower1 = 0.5 * (c1 - spread) * width; pair.lower0 = w0 * w0;
1526 const std::complex<double> root(-0.5 * c1, 0.5 * std::sqrt(std::max(0.0, 4.0 * c0 - c1 * c1)));
1527 const std::complex<double> sum = root * width;
1528 const std::complex<double> spread = std::sqrt(sum * sum - 4.0 * w0 * w0);
1529 std::complex<double> above = 0.5 * (sum + spread), below = 0.5 * (sum - spread);
1530 if (std::norm(above) < std::norm(below)) std::swap(above, below);
1531 pair.upper1 = -2.0 * above.real(); pair.upper0 = std::norm(above);
1532 pair.lower1 = -2.0 * below.real(); pair.lower0 = std::norm(below);
1539 double c1[2] = {}, c0[2] = {};
1544 [[nodiscard]]
static BandFactors bandFactors(
double p2,
double p1,
double p0,
double width,
double w0)
noexcept
1549 const BandPair pair = bandPair(p1 / p2, p0 / p2, width, w0);
1550 f.c1[0] = pair.upper1; f.c0[0] = pair.upper0;
1551 f.c1[1] = pair.lower1; f.c0[1] = pair.lower0;
1557 f.c1[0] = p0 / p1 * width; f.c0[0] = w0 * w0;
1574 static void addBandForm(
const AnalogSection& s,
double width,
double w0, AnalogCascade& out)
noexcept
1576 const BandFactors num = bandFactors(s.b2, s.b1, s.b0, width, w0), den = bandFactors(s.a2, s.a1, s.a0, width, w0);
1577 double gain = den.lead != 0.0 ? num.lead / den.lead : 1.0;
1578 for (
int i = 0; i < den.count; ++i)
1580 if (i < num.count) out.add(
AnalogSection::make(gain, gain * num.c1[i], gain * num.c0[i], 1.0, den.c1[i], den.c0[i]));
1586 [[nodiscard]]
static AnalogCascade bandFilter(
double hz,
double q,
double order,
bool stop)
noexcept
1589 const double nu = wholeOrPart(order);
1590 const double w0 = omegaOf(hz), w02 = w0 * w0, width = w0 / std::clamp(q, 1e-3, 1e3);
1591 if (nu != std::floor(nu))
1595 const AnalogCascade proto = cutPrototype(6.0 * nu,
kButterworthQ);
1596 for (
int i = 0; i < proto.count; ++i)
1598 const AnalogSection& p = proto.sections[
static_cast<size_t>(i)];
1599 addBandForm(stop ?
AnalogSection::make(p.b0, p.b1, p.b2, p.a0, p.a1, p.a2) : p, width, w0, out);
1603 const int n =
static_cast<int>(nu);
1604 const double b2 = stop ? 1.0 : 0.0, b1 = stop ? 0.0 : width, b0 = stop ? w02 : 0.0;
1605 for (
int i = 0; i < n / 2; ++i)
1607 const BandPair pair = bandPair(2.0 * std::sin(kPi * (2 * i + 1) / (2.0 * n)), 1.0, width, w0);
1625 [[nodiscard]]
static Landen landen(
double k,
double complement)
noexcept
1628 double kc = complement;
1629 while (steps.count < 14 && k > 1e-18)
1633 steps.v[steps.count++] = k;
1634 kc = std::sqrt((1.0 - k) * (1.0 + k));
1640 [[nodiscard]]
static double quarterPeriod(
const Landen& steps)
noexcept
1642 double period = 0.5 * kPi;
1643 for (
int i = 0; i < steps.count; ++i) period *= 1.0 + steps.v[i];
1648 [[nodiscard]]
static std::complex<double> ascend(std::complex<double> w,
const Landen& steps)
noexcept
1650 for (
int i = steps.count - 1; i >= 0; --i)
1651 w = (1.0 + steps.v[i]) * w / (1.0 + steps.v[i] * w * w);
1654 [[nodiscard]]
static std::complex<double> ellipticCd(std::complex<double> u,
const Landen& steps)
noexcept
1656 return ascend(std::cos(u * (0.5 * kPi)), steps);
1658 [[nodiscard]]
static std::complex<double> ellipticSn(std::complex<double> u,
const Landen& steps)
noexcept
1660 return ascend(std::sin(u * (0.5 * kPi)), steps);
1664 [[nodiscard]]
static std::complex<double> ellipticArcSn(std::complex<double> w,
double k,
const Landen& steps)
noexcept
1667 for (
int i = 0; i < steps.count; ++i)
1669 w = w / (1.0 + std::sqrt(1.0 - w * w * (before * before))) * (2.0 / (1.0 + steps.v[i]));
1670 before = steps.v[i];
1672 return std::asin(w) * (2.0 / kPi);
1680 [[nodiscard]]
static double ellipticModulus(
int order,
double rippleDb,
double stopDb,
1681 double& ripple,
double& stop)
noexcept
1683 const int n = std::clamp(order, 1,
kMaxOrder);
1684 const double ap = std::isfinite(rippleDb) ? std::clamp(rippleDb, 1e-3, 3.0) : 0.05;
1685 const double as = std::isfinite(stopDb) ? std::clamp(stopDb, 20.0, 140.0) : 100.0;
1686 ripple = std::sqrt(std::expm1(ap * 0.23025850929940458));
1687 stop = std::sqrt(std::expm1(as * 0.23025850929940458));
1688 const double k1 = ripple / stop, k1c = std::sqrt((1.0 - k1) * (1.0 + k1));
1689 const double ratio = quarterPeriod(landen(k1c, k1)) / quarterPeriod(landen(k1, k1c));
1690 const double nome = std::exp(-kPi * ratio / n);
1691 double top = 0.0, bottom = 1.0;
1692 for (
int m = 0; m < 12; ++m)
1694 top += std::pow(nome, m * (m + 1.0));
1695 if (m > 0) bottom += 2.0 * std::pow(nome, 1.0 * m * m);
1697 const double theta = top / bottom;
1698 return std::min(4.0 * std::sqrt(nome) * theta * theta, 1.0 - 1e-12);
1702 [[nodiscard]]
static AnalogCascade ellipticPrototype(
int order,
double rippleDb,
double stopDb)
noexcept
1705 const int n = std::clamp(order, 1,
kMaxOrder);
1706 double ripple = 0.0, stop = 0.0;
1707 const double k = ellipticModulus(n, rippleDb, stopDb, ripple, stop);
1708 const double k1 = ripple / stop;
1709 const Landen steps = landen(k, std::sqrt((1.0 - k) * (1.0 + k)));
1710 const Landen steps1 = landen(k1, std::sqrt((1.0 - k1) * (1.0 + k1)));
1711 const std::complex<double> j(0.0, 1.0);
1712 const double v0 = (-j * ellipticArcSn(j / ripple, k1, steps1)).real() / n;
1714 for (
int i = 0; i < n / 2; ++i)
1716 const double u = (2.0 * i + 1.0) / n;
1717 const double zero = 1.0 / (k * ellipticCd(u, steps).real());
1718 const std::complex<double> pole = j * ellipticCd(std::complex<double>(u, -v0), steps);
1719 const double size = std::norm(pole);
1720 out.add(
AnalogSection::make(1.0 / (zero * zero), 0.0, 1.0, 1.0 / size, -2.0 * pole.real() / size, 1.0));
1724 const double pole = (j * ellipticSn(j * v0, steps)).real();
1727 else if (out.count > 0)
1730 const double gain = 1.0 / std::sqrt(1.0 + ripple * ripple);
1731 AnalogSection& first = at(out, 0);
1732 first.b2 *= gain; first.b0 *= gain;