DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
AuditoryBands.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
55#include "DspMath.h"
56
57#include <algorithm>
58#include <array>
59#include <cmath>
60#include <cstddef>
61#include <vector>
62
63namespace dspark {
64
67{
69 [[nodiscard]] static double hzToBark(double hz) noexcept
70 {
71 const double f = std::max(hz, 0.0);
72 double z = 26.81 * f / (1960.0 + f) - 0.53;
73 if (z < 2.0) z += 0.15 * (2.0 - z);
74 else if (z > 20.1) z += 0.22 * (z - 20.1);
75 return z;
76 }
77
79 [[nodiscard]] static double barkToHz(double bark) noexcept
80 {
81 double z = bark;
82 if (z < 2.0) z = (z - 0.3) / 0.85; // undo z + 0.15 (2 - z)
83 else if (z > 20.1) z = (z + 0.22 * 20.1) / 1.22; // undo z + 0.22 (z - 20.1)
84 z = std::clamp(z, -0.52, 26.0);
85 return 1960.0 * (z + 0.53) / (26.28 - z);
86 }
87
89 [[nodiscard]] static double criticalBandwidth(double hz) noexcept
90 {
91 const double k = std::max(hz, 0.0) / 1000.0;
92 return 25.0 + 75.0 * std::pow(1.0 + 1.4 * k * k, 0.69);
93 }
94
96 [[nodiscard]] static double thresholdInQuietDb(double hz) noexcept
97 {
98 const double k = std::clamp(hz, 10.0, 24000.0) / 1000.0;
99 const double t = 3.64 * std::pow(k, -0.8) - 6.5 * std::exp(-0.6 * (k - 3.3) * (k - 3.3)) + 1e-3 * k * k * k * k;
100 return std::min(t, 120.0);
101 }
102
108 [[nodiscard]] static double loudnessExponent(double hz) noexcept
109 {
110 constexpr double kLowest = -5.0; // the threshold's minimum, near 3.3 kHz
111 return 0.23 + 0.07 * std::clamp((thresholdInQuietDb(hz) - kLowest) / 40.0, 0.0, 1.0);
112 }
113
118 [[nodiscard]] static double dominantPower(double ll, double rr, double lr) noexcept
119 {
120 return dominantPairPower(ll, rr, lr);
121 }
122
130 [[nodiscard]] static double dominantPower(double ll, double rr, double lrReal, double lrImag) noexcept
131 {
132 return dominantPairPower(ll, rr, std::sqrt(lrReal * lrReal + lrImag * lrImag));
133 }
134};
135
142template <FloatType T>
144{
145public:
154 void prepare(double sampleRate, int fftSize, int numBands = 72, double loHz = 20.0, double hiHz = 20000.0)
155 {
156 if (!std::isfinite(sampleRate) || !(sampleRate > 0.0) || fftSize < 8) return;
157 fs_ = sampleRate;
158 numBins_ = fftSize / 2 + 1;
159 binHz_ = fs_ / static_cast<double>(fftSize);
160 n_ = std::clamp(numBands, 2, 512);
161 const double hi = std::clamp(hiHz, 40.0, 0.49 * fs_);
162 const double lo = std::clamp(loHz, 10.0, 0.5 * hi);
163 z0_ = AuditoryScale::hzToBark(lo);
164 dz_ = (AuditoryScale::hzToBark(hi) - z0_) / static_cast<double>(n_ - 1);
165 centre_.resize(static_cast<size_t>(n_));
166 bark_.resize(static_cast<size_t>(n_));
167 exponent_.resize(static_cast<size_t>(n_));
168 threshold_.resize(static_cast<size_t>(n_));
169 thresholdLoudness_.resize(static_cast<size_t>(n_));
170 narrow_.resize(static_cast<size_t>(n_));
171 widthBins_.resize(static_cast<size_t>(n_));
172 for (int b = 0; b < n_; ++b)
173 {
174 const auto i = static_cast<size_t>(b);
175 bark_[i] = z0_ + dz_ * b;
176 centre_[i] = AuditoryScale::barkToHz(bark_[i]);
177 exponent_[i] = AuditoryScale::loudnessExponent(centre_[i]);
178 // A band one spacing wide, in bins.
179 widthBins_[i] = (AuditoryScale::barkToHz(bark_[i] + 0.5 * dz_) - AuditoryScale::barkToHz(bark_[i] - 0.5 * dz_)) / binHz_;
180 narrow_[i] = widthBins_[i] < 2.0;
181 }
182 // Each bin's two bands and their triangular weights.
183 binBand_.assign(static_cast<size_t>(numBins_), -2);
184 binWeight_.assign(static_cast<size_t>(numBins_), 0.0);
185 for (int k = 1; k < numBins_; ++k)
186 {
187 const double pos = (AuditoryScale::hzToBark(binHz_ * k) - z0_) / dz_;
188 if (pos < -1.0 || pos > static_cast<double>(n_)) continue;
189 const int lower = static_cast<int>(std::floor(pos));
190 binBand_[static_cast<size_t>(k)] = lower;
191 binWeight_[static_cast<size_t>(k)] = 1.0 - (pos - lower); // to `lower`; the rest to lower + 1
192 }
193 uniform_ = true;
194 widthBark_.assign(static_cast<size_t>(n_), dz_);
195 widthBark_.front() = widthBark_.back() = 0.5 * dz_;
196 setReferenceSpl(refSpl_);
197 }
198
216 void prepareDetailed(double sampleRate, int fftSize, int barkBands, double loHz, double hiHz, double bandsPerOctave)
217 {
218 if (!std::isfinite(sampleRate) || !(sampleRate > 0.0) || fftSize < 8) return;
219 if (!std::isfinite(bandsPerOctave) || !(bandsPerOctave > 0.0))
220 {
221 prepare(sampleRate, fftSize, barkBands, loHz, hiHz);
222 return;
223 }
224 fs_ = sampleRate;
225 const int base = std::clamp(barkBands, 2, 512);
226 const double hi = std::clamp(hiHz, 40.0, 0.49 * fs_);
227 const double lo = std::clamp(loHz, 10.0, 0.5 * hi);
228 z0_ = AuditoryScale::hzToBark(lo);
229 dz_ = (AuditoryScale::hzToBark(hi) - z0_) / static_cast<double>(base - 1);
230 // Bands counted along the logarithm of frequency, with the density of
231 // the Bark layout or of the octave, whichever is the larger.
232 constexpr int kSteps = 4096;
233 std::vector<double> logHz(kSteps + 1), count(kSteps + 1);
234 const double span = std::log(hi / lo);
235 const double perOctave = bandsPerOctave / 0.6931471805599453;
236 double before = 0.0;
237 for (int i = 0; i <= kSteps; ++i)
238 {
239 const double x = std::log(lo) + span * static_cast<double>(i) / kSteps;
240 const double hz = std::exp(x), step = 1e-3 * hz;
241 const double perBark = (AuditoryScale::hzToBark(hz + step) - AuditoryScale::hzToBark(hz - step)) / (2.0 * step) * hz / dz_;
242 const double density = std::max(perBark, perOctave);
243 logHz[static_cast<size_t>(i)] = x;
244 count[static_cast<size_t>(i)] = i == 0 ? 0.0
245 : count[static_cast<size_t>(i - 1)] + 0.5 * (density + before) * span / kSteps;
246 before = density;
247 }
248 const double total = count[kSteps];
249 n_ = std::clamp(static_cast<int>(std::lround(total)) + 1, 2, 512);
250 resizeBands();
251 size_t at = 0;
252 for (int b = 0; b < n_; ++b)
253 {
254 const auto i = static_cast<size_t>(b);
255 const double want = total * static_cast<double>(b) / static_cast<double>(n_ - 1);
256 while (at + 2 <= static_cast<size_t>(kSteps) && count[at + 1] < want) ++at;
257 const double rise = count[at + 1] - count[at];
258 const double part = rise > 0.0 ? std::clamp((want - count[at]) / rise, 0.0, 1.0) : 0.0;
259 centre_[i] = b == 0 ? lo : (b == n_ - 1 ? hi : std::exp(logHz[at] + part * (logHz[at + 1] - logHz[at])));
260 bark_[i] = AuditoryScale::hzToBark(centre_[i]);
261 exponent_[i] = AuditoryScale::loudnessExponent(centre_[i]);
262 }
263 mapBins(fftSize);
264 setReferenceSpl(refSpl_);
265 }
266
278 void prepareLike(const AuditoryBands& other, double sampleRate, int fftSize)
279 {
280 if (!std::isfinite(sampleRate) || !(sampleRate > 0.0) || fftSize < 8 || other.n_ < 2) return;
281 fs_ = sampleRate;
282 n_ = other.n_;
283 z0_ = other.z0_;
284 dz_ = other.dz_;
285 refSpl_ = other.refSpl_;
286 resizeBands();
287 centre_ = other.centre_;
288 bark_ = other.bark_;
289 exponent_ = other.exponent_;
290 mapBins(fftSize);
291 setReferenceSpl(refSpl_);
292 }
293
295 void setReferenceSpl(double dbSpl) noexcept
296 {
297 if (!std::isfinite(dbSpl)) return;
298 refSpl_ = std::clamp(dbSpl, 60.0, 130.0);
299 for (int b = 0; b < n_; ++b)
300 {
301 const auto i = static_cast<size_t>(b);
302 threshold_[i] = std::pow(10.0, (AuditoryScale::thresholdInQuietDb(centre_[i]) - refSpl_) / 10.0);
303 thresholdLoudness_[i] = std::pow(threshold_[i], exponent_[i]);
304 }
305 }
306
307 [[nodiscard]] int getNumBands() const noexcept { return n_; }
308 [[nodiscard]] int getNumBins() const noexcept { return numBins_; }
310 [[nodiscard]] double getCentre(int band) const noexcept { return centre_[static_cast<size_t>(std::clamp(band, 0, n_ - 1))]; }
312 [[nodiscard]] double getBark(int band) const noexcept { return bark_[static_cast<size_t>(std::clamp(band, 0, n_ - 1))]; }
314 [[nodiscard]] double getSpacing() const noexcept { return dz_; }
322 [[nodiscard]] double getWidthBark(int band) const noexcept { return widthBark_[static_cast<size_t>(std::clamp(band, 0, n_ - 1))]; }
324 [[nodiscard]] bool isUniform() const noexcept { return uniform_; }
326 [[nodiscard]] double getExponent(int band) const noexcept { return exponent_[static_cast<size_t>(std::clamp(band, 0, n_ - 1))]; }
328 [[nodiscard]] double getThreshold(int band) const noexcept { return threshold_[static_cast<size_t>(std::clamp(band, 0, n_ - 1))]; }
330 [[nodiscard]] double getThresholdLoudness(int band) const noexcept { return thresholdLoudness_[static_cast<size_t>(std::clamp(band, 0, n_ - 1))]; }
331
338 void bandPowers(const T* binPower, T* out) const noexcept
339 {
340 bandPowersInterleaved<1>(binPower, out);
341 }
342
350 template <int Lanes>
351 void bandPowersInterleaved(const T* binPower, T* out) const noexcept
352 {
353 static_assert(Lanes >= 1 && Lanes <= 8);
354 constexpr auto lanes = static_cast<size_t>(Lanes);
355 std::fill_n(out, n_ * Lanes, T(0));
356 // The bins that feed the same two bands lie together: their sums are
357 // carried in registers from the first to the last of them.
358 for (int k = 1; k < numBins_;)
359 {
360 const int lower = binBand_[static_cast<size_t>(k)];
361 if (lower < -1)
362 {
363 ++k;
364 continue;
365 }
366 const bool intoLower = lower >= 0 && lower < n_ && !narrow_[static_cast<size_t>(lower)];
367 const bool intoUpper = lower + 1 < n_ && !narrow_[static_cast<size_t>(lower + 1)];
368 std::array<T, lanes> below {}, above {};
369 if (intoLower) std::copy_n(out + Lanes * lower, Lanes, below.data());
370 if (intoUpper) std::copy_n(out + Lanes * (lower + 1), Lanes, above.data());
371 for (; k < numBins_ && binBand_[static_cast<size_t>(k)] == lower; ++k)
372 {
373 const double w = binWeight_[static_cast<size_t>(k)], rest = 1.0 - w;
374 const T* power = binPower + Lanes * k;
375 for (size_t j = 0; j < lanes; ++j)
376 {
377 const double p = static_cast<double>(power[j]);
378 below[j] += static_cast<T>(w * p);
379 above[j] += static_cast<T>(rest * p);
380 }
381 }
382 if (intoLower) std::copy_n(below.data(), Lanes, out + Lanes * lower);
383 if (intoUpper) std::copy_n(above.data(), Lanes, out + Lanes * (lower + 1));
384 }
385 for (int b = 0; b < n_; ++b)
386 {
387 const auto i = static_cast<size_t>(b);
388 if (!narrow_[i]) continue;
389 const double pos = std::clamp(centre_[i] / binHz_, 0.0, static_cast<double>(numBins_ - 1));
390 const int k = std::min(static_cast<int>(pos), numBins_ - 2);
391 const double f = pos - k;
392 const T* at = binPower + Lanes * k;
393 for (int j = 0; j < Lanes; ++j)
394 out[Lanes * b + j] = static_cast<T>(widthBins_[i] * ((1.0 - f) * static_cast<double>(at[j]) + f * static_cast<double>(at[j + Lanes])));
395 }
396 }
397
405 static void smoothAcross(T* v, int n, T coeff) noexcept
406 {
407 if (n < 2 || !(coeff > T(0))) return;
408 const T c = std::min(coeff, T(0.999));
409 for (int b = 1; b < n; ++b) v[b] += c * (v[b - 1] - v[b]);
410 for (int b = n - 2; b >= 0; --b) v[b] += c * (v[b + 1] - v[b]);
411 }
412
417 void specificLoudness(const T* bandPower, T* out) const noexcept
418 {
419 for (int b = 0; b < n_; ++b)
420 {
421 const auto i = static_cast<size_t>(b);
422 const double th = threshold_[i], a = exponent_[i];
423 out[b] = static_cast<T>(std::pow(std::max(0.0, static_cast<double>(bandPower[b])) + th, a) - thresholdLoudness_[i]);
424 }
425 }
426
428 [[nodiscard]] T totalLoudness(const T* specific) const noexcept
429 {
430 double s = 0.0;
431 if (!uniform_)
432 {
433 for (int b = 1; b < n_; ++b)
434 s += 0.5 * (static_cast<double>(specific[b - 1]) + static_cast<double>(specific[b]))
435 * (bark_[static_cast<size_t>(b)] - bark_[static_cast<size_t>(b - 1)]);
436 return static_cast<T>(s);
437 }
438 for (int b = 1; b < n_; ++b) s += 0.5 * (static_cast<double>(specific[b - 1]) + static_cast<double>(specific[b]));
439 return static_cast<T>(s * dz_);
440 }
441
442private:
443 void resizeBands()
444 {
445 centre_.resize(static_cast<size_t>(n_));
446 bark_.resize(static_cast<size_t>(n_));
447 exponent_.resize(static_cast<size_t>(n_));
448 threshold_.resize(static_cast<size_t>(n_));
449 thresholdLoudness_.resize(static_cast<size_t>(n_));
450 narrow_.resize(static_cast<size_t>(n_));
451 widthBins_.resize(static_cast<size_t>(n_));
452 widthBark_.resize(static_cast<size_t>(n_));
453 }
454
460 void mapBins(int fftSize)
461 {
462 uniform_ = false;
463 numBins_ = fftSize / 2 + 1;
464 binHz_ = fs_ / static_cast<double>(fftSize);
465 const auto last = static_cast<size_t>(n_ - 1);
466 for (int b = 0; b < n_; ++b)
467 {
468 const auto i = static_cast<size_t>(b);
469 const double below = b > 0 ? 0.5 * (bark_[i - 1] + bark_[i]) : bark_[i] - 0.5 * (bark_[i + 1] - bark_[i]);
470 const double above = b < n_ - 1 ? 0.5 * (bark_[i] + bark_[i + 1]) : bark_[i] + 0.5 * (bark_[i] - bark_[i - 1]);
471 // A band one spacing wide, in bins; its share of the Bark axis
472 // stops at the first and at the last centre.
473 widthBins_[i] = (AuditoryScale::barkToHz(above) - AuditoryScale::barkToHz(below)) / binHz_;
474 narrow_[i] = widthBins_[i] < 2.0;
475 widthBark_[i] = std::min(above, bark_[last]) - std::max(below, bark_[0]);
476 }
477 binBand_.assign(static_cast<size_t>(numBins_), -2);
478 binWeight_.assign(static_cast<size_t>(numBins_), 0.0);
479 int lower = -1; // the band at or under the bin
480 for (int k = 1; k < numBins_; ++k)
481 {
482 const double z = AuditoryScale::hzToBark(binHz_ * k);
483 while (lower + 1 < n_ && bark_[static_cast<size_t>(lower + 1)] <= z) ++lower;
484 double part = 0.0; // of the way from `lower` to the band above it
485 if (lower < 0)
486 {
487 part = 1.0 - (bark_[0] - z) / (bark_[1] - bark_[0]);
488 if (part < 0.0) continue;
489 }
490 else if (lower >= n_ - 1)
491 {
492 part = (z - bark_[last]) / (bark_[last] - bark_[last - 1]);
493 if (part > 1.0) continue;
494 }
495 else
496 {
497 part = (z - bark_[static_cast<size_t>(lower)]) / (bark_[static_cast<size_t>(lower + 1)] - bark_[static_cast<size_t>(lower)]);
498 }
499 binBand_[static_cast<size_t>(k)] = lower;
500 binWeight_[static_cast<size_t>(k)] = 1.0 - part; // to `lower`; the rest to lower + 1
501 }
502 }
503
504 double fs_ = 48000.0, binHz_ = 23.4375, z0_ = 0.0, dz_ = 0.3, refSpl_ = 100.0;
505 int numBins_ = 0, n_ = 0;
506 std::vector<double> centre_, bark_, exponent_, threshold_, thresholdLoudness_, widthBins_, widthBark_;
507 std::vector<bool> narrow_;
508 bool uniform_ = true;
509 std::vector<int> binBand_;
510 std::vector<double> binWeight_;
511};
512
513} // namespace dspark
Bands uniform in Bark over a power spectrum, with the loudness law.
void bandPowersInterleaved(const T *binPower, T *out) const noexcept
The band powers of several spectra at once: each what bandPowers() gives for its own.
void prepareLike(const AuditoryBands &other, double sampleRate, int fftSize)
Takes the bands of another instance over a spectrum of its own.
void specificLoudness(const T *bandPower, T *out) const noexcept
Specific loudness of band powers: (P + P_th)^a - P_th^a, with the band's exponent and threshold.
double getExponent(int band) const noexcept
int getNumBands() const noexcept
static void smoothAcross(T *v, int n, T coeff) noexcept
Smooths values across bands in both directions with a one-pole (forward, then backward): a spread lik...
double getCentre(int band) const noexcept
double getSpacing() const noexcept
double getThreshold(int band) const noexcept
void bandPowers(const T *binPower, T *out) const noexcept
Band powers from a power spectrum.
void setReferenceSpl(double dbSpl) noexcept
The SPL of a full-scale sine for the loudness law (60 to 130 dB).
double getBark(int band) const noexcept
bool isUniform() const noexcept
int getNumBins() const noexcept
double getWidthBark(int band) const noexcept
T totalLoudness(const T *specific) const noexcept
void prepare(double sampleRate, int fftSize, int numBands=72, double loHz=20.0, double hiHz=20000.0)
Lays the bands out.
void prepareDetailed(double sampleRate, int fftSize, int barkBands, double loHz, double hiHz, double bandsPerOctave)
Lays the bands out with more of them in the low end.
double getThresholdLoudness(int band) const noexcept
Main namespace for the DSPark framework.
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
The published formulas of the auditory scale (all in double).
static double thresholdInQuietDb(double hz) noexcept
static double dominantPower(double ll, double rr, double lrReal, double lrImag) noexcept
static double barkToHz(double bark) noexcept
static double criticalBandwidth(double hz) noexcept
static double loudnessExponent(double hz) noexcept
static double dominantPower(double ll, double rr, double lr) noexcept
static double hzToBark(double hz) noexcept