DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
DetailAnalysis.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
46#include "AudioSpec.h"
47#include "DspMath.h"
48#include "FFT.h"
49#include "FIRFilter.h"
50#include "SimdOps.h"
51#include "SpectralEnvelope.h"
52#include "SpectralFilter.h"
53#include "WindowFunctions.h"
54
55#include <algorithm>
56#include <array>
57#include <cmath>
58#include <cstddef>
59#include <memory>
60#include <vector>
61
62namespace dspark {
63
70template <FloatType T>
72{
73public:
74 static constexpr int kPoints = SpectralReadout<T>::kPoints;
75 static constexpr int kMaxChannels = 16;
76 static constexpr double kFinest = 1.0 / 24.0;
77 static constexpr double kWidest = 1.0;
78
80 [[nodiscard]] static double frequency(int point) noexcept { return SpectralReadout<T>::frequency(point); }
81
86 void prepare(const AudioSpec& spec)
87 {
88 if (!spec.isValid()) return;
89 prepared_ = false;
90 fs_ = spec.sampleRate;
91 channels_ = std::min(spec.numChannels, kMaxChannels);
92 const int octaves = std::clamp(static_cast<int>(std::lround(std::log2(std::max(fs_, 44100.0) / 44100.0))), 0, 3);
93 n_ = kWindow << octaves;
94 bins_ = n_ + 1; // the transform is twice the window
95 // A shorter window takes over beyond these bins of every decimated level, at the finest width.
96 usedBins_ = std::min(bins_, static_cast<int>(std::ceil(4.0 * kPeriods / kFinest * std::exp2(kFinest))) + 8);
97 mean_.assign(static_cast<std::size_t>(bins_), 0.0);
98 levels_ = 1;
99 while (levels_ < kMaxLevels && static_cast<double>(n_ << levels_) / fs_ <= kLongest) ++levels_;
100
101 fft_ = std::make_unique<FFTReal<T>>(static_cast<std::size_t>(2 * n_));
102 window_.resize(static_cast<std::size_t>(n_));
103 WindowFunctions<T>::hann(window_.data(), n_, true);
104 {
105 std::vector<double> hann(static_cast<std::size_t>(n_));
106 WindowFunctions<double>::hann(hann.data(), n_, true);
107 // No narrower than a bin of the window itself (the padding only reads between them).
108 focus_.prepare(hann.data(), n_, 2 * n_, kFocusWidth, 2.0);
109 }
110 for (auto* v : { &focusIn_, &focusRe_, &focusIm_ }) v->assign(static_cast<std::size_t>(2 * n_ + 2), 0.0);
111 lag_.resize(static_cast<std::size_t>(channels_));
112 for (auto& v : lag_)
113 for (auto* p : { &v.power, &v.sum, &v.sumOfSum }) p->assign(static_cast<std::size_t>(bins_ + 1), 0.0);
114 frame_.assign(static_cast<std::size_t>(2 * n_), T(0));
115 spectrum_.assign(static_cast<std::size_t>(2 * n_ + 2), T(0));
116 // What a level is read for lies under 0.19 of its rate, so the folds of
117 // a short half-band fall clear of it.
118 const auto taps = FIRDesign<double>::lowPass(1.0, 0.25, kTaps, FIRDesign<double>::estimateKaiserBeta(100.0));
119 for (int i = 0; i < kTaps; ++i) taps_[static_cast<std::size_t>(i)] = static_cast<T>(taps[static_cast<std::size_t>(i)]);
120
121 const auto size = static_cast<std::size_t>(bins_);
122 channel_.resize(static_cast<std::size_t>(channels_));
123 points_.resize(static_cast<std::size_t>(kPoints));
124 for (auto& c : channel_)
125 for (int l = 0; l < levels_; ++l)
126 {
127 auto& v = c[static_cast<std::size_t>(l)];
128 v.ring.assign(static_cast<std::size_t>(n_), T(0));
129 v.history.assign(static_cast<std::size_t>(kTaps - 1 + n_), T(0));
130 v.power.assign(size + 1, 0.0);
131 v.sum.assign(size + 1, 0.0);
132 v.sumOfSum.assign(size + 1, 0.0);
133 }
134 for (auto* v : { &evens_, &odds_ }) v->assign(static_cast<std::size_t>((kTaps + n_) / 2 + 1), T(0));
135 for (auto* v : { &decimated_, &partial_ }) v->assign(static_cast<std::size_t>(n_ / 2 + 1), T(0));
136 for (int k = 0; k < kTaps; ++k)
137 {
138 T* phase = k % 2 == 0 ? evenTaps_.data() : oddTaps_.data();
139 phase[k / 2] = taps_[static_cast<std::size_t>(k)];
140 }
141 prepared_ = true;
142 mapPoints();
143 reset();
144 }
145
147 void reset() noexcept
148 {
149 if (!prepared_) return;
150 for (auto& c : channel_)
151 for (int l = 0; l < levels_; ++l)
152 {
153 auto& v = c[static_cast<std::size_t>(l)];
154 std::fill(v.ring.begin(), v.ring.end(), T(0));
155 std::fill(v.history.begin(), v.history.end(), T(0));
156 std::fill(v.power.begin(), v.power.end(), 0.0);
157 std::fill(v.sum.begin(), v.sum.end(), 0.0);
158 std::fill(v.sumOfSum.begin(), v.sumOfSum.end(), 0.0);
159 v.write = v.pending = 0;
160 v.odd = false;
161 }
162 lagged_.fill(false);
163 tick_ = 0;
164 }
165
171 void setWidth(double octaves) noexcept
172 {
173 if (!std::isfinite(octaves)) return;
174 const double width = std::clamp(octaves, kFinest, kWidest);
175 if (width == width_) return;
176 width_ = width;
177 if (prepared_) mapPoints();
178 }
180 [[nodiscard]] double getWidth() const noexcept { return width_; }
181
183 void setExhaustive(bool on) noexcept { exhaustive_ = on; }
185 [[nodiscard]] bool isExhaustive() const noexcept { return exhaustive_; }
186
188 void setLinked(bool on) noexcept { linked_ = on; }
190 [[nodiscard]] bool isLinked() const noexcept { return linked_; }
191
197 void setTimeFocus(bool on) noexcept { timeFocus_ = on; }
199 [[nodiscard]] bool isTimeFocus() const noexcept { return timeFocus_; }
200
207 void feed(int channel, const T* x, int count) noexcept
208 {
209 if (!prepared_ || channel < 0 || channel >= channels_ || x == nullptr) return;
210 auto& c = channel_[static_cast<std::size_t>(channel)];
211 auto& v = c[0];
212 // The signal's own level now; the octaves down are decimated at the
213 // next update(), the first to read them (or when a window is waiting).
214 for (int at = 0; at < count;)
215 {
216 const int m = std::min(count - at, n_ - v.pending);
217 T* to = v.history.data() + kTaps - 1 + v.pending;
218 for (int i = 0; i < m; ++i) to[i] = std::isfinite(x[at + i]) ? x[at + i] : T(0);
219 toRing(v, to, m);
220 v.pending += m;
221 at += m;
222 if (levels_ == 1) v.pending = 0;
223 else if (v.pending == n_) catchUp(c);
224 }
225 }
226
233 void update(int channels) noexcept
234 {
235 if (!prepared_) return;
236 constexpr int every[kMaxLevels] = { 1, 1, 2, 4, 4 };
237 constexpr int turn[kMaxLevels] = { 0, 0, 0, 1, 3 };
238 const int count = std::min(channels, channels_);
239 for (auto& c : channel_) catchUp(c);
240 for (int l = 0; l < levels_; ++l)
241 {
242 if (!exhaustive_ && tick_ % every[l] != turn[l]) continue;
243 const auto u = static_cast<std::size_t>(l);
244 const int bins = l == 0 ? bins_ : usedBins_;
245 if (linked_ && count > 1)
246 {
247 std::fill_n(mean_.data(), bins, 0.0);
248 for (int ch = 0; ch < count; ++ch) addPower(channel_[static_cast<std::size_t>(ch)][u], bins, 1.0 / count, l == 0 && timeFocus_);
249 store(channel_[0][u], 0, l, bins);
250 continue;
251 }
252 for (int ch = 0; ch < count; ++ch)
253 {
254 auto& v = channel_[static_cast<std::size_t>(ch)][u];
255 std::fill_n(mean_.data(), bins, 0.0);
256 addPower(v, bins, 1.0, l == 0 && timeFocus_);
257 store(v, ch, l, bins);
258 }
259 }
260 if (!timeFocus_) lagged_.fill(false);
261 tick_ = (tick_ + 1) % 4;
262 }
263
269 void read(int channel, T* power) const noexcept { read(channel, power, 0, kPoints); }
270
279 void read(int channel, T* power, int first, int end) const noexcept
280 {
281 first = std::clamp(first, 0, kPoints);
282 end = std::clamp(end, first, kPoints);
283 if (!prepared_ || channel < 0 || channel >= channels_)
284 {
285 std::fill(power + first, power + end, T(0));
286 return;
287 }
288 const auto& c = channel_[static_cast<std::size_t>(linked_ ? 0 : channel)];
289 for (int i = first; i < end; ++i)
290 {
291 const Point& p = points_[static_cast<std::size_t>(i)];
292 double value = readLevel(c[static_cast<std::size_t>(p.level)], p.read[0]);
293 if (p.blend > 0.0) value += p.blend * (readLevel(c[static_cast<std::size_t>(p.level + 1)], p.read[1]) - value);
294 power[i] = static_cast<T>(value);
295 }
296 }
297
299 [[nodiscard]] double getWindowSeconds(int point) const noexcept
300 {
301 if (!prepared_) return 0.0;
302 const Point& p = points_[static_cast<std::size_t>(std::clamp(point, 0, kPoints - 1))];
303 return static_cast<double>(n_) * std::exp2(p.level + p.blend) / fs_;
304 }
305
306private:
307 static constexpr int kWindow = 1024;
308 static constexpr int kMaxLevels = 5;
309 static constexpr double kLongest = 0.4;
310 static constexpr double kPeriods = 4.0;
311 static constexpr double kFocusWidth = 1.0 / 6.0;
312 static constexpr int kTaps = 23;
313
314 static constexpr int kEvenTaps = (kTaps + 1) / 2, kOddTaps = kTaps / 2;
315
316 struct Level
317 {
318 std::vector<T> ring;
319 std::vector<T> history;
320 std::vector<double> power, sum, sumOfSum;
321 int write = 0, pending = 0;
322 bool odd = false;
323 };
324
326 void toRing(Level& v, const T* x, int m) noexcept
327 {
328 const int first = std::min(m, n_ - v.write);
329 std::copy_n(x, first, v.ring.data() + v.write);
330 std::copy_n(x + first, m - first, v.ring.data());
331 v.write = (v.write + m) & (n_ - 1);
332 }
333
335 void catchUp(std::array<Level, static_cast<std::size_t>(kMaxLevels)>& c) noexcept
336 {
337 for (int l = 0; l + 1 < levels_; ++l)
338 {
339 auto& v = c[static_cast<std::size_t>(l)];
340 if (v.pending == 0) continue;
341 auto& next = c[static_cast<std::size_t>(l + 1)];
342 const int produced = decimate(v);
343 toRing(next, decimated_.data(), produced);
344 if (l + 2 < levels_)
345 {
346 std::copy_n(decimated_.data(), produced, next.history.data() + kTaps - 1 + next.pending);
347 next.pending += produced;
348 }
349 }
350 }
351
358 int decimate(Level& v) noexcept
359 {
360 const int m = v.pending;
361 T* h = v.history.data();
362 const int total = kTaps - 1 + m;
363 const int start = v.odd ? 0 : 1;
364 const int produced = m > start ? (m - start + 1) / 2 : 0;
365 if (produced > 0)
366 {
367 T* even = evens_.data();
368 T* odd = odds_.data();
369 for (int t = 0; 2 * t < total; ++t) even[t] = h[2 * t];
370 for (int t = 0; 2 * t + 1 < total; ++t) odd[t] = h[2 * t + 1];
371 // y[j] = sum_k taps[k] h[start + 2j + k]: the even taps read one phase, the odd taps the other.
372 const T* withEven = (start & 1) != 0 ? odd + (start - 1) / 2 : even + start / 2;
373 const T* withOdd = (start & 1) != 0 ? even + (start + 1) / 2 : odd + start / 2;
374 T* y = decimated_.data();
375 T* rest = partial_.data();
376 simd::firCorrelate(withEven, evenTaps_.data(), kEvenTaps, y, produced, T(1));
377 simd::firCorrelate(withOdd, oddTaps_.data(), kOddTaps, rest, produced, T(1));
378 for (int j = 0; j < produced; ++j) y[j] += rest[j];
379 }
380 if ((m & 1) != 0) v.odd = !v.odd;
381 std::copy(h + m, h + m + kTaps - 1, h);
382 v.pending = 0;
383 return produced;
384 }
385
387 struct Place
388 {
389 double part = 0.0, beyond = 0.0;
390 int bin = 0;
391 };
392
394 struct Reading
395 {
396 Place line, under, topUnder, topOver, over;
397 double perUp = 0.0, perDown = 0.0;
398 bool inside = false;
399 };
400
402 struct Point
403 {
404 std::array<Reading, 2> read {};
405 double blend = 0.0;
406 int level = 0;
407 };
408
409 void mapPoints() noexcept
410 {
411 const double binHz = fs_ / static_cast<double>(2 * n_), shortest = static_cast<double>(n_) / fs_;
412 const double down = std::exp2(-0.5 * width_), up = std::exp2(0.5 * width_);
413 const double halfStep = std::pow(1000.0, 0.5 / (kPoints - 1));
414 for (int i = 0; i < kPoints; ++i)
415 {
416 Point& p = points_[static_cast<std::size_t>(i)];
417 const double hz = frequency(i);
418 const double wanted = kPeriods / (width_ * hz);
419 const double level = std::clamp(std::log2(wanted / shortest), 0.0, static_cast<double>(levels_ - 1));
420 p.level = std::min(static_cast<int>(level), std::max(0, levels_ - 2));
421 p.blend = levels_ > 1 ? level - static_cast<double>(p.level) : 0.0;
422 for (int side = 0; side < (levels_ > 1 ? 2 : 1); ++side)
423 {
424 Reading& r = p.read[static_cast<std::size_t>(side)];
425 const int at = p.level + side, bins = at == 0 ? bins_ : usedBins_;
426 const double bin = hz / binHz * std::exp2(at);
427 // At a weight of nothing a level is not read (nor kept that high).
428 r.inside = bin < static_cast<double>(bins - 1);
429 if (!r.inside) continue;
430 r.line.bin = static_cast<int>(bin);
431 r.line.part = bin - static_cast<double>(r.line.bin);
432 // The bands hold from half a bin under each bin.
433 const auto corner = [bins](double x) {
434 Place c;
435 const double from = std::max(x + 0.5, 0.0), end = static_cast<double>(bins);
436 if (from >= end)
437 {
438 c.bin = bins;
439 c.beyond = from - end;
440 return c;
441 }
442 c.bin = static_cast<int>(from);
443 c.part = from - static_cast<double>(c.bin);
444 return c;
445 };
446 r.under = corner(bin * down);
447 r.topUnder = corner(bin / halfStep);
448 r.topOver = corner(bin * halfStep);
449 r.over = corner(bin * up);
450 // A sine spreads 1.5 bins of the window, three of the transform.
451 r.perUp = 1.0 / (3.0 * bin * (1.0 / halfStep - down));
452 r.perDown = 1.0 / (3.0 * bin * (up - halfStep));
453 }
454 }
455 }
456
458 void addPower(const Level& v, int bins, double share, bool focused) noexcept
459 {
460 const T* r = v.ring.data();
461 const T* w = window_.data();
462 T* frame = frame_.data();
463 const int older = n_ - v.write;
464 for (int i = 0; i < older; ++i) frame[i] = r[v.write + i] * w[i];
465 for (int i = 0; i < v.write; ++i) frame[older + i] = r[i] * w[older + i];
466 std::fill(frame_.begin() + n_, frame_.end(), T(0));
467 fft_->forward(frame_.data(), spectrum_.data());
468 const double scale = share * 16.0 / (static_cast<double>(n_) * static_cast<double>(n_));
469 if (focused)
470 {
471 // Each bin through a stretch of the window of its own, scaled to read what the whole window would.
472 const int all = focus_.getNumBins();
473 for (int k = 0; k < 2 * all; ++k) focusIn_[static_cast<std::size_t>(k)] = static_cast<double>(spectrum_[static_cast<std::size_t>(k)]);
474 focus_.smooth(focusIn_.data(), focusRe_.data(), focusIm_.data());
475 for (int k = 0; k < bins; ++k)
476 {
477 const auto u = static_cast<std::size_t>(k);
478 mean_[u] += scale * focus_.getGain(k) * (focusRe_[u] * focusRe_[u] + focusIm_[u] * focusIm_[u]);
479 }
480 return;
481 }
482 for (int k = 0; k < bins; ++k)
483 {
484 const auto u = static_cast<std::size_t>(k);
485 const double re = static_cast<double>(spectrum_[2 * u]), im = static_cast<double>(spectrum_[2 * u + 1]);
486 mean_[u] += scale * (re * re + im * im);
487 }
488 }
489
491 void integrate(Level& v, int bins) noexcept
492 {
493 double sum = 0.0, sumOfSum = 0.0;
494 for (int k = 0; k < bins; ++k)
495 {
496 const auto u = static_cast<std::size_t>(k);
497 const double power = mean_[u];
498 v.power[u] = power;
499 v.sum[u] = sum;
500 v.sumOfSum[u] = sumOfSum;
501 sumOfSum += sum + 0.5 * power;
502 sum += power;
503 }
504 v.sum[static_cast<std::size_t>(bins)] = sum;
505 v.sumOfSum[static_cast<std::size_t>(bins)] = sumOfSum;
506 }
507
509 void store(Level& v, int ch, int l, int bins) noexcept
510 {
511 if (l != 0 || !timeFocus_)
512 {
513 integrate(v, bins);
514 return;
515 }
516 auto& lag = lag_[static_cast<std::size_t>(ch)];
517 auto& ready = lagged_[static_cast<std::size_t>(ch)];
518 if (!ready)
519 {
520 // The first reading through the focus: no hop before it to show.
521 integrate(lag, bins);
522 std::copy(lag.power.begin(), lag.power.end(), v.power.begin());
523 std::copy(lag.sum.begin(), lag.sum.end(), v.sum.begin());
524 std::copy(lag.sumOfSum.begin(), lag.sumOfSum.end(), v.sumOfSum.begin());
525 ready = true;
526 return;
527 }
528 std::swap(v.power, lag.power);
529 std::swap(v.sum, lag.sum);
530 std::swap(v.sumOfSum, lag.sumOfSum);
531 integrate(lag, bins);
532 }
533
535 [[nodiscard]] static double integral(const Level& v, const Place& x) noexcept
536 {
537 const auto u = static_cast<std::size_t>(x.bin);
538 // The bin past the last has no power: straight from there.
539 return v.sumOfSum[u] + (x.part + x.beyond) * v.sum[u] + 0.5 * x.part * x.part * v.power[u];
540 }
541
542 [[nodiscard]] static double readLevel(const Level& v, const Reading& r) noexcept
543 {
544 if (!r.inside) return 0.0;
545 const auto u = static_cast<std::size_t>(r.line.bin);
546 const double line = v.power[u] + r.line.part * (v.power[u + 1] - v.power[u]);
547 // The band by parts.
548 const double band = (integral(v, r.over) - integral(v, r.topOver)) * r.perDown
549 - (integral(v, r.topUnder) - integral(v, r.under)) * r.perUp;
550 return std::max(line, band);
551 }
552
553 double fs_ = 48000.0, width_ = 1.0 / 12.0;
554 int channels_ = 0, n_ = kWindow, bins_ = kWindow + 1, usedBins_ = kWindow + 1, levels_ = 1, tick_ = 0;
555 bool prepared_ = false, linked_ = false, exhaustive_ = false;
556 std::vector<double> mean_;
557 std::unique_ptr<FFTReal<T>> fft_;
558 std::vector<T> window_, frame_, spectrum_;
559 std::vector<T> evens_, odds_, decimated_, partial_;
560 SpectralFocus<double> focus_;
561 std::vector<double> focusIn_, focusRe_, focusIm_;
562 bool timeFocus_ = false;
563 std::vector<Level> lag_;
564 std::array<bool, static_cast<std::size_t>(kMaxChannels)> lagged_ {};
565 std::array<T, static_cast<std::size_t>(kTaps)> taps_ {};
566 std::array<T, static_cast<std::size_t>(kEvenTaps)> evenTaps_ {};
567 std::array<T, static_cast<std::size_t>(kOddTaps)> oddTaps_ {};
568 std::vector<Point> points_; // a third of a megabyte: not inside the owner
569 std::vector<std::array<Level, static_cast<std::size_t>(kMaxLevels)>> channel_;
570};
571
572} // namespace dspark
Multiresolution power spectrum on the grid of SpectralReadout.
void setLinked(bool on) noexcept
One reading for every channel, of their mean power; it holds from the next update().
static constexpr int kMaxChannels
Channels read at most.
void prepare(const AudioSpec &spec)
Allocates for a layout (an invalid spec is ignored).
double getWidth() const noexcept
void setWidth(double octaves) noexcept
The width of what is told apart, from kWidest to kFinest octaves (1/12 by default)....
bool isExhaustive() const noexcept
void setExhaustive(bool on) noexcept
Reads every level every hop in place of the long ones in turns (for a render).
static double frequency(int point) noexcept
bool isLinked() const noexcept
double getWindowSeconds(int point) const noexcept
void feed(int channel, const T *x, int count) noexcept
Takes the next samples of a channel (any count).
static constexpr double kFinest
Narrowest width, in octaves.
void read(int channel, T *power) const noexcept
The power at every point (a sine of full scale reads 1).
bool isTimeFocus() const noexcept
void setTimeFocus(bool on) noexcept
Reads the shortest window through one shorter as frequency rises and gives that reading a hop later (...
void read(int channel, T *power, int first, int end) const noexcept
The power at the points from first to before end only (the others are left as they are): what read() ...
void reset() noexcept
Clears the signal and the spectra.
static constexpr double kWidest
Widest width, in octaves.
void update(int channels) noexcept
A hop: takes the spectra of the levels due. The two shortest windows are read every hop,...
static constexpr int kPoints
Points of a reading.
Static methods for designing FIR filter coefficients.
Definition FIRFilter.h:78
static std::vector< T > lowPass(double sampleRate, double cutoffHz, int numTaps, T beta=T(5))
Designs a low-pass FIR filter.
Definition FIRFilter.h:89
void smooth(const double *spectrum, double *re, double *im) const noexcept
The smoothed complex spectrum of a frame.
void prepare(const double *window, int windowSize, int transform, double widthOctaves=1.0/3.0, double minBins=1.0)
Sets the window, the transform and the width.
int getNumBins() const noexcept
double getGain(int bin) const noexcept
A per-bin quantity of the last frame (a gain curve, a reduction), read at fixed points for a display ...
static double frequency(int point) noexcept
void firCorrelate(const T *x, const T *h, int taps, T *DSPARK_RESTRICT y, int n, T gain) noexcept
Block FIR as a valid correlation: y[i] = gain * sum_j h[j] * x[i + j] for i in [0,...
Definition SimdOps.h:1496
Main namespace for the DSPark framework.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
static void hann(T *output, int size, bool periodic=true) noexcept
Hann (raised cosine) window.