48#include "AudioBuffer.h"
50#include "DenormalGuard.h"
54#include "SpectralEnvelope.h"
55#include "WindowFunctions.h"
85 void prepare(
int bins)
noexcept { bins_ = bins; }
101 for (
int q = 1; q < size / 2; ++q) c[q] *= 2.0;
102 std::fill(c + size / 2 + 1, c + size, 0.0);
108 for (
int q = 0; q < length; ++q) c[q] *= taper[q];
109 std::fill(c + length, c + size, 0.0);
124template <FloatType T>
138 void prepare(
const AudioSpec& spec,
int windowSize = 2048,
int padding = 2,
int overlap = 4)
146 pad_ = padding >= 8 ? 8 : (padding >= 4 ? 4 : 2);
149 while (r * 2 <= std::clamp(overlap, 2, 16)) r <<= 1;
151 norm_ = 2.0 /
static_cast<double>(r);
153 kernelLength_ = m_ - n_ + 1;
154 fft_ = std::make_unique<FFTReal<double>>(
static_cast<size_t>(m_));
155 window_.resize(
static_cast<size_t>(n_));
157 taper_.assign(
static_cast<size_t>(kernelLength_), 1.0);
159 const int fade = std::max(1, kernelLength_ / 4);
160 for (
int i = 0; i < fade; ++i)
161 taper_[
static_cast<size_t>(kernelLength_ - fade + i)] = 0.5 + 0.5 * std::cos(3.141592653589793 * (i + 1) / (fade + 1));
164 shortLength_ = std::min(kernelLength_, m_ / 2);
165 shortTaper_.resize(
static_cast<size_t>(shortLength_));
166 for (
int i = 0; i < shortLength_; ++i)
167 shortTaper_[
static_cast<size_t>(i)] = 0.5 + 0.5 * std::cos(3.141592653589793 * i / shortLength_);
169 ring_.assign(
static_cast<size_t>(ch), std::vector<double>(
static_cast<size_t>(n_), 0.0));
170 keyRing_.assign(
static_cast<size_t>(ch), std::vector<double>(
static_cast<size_t>(n_), 0.0));
171 keySpectrum_.assign(
static_cast<size_t>(m_ + 2), 0.0);
172 accum_.assign(
static_cast<size_t>(ch), std::vector<double>(
static_cast<size_t>(2 * m_), 0.0));
173 spectra_.assign(
static_cast<size_t>(ch), std::vector<double>(
static_cast<size_t>(m_ + 2), 0.0));
174 writePos_ = readPos_ = 0;
176 frame_.assign(
static_cast<size_t>(m_ + 2), 0.0);
177 kernel_.assign(
static_cast<size_t>(m_ + 2), 0.0);
178 power_.assign(
static_cast<size_t>(bins_), T(0));
179 focusPower_.assign(
static_cast<size_t>(bins_), T(0));
181 focus_.prepare(window_.data(), n_, m_, focusWidth_,
static_cast<double>(pad_));
182 powers_.assign(
static_cast<size_t>(ch), std::vector<T>(
static_cast<size_t>(bins_), T(0)));
183 gain_.assign(
static_cast<size_t>(bins_), T(1));
191 [[nodiscard]]
bool isLinked() const noexcept {
return linked_; }
217 [[nodiscard]]
bool isTimeFocus() const noexcept {
return timeFocus_; }
224 if (std::isfinite(octaves)) focusWidth_ = std::clamp(octaves, 1.0 / 24.0, 1.0);
231 [[nodiscard]]
int getHopSize() const noexcept {
return hop_; }
232 [[nodiscard]]
int getNumBins() const noexcept {
return bins_; }
233 [[nodiscard]]
double getBinHz() const noexcept {
return fs_ /
static_cast<double>(m_); }
243 return channel >= 0 && channel < static_cast<int>(powers_.size()) ? powers_[
static_cast<size_t>(channel)].data() :
nullptr;
249 for (
auto& r : ring_) std::fill(r.begin(), r.end(), 0.0);
250 for (
auto& r : keyRing_) std::fill(r.begin(), r.end(), 0.0);
251 for (
auto& a : accum_) std::fill(a.begin(), a.end(), 0.0);
252 writePos_ = readPos_ = 0;
265 template <
typename Design>
277 template <
typename Design>
280 if (!prepared_)
return;
281 if (key !=
nullptr && (key->getNumChannels() <= 0 || key->getNumSamples() < buffer.getNumSamples())) key =
nullptr;
282 const int nCh = std::min(buffer.getNumChannels(), channels_);
287 for (
int ch = 0; ch < nCh && same; ++ch)
288 same = key->getChannel(std::min(ch, key->getNumChannels() - 1)) == buffer.getChannel(ch);
289 if (same) key =
nullptr;
291 keyActive_ = key !=
nullptr;
293 const int nS = buffer.getNumSamples();
294 const int mask = n_ - 1, accMask = 2 * m_ - 1;
298 const int chunk = std::min(nS - i, hop_ - hopCounter_);
301 for (
int ch = 0; ch < nCh; ++ch)
303 const T* in = buffer.getChannel(ch) + i;
304 double* r = ring_[
static_cast<size_t>(ch)].data();
305 inSpans(writePos_, chunk, n_, [&](
int from,
int at,
int count)
noexcept {
306 for (
int k = 0; k < count; ++k) r[at + k] = static_cast<double>(in[from + k]);
308 const T* kin = key !=
nullptr ? key->getChannel(std::min(ch, key->getNumChannels() - 1)) + i : in;
309 double* kr = keyRing_[
static_cast<size_t>(ch)].data();
310 inSpans(writePos_, chunk, n_, [&](
int from,
int at,
int count)
noexcept {
311 for (
int k = 0; k < count; ++k) kr[at + k] = static_cast<double>(kin[from + k]);
314 for (
int ch = 0; ch < nCh; ++ch)
316 T* out = buffer.getChannel(ch) + i;
317 double* a = accum_[
static_cast<size_t>(ch)].data();
318 inSpans(readPos_, chunk, 2 * m_, [&](
int from,
int at,
int count)
noexcept {
319 for (
int k = 0; k < count; ++k) out[from + k] = static_cast<T>(a[at + k]);
320 std::fill_n(a + at, count, 0.0);
323 writePos_ = (writePos_ + chunk) & mask;
324 readPos_ = (readPos_ + chunk) & accMask;
325 hopCounter_ += chunk;
326 if (hopCounter_ >= hop_)
337 template <
typename Body>
338 static void inSpans(
int start,
int count,
int size, Body&& body)
noexcept
340 const int first = std::min(count, size - start);
341 body(0, start, first);
342 if (first < count) body(first, 0, count - first);
345 template <
typename Design>
346 void hop(
int nCh, Design& design)
noexcept
348 const double scale = 16.0 / (
static_cast<double>(n_) *
static_cast<double>(n_));
350 for (
int ch = 0; ch < nCh; ++ch)
352 const double* r = ring_[
static_cast<size_t>(ch)].data();
353 const double* w = window_.data();
354 double* x = frame_.data();
355 inSpans(writePos_, n_, n_, [&](
int from,
int at,
int count)
noexcept {
356 for (
int k = 0; k < count; ++k) x[from + k] = r[at + k] * w[from + k];
358 std::fill(frame_.begin() + n_, frame_.begin() + m_, 0.0);
359 fft_->forward(frame_.data(), spectra_[
static_cast<size_t>(ch)].data());
362 const auto detectorSpectrum = [&](
int ch) ->
const double* {
363 if (!keyActive_)
return spectra_[
static_cast<size_t>(ch)].data();
364 const auto& r = keyRing_[
static_cast<size_t>(ch)];
365 for (
int k = 0; k < n_; ++k)
366 frame_[
static_cast<size_t>(k)] = r[
static_cast<size_t>((writePos_ + k) & (n_ - 1))] * window_[
static_cast<size_t>(k)];
367 std::fill(frame_.begin() + n_, frame_.begin() + m_, 0.0);
368 fft_->forward(frame_.data(), keySpectrum_.data());
369 return keySpectrum_.data();
371 const auto powerOf = [&](
int ch) {
372 const double* s = detectorSpectrum(ch);
373 T* p = powers_[
static_cast<size_t>(ch)].data();
377 for (
int k = 0; k < bins_; ++k) p[k] *= static_cast<T>(scale);
380 for (
int k = 0; k < bins_; ++k)
381 p[k] =
static_cast<T
>(scale * (s[2 * k] * s[2 * k] + s[2 * k + 1] * s[2 * k + 1]));
383 if (linked_ && nCh > 1)
385 std::fill(power_.begin(), power_.end(), T(0));
386 for (
int ch = 0; ch < nCh; ++ch)
388 const double* s = detectorSpectrum(ch);
391 focus_.power(s, focusPower_.data());
392 const T share =
static_cast<T
>(scale / nCh);
393 for (
int k = 0; k < bins_; ++k) power_[static_cast<size_t>(k)] += share * focusPower_[
static_cast<size_t>(k)];
396 for (
int k = 0; k < bins_; ++k)
397 power_[
static_cast<size_t>(k)] +=
static_cast<T
>(scale * (s[2 * k] * s[2 * k] + s[2 * k + 1] * s[2 * k + 1]) / nCh);
399 std::fill(gain_.begin(), gain_.end(), T(1));
400 design(-1, power_.data(), gain_.data(), bins_);
401 const bool unity = buildKernel();
402 for (
int ch = 0; ch < nCh; ++ch) apply(ch, unity);
407 for (
int ch = 0; ch < nCh; ++ch) powerOf(ch);
408 for (
int ch = 0; ch < nCh; ++ch)
410 std::fill(gain_.begin(), gain_.end(), T(1));
411 design(ch, powers_[
static_cast<size_t>(ch)].data(), gain_.data(), bins_);
412 apply(ch, buildKernel());
422 bool buildKernel() noexcept
425 for (
int k = 0; k < bins_ && unity; ++k) unity = gain_[static_cast<size_t>(k)] == T(1);
426 if (unity)
return true;
427 double* c = frame_.data();
428 double* h = kernel_.data();
431 for (
int k = 0; k < bins_; ++k)
433 h[2 * k] = std::log(std::max(
static_cast<double>(gain_[
static_cast<size_t>(k)]), 1e-6));
436 const int length = shortKernel_ ? shortLength_ : kernelLength_;
437 const double* taper = shortKernel_ ? shortTaper_.data() : taper_.data();
438 minimumPhase_.
build(*fft_, h, c, m_, taper, length);
444 void apply(
int ch,
bool unity)
noexcept
446 double* s = spectra_[
static_cast<size_t>(ch)].data();
447 const double* h = kernel_.data();
450 if (unity) std::fill(s, s + m_ + 2, 0.0);
452 for (
int k = 0; k < bins_; ++k)
454 const double hr = 1.0 - h[2 * k], hi = -h[2 * k + 1];
455 const double xr = s[2 * k], xi = s[2 * k + 1];
456 s[2 * k] = xr * hr - xi * hi;
457 s[2 * k + 1] = xr * hi + xi * hr;
462 for (
int k = 0; k < bins_; ++k)
464 const double hr = h[2 * k], hi = h[2 * k + 1];
465 const double xr = s[2 * k], xi = s[2 * k + 1];
466 s[2 * k] = xr * hr - xi * hi;
467 s[2 * k + 1] = xr * hi + xi * hr;
470 double* y = frame_.data();
472 double* a = accum_[
static_cast<size_t>(ch)].data();
473 const double norm = norm_;
474 inSpans(readPos_, m_, 2 * m_, [&](
int from,
int at,
int count)
noexcept {
475 for (
int k = 0; k < count; ++k) a[at + k] += norm * y[from + k];
479 double fs_ = 48000.0, norm_ = 0.5, focusWidth_ = 1.0 / 6.0;
480 int n_ = 2048, pad_ = 2, m_ = 4096, hop_ = 512, bins_ = 2049, kernelLength_ = 2049, shortLength_ = 2048, channels_ = 0;
481 int writePos_ = 0, readPos_ = 0, hopCounter_ = 0;
482 bool prepared_ =
false, linked_ =
false, removalListen_ =
false, keyActive_ =
false, shortKernel_ =
false, timeFocus_ =
false;
483 SpectralFocus<T> focus_;
484 std::unique_ptr<FFTReal<double>> fft_;
485 std::vector<double> window_, taper_, shortTaper_, frame_, kernel_, keySpectrum_;
486 detail::MinimumPhase minimumPhase_;
487 std::vector<std::vector<double>> ring_, keyRing_, accum_, spectra_;
488 std::vector<T> power_, gain_, focusPower_;
489 std::vector<std::vector<T>> powers_;
509template <FloatType T>
517 [[nodiscard]]
static double frequency(
int point)
noexcept
519 return 20.0 * std::pow(1000.0,
static_cast<double>(std::clamp(point, 0,
kPoints - 1)) / (
kPoints - 1));
531 template <
typename ValueAt>
532 [[nodiscard]]
static double between(
double hz, ValueAt&& valueAt)
noexcept
534 constexpr int last =
kPoints - 1;
535 const double at = hz > 20.0 ? std::min(last * std::log(hz / 20.0) / std::log(1000.0),
static_cast<double>(last)) : 0.0;
536 const int under = std::min(
static_cast<int>(at), last - 1);
537 const double t = at - under;
538 const double a =
static_cast<double>(valueAt(std::max(0, under - 1))), b =
static_cast<double>(valueAt(under));
539 const double c =
static_cast<double>(valueAt(under + 1)), d =
static_cast<double>(valueAt(std::min(last, under + 2)));
540 return b + 0.5 * t * (c - a + t * (2.0 * a - 5.0 * b + 4.0 * c - d + t * (3.0 * (b - c) + d - a)));
546 bins_ = std::max(0, bins);
547 const double half = std::pow(1000.0, 0.5 / (
kPoints - 1));
548 const int top = std::max(0, bins_ - 1);
549 for (
int i = 0; i <
kPoints; ++i)
551 const auto u =
static_cast<size_t>(i);
553 const int first =
static_cast<int>(std::ceil(at / half));
554 const int last =
static_cast<int>(std::floor(at * half));
558 first_[u] = std::clamp(first, 0, top);
559 last_[u] = std::clamp(last, first_[u], top);
563 const int under = std::clamp(
static_cast<int>(std::floor(at)), 0, top);
565 last_[u] = std::min(under + 1, top);
566 part_[u] =
static_cast<float>(std::clamp(at -
static_cast<double>(under), 0.0, 1.0));
574 for (
auto& curve : values_)
575 for (
auto& v : curve) v.store(0.0f, std::memory_order_relaxed);
584 template <
typename V>
585 void publish(
int channel,
const V* perBin,
int bins)
noexcept
587 if (channel < 0 || channel >=
kChannels || perBin ==
nullptr || bins != bins_ || bins <= 0)
return;
588 auto& curve = values_[
static_cast<size_t>(channel)];
589 for (
int i = 0; i <
kPoints; ++i)
591 const auto u =
static_cast<size_t>(i);
595 const double below =
static_cast<double>(perBin[first_[u]]);
596 const double above =
static_cast<double>(perBin[last_[u]]);
597 best = below +
static_cast<double>(part_[u]) * (above - below);
601 for (
int k = first_[u]; k <= last_[u]; ++k)
603 const double v =
static_cast<double>(perBin[k]);
604 if (std::abs(v) > std::abs(best)) best = v;
607 curve[u].store(
static_cast<float>(best), std::memory_order_relaxed);
621 template <
typename GainAt>
622 [[nodiscard]] T
gainPoint(
int point, GainAt&& gainAt)
const noexcept
624 if (point < 0 || point >=
kPoints || bins_ <= 0)
return T(0);
625 const auto decibels = [](
float g)
noexcept {
return 8.6858896f *
fastLog(std::max(g, 1e-6f)); };
626 const auto u =
static_cast<size_t>(point);
627 const int first = first_[u], last = last_[u];
630 const double below =
static_cast<double>(decibels(gainAt(first))), above =
static_cast<double>(decibels(gainAt(last)));
631 return static_cast<T
>(
static_cast<float>(below +
static_cast<double>(part_[u]) * (above - below)));
634 float least = gainAt(first);
635 for (
int k = first + 1; k <= last; ++k) least = std::min(least, static_cast<float>(gainAt(k)));
636 return static_cast<T
>(decibels(least));
645 template <
typename V>
648 if (channel < 0 || channel >=
kChannels || perPoint ==
nullptr)
return;
649 auto& curve = values_[
static_cast<size_t>(channel)];
650 for (
int i = 0; i < kPoints; ++i) curve[static_cast<size_t>(i)].store(
static_cast<float>(perPoint[i]), std::memory_order_relaxed);
654 [[nodiscard]] T
value(
int channel,
int point)
const noexcept
656 if (channel < 0 || channel >=
kChannels || point < 0 || point >=
kPoints)
return T(0);
657 return static_cast<T
>(values_[
static_cast<size_t>(channel)][
static_cast<size_t>(point)].load(std::memory_order_relaxed));
664 for (
const auto& curve : values_)
665 for (
const auto& v : curve)
667 const float x = v.load(std::memory_order_relaxed);
668 if (std::abs(x) > std::abs(best)) best = x;
670 return static_cast<T
>(best);
675 std::array<int, kPoints> first_ {}, last_ {};
676 std::array<float, kPoints> part_ {};
Non-owning view over audio channel data.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
FFT optimised for real-valued input signals (the common audio case).
Minimum-phase filtering by a gain curve designed every hop.
double getBinHz() const noexcept
int getHopSize() const noexcept
void setRemovalListen(bool on) noexcept
Applies one minus the filter (what it takes out).
void setTimeFocusWidth(double octaves) noexcept
The width the focus smooths the spectrum by, 1/24 to 1 octave (1/6 by default). Read at prepare().
void processBlock(AudioBufferView< T > buffer, Design &&design) noexcept
Filters a block in place.
void prepare(const AudioSpec &spec, int windowSize=2048, int padding=2, int overlap=4)
Allocates for a layout.
int getLatency() const noexcept
int getNumBins() const noexcept
bool isShortKernel() const noexcept
bool isLinked() const noexcept
bool isTimeFocus() const noexcept
const T * getFramePower(int channel) const noexcept
static constexpr int kMaxWindow
Longest analysis window.
void setTimeFocus(bool on) noexcept
Gives the design each bin's power through a stretch of the window of its own, shorter as frequency ri...
bool isRemovalListen() const noexcept
void setLinked(bool on) noexcept
One filter for every channel, designed on their mean power.
double getSampleRate() const noexcept
int getTransformSize() const noexcept
int getWindowSize() const noexcept
void reset() noexcept
Clears the input, the output and the hop phase.
static constexpr int kMinWindow
Shortest analysis window.
void processBlock(AudioBufferView< T > buffer, const AudioBufferView< T > *key, Design &&design) noexcept
Filters a block in place, the callback reading the power of a key (the same length or longer; its las...
void setShortKernel(bool on) noexcept
Cuts the filter's impulse response to half the transform and tapers it over its whole length (off by ...
double getTimeFocusWidth() const noexcept
A per-bin quantity of the last frame (a gain curve, a reduction), read at fixed points for a display ...
void publishPoints(int channel, const V *perPoint) noexcept
Publishes one frame of a channel that is already on the points (audio thread; prepare() is not needed...
T gainPoint(int point, GainAt &&gainAt) const noexcept
One point of a frame of gains no higher than 1, in decibels: what publish() would show of their decib...
static double frequency(int point) noexcept
void publish(int channel, const V *perBin, int bins) noexcept
Publishes one frame of a channel's per-bin values (audio thread).
T extreme() const noexcept
static double between(double hz, ValueAt &&valueAt) noexcept
A curve of the points at any frequency, as a display should draw it: a cubic through the four points ...
void prepare(double binHz, int bins) noexcept
Maps the points onto the bins of a transform and clears the curves.
T value(int channel, int point) const noexcept
static constexpr int kChannels
Curves (channels).
void clear() noexcept
Sets every point of every curve to zero.
static constexpr int kPoints
Points of each curve.
The minimum-phase kernel of a log magnitude, by its real cepstrum: what SpectralFilter and DetailFilt...
void prepare(int bins) noexcept
Takes the size of the design (allocates nothing).
static constexpr double kLeastLogGain
A log gain is taken no lower: -120 dB.
void build(FFTReal< double > &fft, double *h, double *c, int size, const double *taper, int length) noexcept
The kernel, cut and tapered.
void complexExp(double *data, int bins) noexcept
The exponential of each complex bin of an interleaved [re, im, ...] spectrum, in place: e^re (cos im ...
Main namespace for the DSPark framework.
T fastLog(T x) noexcept
Fast natural logarithm approximation.
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).
double sampleRate
Sample rate in Hz.
static void hann(T *output, int size, bool periodic=true) noexcept
Hann (raised cosine) window.