61#include "../Core/AudioBuffer.h"
62#include "../Core/AudioSpec.h"
63#include "../Core/DspMath.h"
64#include "../Core/DryWetMixer.h"
65#include "../Core/Oversampling.h"
66#include "../Core/SmoothedValue.h"
67#include "../Core/StateBlob.h"
68#include "../Core/detail/Adaa.h"
69#include "../Core/detail/ClipperShape.h"
122 prepared_.store(
false, std::memory_order_relaxed);
126 int osFactor =
osFactor_.load(std::memory_order_relaxed);
130 osFactor_.store(osFactor, std::memory_order_relaxed);
143 osBand_.load(std::memory_order_relaxed));
175 prepared_.store(
true, std::memory_order_relaxed);
208 if (!
prepared_.load(std::memory_order_relaxed))
return;
209 if (buffer.getNumSamples() == 0 || buffer.getNumChannels() == 0)
return;
213 const int total = buffer.getNumSamples();
215 for (
int off = 0; off < total; off += maxBlock)
216 processChunk(buffer.getSubView(off, std::min(maxBlock, total - off)));
222 T mixVal =
mix_.load(std::memory_order_relaxed);
223 const bool adaa =
antialias_.load(std::memory_order_relaxed);
244 mixer_.mixWet(buffer, mixVal);
255 const int m = std::clamp(
static_cast<int>(mode), 0,
257 mode_.store(
static_cast<Mode>(m), std::memory_order_relaxed);
267 if (!std::isfinite(dB))
return;
268 ceilingDb_.store(std::clamp(dB, T(-60), T(0)), std::memory_order_relaxed);
278 if (!std::isfinite(dB))
return;
279 inputGainDb_.store(std::clamp(dB, T(0), T(48)), std::memory_order_relaxed);
303 if (!std::isfinite(amount))
return;
304 mix_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
321 if (!std::isfinite(ms))
return;
322 slewLimitMs_.store(std::max(ms, T(0)), std::memory_order_relaxed);
339 factor = std::bit_ceil(
static_cast<unsigned int>(std::max(1, factor)));
340 osFactor_.store(std::min(factor, 16), std::memory_order_relaxed);
381 osMode_.store(
static_cast<OversamplingMode>(std::clamp(
static_cast<int>(mode), 0, 1)), std::memory_order_relaxed);
405 osBand_.store(
static_cast<OversamplingBand>(std::clamp(
static_cast<int>(band), 0, 1)), std::memory_order_relaxed);
411 [[nodiscard]]
Mode getMode() const noexcept {
return mode_.load(std::memory_order_relaxed); }
414 [[nodiscard]]
int getStages() const noexcept {
return stages_.load(std::memory_order_relaxed); }
415 [[nodiscard]] T
getMix() const noexcept {
return mix_.load(std::memory_order_relaxed); }
447 [[nodiscard]] std::vector<uint8_t>
getState()
const
450 w.
write(
"mode",
static_cast<int32_t
>(
mode_.load(std::memory_order_relaxed)));
451 w.
write(
"ceiling",
static_cast<float>(
ceilingDb_.load(std::memory_order_relaxed)));
452 w.
write(
"inputGain",
static_cast<float>(
inputGainDb_.load(std::memory_order_relaxed)));
453 w.
write(
"stages",
stages_.load(std::memory_order_relaxed));
454 w.
write(
"mix",
static_cast<float>(
mix_.load(std::memory_order_relaxed)));
455 w.
write(
"slewLimit",
static_cast<float>(
slewLimitMs_.load(std::memory_order_relaxed)));
456 w.
write(
"oversampling",
osFactor_.load(std::memory_order_relaxed));
489 static constexpr T
kPhi =
static_cast<T
>(1.6180339887498948482);
496 Mode modeVal =
mode_.load(std::memory_order_relaxed);
497 T ceilDb =
ceilingDb_.load(std::memory_order_relaxed);
498 T gainDb =
inputGainDb_.load(std::memory_order_relaxed);
499 int numStages =
stages_.load(std::memory_order_relaxed);
500 T slewMs =
slewLimitMs_.load(std::memory_order_relaxed);
515 const T slewScale = (slewMs > T(0))
516 ? T(1) / (slewMs * T(0.001)) /
static_cast<T
>(currentSampleRate)
527 for (
auto& st : chStages) st.state.invalidate();
531 case Mode::Soft: dispatchAntialiased<detail::AdaaTanh>(buffer, numStages, slewScale);
break;
532 case Mode::Analog: dispatchAntialiased<detail::AdaaSinePolynomial>(buffer, numStages, slewScale);
break;
533 case Mode::GoldenRatio: dispatchAntialiased<detail::AdaaRationalKnee>(buffer, numStages, slewScale);
break;
534 default: dispatchAntialiased<detail::AdaaHardClip>(buffer, numStages, slewScale);
break;
540 case Mode::Hard: dispatchClipping<Mode::Hard>(buffer, numStages, slewScale);
break;
541 case Mode::Soft: dispatchClipping<Mode::Soft>(buffer, numStages, slewScale);
break;
542 case Mode::Analog: dispatchClipping<Mode::Analog>(buffer, numStages, slewScale);
break;
543 case Mode::GoldenRatio: dispatchClipping<Mode::GoldenRatio>(buffer, numStages, slewScale);
break;
544 default: dispatchClipping<Mode::Hard>(buffer, numStages, slewScale);
break;
559 for (
auto& st : chStages) st = {};
560 for (
auto& ring :
padRing_) ring.fill(0.0);
561 for (
auto& ring :
dryRing_) ring.fill(T(0));
574 const int nS = std::min(buffer.getNumSamples(),
dryScratch_.getNumSamples());
577 for (
int ch = 0; ch < nCh; ++ch)
579 const T* in = buffer.getChannel(ch);
581 auto& ring =
dryRing_[
static_cast<size_t>(ch)];
583 for (
int i = 0; i < nS; ++i)
585 out[i] = ring[
static_cast<size_t>(pos)];
586 ring[
static_cast<size_t>(pos)] = in[i];
587 pos = pos + 1 == len ? 0 : pos + 1;
596 for (
int ch = 0; ch < nCh; ++ch)
597 std::copy_n(buffer.getChannel(ch), nS,
dryScratch_.getChannel(ch));
602 else if (extra > 0 && nS == buffer.getNumSamples())
615 template <
class Curve>
618 const int nCh = std::min(buffer.getNumChannels(),
kMaxChannels);
619 const int nS = buffer.getNumSamples();
621 const int pad = totalDelay - numStages;
633 const double c0 =
static_cast<double>(
ceilingSm_.getCurrentValue());
634 const double g0 =
static_cast<double>(
stageGainSm_.getCurrentValue());
635 for (
int ch = 0; ch < nCh; ++ch)
637 double u =
static_cast<double>(buffer.getChannel(ch)[0]) / c0;
641 auto& st =
adaaStages_[
static_cast<size_t>(ch)][
static_cast<size_t>(s)];
644 st.out1 = st.out2 = u;
653 const double g0 =
static_cast<double>(
stageGainSm_.getCurrentValue());
654 for (
int ch = 0; ch < nCh; ++ch)
657 auto& prev =
adaaStages_[
static_cast<size_t>(ch)][
static_cast<size_t>(s - 1)];
658 auto& st =
adaaStages_[
static_cast<size_t>(ch)][
static_cast<size_t>(s)];
659 st.state.reset(g0 * prev.out2);
660 st.state.track(g0 * prev.out1);
661 st.out1 = st.out2 = prev.out1;
667 for (
int start = 0; start < nS; start +=
kChunk)
669 const int n = std::min(
kChunk, nS - start);
672 for (
int j = 0; j < n; ++j)
678 const T ceilConst =
ceilingSm_.getCurrentValue();
680 for (
int ch = 0; ch < nCh; ++ch)
682 T* data = buffer.getChannel(ch) + start;
683 auto& stages =
adaaStages_[
static_cast<size_t>(ch)];
684 auto& ring =
padRing_[
static_cast<size_t>(ch)];
686 for (
int j = 0; j < n; ++j)
688 const T stageGain = gliding ?
gainRamp_[
static_cast<size_t>(j)] : gainConst;
689 const T ceiling = gliding ?
ceilRamp_[
static_cast<size_t>(j)] : ceilConst;
690 const double g =
static_cast<double>(stageGain);
691 const double c =
static_cast<double>(ceiling);
692 double u =
static_cast<double>(data[j]) / c;
694 T totalGain = stageGain;
695 for (
int s = 1; s < numStages; ++s) totalGain *= stageGain;
696 const T driven = data[j] * totalGain;
698 for (
int s = 0; s < numStages; ++s)
700 auto& st = stages[
static_cast<size_t>(s)];
701 u = st.state.template process<Curve>(u * g);
707 ring[
static_cast<size_t>(pos)] = u;
708 const double delayed = ring[
static_cast<size_t>((pos - pad) & (
kPadRing - 1))];
711 T sample =
static_cast<T
>(delayed * c);
712 const T maxSlewDelta = ceiling * slewScale;
713 if (maxSlewDelta > T(0))
716 if (std::abs(delta) > maxSlewDelta)
717 sample =
slewPrev_[ch] + std::copysign(maxSlewDelta, delta);
721 peakIn = std::max(peakIn, std::abs(driven));
722 peakOut = std::max(peakOut, std::abs(sample));
725 if (ch == nCh - 1) writePos = pos;
731 if (peakIn > T(1e-6)) {
732 auto ratio = std::min(peakOut / peakIn, T(1));
740 [[nodiscard]]
static T
stageGainFor(T totalGainLin,
int numStages)
noexcept
742 return (numStages > 1) ? std::pow(totalGainLin, T(1) /
static_cast<T
>(numStages))
752 stages_.load(std::memory_order_relaxed)));
762 const int nCh = std::min(buffer.getNumChannels(),
kMaxChannels);
763 const int nS = buffer.getNumSamples();
770 for (
int start = 0; start < nS; start +=
kChunk)
772 const int n = std::min(
kChunk, nS - start);
775 for (
int j = 0; j < n; ++j)
781 const T ceilConst =
ceilingSm_.getCurrentValue();
783 for (
int ch = 0; ch < nCh; ++ch)
785 T* data = buffer.getChannel(ch) + start;
786 for (
int j = 0; j < n; ++j)
788 const T stageGain = gliding ?
gainRamp_[
static_cast<size_t>(j)] : gainConst;
789 const T ceiling = gliding ?
ceilRamp_[
static_cast<size_t>(j)] : ceilConst;
791 T totalGain = stageGain;
792 for (
int s = 1; s < numStages; ++s) totalGain *= stageGain;
793 const T driven = sample * totalGain;
796 for (
int s = 0; s < numStages; ++s)
799 sample = processSample<M>(sample, ceiling);
803 const T maxSlewDelta = ceiling * slewScale;
804 if (maxSlewDelta > T(0))
807 if (std::abs(delta) > maxSlewDelta)
808 sample =
slewPrev_[ch] + std::copysign(maxSlewDelta, delta);
813 peakIn = std::max(peakIn, std::abs(driven));
814 peakOut = std::max(peakOut, std::abs(sample));
821 if (peakIn > T(1e-6)) {
822 auto ratio = std::min(peakOut / peakIn, T(1));
836 return detail::clipperShape<detail::ClipperCurve::Hard>(sample, ceiling);
838 return detail::clipperShape<detail::ClipperCurve::Tanh>(sample, ceiling);
840 return detail::clipperShape<detail::ClipperCurve::Sine>(sample, ceiling);
842 return detail::clipperShape<detail::ClipperCurve::GoldenRatio>(sample, ceiling);
846 [[nodiscard]]
static T
dbToLinear(T dB)
noexcept {
return std::pow(T(10), dB / T(20)); }
849 return linear > T(1e-5) ? T(20) * std::log10(linear) : minusInfinityDb;
867 std::atomic<OversamplingBand>
osBand_ { OversamplingBand::Preset };
Non-owning view over audio channel data.
Owning audio buffer with contiguous, 32-byte aligned storage.
Real-time audio clipper with analog modeling and anti-aliasing features.
std::unique_ptr< Oversampling< T > > oversampler_
SmoothedValue< T > stageGainSm_
void snapParameters() noexcept
std::array< std::array< double, kPadRing >, kMaxChannels > padRing_
std::atomic< T > inputGainDb_
std::atomic< int > osFactor_
OversamplingBand getOversamplingBand() const noexcept
The band of the oversampler's first stage (setOversamplingBand()).
OversamplingMode
How the oversampler filters (see setOversamplingMode()).
@ LinearPhase
Linear-phase half-bands: the latency of the factor, the dry path a delay (default).
@ MinimumPhase
Elliptic allpass half-bands: a few samples of latency, the dry path through the same filters.
AudioBuffer< T > dryScratch_
OversamplingDryPath< T > dryPath_
The dry copy through minimum-phase filters.
std::array< std::array< AdaaStage, kMaxStages >, kMaxChannels > adaaStages_
void setOversamplingBand(OversamplingBand band) noexcept
Chooses the band the oversampler's first stage keeps (applied by the next prepare()).
void resetAntialiasState() noexcept
OversamplingMode getOversamplingMode() const noexcept
The oversampler's filters (setOversamplingMode()).
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob. Oversampling factor applies on the next prepare() as usual.
bool adaaActive_
antialias_ as applied (audio thread).
std::atomic< T > gainReductionDb_
T slewPrev_[kMaxChannels]
std::atomic< T > ceilingDb_
static T processSample(T sample, T ceiling) noexcept
Compile-time resolution of the waveshaping math.
void setSlewLimit(T ms) noexcept
Enables slew limiting to soften clipping edges.
bool isOversamplingAutomatic() const noexcept
Whether the factor follows the host rate (setAutomaticOversampling()).
void setInputGain(T dB) noexcept
Sets the input drive/gain before clipping.
void processInternal(AudioBufferView< T > &buffer, double currentSampleRate) noexcept
Core DSP routing. Resolves atomics and branches to the per-mode template.
int getLatency() const noexcept
Latency in samples: oversampling filters plus, when enabled, the antialiasing delay.
static constexpr double kAutomaticInternalRate
Rate the automatic factor reaches.
static constexpr T kPhi
Mathematical Golden Ratio used for the GoldenRatio soft-knee transition.
static constexpr int kPadRing
‍largest pad (16 * 1 - 1).
bool getAntialiasing() const noexcept
Whether second-order antialiasing is enabled.
static constexpr int kMaxStages
std::atomic< bool > osAutomatic_
The factor follows the host rate.
void prepare(const AudioSpec &spec)
Prepares the clipper for processing, allocating any necessary internal buffers.
void setAutomaticOversampling(bool on) noexcept
Lets the host rate choose the factor (applied by the next prepare(), as setOversampling()).
Mode
Defines the harmonic waveshaping algorithm used for clipping.
@ Hard
Brickwall digital clipping. High odd harmonics.
@ Analog
Sine-based soft clipping. Transformer-like saturation.
@ Soft
Tanh soft clipping. Even/odd blend, tape-like.
@ GoldenRatio
Mathematical soft-knee using phi. Extremely transparent until heavy drive.
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an audio buffer in-place through the clipping algorithm.
void setStages(int count) noexcept
Sets the number of cascaded clipping stages.
std::array< T, kChunk > gainRamp_
void setMode(Mode mode) noexcept
Sets the clipping algorithm.
T getCeiling() const noexcept
bool adaaFresh_
Seed the stage history on the next block.
void dispatchAntialiased(AudioBufferView< T > &buffer, int numStages, T slewScale) noexcept
Second-order antialiased per-mode loop. Works in units of the ceiling: each stage maps u -> curve(u) ...
void dispatchClipping(AudioBufferView< T > &buffer, int numStages, T slewScale) noexcept
Per-mode processing loop (waveshaper inlined at compile time; the slew state and peak metering keep t...
void setOversamplingMode(OversamplingMode mode) noexcept
Chooses the oversampler's filters (applied by the next prepare()).
std::atomic< OversamplingMode > osMode_
setOversamplingMode().
bool dryThroughFilters_
The dry copy crosses the filters (minimum phase).
T getMix() const noexcept
SmoothedValue< T > ceilingSm_
int lastStages_
Stage count the stage-gain glide refers to.
static constexpr double kParamRampMs
void setMix(T amount) noexcept
Sets the dry/wet ratio of the processor.
void reset() noexcept
Resets the internal state of the clipper.
void setOversampling(int factor) noexcept
Sets the oversampling multiplier to mitigate aliasing.
T getGainReductionDb() const noexcept
Retrieves the maximum gain reduction applied during the last block (for UI metering).
std::array< T, kChunk > ceilRamp_
static constexpr int kChunk
Mode getMode() const noexcept
static T stageGainFor(T totalGainLin, int numStages) noexcept
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
void pushDryAligned(AudioBufferView< T > buffer, int extra) noexcept
static T gainToDecibels(T linear, T minusInfinityDb) noexcept
static constexpr int kMaxChannels
int adaaBaseLatency() const noexcept
int getStages() const noexcept
int processFactor_
Oversampling factor in use.
typename Oversampling< T >::Band OversamplingBand
The band the oversampler's first stage keeps (see setOversamplingBand()).
void setAntialiasing(bool on) noexcept
Enables second-order antiderivative antialiasing on every mode.
void setCeiling(T dB) noexcept
Sets the absolute maximum output level.
std::atomic< bool > prepared_
T getInputGain() const noexcept
std::atomic< bool > antialias_
T getSlewLimit() const noexcept
int getOversampling() const noexcept
Returns the published oversampling factor (applied on the next prepare()).
std::atomic< Mode > mode_
std::atomic< OversamplingBand > osBand_
setOversamplingBand().
static T dbToLinear(T dB) noexcept
std::atomic< T > slewLimitMs_
std::atomic< int > stages_
Mode adaaMode_
Curve the cached values belong to.
std::array< std::array< T, kMaxStages >, kMaxChannels > dryRing_
Dry delay, <= 4 samples.
Pre-allocated, SIMD-friendly dry/wet blender for real-time audio.
Carries a dry signal through the same round trip as an Oversampling engine, so that a dry/wet mix add...
Power-of-two oversampling processor with polyphase anti-aliasing.
Band
The band the first stage keeps (see the constructor).
void prepare(const AudioSpec &spec)
Pre-allocates buffers and computes FIR filter coefficients.
static constexpr int factorForRate(double sampleRate, double minimumInternalRate=176400.0, int maxFactor=1<< kMaxStages) noexcept
The smallest factor that brings a host rate up to an internal rate.
Zero-allocation parameter smoother for real-time audio.
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
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.
Per-stream second-order ADAA state.
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").
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.
double out2
Last two stage outputs (ceiling units).