SquidgeDSP/core/Clipper.cpp

42 lines
No EOL
1.1 KiB
C++

#include "Clipper.hpp"
#include <cmath>
Clipper::Clipper(float init_clip, ClipperMode init_mode)
: threshold_(init_clip), mode_(init_mode) {}
void Clipper::process(const float *in, float *out, uint32_t frames) {
for (uint32_t i = 0; i < frames; ++i) {
out[i] = clip(in[i]);
}
}
void Clipper::processStereo(const float *inLeft, const float *inRight,
float *outLeft, float *outRight, uint32_t frames) {
for (uint32_t i = 0; i < frames; ++i) {
outLeft[i] = clip(inLeft[i]);
outRight[i] = clip(inRight[i]);
}
}
float Clipper::clip(const float in) {
switch (mode_) {
case kClipperModeHard: {
return std::fmin(std::fmax(in, -threshold_), threshold_);
}
default:
case kClipperModeSoft: {
float normalized = (in / threshold_) * 0.75f;
return std::tanh(normalized) * threshold_;
}
case kClipperModeFold: {
float x = in;
while (x > threshold_ || x < -threshold_) {
if (x > threshold_) {
x = 2.0f * threshold_ - x;
} else if (x < -threshold_) {
x = -2.0f * threshold_ - x;
}
}
return x;
}
}
}