55#include "CrossoverFilter.h"
56#include "Saturation.h"
57#include "../Core/AudioBuffer.h"
58#include "../Core/AudioSpec.h"
59#include "../Core/DspMath.h"
60#include "../Core/StateBlob.h"
82template <FloatType T,
int MaxBands = 6>
85 static_assert(MaxBands >= 2,
"MultibandSaturation needs at least 2 bands (one split)");
92 for (
auto& band : saturation_) band = std::make_unique<
Saturation<T>>();
110 prepared_.store(
false, std::memory_order_relaxed);
113 for (
int b = 0; b < MaxBands; ++b)
116 saturation_[
static_cast<size_t>(b)]->
prepare(spec);
119 padLines_.assign(
static_cast<size_t>(2 * MaxBands) *
static_cast<size_t>(std::max(spec.
numChannels, 1))
120 *
static_cast<size_t>(kPadSize), T(0));
124 clip_.setOversampling(4);
125 clip_.setCeiling(outputCeilingDb_.load(std::memory_order_relaxed));
127 fadeStep_ = 1.0 / std::max(1.0, kFadeSeconds * spec.
sampleRate);
129 prepared_.store(
true, std::memory_order_relaxed);
136 for (
auto& band : saturation_) band->reset();
137 std::fill(padLines_.begin(), padLines_.end(), T(0));
140 clipping_ = outputClip_.load(std::memory_order_relaxed);
141 mixNow_ =
static_cast<double>(mix_.load(std::memory_order_relaxed));
142 dryRunning_ = mixNow_ < 1.0;
143 for (
int b = 0; b < MaxBands; ++b)
145 BandRamp& ramp = ramps_[
static_cast<size_t>(b)];
146 const Targets t = targets(b, anySolo());
147 ramp.heard = t.heard;
149 ramp.right = t.right;
150 ramp.computed = t.heard > 0.0;
163 if (!prepared_.load(std::memory_order_relaxed))
return;
164 const int total = buffer.getNumSamples();
165 const int chunk = bandBuffers_[0].getNumSamples();
166 if (chunk <= 0)
return;
167 for (
int offset = 0; offset < total; offset += chunk)
168 processChunk(buffer.getSubView(offset, std::min(chunk, total - offset)));
200 return *saturation_[
static_cast<size_t>(std::clamp(band, 0, MaxBands - 1))];
205 return *saturation_[
static_cast<size_t>(std::clamp(band, 0, MaxBands - 1))];
216 if (band < 0 || band >= MaxBands || !std::isfinite(dB))
return;
217 params_[
static_cast<size_t>(band)].levelDb.store(std::clamp(dB, T(-60), T(24)), std::memory_order_relaxed);
222 if (band < 0 || band >= MaxBands || !std::isfinite(pan))
return;
223 params_[
static_cast<size_t>(band)].pan.store(std::clamp(pan, T(-1), T(1)), std::memory_order_relaxed);
228 if (band < 0 || band >= MaxBands)
return;
229 params_[
static_cast<size_t>(band)].mute.store(on, std::memory_order_relaxed);
234 if (band < 0 || band >= MaxBands)
return;
235 params_[
static_cast<size_t>(band)].solo.store(on, std::memory_order_relaxed);
238 [[nodiscard]] T
getBandLevel(
int band)
const noexcept {
return param(band).levelDb.load(std::memory_order_relaxed); }
239 [[nodiscard]] T
getBandPan(
int band)
const noexcept {
return param(band).pan.load(std::memory_order_relaxed); }
240 [[nodiscard]]
bool isBandMuted(
int band)
const noexcept {
return param(band).mute.load(std::memory_order_relaxed); }
241 [[nodiscard]]
bool isBandSoloed(
int band)
const noexcept {
return param(band).solo.load(std::memory_order_relaxed); }
246 return band >= 0 && band < MaxBands && ramps_[static_cast<size_t>(band)].computed;
267 if (std::isfinite(amount)) mix_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
269 [[nodiscard]] T
getMix() const noexcept {
return mix_.load(std::memory_order_relaxed); }
280 void setOutputClip(
bool on)
noexcept { outputClip_.store(on, std::memory_order_relaxed); }
281 [[nodiscard]]
bool getOutputClip() const noexcept {
return outputClip_.load(std::memory_order_relaxed); }
286 if (!std::isfinite(dB))
return;
287 outputCeilingDb_.store(std::clamp(dB, T(-24), T(0)), std::memory_order_relaxed);
288 clip_.setCeiling(outputCeilingDb_.load(std::memory_order_relaxed));
290 [[nodiscard]] T
getOutputCeiling() const noexcept {
return outputCeilingDb_.load(std::memory_order_relaxed); }
297 for (
auto& band : saturation_) band->setOversampling(factor);
302 for (
auto& band : saturation_) band->setOversamplingMode(mode);
308 for (
auto& each : saturation_) each->setOversamplingBand(band);
313 for (
auto& band : saturation_) band->setAntialiasing(mode);
326 + (outputClip_.load(std::memory_order_relaxed) ? clip_.getLatency() : 0);
332 [[nodiscard]] std::vector<uint8_t>
getState()
const
336 w.
write(
"numBands", n);
345 for (
int i = 0; i < n - 1; ++i)
347 std::snprintf(key,
sizeof(key),
"x%d", i);
350 for (
int i = 0; i < n; ++i)
352 std::snprintf(key,
sizeof(key),
"band%d", i);
354 std::snprintf(key,
sizeof(key),
"b%d.level", i);
356 std::snprintf(key,
sizeof(key),
"b%d.pan", i);
358 std::snprintf(key,
sizeof(key),
"b%d.mute", i);
360 std::snprintf(key,
sizeof(key),
"b%d.solo", i);
371 const int n = std::clamp(
static_cast<int>(r.
read(
"numBands", int32_t(3))), 2, MaxBands);
381 for (
int i = 0; i < n - 1; ++i)
383 std::snprintf(key,
sizeof(key),
"x%d", i);
384 const float f = r.
read(key, -1.0f);
387 for (
int i = 0; i < n; ++i)
389 std::snprintf(key,
sizeof(key),
"band%d", i);
390 const auto nested = r.
readBlob(key);
391 if (!nested.empty())
getBandSaturation(i).setState(nested.data(), nested.size());
392 std::snprintf(key,
sizeof(key),
"b%d.level", i);
394 std::snprintf(key,
sizeof(key),
"b%d.pan", i);
396 std::snprintf(key,
sizeof(key),
"b%d.mute", i);
398 std::snprintf(key,
sizeof(key),
"b%d.solo", i);
405 static constexpr double kFadeSeconds = 0.02;
406 static constexpr int kPadSize = 512;
410 std::atomic<T> levelDb { T(0) };
411 std::atomic<T> pan { T(0) };
412 std::atomic<bool> mute {
false };
413 std::atomic<bool> solo {
false };
420 double left = 1.0, right = 1.0;
421 bool computed =
true;
426 double heard, left, right;
429 [[nodiscard]]
const BandParams& param(
int band)
const noexcept
431 return params_[
static_cast<size_t>(std::clamp(band, 0, MaxBands - 1))];
434 [[nodiscard]]
bool anySolo() const noexcept
437 for (
int b = 0; b < n; ++b)
438 if (params_[
static_cast<size_t>(b)].solo.load(std::memory_order_relaxed))
return true;
443 [[nodiscard]] Targets targets(
int band,
bool soloing)
const noexcept
445 const BandParams& p = params_[
static_cast<size_t>(band)];
446 const bool heard = !p.mute.load(std::memory_order_relaxed)
447 && (!soloing || p.solo.load(std::memory_order_relaxed));
448 const double level = std::pow(10.0,
static_cast<double>(p.levelDb.load(std::memory_order_relaxed)) / 20.0);
449 const double pan =
static_cast<double>(p.pan.load(std::memory_order_relaxed));
450 const double left = (pan > 0.0) ? std::cos(0.5 * std::numbers::pi * pan) : 1.0;
451 const double right = (pan < 0.0) ? std::cos(-0.5 * std::numbers::pi * pan) : 1.0;
452 return { heard ? 1.0 : 0.0, level * left, level * right };
456 [[nodiscard]]
int slowestBand(
int n)
const noexcept
459 for (
int b = 0; b < std::clamp(n, 0, MaxBands); ++b)
460 slowest = std::max(slowest, saturation_[
static_cast<size_t>(b)]->getLatency());
461 return std::min(slowest, kPadSize - 1);
464 void processChunk(AudioBufferView<T> buffer)
noexcept
466 const int nCh = std::min(buffer.getNumChannels(), bandBuffers_[0].getNumChannels());
467 const int nS = std::min(buffer.getNumSamples(), bandBuffers_[0].getNumSamples());
468 if (nCh <= 0 || nS <= 0)
return;
470 for (
int b = 0; b < MaxBands; ++b)
471 views_[
static_cast<size_t>(b)] = bandBuffers_[
static_cast<size_t>(b)].toView().getSubView(0, nS);
472 const int nb = crossover_.
processBlock(buffer, views_.data(), MaxBands);
475 const bool soloing = anySolo();
476 const int slowest = slowestBand(nb);
481 const double mixTarget =
static_cast<double>(mix_.load(std::memory_order_relaxed));
482 const bool dry = mixTarget < 1.0 || mixNow_ < 1.0;
483 if (dry && !dryRunning_)
484 for (
int b = 0; b < MaxBands; ++b) clearPad(MaxBands + b);
486 auto dryBand = bandDry_.toView().getSubView(0, nS);
488 for (
int ch = 0; ch < nCh; ++ch) std::fill_n(dryBuffer_.getChannel(ch), nS, T(0));
489 for (
int ch = 0; ch < nCh; ++ch) std::fill_n(buffer.getChannel(ch), nS, T(0));
491 for (
int b = 0; b < nb; ++b)
493 BandRamp& ramp = ramps_[
static_cast<size_t>(b)];
494 const Targets t = targets(b, soloing);
498 const bool silent = t.heard == 0.0 && ramp.heard == 0.0;
501 ramp.computed =
false;
503 ramp.right = t.right;
506 Saturation<T>& sat = *saturation_[
static_cast<size_t>(b)];
512 ramp.computed =
true;
514 auto view = views_[
static_cast<size_t>(b)];
515 if (dry) sat.processPieces(view, &dryBand, mixTarget > 0.0);
516 else sat.processBlock(view);
517 const int pad = slowest - sat.getLatency();
518 if (dry) addDryBand(b, nCh, nS, pad);
520 const double heardStep = std::clamp(t.heard - ramp.heard, -fadeStep_, fadeStep_);
521 const bool fading = ramp.heard != t.heard;
522 const double leftStep = (t.left - ramp.left) * fadeStep_;
523 const double rightStep = (t.right - ramp.right) * fadeStep_;
524 for (
int ch = 0; ch < nCh; ++ch)
526 const T* in = view.getChannel(ch);
527 T* out = buffer.getChannel(ch);
528 T* line = padLines_.data() + (
static_cast<size_t>(b) *
static_cast<size_t>(bandBuffers_[0].getNumChannels())
529 +
static_cast<size_t>(ch)) *
static_cast<size_t>(kPadSize);
530 double heard = ramp.heard, left = ramp.left, right = ramp.right;
531 const bool isRight = (ch == 1);
533 for (
int i = 0; i < nS; ++i)
537 const T aligned = line[(pos - pad) & (kPadSize - 1)];
538 pos = (pos + 1) & (kPadSize - 1);
542 if ((heardStep > 0.0 && heard > t.heard) || (heardStep < 0.0 && heard < t.heard)) heard = t.heard;
546 const double side = (nCh == 2) ? (isRight ? right : left) : 0.5 * (left + right);
547 out[i] +=
static_cast<T
>(
static_cast<double>(aligned) * heard * side);
558 padPos_ = (padPos_ + nS) & (kPadSize - 1);
559 for (
int b = nb; b < MaxBands; ++b) ramps_[static_cast<size_t>(b)].computed =
false;
564 const double step = std::clamp(mixTarget - mixNow_, -fadeStep_, fadeStep_);
565 double mix = mixNow_;
566 for (
int ch = 0; ch < nCh; ++ch)
568 const T* d = dryBuffer_.getChannel(ch);
569 T* out = buffer.getChannel(ch);
571 for (
int i = 0; i < nS; ++i)
573 if (mix != mixTarget)
576 if ((step > 0.0 && mix > mixTarget) || (step < 0.0 && mix < mixTarget)) mix = mixTarget;
578 out[i] =
static_cast<T
>(
static_cast<double>(d[i]) + mix * (
static_cast<double>(out[i]) -
static_cast<double>(d[i])));
586 const bool clip = outputClip_.load(std::memory_order_relaxed);
587 if (clip && !clipping_) clip_.reset();
591 clip_.processBlock(buffer.getSubView(0, nS));
592 const T top =
decibelsToGain(outputCeilingDb_.load(std::memory_order_relaxed));
593 for (
int ch = 0; ch < nCh; ++ch)
595 T* out = buffer.getChannel(ch);
596 for (
int i = 0; i < nS; ++i) out[i] = std::clamp(out[i], -top, top);
602 void addDryBand(
int band,
int channels,
int samples,
int pad)
noexcept
604 for (
int ch = 0; ch < channels; ++ch)
606 const T* in = bandDry_.getChannel(ch);
607 T* sum = dryBuffer_.getChannel(ch);
608 T* line = padLines_.data() + (
static_cast<size_t>(MaxBands + band) *
static_cast<size_t>(bandBuffers_[0].getNumChannels())
609 +
static_cast<size_t>(ch)) *
static_cast<size_t>(kPadSize);
611 for (
int i = 0; i < samples; ++i)
614 sum[i] += line[(pos - pad) & (kPadSize - 1)];
615 pos = (pos + 1) & (kPadSize - 1);
620 void clearPad(
int band)
noexcept
622 const size_t per =
static_cast<size_t>(bandBuffers_[0].getNumChannels()) *
static_cast<size_t>(kPadSize);
623 std::fill_n(padLines_.data() +
static_cast<size_t>(band) * per, per, T(0));
626 std::atomic<bool> prepared_ {
false };
629 std::array<std::unique_ptr<Saturation<T>>, MaxBands> saturation_ {};
630 std::array<AudioBuffer<T>, MaxBands> bandBuffers_ {};
631 std::array<AudioBufferView<T>, MaxBands> views_ {};
632 std::array<BandParams, MaxBands> params_ {};
633 std::array<BandRamp, MaxBands> ramps_ {};
634 std::vector<T> padLines_;
636 AudioBuffer<T> dryBuffer_, bandDry_;
638 std::atomic<T> mix_ { T(1) }, outputCeilingDb_ { T(0) };
639 std::atomic<bool> outputClip_ {
false };
640 double mixNow_ = 1.0;
641 bool dryRunning_ =
false, clipping_ =
false;
642 double fadeStep_ = 1.0 / 960.0;
Non-owning view over audio channel data.
Real-time audio clipper with analog modeling and anti-aliasing features.
Linkwitz-Riley crossover with 2-12 bands: 6, 12, 24, 36 or 48 dB per octave.
int getLatency() const noexcept
Returns latency in samples: 0 for IIR; for linear-phase, three quarters of the FIR (3072 at 48 kHz),...
void setStructure(Structure structure) noexcept
Chooses how the sections of the minimum-phase engine are realised.
void setNumBandsKeepingSplits(int n) noexcept
Sets the number of output bands (2..MaxBands) and keeps the splits.
void setOrder(int order) noexcept
Sets the crossover slope: 6, 12, 24, 36 or 48 (dB/oct). Other values are ignored.
int getNumBands() const noexcept
void setNumBands(int n) noexcept
Sets the number of output bands (2..MaxBands).
void setTopology(Topology topology) noexcept
Arranges the splits of the minimum-phase engine.
Structure
How the minimum-phase sections are realised (see setStructure()).
void setCrossoverFrequency(int index, T freqHz) noexcept
Sets a crossover frequency. Automatically maintains sorting.
T getCrossoverFrequency(int index) const noexcept
Returns the target frequency of split point index.
int processBlock(AudioBufferView< T > input, AudioBufferView< T > *bandOutputs, int numOutputBands) noexcept
Splits input into separate band outputs.
FilterMode
Filter processing mode.
FilterMode getFilterMode() const noexcept
Topology
How the splits of the minimum-phase engine are arranged (see setTopology()).
int getOrder() const noexcept
Topology getTopology() const noexcept
The arrangement set by setTopology().
void setFilterMode(FilterMode mode) noexcept
Sets the processing mode. A live switch resets filter state (transient).
Structure getStructure() const noexcept
The structure set by setStructure().
void prepare(const AudioSpec &spec)
Prepares the crossover for processing.
Multi-band saturation: crossover split, a Saturation per band, sum.
Crossover::Topology getCrossoverTopology() const noexcept
T getBandPan(int band) const noexcept
void setOversamplingMode(typename Saturation< T >::OversamplingMode mode)
The oversampler filters of every band (NOT real-time safe).
T getCrossoverFrequency(int index) const noexcept
void setOversampling(int factor)
The oversampling factor of every band (NOT real-time safe; see Saturation::setOversampling()).
MultibandSaturation(const MultibandSaturation &)=delete
void setAntialiasing(typename Saturation< T >::Antialiasing mode) noexcept
The antialiasing order of every band.
int getLatency() const noexcept
Latency in samples: the crossover's and the slowest band's.
void processBlock(AudioBufferView< T > buffer) noexcept
Processes audio through the bands, in place.
const Saturation< T > & getBandSaturation(int band) const noexcept
The Saturation of a band (the index is clamped).
void prepare(const AudioSpec &spec)
Prepares the crossover, every band and the buffers.
bool getOutputClip() const noexcept
void setBandLevel(int band, T dB) noexcept
Level of a band in dB, -60 to +24 (any thread; glides over 20 ms).
void setBandSolo(int band, bool on) noexcept
Solos a band: while any band is soloed only the soloed ones are heard (any thread; fades over 20 ms).
CrossoverFilter< T, MaxBands > Crossover
void setCrossoverTopology(typename Crossover::Topology topology) noexcept
Cascade or balanced arrangement of the minimum-phase splits (any thread; see CrossoverFilter::setTopo...
bool setState(const uint8_t *data, size_t size)
Restores what getState() wrote (setup thread: the bands may reallocate).
void setNumBandsKeepingSplits(int n) noexcept
Number of bands keeping the split frequencies (any thread; see CrossoverFilter::setNumBandsKeepingSpl...
T getBandLevel(int band) const noexcept
void setBandPan(int band, T pan) noexcept
Pan of a band, -1 (left) to +1 (right); a balance that never lifts a side (any thread).
void setOrder(int order) noexcept
Slope of the crossover in dB per octave (any thread; see CrossoverFilter::setOrder()).
void reset() noexcept
Clears the crossover, the bands and the alignment delays.
MultibandSaturation & operator=(const MultibandSaturation &)=delete
void setBandDrive(int band, T dB)
The drive of a band in dB (any thread).
T getMix() const noexcept
Saturation< T > & getBandSaturation(int band) noexcept
The Saturation of a band (the index is clamped).
int getNumBands() const noexcept
void setCrossoverMode(typename Crossover::FilterMode mode) noexcept
Minimum-phase (IIR) or linear-phase crossover (any thread; see CrossoverFilter).
T getOutputCeiling() const noexcept
void setNumBands(int n) noexcept
Number of bands (2..MaxBands; any thread; re-spaces the split frequencies; a live change fades,...
void setOversamplingBand(typename Saturation< T >::OversamplingBand band)
The band the first stage of every band's oversampler keeps (NOT real-time safe; see Saturation::setOv...
void setBandAlgorithm(int band, typename Saturation< T >::Algorithm algo)
The algorithm of a band (any thread).
bool isBandMuted(int band) const noexcept
void setOutputClip(bool on) noexcept
An oversampled clipper after the sum (off by default; any thread).
bool isBandComputed(int band) const noexcept
Whether a band is computed now (false while it is not heard; audio-thread state).
void setMix(T amount) noexcept
Blends the sum of the bands with the programme, 0 (dry) to 1 (the default: the bands alone; any threa...
void setBandMute(int band, bool on) noexcept
Mutes a band (any thread; fades over 20 ms).
Crossover::Structure getCrossoverStructure() const noexcept
void setOutputCeiling(T dB) noexcept
Ceiling of the output clipper, -24 to 0 dBFS (default 0; any thread).
int getOrder() const noexcept
void setCrossoverFrequency(int index, T hz) noexcept
Sets a split frequency (any thread).
void setCrossoverStructure(typename Crossover::Structure structure) noexcept
Direct-form or ladder sections in the minimum-phase crossover (any thread; see CrossoverFilter::setSt...
bool isBandSoloed(int band) const noexcept
Crossover::FilterMode getCrossoverMode() const noexcept
std::vector< uint8_t > getState() const
Serializes the crossover, each band's Saturation and its level, pan, mute and solo.
Professional multi-algorithm saturation processor with analog simulation.
typename Oversampling< SampleType >::Band OversamplingBand
The band the oversampler's first stage keeps (see setOversamplingBand()).
Algorithm
Defines the harmonic generation topology.
Antialiasing
Antiderivative antialiasing order (see setAntialiasing()).
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
std::vector< uint8_t > readBlob(const char *key) const
Reads a nested blob; empty when the key is absent.
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
bool isValid() const noexcept
uint32_t processorId() const noexcept
Serializes key/value parameters into a versioned blob.
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
void write(const char *key, float value)
Writes a float parameter.
Main namespace for the DSPark framework.
T decibelsToGain(T dB, T minusInfinityDb=T(-100)) noexcept
Converts a value in decibels to linear gain.
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Describes the audio environment for a DSP processor.
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
int maxBlockSize
Maximum number of samples per processing block.
double sampleRate
Sample rate in Hz.