DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
TonalBalance.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
93#include "../Core/AudioBuffer.h"
94#include "../Core/AudioSpec.h"
95#include "../Core/AuditoryBands.h"
96#include "../Core/DenormalGuard.h"
97#include "../Core/DetailAnalysis.h"
98#include "../Core/DetailFilter.h"
99#include "../Core/DspMath.h"
100#include "../Core/FFT.h"
101#include "../Core/SpectralEnvelope.h"
102#include "../Core/SpectralFilter.h"
103#include "../Core/StateBlob.h"
104#include "../Core/WindowFunctions.h"
105
106#include <algorithm>
107#include <array>
108#include <atomic>
109#include <cmath>
110#include <cstdint>
111#include <initializer_list>
112#include <memory>
113#include <numbers>
114#include <vector>
115
116namespace dspark {
117
124template <FloatType T>
126{
127public:
128 static constexpr int kBands = 72;
129
140
149 enum class Response { ByBand, Common };
150
158 enum class Quality { Realtime, Render };
159 static constexpr int kMaxChannels = 2;
160
162 void prepare(const AudioSpec& spec)
163 {
164 if (!spec.isValid()) return;
165 prepared_ = false;
166 fs_ = spec.sampleRate;
167 channels_ = std::min(spec.numChannels, kMaxChannels);
168 // The model scales by octaves with the rate (2048 at 44.1 to 48 kHz).
169 const int octaves = static_cast<int>(std::lround(std::log2(std::max(fs_, 8000.0) / 48000.0)));
170 fft_ = std::clamp(2048 << std::max(0, octaves), 1024, 16384);
171 if (octaves < 0) fft_ = std::max(512, 2048 >> -octaves);
172 render_ = quality_.load(std::memory_order_relaxed) == Quality::Render
173 || (qualityFollowsRender_.load(std::memory_order_relaxed) && offlineRendering_.load(std::memory_order_relaxed));
174 qualityInUse_.store(render_ ? Quality::Render : Quality::Realtime, std::memory_order_relaxed);
175 const int realtimeHop = std::max(16, fft_ / 16);
176 hop_ = render_ ? std::max(8, realtimeHop / 2) : realtimeHop;
177 const int fall = fft_ / 8;
178 transform_ = std::make_unique<FFTReal<double>>(static_cast<size_t>(fft_));
179 window_.resize(static_cast<size_t>(fft_));
180 WindowFunctions<double>::asymmetricHann(window_.data(), fft_, fall);
181 double sw = 0.0, squares = 0.0;
182 for (const double w : window_) { sw += w; squares += w * w; }
183 // Power scale: a full-scale sine reads 1 in its bin.
184 powerScale_ = 4.0 / (sw * sw);
185 // What a band of noise reads over what it holds, in that scale.
186 modelNoiseBins_ = static_cast<double>(fft_) * squares / (sw * sw);
187 bins_ = fft_ / 2 + 1;
188 bands_.prepare(fs_, fft_, kBands, 20.0, std::min(20000.0, 0.45 * fs_));
189 bands_.setReferenceSpl(static_cast<double>(referenceSpl_.load(std::memory_order_relaxed)));
190 envelope_.prepare(bins_, 1.0 / 6.0);
191 focus_.prepare(window_.data(), fft_, fft_, 1.0 / 6.0);
192 for (auto* v : { &focusRe_[0], &focusRe_[1], &focusIm_[0], &focusIm_[1] }) v->assign(static_cast<size_t>(bins_), 0.0);
193 ring_.assign(static_cast<size_t>(channels_), std::vector<double>(static_cast<size_t>(fft_), 0.0));
194 spectra_.assign(static_cast<size_t>(channels_), std::vector<double>(static_cast<size_t>(fft_ + 2), 0.0));
195 fed_.assign(static_cast<size_t>(kFeed), T(0));
196 frame_.assign(static_cast<size_t>(fft_), 0.0);
197 moments_.assign(static_cast<size_t>(kMoments * bins_), 0.0);
198 bandMoments_.assign(static_cast<size_t>(kMoments * kBands), 0.0);
199 for (int b = 0; b < kBands; ++b) centreOctave_[static_cast<size_t>(b)] = std::log2(bands_.getCentre(b) / 1000.0);
200 for (auto* v : { &ll_, &rr_, &lr_, &li_, &loud_, &evenLoud_, &corr_, &tmpA_, &tmpB_, &tmpC_, &tmpD_ }) v->assign(kBands, 0.0);
201 for (int b = 0; b < kBands; ++b)
202 {
203 const double tau = 0.001 * std::clamp(200.0 * std::pow(1000.0 / bands_.getCentre(b), 0.3), 20.0, 2000.0);
204 timeCoeff_[static_cast<size_t>(b)] = std::exp(-static_cast<double>(hop_) / (tau * fs_));
205 // The short integration of Response::Common: four periods of the centre, 8 to 100 ms.
206 const double brief = std::clamp(4.0 / bands_.getCentre(b), 0.008, 0.1);
207 briefCoeff_[static_cast<size_t>(b)] = std::exp(-static_cast<double>(hop_) / (brief * fs_));
208 }
209 filter_.prepare(spec);
210 filter_.setLinked(true);
211 analysis_.setLinked(true);
212 analysis_.setExhaustive(render_);
213 analysis_.prepare(AudioSpec { fs_, spec.maxBlockSize, channels_ });
214 prepareDetail();
215 prepared_ = true;
216 reset();
217 }
218
220 void reset() noexcept
221 {
222 for (auto& r : ring_) std::fill(r.begin(), r.end(), 0.0);
223 for (auto* v : { &ll_, &rr_, &lr_, &li_, &loud_, &evenLoud_, &corr_ }) std::fill(v->begin(), v->end(), 0.0);
224 ringPos_ = hopCounter_ = 0;
225 keyFade_ = 0.0;
226 warm_ = false;
227 filter_.reset();
228 analysis_.reset();
229 resetDetail();
230 for (auto& g : published_) g.store(T(0), std::memory_order_relaxed);
231 loudnessChange_.store(T(0), std::memory_order_relaxed);
232 raised_.store(T(0), std::memory_order_relaxed);
233 lowered_.store(T(0), std::memory_order_relaxed);
234 total_.store(T(-200), std::memory_order_relaxed);
235 centroidShift_.store(T(0), std::memory_order_relaxed);
236 }
237
238 // -- Controls ------------------------------------------------------------
239
241 void setBalance(T amount) noexcept { store(balance_, amount, T(0), T(1)); }
243 void setFillDips(T amount) noexcept { store(fillDips_, amount, T(0), T(1)); }
245 void setTrimPeaks(T amount) noexcept { store(trimPeaks_, amount, T(0), T(1)); }
247 void setTilt(T dbPerOctave) noexcept { store(tilt_, dbPerOctave, T(-6), T(6)); }
249 void setRange(T db) noexcept { store(range_, db, T(0), T(24)); }
251 void setKnee(T db) noexcept { store(knee_, db, T(0.1), T(12)); }
261 void setBalanceAsymmetry(T amount) noexcept { store(balanceAsymmetry_, amount, T(-1), T(1)); }
272 void setBalanceBias(T db) noexcept { store(balanceBias_, db, T(-6), T(6)); }
278 void setContrastKnee(T db) noexcept { store(contrastKnee_, db, T(0.1), T(12)); }
289 void setDetail(T octaves) noexcept
290 {
291 store(detail_, octaves, static_cast<T>(DetailAnalysis<T>::kFinest), static_cast<T>(DetailAnalysis<T>::kWidest));
292 }
299 void setRangeKnee(T db) noexcept { store(rangeKnee_, db, T(0), T(6)); }
309 void setFloor(T db) noexcept { store(floor_, db, T(10), T(120)); }
311 void setFrequencyRange(T loHz, T hiHz) noexcept
312 {
313 if (!std::isfinite(loHz) || !std::isfinite(hiHz)) return;
314 const T lo = std::clamp(std::min(loHz, hiHz), T(10), T(24000));
315 loHz_.store(lo, std::memory_order_relaxed);
316 hiHz_.store(std::clamp(std::max(loHz, hiHz), lo, T(24000)), std::memory_order_relaxed);
317 }
319 void setReference(Reference r) noexcept
320 {
321 reference_.store(r == Reference::EvenPower ? Reference::EvenPower : Reference::FlatLoudness, std::memory_order_relaxed);
322 }
324 void setQuality(Quality q) noexcept { quality_.store(q == Quality::Render ? Quality::Render : Quality::Realtime, std::memory_order_relaxed); }
330 void setQualityFollowsRender(bool on) noexcept { qualityFollowsRender_.store(on, std::memory_order_relaxed); }
332 void setOfflineRendering(bool on) noexcept { offlineRendering_.store(on, std::memory_order_relaxed); }
334 void setResponse(Response r) noexcept
335 {
336 response_.store(r == Response::Common ? Response::Common : Response::ByBand, std::memory_order_relaxed);
337 }
339 void setResponseTime(T ms) noexcept { store(responseMs_, ms, T(10), T(2000)); }
351 void setListeningCompensation(T db) noexcept { store(listening_, db, T(-30), T(30)); }
353 void setLevelCompensation(bool on) noexcept { levelComp_.store(on, std::memory_order_relaxed); }
365 void setLocalSlope(bool on) noexcept { localSlope_.store(on, std::memory_order_relaxed); }
377 void setTimeFocus(bool on) noexcept { timeFocus_.store(on, std::memory_order_relaxed); }
379 void setReferenceLevel(T dbSpl) noexcept { store(referenceSpl_, dbSpl, T(60), T(130)); refDirty_.store(true, std::memory_order_release); }
380
381 [[nodiscard]] T getBalance() const noexcept { return balance_.load(std::memory_order_relaxed); }
382 [[nodiscard]] T getFillDips() const noexcept { return fillDips_.load(std::memory_order_relaxed); }
383 [[nodiscard]] T getTrimPeaks() const noexcept { return trimPeaks_.load(std::memory_order_relaxed); }
384 [[nodiscard]] T getTilt() const noexcept { return tilt_.load(std::memory_order_relaxed); }
385 [[nodiscard]] T getRange() const noexcept { return range_.load(std::memory_order_relaxed); }
386 [[nodiscard]] T getKnee() const noexcept { return knee_.load(std::memory_order_relaxed); }
387 [[nodiscard]] T getBalanceAsymmetry() const noexcept { return balanceAsymmetry_.load(std::memory_order_relaxed); }
388 [[nodiscard]] T getBalanceBias() const noexcept { return balanceBias_.load(std::memory_order_relaxed); }
389 [[nodiscard]] T getContrastKnee() const noexcept { return contrastKnee_.load(std::memory_order_relaxed); }
390 [[nodiscard]] T getDetail() const noexcept { return detail_.load(std::memory_order_relaxed); }
392 [[nodiscard]] static constexpr int getNumBands() noexcept { return kBands; }
393 [[nodiscard]] T getRangeKnee() const noexcept { return rangeKnee_.load(std::memory_order_relaxed); }
394 [[nodiscard]] T getFloor() const noexcept { return floor_.load(std::memory_order_relaxed); }
395 [[nodiscard]] T getLowFrequency() const noexcept { return loHz_.load(std::memory_order_relaxed); }
396 [[nodiscard]] T getHighFrequency() const noexcept { return hiHz_.load(std::memory_order_relaxed); }
397 [[nodiscard]] bool getLevelCompensation() const noexcept { return levelComp_.load(std::memory_order_relaxed); }
398 [[nodiscard]] bool getLocalSlope() const noexcept { return localSlope_.load(std::memory_order_relaxed); }
399 [[nodiscard]] bool getTimeFocus() const noexcept { return timeFocus_.load(std::memory_order_relaxed); }
400 [[nodiscard]] Reference getReference() const noexcept { return reference_.load(std::memory_order_relaxed); }
401 [[nodiscard]] Response getResponse() const noexcept { return response_.load(std::memory_order_relaxed); }
402 [[nodiscard]] Quality getQuality() const noexcept { return quality_.load(std::memory_order_relaxed); }
403 [[nodiscard]] bool getQualityFollowsRender() const noexcept { return qualityFollowsRender_.load(std::memory_order_relaxed); }
405 [[nodiscard]] Quality getQualityInUse() const noexcept { return qualityInUse_.load(std::memory_order_relaxed); }
406 [[nodiscard]] T getResponseTime() const noexcept { return responseMs_.load(std::memory_order_relaxed); }
407 [[nodiscard]] T getListeningCompensation() const noexcept { return listening_.load(std::memory_order_relaxed); }
408 [[nodiscard]] T getReferenceLevel() const noexcept { return referenceSpl_.load(std::memory_order_relaxed); }
409
411 [[nodiscard]] int getLatency() const noexcept { return filter_.getLatency(); }
413 [[nodiscard]] double getBandCentre(int band) const noexcept { return bands_.getCentre(band); }
419 [[nodiscard]] T getCorrection(int band) const noexcept
420 {
421 return published_[static_cast<size_t>(std::clamp(band, 0, kBands - 1))].load(std::memory_order_relaxed);
422 }
426 [[nodiscard]] static double getDisplayFrequency(int point) noexcept { return SpectralReadout<T>::frequency(point); }
428 [[nodiscard]] T getDisplayCorrection(int point) const noexcept { return filter_.playedValue(0, point); }
435 [[nodiscard]] T getLoudnessChange() const noexcept { return loudnessChange_.load(std::memory_order_relaxed); }
441 [[nodiscard]] T getLoudnessRaised() const noexcept { return raised_.load(std::memory_order_relaxed); }
443 [[nodiscard]] T getLoudnessLowered() const noexcept { return lowered_.load(std::memory_order_relaxed); }
445 [[nodiscard]] T getLoudness() const noexcept { return total_.load(std::memory_order_relaxed); }
447 [[nodiscard]] T getCentroidShift() const noexcept { return centroidShift_.load(std::memory_order_relaxed); }
449 [[nodiscard]] double getResponse(double hz) const noexcept
450 {
451 if (!(hz > 0.0)) return 0.0;
452 const double at = std::clamp((kPoints - 1) * std::log(hz / 20.0) / std::log(1000.0), 0.0, static_cast<double>(kPoints - 1));
453 const int under = std::min(static_cast<int>(at), kPoints - 2);
454 const double a = static_cast<double>(filter_.playedValue(0, under)), b = static_cast<double>(filter_.playedValue(0, under + 1));
455 return a + (at - under) * (b - a);
456 }
457
458 // -- Processing ----------------------------------------------------------
459
461 void processBlock(AudioBufferView<T> buffer) noexcept { run(buffer, nullptr); }
462
465 {
466 run(buffer, key.getNumSamples() >= buffer.getNumSamples() && key.getNumChannels() > 0 ? &key : nullptr);
467 }
468
469 // -- State ---------------------------------------------------------------
470
471 [[nodiscard]] std::vector<uint8_t> getState() const
472 {
473 StateWriter w(stateId("TBAL"), 2);
474 w.write("balance", static_cast<float>(getBalance()));
475 w.write("fillDips", static_cast<float>(getFillDips()));
476 w.write("trimPeaks", static_cast<float>(getTrimPeaks()));
477 w.write("tilt", static_cast<float>(getTilt()));
478 w.write("range", static_cast<float>(getRange()));
479 w.write("knee", static_cast<float>(getKnee()));
480 w.write("balanceAsymmetry", static_cast<float>(getBalanceAsymmetry()));
481 w.write("balanceBias", static_cast<float>(getBalanceBias()));
482 w.write("contrastKnee", static_cast<float>(getContrastKnee()));
483 w.write("detailOctaves", static_cast<float>(getDetail()));
484 w.write("rangeKnee", static_cast<float>(getRangeKnee()));
485 w.write("floor", static_cast<float>(getFloor()));
486 w.write("loHz", static_cast<float>(getLowFrequency()));
487 w.write("hiHz", static_cast<float>(getHighFrequency()));
488 w.write("levelComp", getLevelCompensation());
489 w.write("localSlope", getLocalSlope());
490 w.write("timeFocus", getTimeFocus());
491 w.write("reference", static_cast<int32_t>(getReference()));
492 w.write("response", static_cast<int32_t>(getResponse()));
493 w.write("quality", static_cast<int32_t>(getQuality()));
494 w.write("qualityFollowsRender", getQualityFollowsRender());
495 w.write("responseMs", static_cast<float>(getResponseTime()));
496 w.write("listening", static_cast<float>(getListeningCompensation()));
497 w.write("refSpl", static_cast<float>(getReferenceLevel()));
498 return w.blob();
499 }
500
506 bool setState(const uint8_t* data, size_t size)
507 {
508 StateReader r(data, size);
509 if (!r.isValid() || r.processorId() != stateId("TBAL")) return false;
510 setBalance(static_cast<T>(r.read("balance", 0.5f)));
511 setFillDips(static_cast<T>(r.read("fillDips", 0.3f)));
512 setTrimPeaks(static_cast<T>(r.read("trimPeaks", 0.5f)));
513 setTilt(static_cast<T>(r.read("tilt", 0.0f)));
514 setRange(static_cast<T>(r.read("range", 6.0f)));
515 setKnee(static_cast<T>(r.read("knee", 3.0f)));
516 setBalanceAsymmetry(static_cast<T>(r.read("balanceAsymmetry", 0.0f)));
517 setBalanceBias(static_cast<T>(r.read("balanceBias", 0.0f)));
518 setContrastKnee(static_cast<T>(r.read("contrastKnee", 3.0f)));
519 if (r.processorVersion() < 2)
520 {
521 const int step = r.read("detail", -1);
522 setDetail(step == 0 ? T(1.0 / 3.0) : (step == 1 ? T(1.0 / 6.0) : (step == 2 ? T(1.0 / 12.0) : T(1.0 / 4.0))));
523 }
524 else setDetail(static_cast<T>(r.read("detailOctaves", 0.25f)));
525 setRangeKnee(static_cast<T>(r.read("rangeKnee", 0.0f)));
526 setFloor(static_cast<T>(r.read("floor", 30.0f)));
527 setFrequencyRange(static_cast<T>(r.read("loHz", 40.0f)), static_cast<T>(r.read("hiHz", 16000.0f)));
528 setLevelCompensation(r.read("levelComp", false));
529 setLocalSlope(r.read("localSlope", false));
530 setTimeFocus(r.read("timeFocus", false));
532 setResponse(r.read("response", 0) == 1 ? Response::Common : Response::ByBand);
533 setQuality(r.read("quality", 0) == 1 ? Quality::Render : Quality::Realtime);
534 setQualityFollowsRender(r.read("qualityFollowsRender", false));
535 setResponseTime(static_cast<T>(r.read("responseMs", 60.0f)));
536 setListeningCompensation(static_cast<T>(r.read("listening", 0.0f)));
537 setReferenceLevel(static_cast<T>(r.read("refSpl", 100.0f)));
538 return true;
539 }
540
541private:
542 static void store(std::atomic<T>& a, T v, T lo, T hi) noexcept
543 {
544 if (std::isfinite(v)) a.store(std::clamp(v, lo, hi), std::memory_order_relaxed);
545 }
546
547 void run(AudioBufferView<T>& buffer, const AudioBufferView<T>* key) noexcept
548 {
549 if (!prepared_) return;
550 DenormalGuard guard;
551 const int nCh = std::min(buffer.getNumChannels(), channels_);
552 if (nCh <= 0) return;
553 const bool referenceMoved = refDirty_.exchange(false, std::memory_order_acquire);
554 if (referenceMoved) bands_.setReferenceSpl(static_cast<double>(referenceSpl_.load(std::memory_order_relaxed)));
555 if (const T detail = detail_.load(std::memory_order_relaxed); referenceMoved || detail != lastDetail_)
556 {
557 lastDetail_ = detail;
558 refreshDetail();
559 }
560 const double fadeTo = key != nullptr ? 1.0 : 0.0, fadeStep = 1.0 / (0.05 * fs_);
561 filter_.processBlock(
562 buffer,
563 [&](int offset, int count) noexcept { feed(buffer, key, nCh, offset, count, fadeTo, fadeStep); },
564 [&](int, T* curveDb) noexcept {
565 analysis_.update(nCh);
566 design(curveDb);
567 });
568 if (!filter_.isDisplayDue(shownCurve_)) return;
569 shownCurve_ = filter_.getCurveCount();
570 filter_.publishPlayed(nCh);
571 }
572
577 void feed(AudioBufferView<T>& buffer, const AudioBufferView<T>* key, int nCh, int offset, int count,
578 double fadeTo, double fadeStep) noexcept
579 {
580 // What is not a number neither is read nor enters the filter.
581 for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
582 {
583 T* x = buffer.getChannel(ch) + offset;
584 for (int k = 0; k < count; ++k)
585 if (!std::isfinite(x[k])) x[k] = T(0);
586 }
587 int done = 0;
588 while (done < count)
589 {
590 const int chunk = std::min({ count - done, hop_ - hopCounter_, kFeed });
591 double fade = keyFade_;
592 for (int ch = 0; ch < nCh; ++ch)
593 {
594 const T* x = buffer.getChannel(ch) + offset + done;
595 const T* k = key != nullptr ? key->getChannel(std::min(ch, key->getNumChannels() - 1)) + offset + done : nullptr;
596 T* fed = fed_.data();
597 auto& ring = ring_[static_cast<size_t>(ch)];
598 fade = keyFade_;
599 if (fade == 0.0 && fadeTo == 0.0)
600 {
601 // The programme alone, already finite: as it comes.
602 const int head = std::min(chunk, fft_ - ringPos_);
603 double* r = ring.data();
604 for (int i = 0; i < head; ++i) r[ringPos_ + i] = static_cast<double>(x[i]);
605 for (int i = head; i < chunk; ++i) r[i - head] = static_cast<double>(x[i]);
606 analysis_.feed(ch, x, chunk);
607 continue;
608 }
609 for (int i = 0; i < chunk; ++i)
610 {
611 fade = fadeTo > fade ? std::min(fadeTo, fade + fadeStep) : std::max(fadeTo, fade - fadeStep);
612 double a = static_cast<double>(x[i]);
613 if (fade > 0.0 && k != nullptr) a += fade * (static_cast<double>(k[i]) - a);
614 if (!std::isfinite(a)) a = 0.0;
615 fed[i] = static_cast<T>(a);
616 ring[static_cast<size_t>((ringPos_ + i) & (fft_ - 1))] = a;
617 }
618 analysis_.feed(ch, fed, chunk);
619 }
620 keyFade_ = fade;
621 ringPos_ = (ringPos_ + chunk) & (fft_ - 1);
622 hopCounter_ += chunk;
623 if (hopCounter_ >= hop_)
624 {
625 hopCounter_ = 0;
626 analyse(nCh);
627 }
628 done += chunk;
629 }
630 }
631
637 template <int Lanes>
638 void readBands(bool smoothed) noexcept
639 {
640 if (smoothed) envelope_.template computeInterleaved<Lanes>(moments_.data());
641 bands_.template bandPowersInterleaved<Lanes>(moments_.data(), bandMoments_.data());
642 std::vector<double>* const into[kMoments] = { &tmpA_, &tmpB_, &tmpC_, &tmpD_ };
643 for (int j = 0; j < Lanes; ++j)
644 {
645 double* out = into[j]->data();
646 for (int b = 0; b < kBands; ++b) out[b] = bandMoments_[static_cast<size_t>(Lanes * b + j)];
648 }
649 }
650
652 void analyse(int nCh) noexcept
653 {
654 for (int ch = 0; ch < nCh; ++ch)
655 {
656 const double* r = ring_[static_cast<size_t>(ch)].data();
657 const double* w = window_.data();
658 double* frame = frame_.data();
659 const int older = fft_ - ringPos_;
660 for (int k = 0; k < older; ++k) frame[k] = r[ringPos_ + k] * w[k];
661 for (int k = 0; k < ringPos_; ++k) frame[older + k] = r[k] * w[older + k];
662 transform_->forward(frame_.data(), spectra_[static_cast<size_t>(ch)].data());
663 }
664 // Band powers of the two channels and of their cross term, each from
665 // a spectrum smoothed across frequency: the four moments of each bin
666 // side by side, read together.
667 const double* s0 = spectra_[0].data();
668 const double* s1 = spectra_[static_cast<size_t>(nCh > 1 ? 1 : 0)].data();
669 const bool focused = timeFocus_.load(std::memory_order_relaxed);
670 double* m = moments_.data();
671 if (focused)
672 {
673 // Through the focus: each channel's complex spectrum smoothed
674 // across frequency (every bin read through a stretch of the window
675 // of its own, shorter as frequency rises), then the products.
676 const size_t other = nCh > 1 ? 1 : 0;
677 focus_.smooth(s0, focusRe_[0].data(), focusIm_[0].data());
678 if (nCh > 1) focus_.smooth(s1, focusRe_[1].data(), focusIm_[1].data());
679 const double* ar = focusRe_[0].data();
680 const double* ai = focusIm_[0].data();
681 const double* br = focusRe_[other].data();
682 const double* bi = focusIm_[other].data();
683 for (int k = 0; k < bins_; ++k)
684 {
685 const double scale = powerScale_ * focus_.getGain(k);
686 if (nCh > 1)
687 {
688 m[kMoments * k] = scale * (ar[k] * ar[k] + ai[k] * ai[k]);
689 m[kMoments * k + 1] = scale * (br[k] * br[k] + bi[k] * bi[k]);
690 m[kMoments * k + 2] = scale * (ar[k] * br[k] + ai[k] * bi[k]);
691 m[kMoments * k + 3] = scale * (ai[k] * br[k] - ar[k] * bi[k]);
692 }
693 else
694 {
695 m[k] = scale * (ar[k] * ar[k] + ai[k] * ai[k]);
696 }
697 }
698 }
699 else if (nCh > 1)
700 {
701 for (int k = 0; k < bins_; ++k)
702 {
703 const double lr = s0[2 * k], li = s0[2 * k + 1], rr = s1[2 * k], ri = s1[2 * k + 1];
704 m[kMoments * k] = powerScale_ * (lr * lr + li * li);
705 m[kMoments * k + 1] = powerScale_ * (rr * rr + ri * ri);
706 m[kMoments * k + 2] = powerScale_ * (lr * rr + li * ri);
707 m[kMoments * k + 3] = powerScale_ * (li * rr - lr * ri);
708 }
709 }
710 else
711 {
712 for (int k = 0; k < bins_; ++k) m[k] = powerScale_ * (s0[2 * k] * s0[2 * k] + s0[2 * k + 1] * s0[2 * k + 1]);
713 }
714 if (nCh > 1) readBands<kMoments>(!focused);
715 else readBands<1>(!focused);
716 // The two smoothings in time: by band (both the band's own time,
717 // longer in the low end) or a short integration per band and then a
718 // response common to all.
719 const bool common = response_.load(std::memory_order_relaxed) == Response::Common;
720 const double commonCoeff = std::exp(-static_cast<double>(hop_)
721 / (0.001 * static_cast<double>(responseMs_.load(std::memory_order_relaxed)) * fs_));
722 // The covariance in time; the dominant power.
723 for (int b = 0; b < kBands; ++b)
724 {
725 const auto i = static_cast<size_t>(b);
726 const double c = warm_ ? (common ? briefCoeff_[i] : timeCoeff_[i]) : 0.0;
727 ll_[i] = tmpA_[i] + c * (ll_[i] - tmpA_[i]);
728 if (nCh > 1)
729 {
730 rr_[i] = tmpB_[i] + c * (rr_[i] - tmpB_[i]);
731 lr_[i] = tmpC_[i] + c * (lr_[i] - tmpC_[i]);
732 li_[i] = tmpD_[i] + c * (li_[i] - tmpD_[i]);
733 tmpA_[i] = AuditoryScale::dominantPower(ll_[i], rr_[i], lr_[i], li_[i]);
734 }
735 else
736 {
737 tmpA_[i] = ll_[i];
738 }
739 }
740 bands_.specificLoudness(tmpA_.data(), tmpB_.data());
741 const bool comp = levelComp_.load(std::memory_order_relaxed);
742 constexpr double kMidExponent = 0.23;
743 // The even programme: the same power in every band (the mean of this
744 // programme's), and its loudness through the same model and the same
745 // smoothing in time.
746 double meanPower = 0.0;
747 for (int b = 0; b < kBands; ++b) meanPower += tmpA_[static_cast<size_t>(b)];
748 meanPower /= kBands;
749 for (int b = 0; b < kBands; ++b) tmpD_[static_cast<size_t>(b)] = meanPower;
750 bands_.specificLoudness(tmpD_.data(), tmpC_.data());
751 for (int b = 0; b < kBands; ++b)
752 {
753 const auto i = static_cast<size_t>(b);
754 const double c = warm_ ? (common ? commonCoeff : timeCoeff_[i]) : 0.0;
755 loud_[i] = tmpB_[i] + c * (loud_[i] - tmpB_[i]);
756 evenLoud_[i] = tmpC_[i] + c * (evenLoud_[i] - tmpC_[i]);
757 }
758 warm_ = true;
759 const bool evenPower = reference_.load(std::memory_order_relaxed) == Reference::EvenPower;
760 const bool localSlope = localSlope_.load(std::memory_order_relaxed);
761 // Loudness in decibels of power, the trend, the two deviations.
762 const double tilt = static_cast<double>(tilt_.load(std::memory_order_relaxed));
763 const double lo = static_cast<double>(loHz_.load(std::memory_order_relaxed));
764 const double hi = static_cast<double>(hiHz_.load(std::memory_order_relaxed));
765 const double zLo = AuditoryScale::hzToBark(lo), zHi = AuditoryScale::hzToBark(hi);
766 // How audible each band is: its power over its threshold in quiet,
767 // nothing under it, all of it from kAudibleSpan dB over. A band
768 // under the threshold has a loudness of almost nothing, and its
769 // level would read as a hole of tens of decibels: it neither shapes
770 // the trend nor takes a correction (filling it would raise content
771 // nobody hears, the ends of the band first).
772 std::array<double, kBands> level {}, trend {}, weight {}, exponent {}, steep {}, audible {}, weighed {}, present {}, inRange {};
773 for (int b = 0; b < kBands; ++b)
774 {
775 const auto i = static_cast<size_t>(b);
776 exponent[i] = comp ? bands_.getExponent(b) : kMidExponent;
777 steep[i] = exponent[i];
778 if (localSlope)
779 {
780 // d ln N / d ln P of N = (P + th)^a - th^a at the power this
781 // band's loudness stands for: a far over the threshold, 1 under it.
782 const double a = bands_.getExponent(b), th = bands_.getThreshold(b);
783 const double whole = loud_[i] + bands_.getThresholdLoudness(b); // (P + th)^a
784 const double power = std::pow(whole, 1.0 / a) - th; // P
785 steep[i] = loud_[i] > 1e-30 && power > 0.0 ? std::clamp(a * power * whole / ((power + th) * loud_[i]), exponent[i], 1.0) : 1.0;
786 }
787 level[i] = 10.0 * std::log10(loud_[i] + 1e-12) / exponent[i];
788 // Against the even programme, the level is how far this one
789 // stands from it in each band.
790 if (evenPower) level[i] -= 10.0 * std::log10(evenLoud_[i] + 1e-12) / exponent[i];
791 const double over = 10.0 * std::log10((tmpA_[i] + 1e-30) / bands_.getThreshold(b));
792 audible[i] = std::clamp(over / kAudibleSpan, 0.0, 1.0);
793 trend[i] = audible[i] * level[i];
794 weighed[i] = audible[i];
795 const double z = bands_.getBark(b);
796 inRange[i] = std::clamp(z - zLo + 0.5, 0.0, 1.0) * std::clamp(zHi - z + 0.5, 0.0, 1.0);
797 weight[i] = inRange[i] * audible[i];
798 }
799 // How far under the programme each band lies: one setFloor() dB under
800 // the loudest audible band (in the model's level) is no part of the
801 // balance to give back (the floor of a recording, what lies past the
802 // end of the content), and it takes neither the balance nor the
803 // offset that keeps the loudness; it counts in full from kMaskedSpan
804 // dB over that. A dip between two sides that sound is still a dip.
805 {
806 const double floorDb = static_cast<double>(floor_.load(std::memory_order_relaxed));
807 double loudest = -1e9;
808 for (int b = 0; b < kBands; ++b)
809 if (audible[static_cast<size_t>(b)] > 0.0) loudest = std::max(loudest, level[static_cast<size_t>(b)]);
810 for (int b = 0; b < kBands; ++b)
811 present[static_cast<size_t>(b)] = std::clamp((level[static_cast<size_t>(b)] - loudest + floorDb) / kMaskedSpan, 0.0, 1.0);
812 }
813 // The trend across the bands, each weighed by how audible it is (a
814 // normalized smoothing: the audible neighbours of a band decide it).
816 AuditoryBands<double>::smoothAcross(weighed.data(), kBands, 0.9);
817 for (int b = 0; b < kBands; ++b)
818 {
819 const auto i = static_cast<size_t>(b);
820 trend[i] = weighed[i] > 1e-9 ? trend[i] / weighed[i] : level[i];
821 }
822 double meanDev = 0.0, wsum = 0.0;
823 for (int b = 0; b < kBands; ++b)
824 {
825 const auto i = static_cast<size_t>(b);
826 const double ref = tilt * centreOctave_[i];
827 tmpC_[i] = trend[i] - ref;
828 meanDev += weight[i] * tmpC_[i];
829 wsum += weight[i];
830 }
831 meanDev = wsum > 0.0 ? meanDev / wsum : 0.0;
832 const double balance = static_cast<double>(balance_.load(std::memory_order_relaxed));
833 // What is lacking (under the reference) and what is in excess, each
834 // with its share of the balance; the point between them moved by the bias.
835 const double asymmetry = static_cast<double>(balanceAsymmetry_.load(std::memory_order_relaxed));
836 const double bias = static_cast<double>(balanceBias_.load(std::memory_order_relaxed));
837 const double liftShare = balance * (1.0 + asymmetry), cutShare = balance * (1.0 - asymmetry);
838 const double range = static_cast<double>(range_.load(std::memory_order_relaxed));
839 const double knee = static_cast<double>(knee_.load(std::memory_order_relaxed));
840 const auto soft = [knee](double d) { return std::copysign(std::sqrt(d * d + knee * knee) - knee, d); };
841 const double rangeKnee = static_cast<double>(rangeKnee_.load(std::memory_order_relaxed));
842 const double listening = static_cast<double>(listening_.load(std::memory_order_relaxed));
843 const double midExponent = AuditoryScale::loudnessExponent(3300.0);
844 // The limit of the range: hard, or the smaller of the correction and
845 // the range through a hyperbola (set to pass through 0 and to settle
846 // on the range).
847 const double atZero = 0.5 * (range - std::sqrt(range * range + rangeKnee * rangeKnee));
848 const auto limited = [range, rangeKnee, atZero](double c) {
849 if (!(rangeKnee > 0.0)) return std::clamp(c, -range, range);
850 const double a = std::abs(c), past = a - range;
851 const double rounded = 0.5 * (a + range - std::sqrt(past * past + rangeKnee * rangeKnee));
852 return std::copysign((rounded - atZero) * range / (range - atZero), c);
853 };
854 for (int b = 0; b < kBands; ++b)
855 {
856 const auto i = static_cast<size_t>(b);
857 // With the local slope, what a band lacks or has in excess is read with
858 // the slope of its own loudness curve (never more than the exponent says).
859 const double ease = exponent[i] / steep[i];
860 const double global = ease * (tmpC_[i] - meanDev - bias);
861 // The balance by how present the band is (limited first, so a band
862 // half way down to the floor takes half of it), then what the
863 // detail moves in the band.
864 double c = limited(-(global < 0.0 ? liftShare : cutShare) * soft(global));
865 if (present[i] < 1.0) c *= present[i];
866 c = std::clamp(c * weight[i] + detailMean_[i], -range, range);
867 // The listening level: a fixed contour, whatever the programme.
868 if (listening != 0.0)
869 c = std::clamp(c + listening * (1.0 - midExponent / bands_.getExponent(b)) * inRange[i], -range, range);
870 corr_[i] = c;
871 }
872 // The total loudness stays: every band in range takes the same
873 // loudness ratio (by its weight), found with the limits in place: a
874 // band at its limit or out of the range gives nothing, so the others
875 // make up for it. The loudness after an offset rises with it; a few
876 // steps on its logarithm (exact in one when no band is held) with a
877 // bracket find where it meets the loudness before.
878 constexpr double kPerDb = 0.23025850929940457; // ln(10) / 10
879 std::array<double, kBands> part {};
880 double before = 0.0;
881 for (int b = 0; b < kBands; ++b)
882 {
883 const auto i = static_cast<size_t>(b);
884 part[i] = ((b == 0 || b == kBands - 1) ? 0.5 : 1.0) * loud_[i];
885 before += part[i];
886 }
887 const auto loudnessAt = [&](double offset, double& slope) {
888 double sum = 0.0;
889 slope = 0.0;
890 for (int b = 0; b < kBands; ++b)
891 {
892 const auto i = static_cast<size_t>(b);
893 const double raw = corr_[i] + offset * weight[i] * present[i] / steep[i];
894 const double l = part[i] * std::exp(kPerDb * steep[i] * std::clamp(raw, -range, range));
895 sum += l;
896 if (raw > -range && raw < range) slope += l * kPerDb * weight[i] * present[i];
897 }
898 return sum;
899 };
900 double offset = 0.0, change = 0.0;
901 if (before > 1e-20)
902 {
903 double under = -kOffsetLimit, over = kOffsetLimit; // the offset lies between them
904 bool measured = false; // whether `change` was read at the offset kept
905 for (int step = 0; step < kOffsetSteps; ++step)
906 {
907 double slope = 0.0;
908 const double after = loudnessAt(offset, slope);
909 change = std::log(std::max(after, 1e-300) / before);
910 measured = true;
911 if (std::abs(change) < 1e-9) break;
912 if (change > 0.0) over = offset; else under = offset;
913 // Where every band that could move is at its limit there is
914 // no slope: the offset is halfway back in the bracket.
915 const double next = slope > 1e-30 * before ? offset - change * after / slope : over + 1.0;
916 offset = next > under && next < over ? next : 0.5 * (under + over);
917 measured = false;
918 }
919 if (!measured)
920 {
921 double slope = 0.0;
922 change = std::log(std::max(loudnessAt(offset, slope), 1e-300) / before);
923 }
924 change /= kPerDb;
925 }
926 loudnessChange_.store(static_cast<T>(change), std::memory_order_relaxed);
927 for (int b = 0; b < kBands; ++b)
928 {
929 const auto i = static_cast<size_t>(b);
930 corr_[i] = std::clamp(corr_[i] + offset * weight[i] * present[i] / steep[i], -range, range);
931 // The broad curve: the band's, less what was the detail's.
932 base_[i] = corr_[i] - detailMean_[i];
933 published_[i].store(static_cast<T>(corr_[i]), std::memory_order_relaxed);
934 }
935 // What the corrections do to the loudness: the share the raised bands
936 // gain, the share the lowered ones lose, the total, and how far its
937 // centre moves along the ear's scale.
938 {
939 double raised = 0.0, lowered = 0.0, after = 0.0, centreBefore = 0.0, centreAfter = 0.0;
940 for (int b = 0; b < kBands; ++b)
941 {
942 const auto i = static_cast<size_t>(b);
943 const double l = part[i] * std::exp(kPerDb * steep[i] * corr_[i]);
944 const double d = l - part[i];
945 if (d > 0.0) raised += d; else lowered += d;
946 after += l;
947 centreBefore += part[i] * bands_.getBark(b);
948 centreAfter += l * bands_.getBark(b);
949 }
950 const bool sounding = before > 1e-20 && after > 1e-20;
951 raised_.store(static_cast<T>(sounding ? raised / before : 0.0), std::memory_order_relaxed);
952 lowered_.store(static_cast<T>(sounding ? lowered / before : 0.0), std::memory_order_relaxed);
953 total_.store(static_cast<T>(sounding ? 10.0 * std::log10(before) : -200.0), std::memory_order_relaxed);
954 centroidShift_.store(static_cast<T>(sounding ? centreAfter / after - centreBefore / before : 0.0), std::memory_order_relaxed);
955 }
956 }
957
958 // -- The detail: the dips and the peaks over the whole band -----------------
959
960 static constexpr int kPoints = SpectralReadout<T>::kPoints;
961
963 void prepareDetail()
964 {
965 const auto size = static_cast<size_t>(kPoints);
966 for (auto* v : { &power_, &smoothPower_, &seen_, &level_, &gapLevel_, &heard_, &asked_, &detailGain_,
967 &lowerSide_, &upperSide_, &quarter_, &octave_, &threshold_, &slowCoeff_ })
968 v->assign(size, T(0));
969 sum_.assign(size + 1, 0.0);
970 place_.resize(size);
971 for (auto* v : { &heldSum_, &movedSum_ }) v->assign(size + 1, 0.0);
972 for (auto* v : { &pointShare_, &seenShare_ }) v->assign(size, 0.0);
973 for (auto* v : { &seenFrom_, &seenTo_ }) v->assign(size, 0);
974 hopSeconds_ = static_cast<double>(filter_.getHopSize()) / fs_;
975 top_ = 0;
976 for (int i = 0; i < kPoints; ++i)
977 {
978 const auto u = static_cast<size_t>(i);
980 if (hz < 0.45 * fs_) top_ = i + 1;
981 octave_[u] = static_cast<T>(std::log2(hz / 1000.0));
982 const double at = std::clamp((AuditoryScale::hzToBark(hz) - bands_.getBark(0)) / bands_.getSpacing(), 0.0, kBands - 1.0);
983 const int under = std::min(static_cast<int>(at), kBands - 2);
984 const double t = at - under;
985 Place& p = place_[u];
986 p.band = under;
987 p.part = static_cast<T>(t);
988 // Catmull-Rom between the centres: the broad curve has no corners.
989 p.weight[0] = static_cast<T>(0.5 * t * ((2.0 - t) * t - 1.0));
990 p.weight[1] = static_cast<T>(0.5 * (t * t * (3.0 * t - 5.0) + 2.0));
991 p.weight[2] = static_cast<T>(0.5 * t * ((4.0 - 3.0 * t) * t + 1.0));
992 p.weight[3] = static_cast<T>(0.5 * t * t * (t - 1.0));
993 // Few bins at the bottom: the low end takes longer to settle.
994 slowCoeff_[u] = static_cast<T>(std::exp(-hopSeconds_ / std::clamp(1.5 * std::sqrt(100.0 / hz), kShortestSmoothing, 2.0)));
995 }
996 detailGlide_ = static_cast<T>(std::exp(-hopSeconds_ / kDetailGlideSeconds));
997 lastDetail_ = detail_.load(std::memory_order_relaxed);
998 refreshDetail();
999 }
1000
1002 void refreshDetail() noexcept
1003 {
1004 const double width = static_cast<double>(lastDetail_);
1005 analysis_.setWidth(width);
1006 const double perOctave = (kPoints - 1) * std::numbers::ln2 / std::log(1000.0);
1007 aside_ = std::max(2, static_cast<int>(std::lround(0.5 * width * perOctave)));
1008 // The rule of the space between partials comes in from a sixth of an
1009 // octave down to a twelfth, so that a sweep of the detail has no step.
1010 gapShare_ = static_cast<T>(std::clamp(std::log2(kFinestDip / width), 0.0, 1.0));
1011 gapHalf_ = static_cast<int>(std::lround(0.5 * kFinestDip * perOctave));
1012 acrossHalf_ = std::max(1, static_cast<int>(std::lround(width * perOctave / 8.0)));
1013 sidePole_ = std::exp(-1.0 / (std::max(kSideOctaves, 2.0 * width) * perOctave));
1014 const double bandShare = 0.5 * (std::exp2(0.5 * width) - std::exp2(-0.5 * width)) + 0.5 * (std::pow(1000.0, 1.0 / (kPoints - 1)) - 1.0);
1015 for (int i = 0; i < kPoints; ++i)
1016 {
1017 const auto u = static_cast<size_t>(i);
1019 const Place& p = place_[u];
1020 // A point holds the power of its width (of the window's, where that
1021 // is wider); the threshold is that of a band of the model around it.
1022 const double held = std::max(bandShare * hz, 1.5 / std::max(analysis_.getWindowSeconds(i), 1e-3));
1023 const double band = AuditoryScale::criticalBandwidth(hz) * bands_.getSpacing() * modelNoiseBins_;
1024 const double a = 10.0 * std::log10(bands_.getThreshold(p.band) + 1e-30), b = 10.0 * std::log10(bands_.getThreshold(p.band + 1) + 1e-30);
1025 threshold_[u] = static_cast<T>(a + static_cast<double>(p.part) * (b - a) - 10.0 * std::log10(band / held));
1026 // A point stands for the hertz to the next: that share of what it holds.
1027 pointShare_[u] = hz / held;
1028 // And a band of the model sees a stretch around it: its envelope's
1029 // sixth of an octave, or the lobe of its window where that is wider.
1030 const double reach = std::max(hz * 0.5 * (std::exp2(1.0 / 12.0) - std::exp2(-1.0 / 12.0)), 0.5 * modelNoiseBins_ * fs_ / fft_);
1031 const double last = kPoints - 1.0, perLog = last / std::log(1000.0);
1032 const int from = static_cast<int>(std::lround(perLog * std::log(std::max(20.0, hz - reach) / 20.0)));
1033 const int to = static_cast<int>(std::lround(std::min(last, perLog * std::log((hz + reach) / 20.0)))) + 1;
1034 seenFrom_[u] = std::clamp(from, 0, i);
1035 seenTo_[u] = std::clamp(to, i + 1, kPoints);
1036 seenShare_[u] = hz / (2.0 * reach);
1037 }
1038 }
1039
1040 void resetDetail() noexcept
1041 {
1042 for (auto* v : { &smoothPower_, &seen_, &detailGain_ }) std::fill(v->begin(), v->end(), T(0));
1043 base_.fill(0.0);
1044 detailMean_.fill(0.0);
1045 shownCurve_ = 0;
1046 }
1047
1049 void design(T* curve) noexcept
1050 {
1051 readDetail();
1052 const T range = range_.load(std::memory_order_relaxed);
1053 for (int i = 0; i < kPoints; ++i)
1054 {
1055 const Place& p = place_[static_cast<size_t>(i)];
1056 const auto under = static_cast<size_t>(p.band);
1057 const double before = base_[under > 0 ? under - 1 : 0], after = base_[std::min(under + 2, static_cast<size_t>(kBands - 1))];
1058 const T broad = static_cast<T>(static_cast<double>(p.weight[0]) * before + static_cast<double>(p.weight[1]) * base_[under]
1059 + static_cast<double>(p.weight[2]) * base_[under + 1] + static_cast<double>(p.weight[3]) * after);
1060 curve[i] = std::clamp(broad + detailGain_[static_cast<size_t>(i)], -range, range);
1061 }
1062 }
1063
1065 void readDetail() noexcept
1066 {
1067 analysis_.read(0, power_.data());
1068 const bool common = response_.load(std::memory_order_relaxed) == Response::Common;
1069 const T shared = common ? static_cast<T>(std::exp(-hopSeconds_
1070 / std::max(kShortestCommon, 0.001 * static_cast<double>(responseMs_.load(std::memory_order_relaxed))))) : T(0);
1071 for (int i = 0; i < top_; ++i)
1072 {
1073 const auto u = static_cast<size_t>(i);
1074 const T keep = common ? shared : slowCoeff_[u];
1075 const T p = std::isfinite(power_[u]) ? power_[u] : T(0);
1076 smoothPower_[u] = p + keep * (smoothPower_[u] - p);
1077 seen_[u] = T(1) + keep * (seen_[u] - T(1)); // of the smoothing filled: no rise out of the start
1078 power_[u] = seen_[u] > T(0) ? smoothPower_[u] / seen_[u] : T(0);
1079 level_[u] = T(4.3429448190325183) * fastLog(power_[u] + T(1e-30));
1080 heard_[u] = std::clamp((level_[u] - threshold_[u]) / static_cast<T>(kAudibleSpan), T(0), T(1));
1081 }
1082 const T fill = fillDips_.load(std::memory_order_relaxed), trim = trimPeaks_.load(std::memory_order_relaxed);
1083 std::fill(asked_.begin(), asked_.end(), T(0));
1084 if (fill > T(0) || trim > T(0)) readContrast(fill, trim);
1085
1086 std::array<double, kBands> moved {}, held {};
1087 bool moving = false;
1088 for (int i = 0; i < kPoints; ++i)
1089 {
1090 const auto u = static_cast<size_t>(i);
1091 T& g = detailGain_[u];
1092 g = asked_[u] + detailGlide_ * (g - asked_[u]);
1093 if (asked_[u] == T(0) && std::abs(g) < T(1e-6)) g = T(0);
1094 moving = moving || g != T(0);
1095 }
1096 detailMean_.fill(0.0);
1097 if (!moving) return;
1098 // By the power it moves there, as the model reads it: a band of the
1099 // model sees what is around it through its window and its envelope,
1100 // so a gap beside a partial is as loud as the partial makes it, and
1101 // what raises the gap adds next to nothing.
1102 double power = 0.0, change = 0.0;
1103 for (int i = 0; i < top_; ++i)
1104 {
1105 const auto u = static_cast<size_t>(i);
1106 heldSum_[u] = power;
1107 movedSum_[u] = change;
1108 const double p = static_cast<double>(power_[u]) * pointShare_[u];
1109 power += p;
1110 change += p * static_cast<double>(std::exp(T(0.23025850929940457) * detailGain_[u]) - T(1));
1111 }
1112 heldSum_[static_cast<size_t>(top_)] = power;
1113 movedSum_[static_cast<size_t>(top_)] = change;
1114 for (int i = 0; i < top_; ++i)
1115 {
1116 const auto u = static_cast<size_t>(i);
1117 const Place& p = place_[u];
1118 const double part = static_cast<double>(p.part);
1119 const auto first = static_cast<size_t>(std::min(seenFrom_[u], top_)), end = static_cast<size_t>(std::min(seenTo_[u], top_));
1120 const double share = seenShare_[u];
1121 const double around = share * (heldSum_[end] - heldSum_[first]), moves = share * (movedSum_[end] - movedSum_[first]);
1122 const auto under = static_cast<size_t>(p.band);
1123 held[under] += (1.0 - part) * around;
1124 held[under + 1] += part * around;
1125 moved[under] += (1.0 - part) * moves;
1126 moved[under + 1] += part * moves;
1127 }
1128 AuditoryBands<double>::smoothAcross(held.data(), kBands, kReadAcross);
1129 AuditoryBands<double>::smoothAcross(moved.data(), kBands, kReadAcross);
1130 for (int b = 0; b < kBands; ++b)
1131 {
1132 const auto i = static_cast<size_t>(b);
1133 if (held[i] > 0.0) detailMean_[i] = 10.0 * std::log10(std::max(1.0 + moved[i] / held[i], 1e-12));
1134 }
1135 }
1136
1138 void readContrast(T fill, T trim) noexcept
1139 {
1140 const T* db = level_.data();
1141 const T* power = power_.data();
1142 const T* heard = heard_.data();
1143 const double pole = sidePole_;
1144 // Audible points alone, and none within the detail of the point itself.
1145 // A side is the mean of its loudness (the power to a quarter, as the
1146 // ear has it): the emptiness past a group of lines would pull a mean
1147 // of decibels under the gaps inside the group, and in a mean of
1148 // amplitudes a line as wide as the window would hide the one beside it.
1149 const auto sideDb = [](double sum, double weight) {
1150 return T(17.371779276130073) * fastLog(static_cast<T>(sum / weight) + T(1e-8));
1151 };
1152 T* quarter = quarter_.data();
1153 for (int i = 0; i < top_; ++i) quarter[i] = heard[i] * std::sqrt(std::sqrt(power[i]));
1154 double num = 0.0, den = 0.0;
1155 for (int i = 0; i < top_; ++i)
1156 {
1157 if (const int j = i - aside_; j >= 0)
1158 {
1159 num = pole * num + static_cast<double>(quarter[j]);
1160 den = pole * den + static_cast<double>(heard[j]);
1161 }
1162 lowerSide_[static_cast<size_t>(i)] = den > 1e-9 ? sideDb(num, den) : db[i];
1163 }
1164 num = 0.0; den = 0.0;
1165 for (int i = top_ - 1; i >= 0; --i)
1166 {
1167 if (const int j = i + aside_; j < top_)
1168 {
1169 num = pole * num + static_cast<double>(quarter[j]);
1170 den = pole * den + static_cast<double>(heard[j]);
1171 }
1172 upperSide_[static_cast<size_t>(i)] = den > 1e-9 ? sideDb(num, den) : db[i];
1173 }
1174
1175 const T* dips = db;
1176 if (gapShare_ > T(0))
1177 {
1178 // A dip is looked for no finer than a sixth of an octave: what is
1179 // narrower between two partials is the space between them.
1180 double total = 0.0;
1181 for (int i = 0; i < top_; ++i)
1182 {
1183 sum_[static_cast<size_t>(i)] = total;
1184 total += static_cast<double>(power[i]);
1185 }
1186 sum_[static_cast<size_t>(top_)] = total;
1187 for (int i = 0; i < top_; ++i)
1188 {
1189 const int first = std::max(0, i - gapHalf_), end = std::min(top_, i + gapHalf_ + 1);
1190 const double around = (sum_[static_cast<size_t>(end)] - sum_[static_cast<size_t>(first)]) / (end - first);
1191 const T over = T(4.3429448190325183) * fastLog(static_cast<T>(around) + T(1e-30)) - db[i];
1192 gapLevel_[static_cast<size_t>(i)] = db[i] + gapShare_ * std::max(T(0), over);
1193 }
1194 dips = gapLevel_.data();
1195 }
1196 const T knee = contrastKnee_.load(std::memory_order_relaxed);
1197 const auto bend = [knee](T d) { return std::copysign(std::sqrt(d * d + knee * knee) - knee, d); };
1198 const T range = range_.load(std::memory_order_relaxed), rangeKnee = rangeKnee_.load(std::memory_order_relaxed);
1199 const T atZero = T(0.5) * (range - std::sqrt(range * range + rangeKnee * rangeKnee));
1200 const T from = std::log2(loHz_.load(std::memory_order_relaxed) / T(1000));
1201 const T to = std::log2(hiHz_.load(std::memory_order_relaxed) / T(1000));
1202 for (int i = 0; i < top_; ++i)
1203 {
1204 const auto u = static_cast<size_t>(i);
1205 if (heard[i] == T(0)) continue;
1206 // The edges of the range are a third of an octave wide here (one
1207 // Bark would reach from 40 Hz to 90 Hz).
1208 const T inside = std::clamp(T(3) * (octave_[u] - from) + T(0.5), T(0), T(1))
1209 * std::clamp(T(3) * (to - octave_[u]) + T(0.5), T(0), T(1));
1210 if (inside == T(0)) continue;
1211 const T under = std::min(T(0), dips[i] - std::min(lowerSide_[u], upperSide_[u]));
1212 // Nor is that space cut with the partials beside it.
1213 const T over = std::max(T(0), db[i] - std::max(lowerSide_[u], upperSide_[u]) - (dips[i] - db[i]));
1214 const T low = std::clamp((static_cast<T>(kEmpty) + under) / static_cast<T>(kEmptyFade), T(0), T(1));
1215 T c = -trim * bend(over) - fill * low * bend(std::max(under, static_cast<T>(-kDipLimit)));
1216 if (!(rangeKnee > T(0))) c = std::clamp(c, -range, range);
1217 else
1218 {
1219 const T a = std::abs(c), past = a - range;
1220 const T rounded = T(0.5) * (a + range - std::sqrt(past * past + rangeKnee * rangeKnee));
1221 c = std::copysign((rounded - atZero) * range / (range - atZero), c);
1222 }
1223 asked_[u] = inside * heard[i] * c;
1224 }
1225 // No finer than the detail: over an eighth of it on either side, a point
1226 // at least (a step of one point would ring between two of them).
1227 double sum = 0.0;
1228 for (int i = 0; i < kPoints; ++i)
1229 {
1230 sum_[static_cast<size_t>(i)] = sum;
1231 sum += static_cast<double>(asked_[static_cast<size_t>(i)]);
1232 }
1233 sum_[static_cast<size_t>(kPoints)] = sum;
1234 for (int i = 0; i < kPoints; ++i)
1235 {
1236 const int first = std::max(0, i - acrossHalf_), end = std::min(kPoints, i + acrossHalf_ + 1);
1237 asked_[static_cast<size_t>(i)] = static_cast<T>((sum_[static_cast<size_t>(end)] - sum_[static_cast<size_t>(first)]) / (end - first));
1238 }
1239 }
1240
1242 struct Place
1243 {
1244 T weight[4] {};
1245 T part = T(0);
1246 int band = 0;
1247 };
1248
1249 static constexpr int kFeed = 256;
1250 static constexpr double kReadAcross = 0.1;
1251 static constexpr double kSideOctaves = 0.5;
1252 static constexpr double kFinestDip = 1.0 / 6.0;
1253 static constexpr double kDipLimit = 18.0;
1254 static constexpr double kEmpty = 45.0;
1255 static constexpr double kEmptyFade = 15.0;
1256 static constexpr double kShortestSmoothing = 0.4;
1257 static constexpr double kShortestCommon = 0.1;
1258 static constexpr double kDetailGlideSeconds = 0.1;
1259 static constexpr double kAudibleSpan = 10.0;
1260 static constexpr double kMaskedSpan = 10.0;
1261 static constexpr double kOffsetLimit = 60.0;
1262 static constexpr int kOffsetSteps = 24;
1263
1264 double fs_ = 48000.0, powerScale_ = 1.0, modelNoiseBins_ = 1.5, keyFade_ = 0.0;
1265 int channels_ = 0, fft_ = 2048, hop_ = 128, bins_ = 1025;
1266 int ringPos_ = 0, hopCounter_ = 0;
1267 bool prepared_ = false, warm_ = false;
1268
1269 std::atomic<T> balance_ { T(0.5) }, fillDips_ { T(0.3) }, trimPeaks_ { T(0.5) }, tilt_ { T(0) };
1270 std::atomic<T> balanceAsymmetry_ { T(0) }, balanceBias_ { T(0) };
1271 std::atomic<T> range_ { T(6) }, knee_ { T(3) }, loHz_ { T(40) }, hiHz_ { T(16000) }, referenceSpl_ { T(100) };
1272 std::atomic<bool> levelComp_ { false }, refDirty_ { false }, localSlope_ { false };
1273 std::atomic<Reference> reference_ { Reference::FlatLoudness };
1274 std::atomic<Response> response_ { Response::ByBand };
1275 std::atomic<Quality> quality_ { Quality::Realtime }, qualityInUse_ { Quality::Realtime };
1276 std::atomic<bool> qualityFollowsRender_ { false }, offlineRendering_ { false };
1277 bool render_ = false;
1278 std::atomic<T> responseMs_ { T(60) }, listening_ { T(0) };
1279 std::array<std::atomic<T>, kBands> published_ {};
1280 std::atomic<T> loudnessChange_ { T(0) }, raised_ { T(0) }, lowered_ { T(0) }, total_ { T(-200) }, centroidShift_ { T(0) };
1281 std::atomic<T> rangeKnee_ { T(0) }, floor_ { T(30) };
1282 std::atomic<T> contrastKnee_ { T(3) }, detail_ { T(1.0 / 4.0) };
1283
1284 std::unique_ptr<FFTReal<double>> transform_;
1285 AuditoryBands<double> bands_;
1286 SpectralEnvelope<double> envelope_;
1287 SpectralFocus<double> focus_;
1288 std::array<std::vector<double>, 2> focusRe_, focusIm_;
1289 std::atomic<bool> timeFocus_ { false };
1290 static constexpr int kMoments = 4;
1291 std::vector<double> window_, frame_, moments_, bandMoments_;
1292 std::array<double, kBands> centreOctave_ {};
1293 std::vector<std::vector<double>> ring_, spectra_;
1294 std::vector<double> ll_, rr_, lr_, li_, loud_, evenLoud_, corr_, tmpA_, tmpB_, tmpC_, tmpD_;
1295 std::array<double, kBands> timeCoeff_ {}, briefCoeff_ {};
1296
1297 // The detail, and the filter that plays both.
1298 DetailFilter<T, DetailLatency::Block> filter_;
1299 DetailAnalysis<T> analysis_;
1300 std::array<double, kBands> base_ {};
1301 std::array<double, kBands> detailMean_ {};
1302 std::vector<double> heldSum_, movedSum_;
1303 std::vector<double> pointShare_, seenShare_;
1304 std::vector<int> seenFrom_, seenTo_;
1305 std::vector<Place> place_;
1306 std::vector<T> fed_, power_, smoothPower_, seen_, level_, gapLevel_, heard_, asked_, detailGain_;
1307 std::vector<T> lowerSide_, upperSide_, quarter_, octave_, threshold_, slowCoeff_;
1308 std::vector<double> sum_;
1309 double hopSeconds_ = 256.0 / 48000.0, sidePole_ = 0.98;
1310 T lastDetail_ = T(1.0 / 4.0), detailGlide_ = T(0);
1311 T gapShare_ = T(0);
1312 int top_ = 0, aside_ = 8, acrossHalf_ = 1, gapHalf_ = 0, shownCurve_ = 0;
1313};
1314
1315} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
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
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 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
void prepare(double sampleRate, int fftSize, int numBands=72, double loHz=20.0, double hiHz=20000.0)
Lays the bands out.
double getThresholdLoudness(int band) const noexcept
Multiresolution power spectrum on the grid of SpectralReadout.
void prepare(const AudioSpec &spec)
Allocates for a layout (an invalid spec is ignored; channels over kMaxChannels pass through).
int getHopSize() const noexcept
void setLinked(bool on) noexcept
One curve and one filter for every channel.
void publishPlayed(int channels=2) noexcept
Hands the last kernels of both parts to a display (audio thread): a copy of them, for playedValue() a...
static double frequency(int point) noexcept
bool isDisplayDue(int shownAt) const noexcept
void processBlock(AudioBufferView< T > buffer, Design &&design) noexcept
Filters a block in place by curves that do not read the signal.
int getLatency() const noexcept
void reset() noexcept
Clears the signal and the curves.
int getCurveCount() const noexcept
T playedValue(int channel, int point) const noexcept
void prepare(int numBins, double widthOctaves=1.0/3.0, double minBins=1.0)
Sets the bins and the width.
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.
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
static constexpr int kPoints
Points of each curve.
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
Adaptive equalizer toward a balanced loudness shape.
T getLoudnessChange() const noexcept
Quality
How often the two readings run (setQuality(); it applies at the next prepare()). Realtime,...
T getRangeKnee() const noexcept
T getTrimPeaks() const noexcept
void setQuality(Quality q) noexcept
Realtime or Render (see Quality; applies at the next prepare()).
bool getLevelCompensation() const noexcept
bool getQualityFollowsRender() const noexcept
void setDetail(T octaves) noexcept
The detail: how finely the peaks and the dips (these no finer than a sixth, so that the space between...
void setBalanceAsymmetry(T amount) noexcept
How differently the balance lifts what is lacking and lowers what is in excess, -1 to 1 (default 0: a...
static constexpr int kDisplayPoints
Points of the display curve, evenly in log frequency from 20 Hz to 20 kHz.
void setReference(Reference r) noexcept
The shape the programme is compared against (see Reference; out-of-range values read as FlatLoudness)...
int getLatency() const noexcept
void setKnee(T db) noexcept
Knee of the balance, 0.1 to 12 dB (default 3); the dips and peaks have setContrastKnee().
T getResponseTime() const noexcept
T getContrastKnee() const noexcept
T getListeningCompensation() const noexcept
Reference getReference() const noexcept
T getCentroidShift() const noexcept
double getBandCentre(int band) const noexcept
T getKnee() const noexcept
void setFrequencyRange(T loHz, T hiHz) noexcept
Frequencies the corrections act on, with edges one Bark wide (default 40 Hz to 16 kHz: the ends of th...
void setTimeFocus(bool on) noexcept
Reads each band through a stretch of the analysis window of its own, shorter as frequency rises (Spec...
T getLoudnessLowered() const noexcept
T getRange() const noexcept
std::vector< uint8_t > getState() const
void setRangeKnee(T db) noexcept
Rounds the approach to the range, 0 to 6 dB (0, the default, is the hard limit): a correction that gr...
Response getResponse() const noexcept
T getHighFrequency() const noexcept
bool getLocalSlope() const noexcept
void processBlock(AudioBufferView< T > buffer) noexcept
Analyses and equalizes the programme in place.
T getBalance() const noexcept
T getBalanceAsymmetry() const noexcept
T getFillDips() const noexcept
T getFloor() const noexcept
Response
How the analysis follows the programme in time (setResponse()). ByBand, the default: two smoothings w...
T getLoudness() const noexcept
T getLoudnessRaised() const noexcept
Reference
What a balanced programme is (setReference()). FlatLoudness, the default: the same loudness in every ...
void setLocalSlope(bool on) noexcept
Loudness to decibels with the slope of the loudness curve at each band's own level (default off): wha...
void setFloor(T db) noexcept
How far under its loudest band (in the model's level) a band may lie and still be given back by the b...
void setListeningCompensation(T db) noexcept
Compensates a listening level this many dB lower than the one the programme is balanced at,...
Quality getQualityInUse() const noexcept
static double getDisplayFrequency(int point) noexcept
void setQualityFollowsRender(bool on) noexcept
With it on, a prepare() made while the host renders offline (setOfflineRendering(true)) takes the Ren...
T getTilt() const noexcept
void setTrimPeaks(T amount) noexcept
How much peaks (a detail over both of its sides) are lowered, 0 to 1 (default 0.5).
void prepare(const AudioSpec &spec)
Allocates for a rate and a layout (an invalid spec is ignored).
void setBalance(T amount) noexcept
How far the trend moves toward the reference shape, 0 to 1 (default 0.5).
void setBalanceBias(T db) noexcept
Moves the point the balance tells lacking from excess at, -6 to +6 dB (default 0: the programme's own...
void processBlock(AudioBufferView< T > buffer, AudioBufferView< T > key) noexcept
Equalizes the programme by the analysis of a key (same channels or one).
void setResponseTime(T ms) noexcept
The response time of Response::Common, 10 to 2000 ms (default 60).
static constexpr int kMaxChannels
Channels analysed (the others take the same curve).
Quality getQuality() const noexcept
bool getTimeFocus() const noexcept
T getCorrection(int band) const noexcept
void setContrastKnee(T db) noexcept
Knee of the dips and peaks, 0.1 to 12 dB (default 3): smaller and the ripple of a noisy programme is ...
void setReferenceLevel(T dbSpl) noexcept
The SPL a full-scale sine stands for, 60 to 130 dB (default 100).
T getReferenceLevel() const noexcept
T getDisplayCorrection(int point) const noexcept
void setFillDips(T amount) noexcept
How much dips (a detail under both of its sides, a sixth of an octave or wider) are raised,...
void setRange(T db) noexcept
Largest correction of a band, 0 to 24 dB (default 6).
void setTilt(T dbPerOctave) noexcept
Tilt of the reference shape in dB per octave around 1 kHz, -6 to +6 (default 0: flat loudness per Bar...
T getLowFrequency() const noexcept
void setOfflineRendering(bool on) noexcept
Tells the processor whether the host renders offline (read by the next prepare()).
double getResponse(double hz) const noexcept
T getBalanceBias() const noexcept
void reset() noexcept
Clears the analysis, the corrections and the filter.
static constexpr int kBands
Bands of the loudness model.
T getDetail() const noexcept
bool setState(const uint8_t *data, size_t size)
Restores the settings. A blob of the first version gives the default detail, or a third,...
void setResponse(Response r) noexcept
How the analysis follows the programme in time (see Response; out-of-range values read as ByBand).
void setLevelCompensation(bool on) noexcept
Loudness to decibels with each band's exponent (default off: one exponent).
static constexpr int getNumBands() noexcept
Main namespace for the DSPark framework.
T fastLog(T x) noexcept
Fast natural logarithm approximation.
Definition DspMath.h:393
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
int maxBlockSize
Maximum number of samples per processing block.
Definition AudioSpec.h:53
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
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
static void asymmetricHann(T *output, int size, int fall) noexcept
Asymmetric window for low-latency analysis: the rising half of a Hann window over the first size - fa...