DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
SpectralDenoiser.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
72#include "../Core/AudioBuffer.h"
73#include "../Core/AudioSpec.h"
74#include "../Core/DspMath.h"
75#include "../Core/FFT.h"
76#include "../Core/KeyEqualizer.h"
77#include "../Core/SpectralFilter.h"
78#include "../Core/SpectralProcessor.h"
79#include "../Core/StateBlob.h"
80#include "../Core/WindowFunctions.h"
81
82#include <algorithm>
83#include <array>
84#include <atomic>
85#include <cmath>
86#include <cstddef>
87#include <cstdint>
88#include <numbers>
89#include <vector>
90
91namespace dspark {
92
99template <FloatType T>
101{
102public:
103 // -- Lifecycle ---------------------------------------------------------------
104
121 void prepare(const AudioSpec& spec, int fftSize = 2048)
122 {
123 if (!spec.isValid()) return;
124 prepared_.store(false, std::memory_order_relaxed);
125 numChannels_ = spec.numChannels;
126 sampleRate_ = spec.sampleRate;
127 const int octaves = std::clamp(static_cast<int>(std::lround(std::log2(std::max(spec.sampleRate, 44100.0) / 44100.0))), 0, 3);
128 const int rateSize = 2048 << octaves; // the rate's own
129 if (fftSize <= 0) fftSize = rateSize;
130 stft_.prepare(spec, fftSize, fftSize / 4);
131 const int size = stft_.getFFTSize();
132 dense_ = size > rateSize;
133 if (dense_) stft_.prepare(spec, size, size / kDenseFrames);
134 // The same memories in seconds at either spacing of the frames.
135 longAlpha_ = dense_ ? static_cast<float>(std::pow(static_cast<double>(kDDAlpha), 4.0 / kDenseFrames)) : kDDAlpha;
136 learnMost_ = dense_ ? kMaxLearnFrames * kDenseFrames / 4 : kMaxLearnFrames;
137 displayEvery_ = dense_ ? kDenseFrames / 2 : 2;
138 numBins_ = stft_.getNumBins();
139 prepareShort(spec);
140
141 profile_.assign(static_cast<size_t>(numBins_), 0.0f);
142 learnFrames_ = 0;
143 cleanPower_.assign(static_cast<size_t>(numChannels_),
144 std::vector<float>(static_cast<size_t>(numBins_), 0.0f));
145 heldGain_.assign(static_cast<size_t>(numChannels_),
146 std::vector<float>(static_cast<size_t>(numBins_), 1.0f));
147 for (auto& v : pairPower_) v.assign(static_cast<size_t>(numBins_), 0.0f);
148 const auto most = static_cast<size_t>(numBins_);
149 gains_.assign(most, 1.0f);
150 for (auto* v : { &detect_, &noiseHere_ }) v->assign(most, 0.0f);
151 sum_.assign(most + 1, 0.0);
152 stftBands_.prepare(numBins_);
153 shortBands_.prepare(shortBins_);
154 bandsFor_ = -1.0;
155 noiseHolds_ = false;
156 stftReadout_.prepare(spec.sampleRate / static_cast<double>(stft_.getFFTSize()), numBins_);
157 shownGains_ = std::vector<std::atomic<float>>(static_cast<size_t>(numBins_));
158 for (auto& g : shownGains_) g.store(1.0f, std::memory_order_relaxed);
159 weight_.assign(static_cast<size_t>(numBins_), 1.0f);
160 release_.assign(static_cast<size_t>(numBins_), 0.0f);
161 shortRelease_.assign(static_cast<size_t>(shortBins_), 0.0f);
162 shortWeight_.assign(static_cast<size_t>(shortBins_), 1.0f);
163 sensitivity_.prepare(spec.sampleRate);
164 weightDirty_.store(true, std::memory_order_release);
165 releaseFor_ = -1.0f;
166
167 prepared_.store(true, std::memory_order_relaxed);
168 reset();
169 }
170
172 void reset() noexcept
173 {
174 if (!prepared_.load(std::memory_order_relaxed)) return;
175 stft_.reset();
176 for (auto& c : cleanPower_)
177 std::fill(c.begin(), c.end(), 0.0f);
178 for (auto& c : heldGain_) std::fill(c.begin(), c.end(), 1.0f);
179 // The stream starts in silence: the short frames miss nothing of it.
180 resetShort(0);
181 shortRuns_ = filterMode_.load(std::memory_order_relaxed);
182 displayHop_ = 0;
183 for (auto& g : shownGains_) g.store(1.0f, std::memory_order_relaxed);
184 }
185
187 void clearProfile() noexcept
188 {
189 std::fill(profile_.begin(), profile_.end(), 0.0f);
190 noiseHolds_ = false;
191 shortNoiseHolds_ = false;
192 learnFrames_ = 0;
193 }
194
195 // -- Parameters (thread-safe) ---------------------------------------------------
196
198 void setLearning(bool learning) noexcept
199 {
200 learning_.store(learning, std::memory_order_relaxed);
201 }
202
205 void setReduction(T db) noexcept
206 {
207 if (!std::isfinite(db)) return;
208 reduction_.store(std::clamp(db, T(0), T(40)), std::memory_order_relaxed);
209 }
210
215 void setThreshold(T factor) noexcept
216 {
217 if (!std::isfinite(factor)) return;
218 threshold_.store(std::clamp(factor, T(1), T(8)), std::memory_order_relaxed);
219 }
220
229 void setDetail(T octaves) noexcept
230 {
231 if (!std::isfinite(octaves)) return;
232 detail_.store(std::clamp(octaves, T(0), T(1)), std::memory_order_relaxed);
233 }
235 void setGainRelease(T ms) noexcept
236 {
237 if (!std::isfinite(ms)) return;
238 releaseMs_.store(std::clamp(ms, T(0), T(2000)), std::memory_order_relaxed);
239 }
241 void setSensitivityBand(int index, const typename KeyEqualizer<T, 2>::Band& band) noexcept
242 {
243 sensitivity_.setBand(index, band);
244 weightDirty_.store(true, std::memory_order_release);
245 }
247 [[nodiscard]] typename KeyEqualizer<T, 2>::Band getSensitivityBand(int index) const noexcept { return sensitivity_.getBand(index); }
249 void setRemovalListen(bool on) noexcept { removalListen_.store(on, std::memory_order_relaxed); }
256 void setFilterMode(bool on) noexcept { filterMode_.store(on, std::memory_order_relaxed); }
258 void setLink(T amount) noexcept
259 {
260 if (!std::isfinite(amount)) return;
261 link_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
262 }
263
265 [[nodiscard]] T getDetail() const noexcept { return detail_.load(std::memory_order_relaxed); }
269 [[nodiscard]] static double getDisplayFrequency(int point) noexcept { return SpectralReadout<T>::frequency(point); }
271 [[nodiscard]] T getDisplayGain(int point) const noexcept
272 {
273 return stftReadout_.gainPoint(point, [this](int bin) noexcept { return shownGains_[static_cast<size_t>(bin)].load(std::memory_order_relaxed); });
274 }
275 [[nodiscard]] T getGainRelease() const noexcept { return releaseMs_.load(std::memory_order_relaxed); }
276 [[nodiscard]] bool getRemovalListen() const noexcept { return removalListen_.load(std::memory_order_relaxed); }
277 [[nodiscard]] bool getFilterMode() const noexcept { return filterMode_.load(std::memory_order_relaxed); }
278 [[nodiscard]] T getLink() const noexcept { return link_.load(std::memory_order_relaxed); }
279
280 [[nodiscard]] bool getLearning() const noexcept { return learning_.load(std::memory_order_relaxed); }
281 [[nodiscard]] T getReduction() const noexcept { return reduction_.load(std::memory_order_relaxed); }
282 [[nodiscard]] T getThreshold() const noexcept { return threshold_.load(std::memory_order_relaxed); }
283
286 [[nodiscard]] int getLatency() const noexcept
287 {
288 return prepared_.load(std::memory_order_relaxed) ? stft_.getLatency() : 0;
289 }
290
293 [[nodiscard]] std::vector<uint8_t> getState() const
294 {
295 StateWriter w(stateId("DNSE"), 2);
296 // Explicit float casts: the blob stores float, and with T = double the
297 // unqualified write(key, double) would be ambiguous (float/int32/bool).
298 w.write("reduction", static_cast<float>(reduction_.load(std::memory_order_relaxed)));
299 w.write("threshold", static_cast<float>(threshold_.load(std::memory_order_relaxed)));
300 w.write("detailOctaves", static_cast<float>(getDetail()));
301 w.write("release", static_cast<float>(getGainRelease()));
302 w.write("filterMode", getFilterMode());
303 w.write("link", static_cast<float>(getLink()));
304 sensitivity_.writeState(w, "sens");
305 return w.blob();
306 }
307
313 bool setState(const uint8_t* data, size_t size)
314 {
315 StateReader r(data, size);
316 if (!r.isValid() || r.processorId() != stateId("DNSE")) return false;
317 setReduction(static_cast<T>(r.read("reduction", 18.0f)));
318 setThreshold(static_cast<T>(r.read("threshold", 2.0f)));
319 if (r.processorVersion() < 2)
320 {
321 // A pole a both ways spreads sqrt(2a) / (1 - a) bins, a box as wide sqrt(12) of that.
322 const double a = std::clamp(static_cast<double>(r.read("smoothing", 0.0f)), 0.0, 0.95);
323 const double wide = std::sqrt(24.0 * a) / (1.0 - a) * 48000.0 / 2048.0;
324 setDetail(static_cast<T>(std::log2(1.0 + wide / 1000.0)));
325 }
326 else setDetail(static_cast<T>(r.read("detailOctaves", 0.0f)));
327 setGainRelease(static_cast<T>(r.read("release", 0.0f)));
328 setFilterMode(r.read("filterMode", false));
329 setLink(static_cast<T>(r.read("link", 0.0f)));
330 sensitivity_.readState(r, "sens");
331 weightDirty_.store(true, std::memory_order_release);
332 return true;
333 }
334
335 // -- Processing -------------------------------------------------------------------
336
338 void processBlock(AudioBufferView<T> buffer) noexcept
339 {
340 if (!prepared_.load(std::memory_order_relaxed)) return;
341
342 const bool learning = learning_.load(std::memory_order_relaxed);
343 const float floorGain = std::pow(
344 10.0f, -static_cast<float>(reduction_.load(std::memory_order_relaxed)) / 20.0f);
345 const float thresh = static_cast<float>(threshold_.load(std::memory_order_relaxed));
346
347 // The STFT processes min(buffer, prepared) channels.
348 const int nChEff = std::min(buffer.getNumChannels(), numChannels_);
349 const int samples = buffer.getNumSamples();
350 if (nChEff <= 0 || samples <= 0) return;
351
352 Now now;
353 now.channels = nChEff;
354 now.learning = learning;
355 now.floorGain = floorGain;
356 // Over-subtraction: the learned noise power is scaled by threshold^2.
357 now.overSub = thresh * thresh;
358 now.reductionDb = static_cast<float>(reduction_.load(std::memory_order_relaxed));
359 now.removal = removalListen_.load(std::memory_order_relaxed);
360 const bool spreadsNothing = filterMode_.load(std::memory_order_relaxed);
361 now.link = spreadsNothing && nChEff == 2 ? static_cast<float>(link_.load(std::memory_order_relaxed)) : 0.0f;
362
363 refreshOptions();
364 if (spreadsNothing && !shortRuns_)
365 {
366 // Switched on while playing: nothing of it until it has seen the stream.
367 resetShort(stft_.getFFTSize() + kPastFrames * shortHop_);
368 shortRuns_ = true;
369 }
370 if (!shortRuns_)
371 {
372 processLong(buffer, now);
373 return;
374 }
375 // Switched off, it stays until what it is playing is over.
376 if (!spreadsNothing && hold_ <= 0 && ramp_ <= 0)
377 {
378 shortRuns_ = false;
379 processLong(buffer, now);
380 return;
381 }
382 for (int done = 0; done < samples;)
383 {
384 const int count = std::min(samples - done, shortHop_ - shortPhase_);
385 playAhead(buffer.getSubView(done, count), now, spreadsNothing);
386 done += count;
387 shortPhase_ += count;
388 if (shortPhase_ == shortHop_) shortPhase_ = 0;
389 }
390 }
391
392private:
394 void refreshOptions() noexcept
395 {
396 const double width = static_cast<double>(detail_.load(std::memory_order_relaxed));
397 if (width != bandsFor_)
398 {
399 bandsFor_ = width;
400 const double share = std::exp2(0.5 * width) - std::exp2(-0.5 * width);
401 stftBands_.lay(numBins_, share);
402 shortBands_.lay(shortBins_, share);
403 noiseHolds_ = false;
404 shortNoiseHolds_ = false;
405 }
406 releaseNow_ = static_cast<float>(releaseMs_.load(std::memory_order_relaxed));
407 if (weightDirty_.exchange(false, std::memory_order_acquire))
408 {
409 weighted_ = sensitivity_.hasBands();
410 const auto response = sensitivity_.getResponse();
411 const double binHz = sampleRate_ / static_cast<double>(stft_.getFFTSize());
412 for (int k = 0; k < numBins_; ++k)
413 weight_[static_cast<size_t>(k)] = weighted_
414 ? static_cast<float>(std::clamp(1.0 + response.magnitudeDb(std::max(1.0, k * binHz)) / 12.0, 0.0, 2.0))
415 : 1.0f;
416 const double shortHz = sampleRate_ / static_cast<double>(shortSize_);
417 for (int k = 0; k < shortBins_; ++k)
418 shortWeight_[static_cast<size_t>(k)] = weighted_
419 ? static_cast<float>(std::clamp(1.0 + response.magnitudeDb(std::max(1.0, k * shortHz)) / 12.0, 0.0, 2.0))
420 : 1.0f;
421 }
422 if (releaseNow_ != releaseFor_)
423 {
424 releaseFor_ = releaseNow_;
425 const auto fill = [&](std::vector<float>& r, double binHz, double hop) {
426 for (size_t k = 0; k < r.size(); ++k)
427 {
428 const double f = std::max(20.0, static_cast<double>(k) * binHz);
429 const double tau = 0.001 * static_cast<double>(releaseNow_) * std::sqrt(1000.0 / f);
430 r[k] = releaseNow_ > 0.0f ? static_cast<float>(std::exp(-hop / std::max(tau, 1e-6))) : 0.0f;
431 }
432 };
433 // One hop of either: a part of the transform.
434 fill(release_, sampleRate_ / static_cast<double>(stft_.getFFTSize()),
435 static_cast<double>(stft_.getFFTSize()) / (dense_ ? static_cast<double>(kDenseFrames) : 4.0) / sampleRate_);
436 fill(shortRelease_, sampleRate_ / static_cast<double>(shortSize_), static_cast<double>(shortHop_) / sampleRate_);
437 }
438 }
439
444 static float binGain(float power, float noise, float prevClean, float overSub, float floorGain, float alpha) noexcept
445 {
446 float gain = 1.0f;
447 const float lambda = overSub * noise;
448 if (lambda > 0.0f)
449 {
450 const float post = power / lambda;
451 const float prio = std::max(alpha * prevClean / lambda
452 + (1.0f - alpha) * std::max(post - 1.0f, 0.0f),
453 kMinPrioriSnr);
454 gain = std::max(prio / (1.0f + prio), floorGain);
455 }
456 return gain;
457 }
458
460 struct Bands
461 {
462 struct Edge
463 {
464 double part = 0.0;
465 int bin = 0;
466 };
467
468 void prepare(int bins)
469 {
470 edges_.assign(2 * static_cast<size_t>(bins), Edge {});
471 scale_.assign(static_cast<size_t>(bins), 1.0);
472 first_ = bins;
473 }
474
476 void lay(int bins, double share) noexcept
477 {
478 first_ = share * static_cast<double>(bins - 1) > 1.0 ? static_cast<int>(1.0 / share) + 1 : bins;
479 for (int k = first_; k < bins; ++k)
480 {
481 const double middle = k + 0.5, half = 0.5 * k * share;
482 const double from = std::max(0.0, middle - half), to = std::min(static_cast<double>(bins), middle + half);
483 const auto u = static_cast<size_t>(k);
484 edges_[2 * u] = place(from, bins);
485 edges_[2 * u + 1] = place(to, bins);
486 scale_[u] = 1.0 / (to - from);
487 }
488 }
489
490 [[nodiscard]] static Edge place(double at, int bins) noexcept
491 {
492 const int bin = std::min(static_cast<int>(at), bins - 1);
493 return Edge { at - bin, bin };
494 }
495
497 void read(float* v, int bins, double* sum) const noexcept
498 {
499 if (first_ >= bins) return;
500 double total = 0.0;
501 for (int k = 0; k < bins; ++k)
502 {
503 sum[k] = total;
504 if (std::isfinite(v[k])) total += static_cast<double>(v[k]);
505 }
506 sum[bins] = total;
507 for (int k = first_; k < bins; ++k)
508 {
509 const auto u = static_cast<size_t>(k);
510 const Edge a = edges_[2 * u], b = edges_[2 * u + 1];
511 const double low = sum[a.bin] + a.part * (sum[a.bin + 1] - sum[a.bin]);
512 const double high = sum[b.bin] + b.part * (sum[b.bin + 1] - sum[b.bin]);
513 v[k] = static_cast<float>(std::max(0.0, (high - low) * scale_[u]));
514 }
515 }
516
517 std::vector<Edge> edges_;
518 std::vector<double> scale_;
519 int first_ = 0;
520 };
521
523 [[nodiscard]] bool isDisplayDue() noexcept
524 {
525 const bool due = displayHop_ == 0;
526 if (++displayHop_ >= displayEvery_) displayHop_ = 0;
527 return due;
528 }
529
531 void publish(int n) noexcept
532 {
533 if (n != static_cast<int>(shownGains_.size())) return;
534 for (int k = 0; k < n; ++k) shownGains_[static_cast<size_t>(k)].store(gains_[static_cast<size_t>(k)], std::memory_order_relaxed);
535 }
536
538 void shapeGains(float* g, int n, std::vector<float>& held, const std::vector<float>& release) noexcept
539 {
540 if (releaseNow_ > 0.0f)
541 for (int k = 0; k < n; ++k)
542 {
543 float& h = held[static_cast<size_t>(k)];
544 h = g[k] < h ? g[k] : g[k] + release[static_cast<size_t>(k)] * (h - g[k]);
545 g[k] = h;
546 }
547 }
548
550 struct Now
551 {
552 int channels = 0;
553 bool learning = false, removal = false;
554 float floorGain = 1.0f, overSub = 1.0f, reductionDb = 0.0f, link = 0.0f;
555 };
556
558 struct Frames
559 {
560 std::vector<std::vector<float>>& clean;
561 std::vector<std::vector<float>>& held;
562 std::array<std::vector<float>, 2>& pair;
563 const std::vector<float>& weight;
564 const std::vector<float>& release;
565 const Bands& bands;
566 float* noise;
567 float alpha;
568 };
569
571 static float powerOf(const T* bins, int k) noexcept
572 {
573 const float re = static_cast<float>(bins[2 * k]), im = static_cast<float>(bins[2 * k + 1]);
574 const float p = re * re + im * im;
575 return std::isfinite(p) ? p : 0.0f;
576 }
577
579 static void observePair(int ch, const T* bins, int count, const Now& now, std::array<std::vector<float>, 2>& pair) noexcept
580 {
581 if (now.link <= 0.0f || ch >= 2) return;
582 float* p = pair[static_cast<size_t>(ch)].data();
583 for (int k = 0; k < count; ++k) p[k] = powerOf(bins, k);
584 }
585
587 void reduceFrame(int ch, T* bins, int count, const Now& now, const Frames& f) noexcept
588 {
589 const auto c = static_cast<size_t>(ch);
590 float* power = detect_.data();
591 if (now.link > 0.0f && ch < 2)
592 {
593 // Read part of the way to the mean of the pair, in this same hop;
594 // at 1 one reading, the same to the bit on both.
595 const float* own = f.pair[c].data();
596 const float* other = f.pair[1 - c].data();
597 const float part = 0.5f * now.link;
598 if (now.link >= 1.0f)
599 for (int k = 0; k < count; ++k) power[k] = 0.5f * (own[k] + other[k]);
600 else
601 for (int k = 0; k < count; ++k) power[k] = own[k] + part * (other[k] - own[k]);
602 }
603 else
604 for (int k = 0; k < count; ++k) power[k] = powerOf(bins, k);
605 f.bands.read(power, count, sum_.data());
606
607 auto& clean = f.clean[c];
608 for (int k = 0; k < count; ++k)
609 {
610 const auto u = static_cast<size_t>(k);
611 const float fl = weighted_ ? std::pow(10.0f, -now.reductionDb * f.weight[u] / 20.0f) : now.floorGain;
612 gains_[u] = binGain(power[k], f.noise[k], clean[u], now.overSub, fl, f.alpha);
613 }
614 shapeGains(gains_.data(), count, f.held[c], f.release);
615 for (int k = 0; k < count; ++k)
616 {
617 const auto u = static_cast<size_t>(k);
618 float& g = gains_[u];
619 const float re = static_cast<float>(bins[2 * k]), im = static_cast<float>(bins[2 * k + 1]);
620 // The gain memory is recursive: a NaN in it would stay for the whole stream.
621 if (!std::isfinite(re * re + im * im))
622 {
623 g = 0.0f;
624 clean[u] = 0.0f;
625 bins[2 * k] = T(0);
626 bins[2 * k + 1] = T(0);
627 continue;
628 }
629 clean[u] = g * g * power[k];
630 const float applied = now.removal ? 1.0f - g : g;
631 bins[2 * k] = static_cast<T>(re * applied);
632 bins[2 * k + 1] = static_cast<T>(im * applied);
633 }
634 }
635
640 template <bool Learning, bool Shown>
641 void reduceFramePlain(int ch, T* bins, int count, const Now& now, float learnRate) noexcept
642 {
643 float* clean = cleanPower_[static_cast<size_t>(ch)].data();
644 float* learned = profile_.data();
645 std::atomic<float>* shown = shownGains_.data();
646 const float floorGain = now.floorGain, overSub = now.overSub, alpha = longAlpha_;
647 for (int k = 0; k < count; ++k)
648 {
649 const float re = static_cast<float>(bins[2 * k]), im = static_cast<float>(bins[2 * k + 1]);
650 const float power = re * re + im * im;
651 if (!std::isfinite(power))
652 {
653 if constexpr (Shown) shown[k].store(0.0f, std::memory_order_relaxed);
654 clean[k] = 0.0f;
655 bins[2 * k] = T(0);
656 bins[2 * k + 1] = T(0);
657 continue;
658 }
659 if constexpr (Learning) learned[k] += learnRate * (power - learned[k]);
660 const float g = binGain(power, learned[k], clean[k], overSub, floorGain, alpha);
661 if constexpr (Shown) shown[k].store(g, std::memory_order_relaxed);
662 clean[k] = g * g * power;
663 bins[2 * k] = static_cast<T>(re * g);
664 bins[2 * k + 1] = static_cast<T>(im * g);
665 }
666 }
667
669 void processLong(AudioBufferView<T> buffer, const Now& now) noexcept
670 {
671 // Nothing to read in bands or by the pair, and nothing to shape a gain.
672 const bool plain = now.link <= 0.0f && !now.removal && !weighted_ && !(releaseNow_ > 0.0f)
673 && stftBands_.first_ >= numBins_;
674 const auto process = [&](int ch, T* bins, int count) noexcept
675 {
676 if (plain)
677 {
678 // The gains go to the display only when one is due, as they are made.
679 const bool shown = ch == 0 && isDisplayDue() && count == static_cast<int>(shownGains_.size());
680 if (now.learning)
681 {
682 learnFrames_ = std::min(learnFrames_ + 1, learnMost_);
683 const float rate = 1.0f / static_cast<float>(learnFrames_);
684 if (shown) reduceFramePlain<true, true>(ch, bins, count, now, rate);
685 else reduceFramePlain<true, false>(ch, bins, count, now, rate);
686 noiseHolds_ = false;
687 shortNoiseHolds_ = false;
688 }
689 else if (shown) reduceFramePlain<false, true>(ch, bins, count, now, 0.0f);
690 else reduceFramePlain<false, false>(ch, bins, count, now, 0.0f);
691 return;
692 }
693 if (now.learning)
694 {
695 // The running mean of the noise power in each bin, an
696 // exponential one once kMaxLearnFrames are in.
697 learnFrames_ = std::min(learnFrames_ + 1, learnMost_);
698 const float rate = 1.0f / static_cast<float>(learnFrames_);
699 for (int k = 0; k < count; ++k)
700 {
701 const float re = static_cast<float>(bins[2 * k]), im = static_cast<float>(bins[2 * k + 1]);
702 const float p = re * re + im * im;
703 auto& learned = profile_[static_cast<size_t>(k)];
704 if (std::isfinite(p)) learned += rate * (p - learned);
705 }
706 shortNoiseHolds_ = false;
707 }
708 // The profile in the bands holds until it or they move.
709 if (now.learning || !noiseHolds_)
710 {
711 noiseHolds_ = true;
712 std::copy_n(profile_.data(), count, noiseHere_.data());
713 stftBands_.read(noiseHere_.data(), count, sum_.data());
714 }
715 const Frames frames { cleanPower_, heldGain_, pairPower_, weight_, release_, stftBands_, noiseHere_.data(), longAlpha_ };
716 reduceFrame(ch, bins, count, now, frames);
717 if (ch == 0 && isDisplayDue()) publish(count);
718 };
719 if (now.link > 0.0f)
720 {
721 stft_.processBlock(buffer, [&](int ch, const T* bins, int count) noexcept { observePair(ch, bins, count, now, pairPower_); }, process);
722 return;
723 }
724 // Channel by channel, through the one spectrum: the callback runs once
725 // per channel processed and hop, in channel order.
726 int call = 0;
727 stft_.processBlock(buffer, [&](T* bins, int count) noexcept
728 {
729 process(call % now.channels, bins, count);
730 ++call;
731 });
732 }
733
734 // -- The frames that play where an attack is ahead -------------------------
735
736 void prepareShort(const AudioSpec& spec)
737 {
738 const int size = stft_.getFFTSize();
739 // About 5 ms, and shorter than the long frames.
740 const double wanted = std::min(kShortSeconds * spec.sampleRate, 0.5 * static_cast<double>(size));
741 int n = std::min(16, size);
742 while (n * 1.45 < wanted) n *= 2;
743 short_.prepare(spec, n, n / 4);
744 shortSize_ = short_.getFFTSize();
745 shortHop_ = short_.getHopSize();
746 shortBins_ = short_.getNumBins();
747 const int longHop = dense_ ? size / 4 : stft_.getHopSize(); // the hop the memory is stated for
748 shortAlpha_ = static_cast<float>(std::pow(static_cast<double>(kDDAlpha), static_cast<double>(shortHop_) / static_cast<double>(longHop)));
749 fadeIn_ = std::max(1, shortSize_);
750 after_ = std::min(size, static_cast<int>(kAfterSeconds * spec.sampleRate));
751 lag_ = size - shortSize_;
752
753 const auto channels = static_cast<size_t>(numChannels_);
754 const auto bins = static_cast<size_t>(shortBins_);
755 shortClean_.assign(channels, std::vector<float>(bins, 0.0f));
756 shortHeld_.assign(channels, std::vector<float>(bins, 1.0f));
757 shortDelay_.assign(channels, std::vector<T>(static_cast<size_t>(lag_), T(0)));
758 shortAudio_.resize(std::min(numChannels_, kMostChannels), shortHop_);
759 for (auto& v : shortPair_) v.assign(bins, 0.0f);
760 shortNoise_.assign(bins, 0.0f);
761 shortNoiseRead_.assign(bins, 0.0f);
762 past_.assign(channels * kAttackBands * static_cast<size_t>(kPastFrames), 0.0f);
763
764 // What each of the four bands of the detector holds.
765 const double edges[] = { 750.0, 3000.0, 8000.0 };
766 bandEdge_[0] = 0;
767 for (int b = 1; b < kAttackBands; ++b)
768 bandEdge_[static_cast<size_t>(b)] = std::clamp(static_cast<int>(std::lround(edges[b - 1] * shortSize_ / spec.sampleRate)),
769 bandEdge_[static_cast<size_t>(b - 1)], shortBins_);
770 bandEdge_[static_cast<size_t>(kAttackBands)] = shortBins_;
771
772 // A short bin of the profile: the long bins under the short window's lobe.
773 ratio_ = size / shortSize_;
774 spreadReach_ = std::min(kLobeBins * ratio_, size / 2);
775 FFTReal<double> fft(static_cast<size_t>(size));
776 std::vector<double> time(static_cast<size_t>(size), 0.0), spectrum(static_cast<size_t>(size + 2), 0.0);
777 WindowFunctions<double>::hann(time.data(), shortSize_, true);
778 for (int i = 0; i < shortSize_; ++i) time[static_cast<size_t>(i)] = std::sqrt(time[static_cast<size_t>(i)]);
779 fft.forward(time.data(), spectrum.data());
780 spread_.assign(static_cast<size_t>(spreadReach_ + 1), 0.0f);
781 double whole = 0.0;
782 for (int d = 0; d <= spreadReach_; ++d)
783 {
784 const double re = spectrum[static_cast<size_t>(2 * d)], im = spectrum[static_cast<size_t>(2 * d + 1)];
785 whole += (d == 0 ? 1.0 : 2.0) * (re * re + im * im);
786 }
787 // White noise reads by the energy of each window.
788 const double scale = static_cast<double>(shortSize_) / (static_cast<double>(size) * whole);
789 for (int d = 0; d <= spreadReach_; ++d)
790 {
791 const double re = spectrum[static_cast<size_t>(2 * d)], im = spectrum[static_cast<size_t>(2 * d + 1)];
792 spread_[static_cast<size_t>(d)] = static_cast<float>(scale * (re * re + im * im));
793 }
794 shortNoiseHolds_ = false;
795 }
796
798 void resetShort(int unseen) noexcept
799 {
800 short_.reset();
801 for (auto& c : shortClean_) std::fill(c.begin(), c.end(), 0.0f);
802 for (auto& c : shortHeld_) std::fill(c.begin(), c.end(), 1.0f);
803 for (auto& d : shortDelay_) std::fill(d.begin(), d.end(), T(0));
804 std::fill(past_.begin(), past_.end(), 0.0f);
805 delayAt_ = 0;
806 pastAt_ = 0;
807 shortPhase_ = 0;
808 hold_ = 0;
809 ramp_ = 0;
810 unseen_ = unseen;
811 attack_ = false;
812 }
813
815 [[nodiscard]] bool startsAttack(int ch, const T* bins) noexcept
816 {
817 float* past = past_.data() + static_cast<size_t>(ch) * static_cast<size_t>(kAttackBands * kPastFrames);
818 bool starts = false;
819 for (int b = 0; b < kAttackBands; ++b, past += kPastFrames)
820 {
821 float energy = 0.0f, noise = 0.0f;
822 for (int k = bandEdge_[static_cast<size_t>(b)]; k < bandEdge_[static_cast<size_t>(b + 1)]; ++k)
823 {
824 energy += powerOf(bins, k);
825 noise += shortNoise_[static_cast<size_t>(k)];
826 }
827 if (energy > kOverNoise * noise)
828 {
829 // Not the two frames just before: they overlap this one.
830 float most = 0.0f;
831 for (int age = 3; age <= kPastFrames; ++age)
832 {
833 const int at = pastAt_ - age < 0 ? pastAt_ - age + kPastFrames : pastAt_ - age;
834 most = std::max(most, past[at]);
835 if (energy <= kRise * most) break;
836 }
837 starts = starts || energy > kRise * most;
838 }
839 past[pastAt_] = energy;
840 }
841 return starts;
842 }
843
845 void playAhead(AudioBufferView<T> chunk, const Now& now, bool seeks) noexcept
846 {
847 const int count = chunk.getNumSamples(), channels = std::min(now.channels, shortAudio_.getNumChannels());
848 T* of[kMostChannels] {};
849 for (int ch = 0; ch < channels; ++ch)
850 {
851 of[ch] = shortAudio_.getChannel(ch);
852 std::copy_n(chunk.getChannel(ch), count, of[ch]);
853 }
854 processLong(chunk, now);
855
856 const auto observe = [&](int ch, const T* bins, int bins2) noexcept
857 {
858 if (!shortNoiseHolds_) readShortNoise();
859 observePair(ch, bins, bins2, now, shortPair_);
860 attack_ = startsAttack(ch, bins) || attack_;
861 if (ch == channels - 1) pastAt_ = (pastAt_ + 1) % kPastFrames;
862 };
863 const auto process = [&](int ch, T* bins, int bins2) noexcept
864 {
865 const Frames frames { shortClean_, shortHeld_, shortPair_, shortWeight_, shortRelease_, shortBands_, shortNoiseRead_.data(), shortAlpha_ };
866 reduceFrame(ch, bins, bins2, now, frames);
867 };
868 // What plays now was settled by the hops before this chunk's.
869 const int hold = hold_, ramp = ramp_;
870 short_.processBlock(AudioBufferView<T>(of, channels, count), observe, process);
871
872 int at = delayAt_;
873 for (int ch = 0; ch < channels; ++ch)
874 {
875 T* in = shortAudio_.getChannel(ch);
876 T* line = shortDelay_[static_cast<size_t>(ch)].data();
877 at = delayAt_;
878 for (int i = 0; i < count && lag_ > 0; ++i)
879 {
880 const T late = line[at];
881 line[at] = in[i];
882 in[i] = late;
883 if (++at == lag_) at = 0;
884 }
885 }
886 delayAt_ = at;
887
888 if (hold > 0 || ramp > 0)
889 {
890 int held = hold, r = ramp;
891 for (int i = 0; i < count; ++i)
892 {
893 if (held > 0)
894 {
895 --held;
896 r = std::min(r + 1, fadeIn_);
897 }
898 else if (r > 0) --r;
899 if (r <= 0) continue;
900 const T share = r >= fadeIn_ ? T(1)
901 : T(0.5) - T(0.5) * std::cos(std::numbers::pi_v<T> * static_cast<T>(r) / static_cast<T>(fadeIn_));
902 for (int ch = 0; ch < channels; ++ch)
903 {
904 T& out = chunk.getChannel(ch)[i];
905 out += share * (shortAudio_.getChannel(ch)[i] - out);
906 }
907 }
908 hold_ = held;
909 ramp_ = r;
910 }
911 if (unseen_ > 0) unseen_ -= count;
912 if (attack_)
913 {
914 attack_ = false;
915 // Its start is a hop back, and is heard the latency later.
916 if (seeks && unseen_ <= 0) hold_ = std::max(hold_, stft_.getFFTSize() - shortHop_ + after_);
917 }
918 }
919
921 void readShortNoise() noexcept
922 {
923 shortNoiseHolds_ = true;
924 const int last = numBins_ - 1;
925 for (int j = 0; j < shortBins_; ++j)
926 {
927 const int centre = j * ratio_;
928 float sum = 0.0f;
929 for (int d = -spreadReach_; d <= spreadReach_; ++d)
930 {
931 int k = centre + d;
932 if (k < 0) k = -k;
933 if (k > last) k = 2 * last - k;
934 sum += spread_[static_cast<size_t>(d < 0 ? -d : d)] * profile_[static_cast<size_t>(std::clamp(k, 0, last))];
935 }
936 shortNoise_[static_cast<size_t>(j)] = sum;
937 }
938 std::copy(shortNoise_.begin(), shortNoise_.end(), shortNoiseRead_.begin());
939 shortBands_.read(shortNoiseRead_.data(), shortBins_, sum_.data());
940 }
941
942 static constexpr int kMostChannels = 16;
943 static constexpr int kAttackBands = 4;
944 static constexpr int kPastFrames = 72;
945 static constexpr int kLobeBins = 4;
946 static constexpr float kRise = 4.0f;
947 static constexpr float kOverNoise = 8.0f;
948 static constexpr double kShortSeconds = 0.00533;
949 static constexpr double kAfterSeconds = 0.0107;
950
951 SpectralProcessor<T> stft_, short_;
952 KeyEqualizer<T, 2> sensitivity_;
953 int numChannels_ = 0;
954 int numBins_ = 0;
955 int shortSize_ = 256, shortHop_ = 64, shortBins_ = 129, lag_ = 0, delayAt_ = 0, shortPhase_ = 0;
956 int fadeIn_ = 1, after_ = 0, hold_ = 0, ramp_ = 0, unseen_ = 0, pastAt_ = 0, ratio_ = 1, spreadReach_ = 0;
957 float shortAlpha_ = 0.98f;
958 bool shortRuns_ = false, attack_ = false, shortNoiseHolds_ = false, noiseHolds_ = false;
959 std::array<int, static_cast<size_t>(kAttackBands + 1)> bandEdge_ {};
960 std::array<std::vector<float>, 2> pairPower_, shortPair_;
961 std::vector<std::vector<float>> shortClean_, shortHeld_;
962 std::vector<std::vector<T>> shortDelay_;
963 AudioBuffer<T, kMostChannels> shortAudio_;
964 std::vector<float> shortNoise_, shortNoiseRead_, shortWeight_, shortRelease_, spread_, past_;
965 double sampleRate_ = 48000.0;
966 std::atomic<bool> prepared_ { false };
967 std::atomic<T> detail_ { T(0) }, releaseMs_ { T(0) }, link_ { T(0) };
968 std::atomic<bool> removalListen_ { false }, filterMode_ { false }, weightDirty_ { true };
969 bool weighted_ = false;
970 float releaseNow_ = 0.0f, releaseFor_ = -1.0f;
971 Bands stftBands_, shortBands_;
972 double bandsFor_ = -1.0;
973 int displayHop_ = 0, displayEvery_ = 2;
974 bool dense_ = false;
975 float longAlpha_ = 0.98f;
976 int learnMost_ = 4096;
977 std::vector<std::vector<float>> heldGain_;
978 std::vector<float> gains_, weight_, release_, detect_, noiseHere_;
979 std::vector<double> sum_;
980 SpectralReadout<T> stftReadout_;
981 std::vector<std::atomic<float>> shownGains_;
982
983 static constexpr float kDDAlpha = 0.98f;
984 static constexpr float kMinPrioriSnr = 0.003162f;
985 static constexpr int kMaxLearnFrames = 4096;
986 static constexpr int kDenseFrames = 16;
987
988 std::vector<float> profile_;
989 int learnFrames_ = 0;
990 std::vector<std::vector<float>> cleanPower_;
991
992 std::atomic<bool> learning_ { false };
993 std::atomic<T> reduction_ { T(18) };
994 std::atomic<T> threshold_ { T(2) };
995};
996
997} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
int getNumChannels() const noexcept
Returns the number of active channels.
T * getChannel(int ch) noexcept
Returns a pointer to the sample data.
void resize(int numChannels, int numSamples)
Allocates the buffer for the given dimensions.
void writeState(StateWriter &w, const char *prefix) const
Writes the bands under keys that start with a prefix ("<prefix><band>.shape", ".freq",...
Response getResponse(Placement part=Placement::Stereo) const noexcept
The sections of the published bands, designed as the audio thread designs them, for a display.
void readState(const StateReader &r, const char *prefix) noexcept
Reads the bands writeState() wrote (a band that is missing reads as Off, a placement that is missing ...
Band getBand(int band) const noexcept
The published settings of a band (a band out of range reads as Off).
void setBand(int band, const Band &settings) noexcept
Publishes the settings of a band.
bool hasBands() const noexcept
Whether any published band is in the path.
void prepare(double sampleRate) noexcept
Prepares the equalizer for a sample rate and clears its memory.
Learn-a-profile spectral noise reduction (hiss/hum/room-tone).
void setSensitivityBand(int index, const typename KeyEqualizer< T, 2 >::Band &band) noexcept
One band of the sensitivity curve: the reduction is scaled by its gain in dB / 12 + 1,...
void setThreshold(T factor) noexcept
Noise over-subtraction factor over the learned profile, in magnitude [1, 8] (default 2): the gain rul...
bool getRemovalListen() const noexcept
void setReduction(T db) noexcept
Maximum attenuation of noise bins in dB [0, 40] (default 18): the floor of the per-bin gain....
T getLink() const noexcept
void setLink(T amount) noexcept
In filter mode, how far the power each channel is read by goes to the mean of the pair,...
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids). The smoothing of the first version,...
static double getDisplayFrequency(int point) noexcept
T getReduction() const noexcept
T getThreshold() const noexcept
void setGainRelease(T ms) noexcept
Release of each bin's gain at 1 kHz, 0 (off, default) to 2000 ms; slower below, faster above.
T getDisplayGain(int point) const noexcept
void setFilterMode(bool on) noexcept
Spreads no further ahead of an attack than one short frame of 5 ms (see the file comment): the defaul...
bool getFilterMode() const noexcept
std::vector< uint8_t > getState() const
Serializes the parameter state (the learned profile is material- dependent content,...
static constexpr int kDisplayPoints
Points of the display curve, evenly in log frequency from 20 Hz to 20 kHz.
void processBlock(AudioBufferView< T > buffer) noexcept
Processes a block in-place. Pass-through until prepare() succeeds.
void clearProfile() noexcept
Forgets the learned noise profile (stream-owner thread).
int getLatency() const noexcept
Latency in samples (the STFT pipeline's); 0 before prepare() succeeds, while the instance passes audi...
void setRemovalListen(bool on) noexcept
Outputs what is taken out instead of what is kept.
bool getLearning() const noexcept
KeyEqualizer< T, 2 >::Band getSensitivityBand(int index) const noexcept
void prepare(const AudioSpec &spec, int fftSize=2048)
Prepares the STFT pipeline and the per-channel bin state.
void reset() noexcept
Clears signal state and per-bin gain memories (keeps profile).
T getGainRelease() const noexcept
T getDetail() const noexcept
void setDetail(T octaves) noexcept
The detail: the band, in octaves, in which the signal and the noise are read at each bin,...
void setLearning(bool learning) noexcept
While true, incoming audio trains the noise profile.
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
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
uint16_t processorVersion() const noexcept
Definition StateBlob.h:211
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
Definition StateBlob.h:214
bool isValid() const noexcept
Definition StateBlob.h:209
uint32_t processorId() const noexcept
Definition StateBlob.h:210
Serializes key/value parameters into a versioned blob.
Definition StateBlob.h:53
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
Definition StateBlob.h:112
void write(const char *key, float value)
Writes a float parameter.
Definition StateBlob.h:71
Main namespace for the DSPark framework.
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
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
The settings of one band.
static void hann(T *output, int size, bool periodic=true) noexcept
Hann (raised cosine) window.