DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Clipper.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
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"
70
71#include <algorithm>
72#include <array>
73#include <atomic>
74#include <bit>
75#include <cmath>
76#include <cstddef>
77#include <cstdint>
78#include <memory>
79#include <numbers>
80#include <vector>
81
82namespace dspark {
83
90template <FloatType T>
92{
93public:
95 enum class Mode
96 {
97 Hard,
98 Soft,
99 Analog,
101 };
102
103 // -- Lifecycle --------------------------------------------------------------
104
118 void prepare(const AudioSpec& spec)
119 {
120 if (!spec.isValid()) return;
121
122 prepared_.store(false, std::memory_order_relaxed);
123 spec_ = spec;
124 mixer_.prepare(spec);
125
126 int osFactor = osFactor_.load(std::memory_order_relaxed);
127 if (osAutomatic_.load(std::memory_order_relaxed))
128 {
130 osFactor_.store(osFactor, std::memory_order_relaxed);
131 }
132
133 if (osFactor > 1) {
134 // At 16x the antialiased curves leave less than the High
135 // preset's last stage lets through (93 dB): every stage is then
136 // made at least 100 dB deep. Below that the folding of the curve
137 // itself is what is left, so the preset stays.
138 const bool minimum = osMode_.load(std::memory_order_relaxed) == OversamplingMode::MinimumPhase;
139 oversampler_ = std::make_unique<Oversampling<T>>(
143 osBand_.load(std::memory_order_relaxed));
144 oversampler_->prepare(spec);
145 } else {
146 oversampler_.reset();
147 }
148
149 // Align the dry copy with the latent (oversampled) wet path so that a
150 // dry/wet blend below 100% does not comb-filter. The antialiasing
151 // delay is added on top by delaying the dry input (pushDryAligned).
152 // Behind minimum-phase filters the dry copy crosses the same filters
153 // instead (OversamplingDryPath): the mix then adds in phase at every
154 // frequency, which a delay cannot do against a fractional,
155 // frequency-dependent delay.
158 mixer_.setLatencyCompensation(oversampler_ && !dryThroughFilters_ ? oversampler_->getLatency() : 0);
159 processFactor_ = oversampler_ ? oversampler_->getFactor() : 1;
160 dryScratch_.resize(spec.numChannels, spec.maxBlockSize);
162
163 // Parameter glides run at the processing (possibly oversampled) rate.
164 const double procRate = spec.sampleRate * (oversampler_ ? oversampler_->getFactor() : 1);
165 for (auto* sm : { &stageGainSm_, &ceilingSm_ })
166 {
167 sm->prepare(procRate, kParamRampMs);
168 sm->setSmoothingType(SmoothedValue<T>::SmoothingType::Linear);
169 }
171
172 for (int ch = 0; ch < kMaxChannels; ++ch)
173 slewPrev_[ch] = T(0);
174
175 prepared_.store(true, std::memory_order_relaxed);
176 }
177
184 void reset() noexcept
185 {
186 mixer_.reset();
187 dryPath_.reset();
188 if (oversampler_) oversampler_->reset();
189 for (int ch = 0; ch < kMaxChannels; ++ch)
190 slewPrev_[ch] = T(0);
193 gainReductionDb_.store(T(0), std::memory_order_relaxed);
194 }
195
196 // -- Processing -------------------------------------------------------------
197
206 void processBlock(AudioBufferView<T> buffer) noexcept
207 {
208 if (!prepared_.load(std::memory_order_relaxed)) return;
209 if (buffer.getNumSamples() == 0 || buffer.getNumChannels() == 0) return;
210
211 // The oversampler and the dry mixer hold one maximum block: longer
212 // blocks used to leave their tail unclipped.
213 const int total = buffer.getNumSamples();
214 const int maxBlock = std::max(1, spec_.maxBlockSize);
215 for (int off = 0; off < total; off += maxBlock)
216 processChunk(buffer.getSubView(off, std::min(maxBlock, total - off)));
217 }
218
219private:
220 void processChunk(AudioBufferView<T> buffer) noexcept
221 {
222 T mixVal = mix_.load(std::memory_order_relaxed);
223 const bool adaa = antialias_.load(std::memory_order_relaxed);
224 if (adaa != adaaActive_)
225 {
226 // Start each stage from its current input rather than from
227 // stale history; the latency change itself steps the output.
228 adaaActive_ = adaa;
229 adaaFresh_ = true;
230 }
231 pushDryAligned(buffer, adaa ? adaaBaseLatency() : 0);
232
233 if (oversampler_ && oversampler_->getFactor() > 1)
234 {
235 auto upView = oversampler_->upsample(buffer);
236 processInternal(upView, spec_.sampleRate * oversampler_->getFactor());
237 oversampler_->downsample(buffer);
238 }
239 else
240 {
242 }
243
244 mixer_.mixWet(buffer, mixVal);
245 }
246
247public:
248
253 void setMode(Mode mode) noexcept
254 {
255 const int m = std::clamp(static_cast<int>(mode), 0,
256 static_cast<int>(Mode::GoldenRatio));
257 mode_.store(static_cast<Mode>(m), std::memory_order_relaxed);
258 }
259
265 void setCeiling(T dB) noexcept
266 {
267 if (!std::isfinite(dB)) return;
268 ceilingDb_.store(std::clamp(dB, T(-60), T(0)), std::memory_order_relaxed);
269 }
270
276 void setInputGain(T dB) noexcept
277 {
278 if (!std::isfinite(dB)) return;
279 inputGainDb_.store(std::clamp(dB, T(0), T(48)), std::memory_order_relaxed);
280 }
281
291 void setStages(int count) noexcept
292 {
293 stages_.store(std::clamp(count, 1, kMaxStages), std::memory_order_relaxed);
294 }
295
301 void setMix(T amount) noexcept
302 {
303 if (!std::isfinite(amount)) return;
304 mix_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
305 }
306
319 void setSlewLimit(T ms) noexcept
320 {
321 if (!std::isfinite(ms)) return;
322 slewLimitMs_.store(std::max(ms, T(0)), std::memory_order_relaxed);
323 }
324
337 void setOversampling(int factor) noexcept
338 {
339 factor = std::bit_ceil(static_cast<unsigned int>(std::max(1, factor)));
340 osFactor_.store(std::min(factor, 16), std::memory_order_relaxed);
341 osAutomatic_.store(false, std::memory_order_relaxed);
342 }
343
357 void setAutomaticOversampling(bool on) noexcept { osAutomatic_.store(on, std::memory_order_relaxed); }
358
360 [[nodiscard]] bool isOversamplingAutomatic() const noexcept { return osAutomatic_.load(std::memory_order_relaxed); }
361
364 {
367 };
368
380 {
381 osMode_.store(static_cast<OversamplingMode>(std::clamp(static_cast<int>(mode), 0, 1)), std::memory_order_relaxed);
382 }
383
385 [[nodiscard]] OversamplingMode getOversamplingMode() const noexcept { return osMode_.load(std::memory_order_relaxed); }
386
389
404 {
405 osBand_.store(static_cast<OversamplingBand>(std::clamp(static_cast<int>(band), 0, 1)), std::memory_order_relaxed);
406 }
407
409 [[nodiscard]] OversamplingBand getOversamplingBand() const noexcept { return osBand_.load(std::memory_order_relaxed); }
410
411 [[nodiscard]] Mode getMode() const noexcept { return mode_.load(std::memory_order_relaxed); }
412 [[nodiscard]] T getCeiling() const noexcept { return ceilingDb_.load(std::memory_order_relaxed); }
413 [[nodiscard]] T getInputGain() const noexcept { return inputGainDb_.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); }
416 [[nodiscard]] T getSlewLimit() const noexcept { return slewLimitMs_.load(std::memory_order_relaxed); }
417
419 [[nodiscard]] int getOversampling() const noexcept { return osFactor_.load(std::memory_order_relaxed); }
420
429 void setAntialiasing(bool on) noexcept { antialias_.store(on, std::memory_order_relaxed); }
430
432 [[nodiscard]] bool getAntialiasing() const noexcept { return antialias_.load(std::memory_order_relaxed); }
433
436 [[nodiscard]] int getLatency() const noexcept
437 {
438 return (oversampler_ ? oversampler_->getLatency() : 0)
439 + (antialias_.load(std::memory_order_relaxed) ? adaaBaseLatency() : 0);
440 }
441
443 [[nodiscard]] T getGainReductionDb() const noexcept { return gainReductionDb_.load(std::memory_order_relaxed); }
444
445
447 [[nodiscard]] std::vector<uint8_t> getState() const
448 {
449 StateWriter w(stateId("CLIP"), 1);
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));
457 w.write("oversamplingAuto", osAutomatic_.load(std::memory_order_relaxed));
458 w.write("oversamplingMode", static_cast<int32_t>(getOversamplingMode()));
459 w.write("oversamplingBand", static_cast<int32_t>(getOversamplingBand()));
460 w.write("antialias", antialias_.load(std::memory_order_relaxed));
461 return w.blob();
462 }
463
466 bool setState(const uint8_t* data, size_t size)
467 {
468 StateReader r(data, size);
469 if (!r.isValid() || r.processorId() != stateId("CLIP")) return false;
470 setMode(static_cast<Mode>(r.read("mode", 0)));
471 setCeiling(static_cast<T>(r.read("ceiling", 0.0f)));
472 setInputGain(static_cast<T>(r.read("inputGain", 0.0f)));
473 setStages(r.read("stages", 1));
474 setMix(static_cast<T>(r.read("mix", 1.0f)));
475 setSlewLimit(static_cast<T>(r.read("slewLimit", 0.0f)));
476 setOversampling(r.read("oversampling", 1));
477 setAutomaticOversampling(r.read("oversamplingAuto", false));
478 setOversamplingMode(static_cast<OversamplingMode>(r.read("oversamplingMode", 0)));
479 setOversamplingBand(static_cast<OversamplingBand>(r.read("oversamplingBand", 0)));
480 setAntialiasing(r.read("antialias", false));
481 return true;
482 }
483
484protected:
485 static constexpr int kMaxStages = 4;
486 static constexpr int kMaxChannels = 16;
487
489 static constexpr T kPhi = static_cast<T>(1.6180339887498948482);
490
494 void processInternal(AudioBufferView<T>& buffer, double currentSampleRate) noexcept
495 {
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);
501
502 if (numStages != lastStages_)
503 {
504 // Keep the running TOTAL gain continuous: the per-stage gain of
505 // the old count, applied numStages times, jumped (1 -> 4 stages
506 // at +18 dB drove a -20 dBFS tone to the ceiling for 20 ms).
507 const T total = std::pow(stageGainSm_.getCurrentValue(), static_cast<T>(lastStages_));
508 stageGainSm_.reset(stageGainFor(total, numStages));
509 lastStages_ = numStages;
510 }
511 ceilingSm_.setTargetValue(dbToLinear(ceilDb));
512 stageGainSm_.setTargetValue(stageGainFor(dbToLinear(gainDb), numStages));
513
514 // Maximum slew per sample is ceiling * slewScale (time-aware).
515 const T slewScale = (slewMs > T(0))
516 ? T(1) / (slewMs * T(0.001)) / static_cast<T>(currentSampleRate)
517 : T(0);
518
519 // The mode switch is resolved once per block, outside the sample loop.
520 if (adaaActive_)
521 {
522 // Cached antiderivative values belong to one curve.
523 if (modeVal != adaaMode_)
524 {
525 adaaMode_ = modeVal;
526 for (auto& chStages : adaaStages_)
527 for (auto& st : chStages) st.state.invalidate();
528 }
529 switch (modeVal)
530 {
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;
535 }
536 return;
537 }
538 switch (modeVal)
539 {
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;
545 }
546 }
547
550 [[nodiscard]] int adaaBaseLatency() const noexcept
551 {
552 const int factor = std::max(1, processFactor_);
553 return (kMaxStages + factor - 1) / factor;
554 }
555
556 void resetAntialiasState() noexcept
557 {
558 for (auto& chStages : adaaStages_)
559 for (auto& st : chStages) st = {};
560 for (auto& ring : padRing_) ring.fill(0.0);
561 for (auto& ring : dryRing_) ring.fill(T(0));
562 padPos_ = 0;
563 dryPos_ = 0;
564 adaaFresh_ = true;
565 adaaStageCount_ = stages_.load(std::memory_order_relaxed);
566 }
567
571 void pushDryAligned(AudioBufferView<T> buffer, int extra) noexcept
572 {
573 const int nCh = std::min({buffer.getNumChannels(), dryScratch_.getNumChannels(), kMaxChannels});
574 const int nS = std::min(buffer.getNumSamples(), dryScratch_.getNumSamples());
575 const int len = adaaBaseLatency();
576 int pos = dryPos_;
577 for (int ch = 0; ch < nCh; ++ch)
578 {
579 const T* in = buffer.getChannel(ch);
580 T* out = dryScratch_.getChannel(ch);
581 auto& ring = dryRing_[static_cast<size_t>(ch)];
582 pos = dryPos_;
583 for (int i = 0; i < nS; ++i)
584 {
585 out[i] = ring[static_cast<size_t>(pos)]; // input len samples ago
586 ring[static_cast<size_t>(pos)] = in[i];
587 pos = pos + 1 == len ? 0 : pos + 1;
588 }
589 }
590 dryPos_ = pos;
591 // The mixer blends only the prepared channels, so the scratch view
592 // (prepared channels) is enough whatever the buffer's width.
593 if (dryThroughFilters_ && nS == buffer.getNumSamples())
594 {
595 if (extra <= 0)
596 for (int ch = 0; ch < nCh; ++ch)
597 std::copy_n(buffer.getChannel(ch), nS, dryScratch_.getChannel(ch));
598 auto dry = dryScratch_.toView().getSubView(0, nS);
599 dryPath_.process(dry);
600 mixer_.pushDry(dry);
601 }
602 else if (extra > 0 && nS == buffer.getNumSamples())
603 mixer_.pushDry(dryScratch_.toView().getSubView(0, nS));
604 else
605 mixer_.pushDry(buffer);
606 }
607
615 template <class Curve>
616 void dispatchAntialiased(AudioBufferView<T>& buffer, int numStages, T slewScale) noexcept
617 {
618 const int nCh = std::min(buffer.getNumChannels(), kMaxChannels);
619 const int nS = buffer.getNumSamples();
620 const int totalDelay = std::max(1, processFactor_) * adaaBaseLatency();
621 const int pad = totalDelay - numStages;
622
623 T peakIn = T(0);
624 T peakOut = T(0);
625
626 if (adaaFresh_)
627 {
628 // Hold the first input as the whole history of every stage.
629 adaaFresh_ = false;
630 adaaStageCount_ = numStages;
631 if (nS > 0)
632 {
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)
636 {
637 double u = static_cast<double>(buffer.getChannel(ch)[0]) / c0;
638 for (int s = 0; s < kMaxStages; ++s)
639 {
640 u *= g0;
641 auto& st = adaaStages_[static_cast<size_t>(ch)][static_cast<size_t>(s)];
642 st.state.reset(u);
643 u = Curve::d2(u);
644 st.out1 = st.out2 = u;
645 }
646 }
647 }
648 }
649 else if (numStages > adaaStageCount_)
650 {
651 // Newly active stages continue from the previous stage's recent
652 // output, as if they had been running.
653 const double g0 = static_cast<double>(stageGainSm_.getCurrentValue());
654 for (int ch = 0; ch < nCh; ++ch)
655 for (int s = adaaStageCount_; s < numStages; ++s)
656 {
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;
662 }
663 }
664 adaaStageCount_ = numStages;
665
666 int writePos = padPos_;
667 for (int start = 0; start < nS; start += kChunk)
668 {
669 const int n = std::min(kChunk, nS - start);
670 const bool gliding = stageGainSm_.isSmoothing() || ceilingSm_.isSmoothing();
671 if (gliding)
672 for (int j = 0; j < n; ++j)
673 {
674 gainRamp_[static_cast<size_t>(j)] = stageGainSm_.getNextValue();
675 ceilRamp_[static_cast<size_t>(j)] = ceilingSm_.getNextValue();
676 }
677 const T gainConst = stageGainSm_.getCurrentValue();
678 const T ceilConst = ceilingSm_.getCurrentValue();
679
680 for (int ch = 0; ch < nCh; ++ch)
681 {
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)];
685 int pos = writePos;
686 for (int j = 0; j < n; ++j)
687 {
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;
693
694 T totalGain = stageGain;
695 for (int s = 1; s < numStages; ++s) totalGain *= stageGain;
696 const T driven = data[j] * totalGain;
697
698 for (int s = 0; s < numStages; ++s)
699 {
700 auto& st = stages[static_cast<size_t>(s)];
701 u = st.state.template process<Curve>(u * g);
702 st.out2 = st.out1;
703 st.out1 = u;
704 }
705
706 // Pad to the fixed total delay (ring of kPadRing samples).
707 ring[static_cast<size_t>(pos)] = u;
708 const double delayed = ring[static_cast<size_t>((pos - pad) & (kPadRing - 1))];
709 pos = (pos + 1) & (kPadRing - 1);
710
711 T sample = static_cast<T>(delayed * c);
712 const T maxSlewDelta = ceiling * slewScale;
713 if (maxSlewDelta > T(0))
714 {
715 const T delta = sample - slewPrev_[ch];
716 if (std::abs(delta) > maxSlewDelta)
717 sample = slewPrev_[ch] + std::copysign(maxSlewDelta, delta);
718 }
719 slewPrev_[ch] = sample;
720
721 peakIn = std::max(peakIn, std::abs(driven));
722 peakOut = std::max(peakOut, std::abs(sample));
723 data[j] = sample;
724 }
725 if (ch == nCh - 1) writePos = pos;
726 }
727 if (nCh == 0) break;
728 }
729 padPos_ = writePos;
730
731 if (peakIn > T(1e-6)) {
732 auto ratio = std::min(peakOut / peakIn, T(1));
733 gainReductionDb_.store(gainToDecibels(ratio, T(-100)), std::memory_order_relaxed);
734 } else {
735 gainReductionDb_.store(T(0), std::memory_order_relaxed);
736 }
737 }
738
740 [[nodiscard]] static T stageGainFor(T totalGainLin, int numStages) noexcept
741 {
742 return (numStages > 1) ? std::pow(totalGainLin, T(1) / static_cast<T>(numStages))
743 : totalGainLin;
744 }
745
747 void snapParameters() noexcept
748 {
749 lastStages_ = stages_.load(std::memory_order_relaxed);
750 ceilingSm_.reset(dbToLinear(ceilingDb_.load(std::memory_order_relaxed)));
751 stageGainSm_.reset(stageGainFor(dbToLinear(inputGainDb_.load(std::memory_order_relaxed)),
752 stages_.load(std::memory_order_relaxed)));
753 }
754
759 template <Mode M>
760 void dispatchClipping(AudioBufferView<T>& buffer, int numStages, T slewScale) noexcept
761 {
762 const int nCh = std::min(buffer.getNumChannels(), kMaxChannels);
763 const int nS = buffer.getNumSamples();
764
765 T peakIn = T(0);
766 T peakOut = T(0);
767
768 // Chunks: the parameter glides are computed once per sample and shared
769 // by every channel; settled, both are plain constants.
770 for (int start = 0; start < nS; start += kChunk)
771 {
772 const int n = std::min(kChunk, nS - start);
773 const bool gliding = stageGainSm_.isSmoothing() || ceilingSm_.isSmoothing();
774 if (gliding)
775 for (int j = 0; j < n; ++j)
776 {
777 gainRamp_[static_cast<size_t>(j)] = stageGainSm_.getNextValue();
778 ceilRamp_[static_cast<size_t>(j)] = ceilingSm_.getNextValue();
779 }
780 const T gainConst = stageGainSm_.getCurrentValue();
781 const T ceilConst = ceilingSm_.getCurrentValue();
782
783 for (int ch = 0; ch < nCh; ++ch)
784 {
785 T* data = buffer.getChannel(ch) + start;
786 for (int j = 0; j < n; ++j)
787 {
788 const T stageGain = gliding ? gainRamp_[static_cast<size_t>(j)] : gainConst;
789 const T ceiling = gliding ? ceilRamp_[static_cast<size_t>(j)] : ceilConst;
790 T sample = data[j];
791 T totalGain = stageGain;
792 for (int s = 1; s < numStages; ++s) totalGain *= stageGain;
793 const T driven = sample * totalGain;
794
795 // Compiler will unroll this loop for small bounded N
796 for (int s = 0; s < numStages; ++s)
797 {
798 sample *= stageGain;
799 sample = processSample<M>(sample, ceiling);
800 }
801
802 // Slew Limiter processing (branch highly predictable if static)
803 const T maxSlewDelta = ceiling * slewScale;
804 if (maxSlewDelta > T(0))
805 {
806 T delta = sample - slewPrev_[ch];
807 if (std::abs(delta) > maxSlewDelta)
808 sample = slewPrev_[ch] + std::copysign(maxSlewDelta, delta);
809 }
810
811 slewPrev_[ch] = sample;
812
813 peakIn = std::max(peakIn, std::abs(driven));
814 peakOut = std::max(peakOut, std::abs(sample));
815 data[j] = sample;
816 }
817 }
818 }
819
820 // Safe gain reduction calculation
821 if (peakIn > T(1e-6)) {
822 auto ratio = std::min(peakOut / peakIn, T(1));
823 gainReductionDb_.store(gainToDecibels(ratio, T(-100)), std::memory_order_relaxed);
824 } else {
825 gainReductionDb_.store(T(0), std::memory_order_relaxed);
826 }
827 }
828
832 template <Mode M>
833 [[nodiscard]] static inline T processSample(T sample, T ceiling) noexcept
834 {
835 if constexpr (M == Mode::Hard)
836 return detail::clipperShape<detail::ClipperCurve::Hard>(sample, ceiling);
837 else if constexpr (M == Mode::Soft)
838 return detail::clipperShape<detail::ClipperCurve::Tanh>(sample, ceiling);
839 else if constexpr (M == Mode::Analog)
840 return detail::clipperShape<detail::ClipperCurve::Sine>(sample, ceiling);
841 else // Mode::GoldenRatio (the mode switch instantiates no other value)
842 return detail::clipperShape<detail::ClipperCurve::GoldenRatio>(sample, ceiling);
843 }
844
845 // Mathematical utility helpers
846 [[nodiscard]] static T dbToLinear(T dB) noexcept { return std::pow(T(10), dB / T(20)); }
847 [[nodiscard]] static T gainToDecibels(T linear, T minusInfinityDb) noexcept
848 {
849 return linear > T(1e-5) ? T(20) * std::log10(linear) : minusInfinityDb;
850 }
851
853 std::atomic<bool> prepared_ { false };
855 std::unique_ptr<Oversampling<T>> oversampler_;
856
857 // Lock-free parameter states
858 std::atomic<Mode> mode_ { Mode::Hard };
859 std::atomic<T> ceilingDb_ { T(0) };
860 std::atomic<T> inputGainDb_ { T(0) };
861 std::atomic<int> stages_ { 1 };
862 std::atomic<T> mix_ { T(1) };
863 std::atomic<T> slewLimitMs_ { T(0) };
864 std::atomic<int> osFactor_ { 1 }; // Default to 1 (off)
865 std::atomic<bool> osAutomatic_ { false };
866 std::atomic<OversamplingMode> osMode_ { OversamplingMode::LinearPhase };
867 std::atomic<OversamplingBand> osBand_ { OversamplingBand::Preset };
869 bool dryThroughFilters_ = false;
870 static constexpr double kAutomaticInternalRate = 88200.0;
871
872 // History states per channel
874
875 // Parameter glides (processing rate) and their per-chunk ramps.
876 static constexpr double kParamRampMs = 20.0;
877 static constexpr int kChunk = 256;
880 int lastStages_ = 1;
881 std::array<T, kChunk> gainRamp_ {};
882 std::array<T, kChunk> ceilRamp_ {};
883
884 // Metering state
885 std::atomic<T> gainReductionDb_ { T(0) };
886
887 // Second-order antialiasing (processing rate, per channel and stage).
889 {
891 double out1 = 0.0, out2 = 0.0;
892 };
893 static constexpr int kPadRing = 32;
894 std::atomic<bool> antialias_ { false };
895 bool adaaActive_ = false;
896 bool adaaFresh_ = true;
900 std::array<std::array<AdaaStage, kMaxStages>, kMaxChannels> adaaStages_ {};
901 std::array<std::array<double, kPadRing>, kMaxChannels> padRing_ {};
902 int padPos_ = 0;
903 std::array<std::array<T, kMaxStages>, kMaxChannels> dryRing_ {};
904 int dryPos_ = 0;
906};
907
908} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Owning audio buffer with contiguous, 32-byte aligned storage.
Real-time audio clipper with analog modeling and anti-aliasing features.
Definition Clipper.h:92
std::unique_ptr< Oversampling< T > > oversampler_
Definition Clipper.h:855
SmoothedValue< T > stageGainSm_
Definition Clipper.h:878
void snapParameters() noexcept
Definition Clipper.h:747
std::array< std::array< double, kPadRing >, kMaxChannels > padRing_
Definition Clipper.h:901
std::atomic< T > inputGainDb_
Definition Clipper.h:860
std::atomic< int > osFactor_
Definition Clipper.h:864
OversamplingBand getOversamplingBand() const noexcept
The band of the oversampler's first stage (setOversamplingBand()).
Definition Clipper.h:409
OversamplingMode
How the oversampler filters (see setOversamplingMode()).
Definition Clipper.h:364
@ 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_
Definition Clipper.h:905
OversamplingDryPath< T > dryPath_
The dry copy through minimum-phase filters.
Definition Clipper.h:868
std::array< std::array< AdaaStage, kMaxStages >, kMaxChannels > adaaStages_
Definition Clipper.h:900
void setOversamplingBand(OversamplingBand band) noexcept
Chooses the band the oversampler's first stage keeps (applied by the next prepare()).
Definition Clipper.h:403
AudioSpec spec_
Definition Clipper.h:852
void resetAntialiasState() noexcept
Definition Clipper.h:556
OversamplingMode getOversamplingMode() const noexcept
The oversampler's filters (setOversamplingMode()).
Definition Clipper.h:385
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob. Oversampling factor applies on the next prepare() as usual.
Definition Clipper.h:466
bool adaaActive_
antialias_ as applied (audio thread).
Definition Clipper.h:895
std::atomic< T > gainReductionDb_
Definition Clipper.h:885
T slewPrev_[kMaxChannels]
Definition Clipper.h:873
std::atomic< T > ceilingDb_
Definition Clipper.h:859
static T processSample(T sample, T ceiling) noexcept
Compile-time resolution of the waveshaping math.
Definition Clipper.h:833
void setSlewLimit(T ms) noexcept
Enables slew limiting to soften clipping edges.
Definition Clipper.h:319
bool isOversamplingAutomatic() const noexcept
Whether the factor follows the host rate (setAutomaticOversampling()).
Definition Clipper.h:360
void setInputGain(T dB) noexcept
Sets the input drive/gain before clipping.
Definition Clipper.h:276
void processInternal(AudioBufferView< T > &buffer, double currentSampleRate) noexcept
Core DSP routing. Resolves atomics and branches to the per-mode template.
Definition Clipper.h:494
int getLatency() const noexcept
Latency in samples: oversampling filters plus, when enabled, the antialiasing delay.
Definition Clipper.h:436
static constexpr double kAutomaticInternalRate
Rate the automatic factor reaches.
Definition Clipper.h:870
static constexpr T kPhi
Mathematical Golden Ratio used for the GoldenRatio soft-knee transition.
Definition Clipper.h:489
static constexpr int kPadRing
‍largest pad (16 * 1 - 1).
Definition Clipper.h:893
bool getAntialiasing() const noexcept
Whether second-order antialiasing is enabled.
Definition Clipper.h:432
static constexpr int kMaxStages
Definition Clipper.h:485
std::atomic< bool > osAutomatic_
The factor follows the host rate.
Definition Clipper.h:865
void prepare(const AudioSpec &spec)
Prepares the clipper for processing, allocating any necessary internal buffers.
Definition Clipper.h:118
void setAutomaticOversampling(bool on) noexcept
Lets the host rate choose the factor (applied by the next prepare(), as setOversampling()).
Definition Clipper.h:357
Mode
Defines the harmonic waveshaping algorithm used for clipping.
Definition Clipper.h:96
@ 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.
Definition Clipper.h:206
void setStages(int count) noexcept
Sets the number of cascaded clipping stages.
Definition Clipper.h:291
std::array< T, kChunk > gainRamp_
Definition Clipper.h:881
void setMode(Mode mode) noexcept
Sets the clipping algorithm.
Definition Clipper.h:253
T getCeiling() const noexcept
Definition Clipper.h:412
bool adaaFresh_
Seed the stage history on the next block.
Definition Clipper.h:896
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) ...
Definition Clipper.h:616
int adaaStageCount_
Definition Clipper.h:898
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...
Definition Clipper.h:760
void setOversamplingMode(OversamplingMode mode) noexcept
Chooses the oversampler's filters (applied by the next prepare()).
Definition Clipper.h:379
std::atomic< OversamplingMode > osMode_
setOversamplingMode().
Definition Clipper.h:866
bool dryThroughFilters_
The dry copy crosses the filters (minimum phase).
Definition Clipper.h:869
T getMix() const noexcept
Definition Clipper.h:415
std::atomic< T > mix_
Definition Clipper.h:862
SmoothedValue< T > ceilingSm_
Definition Clipper.h:879
int lastStages_
Stage count the stage-gain glide refers to.
Definition Clipper.h:880
static constexpr double kParamRampMs
Definition Clipper.h:876
void setMix(T amount) noexcept
Sets the dry/wet ratio of the processor.
Definition Clipper.h:301
void reset() noexcept
Resets the internal state of the clipper.
Definition Clipper.h:184
void setOversampling(int factor) noexcept
Sets the oversampling multiplier to mitigate aliasing.
Definition Clipper.h:337
T getGainReductionDb() const noexcept
Retrieves the maximum gain reduction applied during the last block (for UI metering).
Definition Clipper.h:443
std::array< T, kChunk > ceilRamp_
Definition Clipper.h:882
static constexpr int kChunk
Definition Clipper.h:877
DryWetMixer< T > mixer_
Definition Clipper.h:854
Mode getMode() const noexcept
Definition Clipper.h:411
static T stageGainFor(T totalGainLin, int numStages) noexcept
Definition Clipper.h:740
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
Definition Clipper.h:447
void pushDryAligned(AudioBufferView< T > buffer, int extra) noexcept
Definition Clipper.h:571
static T gainToDecibels(T linear, T minusInfinityDb) noexcept
Definition Clipper.h:847
static constexpr int kMaxChannels
Definition Clipper.h:486
int adaaBaseLatency() const noexcept
Definition Clipper.h:550
int getStages() const noexcept
Definition Clipper.h:414
int processFactor_
Oversampling factor in use.
Definition Clipper.h:899
typename Oversampling< T >::Band OversamplingBand
The band the oversampler's first stage keeps (see setOversamplingBand()).
Definition Clipper.h:388
void setAntialiasing(bool on) noexcept
Enables second-order antiderivative antialiasing on every mode.
Definition Clipper.h:429
void setCeiling(T dB) noexcept
Sets the absolute maximum output level.
Definition Clipper.h:265
std::atomic< bool > prepared_
Definition Clipper.h:853
T getInputGain() const noexcept
Definition Clipper.h:413
std::atomic< bool > antialias_
Definition Clipper.h:894
T getSlewLimit() const noexcept
Definition Clipper.h:416
int getOversampling() const noexcept
Returns the published oversampling factor (applied on the next prepare()).
Definition Clipper.h:419
std::atomic< Mode > mode_
Definition Clipper.h:858
std::atomic< OversamplingBand > osBand_
setOversamplingBand().
Definition Clipper.h:867
static T dbToLinear(T dB) noexcept
Definition Clipper.h:846
std::atomic< T > slewLimitMs_
Definition Clipper.h:863
std::atomic< int > stages_
Definition Clipper.h:861
Mode adaaMode_
Curve the cached values belong to.
Definition Clipper.h:897
std::array< std::array< T, kMaxStages >, kMaxChannels > dryRing_
Dry delay, <= 4 samples.
Definition Clipper.h:903
Pre-allocated, SIMD-friendly dry/wet blender for real-time audio.
Definition DryWetMixer.h:83
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.
Definition StateBlob.h:171
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
Per-stream second-order ADAA state.
Definition Adaa.h:411
Main namespace for the DSPark framework.
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
int maxBlockSize
Maximum number of samples per processing block.
Definition AudioSpec.h:53
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
double out2
Last two stage outputs (ceiling units).
Definition Clipper.h:891