DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
DspMath.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
16#include <algorithm>
17#include <array>
18#include <bit>
19#include <cmath>
20#include <cstdint>
21#include <type_traits>
22#include <concepts>
23#include <numbers>
24
25namespace dspark {
26
27// ============================================================================
28// Concepts
29// ============================================================================
30
32template <typename T>
33concept FloatType = std::floating_point<T>;
34
35namespace detail {
36// Shared coefficients of the existing reduced-range odd sine polynomial.
37// Nonlinear offline kernels also use its exact slope and residual bounds.
38template <FloatType T> inline constexpr std::array<T, 5> fastSinPolynomial{
39 T(0.99999997408724855), T(-0.16666646026660671), T(0.0083328727116396326),
40 T(-0.00019799239565814083), T(2.5871610835732768e-6)};
41} // namespace detail
42
43// ============================================================================
44// Constants
45// ============================================================================
46
48template <FloatType T> inline constexpr T pi = std::numbers::pi_v<T>;
49
51template <FloatType T> inline constexpr T twoPi = T(2) * std::numbers::pi_v<T>;
52
54template <FloatType T> inline constexpr T invTwoPi = T(1) / twoPi<T>;
55
57template <FloatType T> inline constexpr T halfPi = std::numbers::pi_v<T> / T(2);
58
60template <FloatType T> inline constexpr T sqrt2 = std::numbers::sqrt2_v<T>;
61
63template <FloatType T> inline constexpr T invSqrt2 = T(1) / std::numbers::sqrt2_v<T>;
64
65// ============================================================================
66// Decibel / Gain Conversions
67// ============================================================================
68
76template <FloatType T>
77[[nodiscard]] inline T decibelsToGain(T dB, T minusInfinityDb = T(-100)) noexcept
78{
79 // exp(dB * ln(10)/20): the same accuracy as pow(10, dB/20) (measured
80 // 2.97e-7 vs 2.78e-7 relative in float over +-60 dB) at half the cost.
81 return dB <= minusInfinityDb ? T(0) : std::exp(dB * T(0.11512925464970228420));
82}
83
91template <FloatType T>
92[[nodiscard]] inline T gainToDecibels(T gain, T minusInfinityDb = T(-100)) noexcept
93{
94 // 20/ln(10) * ln(gain): log() is about twice as fast as log10() in float
95 // at the same accuracy (glibc's log10f is not the optimised kernel).
96 return gain > T(0) ? std::max(minusInfinityDb, T(8.6858896380650365530) * std::log(gain))
97 : minusInfinityDb;
98}
99
100// ============================================================================
101// Interpolation and Mapping
102// ============================================================================
103
116template <FloatType T>
117[[nodiscard]] inline T mapRange(T value, T inMin, T inMax, T outMin, T outMax) noexcept
118{
119 if (inMin == inMax) return outMin; // Safety: prevent NaN/Inf in audio pipeline
120 return outMin + (outMax - outMin) * ((value - inMin) / (inMax - inMin));
121}
122
136template <FloatType T>
137[[nodiscard]] inline T moveTowards(T from, T to, T maxDelta) noexcept
138{
139 // Return the target itself once within reach: from + (to - from) rounds
140 // off it in about 10% of float cases, leaving a settled ramp one ulp away.
141 const T delta = to - from;
142 return std::abs(delta) <= maxDelta ? to : from + std::clamp(delta, -maxDelta, maxDelta);
143}
144
145// ============================================================================
146// Fast Approximations
147// ============================================================================
148
168template <FloatType T>
169[[nodiscard]] inline T fastTanh(T x) noexcept
170{
171 // std::clamp translates to SIMD min/max intrinsics (no branching).
172 // Maintains continuity avoiding step-aliasing at the bounds.
173 x = std::clamp(x, T(-3), T(3));
174
175 const auto x2 = x * x;
176 const auto x4 = x2 * x2;
177 // Pade [5,4] approximant: max error 0.04% for |x| <= 3 (measured)
178 return x * (T(945) + T(105) * x2 + x4) / (T(945) + T(420) * x2 + T(15) * x4);
179}
180
196template <FloatType T>
197[[nodiscard]] inline T fastPow10(T x) noexcept
198{
199 // log2(10) folded into one constant: rounding it once is more accurate
200 // than multiplying log2(e) * ln(10) at runtime, and it saves a multiply
201 // (compilers may not reassociate x * a * b without fast-math).
202 constexpr T kLog2Of10 =
203 static_cast<T>(std::numbers::ln10_v<long double> / std::numbers::ln2_v<long double>);
204 return std::exp2(x * kLog2Of10);
205}
206
219template <FloatType T>
220[[nodiscard]] inline T fastExp(T x) noexcept
221{
222 return std::exp2(x * std::numbers::log2e_v<T>);
223}
224
241template <FloatType T>
242[[nodiscard]] inline T fastDecay(T x) noexcept
243{
244 const T v = std::min(std::max(x, T(0)), T(4));
245 const T v2 = v * v;
246 const T even = T(120) + T(12) * v2;
247 const T odd = v * (T(60) + v2);
248 return (even - odd) / (even + odd);
249}
250
263[[nodiscard]] inline double dominantPairPower(double ll, double rr, double lr) noexcept
264{
265 const double half = 0.5 * (ll - rr);
266 return std::max(0.0, 0.5 * (ll + rr) + std::sqrt(half * half + lr * lr));
267}
268
284template <FloatType T>
285[[nodiscard]] inline T dominantPairLevel(T levelL, T levelR, double rho2) noexcept
286{
287 const double pl = static_cast<double>(levelL) * static_cast<double>(levelL);
288 const double pr = static_cast<double>(levelR) * static_cast<double>(levelR);
289 const double cross = std::sqrt(std::clamp(rho2, 0.0, 1.0) * pl * pr);
290 return static_cast<T>(std::sqrt(0.5 * dominantPairPower(pl, pr, cross)));
291}
292
309template <FloatType T>
310[[nodiscard]] inline T fastTan(T x) noexcept
311{
312 constexpr T limit = T(1.520); // ~pi/2 - 0.05
313 if (std::abs(x) > limit) return std::tan(x);
314 const T x2 = x * x;
315 const T x4 = x2 * x2;
316 // Pade [5,4]: tan(x) ~= x * (945 - 105*x^2 + x^4) / (945 - 420*x^2 + 15*x^4)
317 return x * (T(945) - T(105) * x2 + x4) / (T(945) - T(420) * x2 + T(15) * x4);
318}
319
339template <FloatType T>
340[[nodiscard]] inline T fastSin(T x) noexcept
341{
342 // Range-reduce to [-pi, pi] with a two-term Cody-Waite split of 2*pi so the
343 // subtraction stays accurate in float even for arguments several periods out.
344 const T k = std::floor(x * invTwoPi<T> + T(0.5));
345 x -= k * T(6.28125); // high part (exactly representable)
346 x -= k * T(0.0019353071795864769253); // low part of 2*pi
347
348 // Fold into [-pi/2, pi/2] where the polynomial converges fast:
349 // sin(x) = sin(pi - x) for x > pi/2 (and the odd mirror for x < -pi/2).
350 if (x > halfPi<T>) x = pi<T> - x;
351 else if (x < -halfPi<T>) x = -pi<T> - x;
352
353 const T x2 = x * x;
354 // Endpoint-constrained Remez minimax coefficients for sin on [-pi/2, pi/2]
355 // (equiripple error 3.73e-9, p(pi/2) == 1). Near-Taylor coefficients of
356 // the same degree leave ~3e-6 of error: a -110 dB harmonic floor.
357 constexpr auto c = detail::fastSinPolynomial<T>;
358 return x * (c[0] + x2 * (c[1] + x2 * (c[2] + x2 * (c[3] + x2 * c[4]))));
359}
360
368template <FloatType T>
369[[nodiscard]] inline T fastCos(T x) noexcept
370{
371 return fastSin(x + halfPi<T>);
372}
373
392template <FloatType T>
393[[nodiscard]] inline T fastLog(T x) noexcept
394{
395 int e = 0;
396 T m; // x = m * 2^e, m in [0.5, 1)
397 if constexpr (std::is_same_v<T, float>)
398 {
399 const std::uint32_t bits = std::bit_cast<std::uint32_t>(x);
400 if (bits - 0x00800000u < 0x7F000000u) // positive, normal, finite
401 {
402 e = static_cast<int>(bits >> 23) - 126;
403 m = std::bit_cast<float>((bits & 0x007FFFFFu) | 0x3F000000u);
404 }
405 else m = std::frexp(x, &e);
406 }
407 else if constexpr (std::is_same_v<T, double>)
408 {
409 const std::uint64_t bits = std::bit_cast<std::uint64_t>(x);
410 if (bits - 0x0010000000000000ull < 0x7FE0000000000000ull)
411 {
412 e = static_cast<int>(bits >> 52) - 1022;
413 m = std::bit_cast<double>((bits & 0x000FFFFFFFFFFFFFull) | 0x3FE0000000000000ull);
414 }
415 else m = std::frexp(x, &e);
416 }
417 else
418 {
419 m = std::frexp(x, &e);
420 }
421 // Normalise mantissa into [sqrt(0.5), sqrt(2)) so the series is centred.
422 if (m < T(0.70710678118654752440)) { m *= T(2); --e; }
423
424 // Classic atanh form (Cephes): ln(m) = 2*atanh(s), s = (m-1)/(m+1).
425 // |s| <= 0.1716 so the odd series converges below 1e-7 with 4 terms.
426 const T s = (m - T(1)) / (m + T(1));
427 const T s2 = s * s;
428 const T lnm = T(2) * s * (T(1)
429 + s2 * (T(1.0 / 3.0)
430 + s2 * (T(1.0 / 5.0)
431 + s2 * T(1.0 / 7.0))));
432
433 return lnm + static_cast<T>(e) * std::numbers::ln2_v<T>; // + e * ln2
434}
435
436// ============================================================================
437// Utility
438// ============================================================================
439
455template <FloatType T>
456[[nodiscard]] inline T wrapPhase(T phase) noexcept
457{
458 // floor() correctly handles negative values, preventing branching
459 T wrapped = phase - twoPi<T> * std::floor(phase * invTwoPi<T>);
460 // Rounding in the k * twoPi product can land wrapped just outside
461 // [0, 2*pi) on either side: large phases where the product overshoots
462 // the input leave a slightly negative result, and tiny negative phases
463 // can round the sum up to exactly twoPi. Enforce the documented
464 // half-open range. Order matters: the += branch can itself round up to
465 // exactly twoPi, which the second branch then folds to 0.
466 if (wrapped < T(0)) wrapped += twoPi<T>;
467 if (wrapped >= twoPi<T>) wrapped -= twoPi<T>;
468 return wrapped;
469}
470
471} // namespace dspark
Constrains a type to IEEE floating-point (float or double).
Definition DspMath.h:33
constexpr std::array< T, 5 > fastSinPolynomial
Definition DspMath.h:38
Main namespace for the DSPark framework.
constexpr T invSqrt2
1 / square root of 2 (0.70710...). Butterworth Q factor.
Definition DspMath.h:63
T fastTan(T x) noexcept
Fast approximation of tan(x) using a Pade [5,4] rational approximant.
Definition DspMath.h:310
T moveTowards(T from, T to, T maxDelta) noexcept
Moves a value toward a target by at most a given distance.
Definition DspMath.h:137
T dominantPairLevel(T levelL, T levelR, double rho2) noexcept
Level of the dominant component of a stereo pair from the levels of its two channels and their square...
Definition DspMath.h:285
T fastPow10(T x) noexcept
Fast approximation of 10^x using exp2.
Definition DspMath.h:197
T decibelsToGain(T dB, T minusInfinityDb=T(-100)) noexcept
Converts a value in decibels to linear gain.
Definition DspMath.h:77
T fastDecay(T x) noexcept
e^(-x) for x >= 0 by a rational approximation: the coefficient of a one-pole whose time changes every...
Definition DspMath.h:242
double dominantPairPower(double ll, double rr, double lr) noexcept
Power of the dominant component of a stereo pair: the larger eigenvalue of the pair's covariance [ll ...
Definition DspMath.h:263
T mapRange(T value, T inMin, T inMax, T outMin, T outMax) noexcept
Maps a value from one range to another (linear interpolation).
Definition DspMath.h:117
constexpr T sqrt2
Square root of 2 (1.41421...).
Definition DspMath.h:60
constexpr T pi
Pi (3.14159...) for the given floating-point type.
Definition DspMath.h:48
T fastSin(T x) noexcept
Fast sine approximation (degree-9 odd minimax polynomial).
Definition DspMath.h:340
T fastCos(T x) noexcept
Fast cosine approximation. See fastSin() for accuracy notes (the pi/2 offset costs float about one ul...
Definition DspMath.h:369
T fastLog(T x) noexcept
Fast natural logarithm approximation.
Definition DspMath.h:393
T gainToDecibels(T gain, T minusInfinityDb=T(-100)) noexcept
Converts a linear gain value to decibels.
Definition DspMath.h:92
T fastTanh(T x) noexcept
Fast tanh approximation using a Pade [5,4] rational function.
Definition DspMath.h:169
constexpr T invTwoPi
1 / (2 * Pi) (0.15915...). Useful for fast phase divisions.
Definition DspMath.h:54
T fastExp(T x) noexcept
e^x via std::exp2, using the identity e^x = 2^(x * log2(e)).
Definition DspMath.h:220
constexpr T halfPi
Pi / 2 (1.57079...). Quarter period; sin/cos phase offset.
Definition DspMath.h:57
constexpr T twoPi
2 * Pi (6.28318...).
Definition DspMath.h:51
T wrapPhase(T phase) noexcept
Normalises a phase value to the range [0, 2*pi).
Definition DspMath.h:456