Limit convolution processing to the output ambisonic order
[openal-soft.git] / alc / effects / distortion.cpp
blob93f0e0069048cb658c78d19dc91c4b61bc3a6702
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 2013 by Mike Gorchak
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #include "config.h"
23 #include <algorithm>
24 #include <cmath>
25 #include <cstdlib>
27 #include "al/auxeffectslot.h"
28 #include "alcmain.h"
29 #include "alcontext.h"
30 #include "alu.h"
31 #include "filters/biquad.h"
34 namespace {
36 struct DistortionState final : public EffectState {
37 /* Effect gains for each channel */
38 float mGain[MAX_OUTPUT_CHANNELS]{};
40 /* Effect parameters */
41 BiquadFilter mLowpass;
42 BiquadFilter mBandpass;
43 float mAttenuation{};
44 float mEdgeCoeff{};
46 float mBuffer[2][BUFFERSIZE]{};
49 void deviceUpdate(const ALCdevice *device) override;
50 void update(const ALCcontext *context, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target) override;
51 void process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut) override;
53 DEF_NEWDEL(DistortionState)
56 void DistortionState::deviceUpdate(const ALCdevice*)
58 mLowpass.clear();
59 mBandpass.clear();
62 void DistortionState::update(const ALCcontext *context, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target)
64 const ALCdevice *device{context->mDevice.get()};
66 /* Store waveshaper edge settings. */
67 const float edge{minf(std::sin(al::MathDefs<float>::Pi()*0.5f * props->Distortion.Edge),
68 0.99f)};
69 mEdgeCoeff = 2.0f * edge / (1.0f-edge);
71 float cutoff{props->Distortion.LowpassCutoff};
72 /* Bandwidth value is constant in octaves. */
73 float bandwidth{(cutoff / 2.0f) / (cutoff * 0.67f)};
74 /* Divide normalized frequency by the amount of oversampling done during
75 * processing.
77 auto frequency = static_cast<float>(device->Frequency);
78 mLowpass.setParamsFromBandwidth(BiquadType::LowPass, cutoff/frequency/4.0f, 1.0f, bandwidth);
80 cutoff = props->Distortion.EQCenter;
81 /* Convert bandwidth in Hz to octaves. */
82 bandwidth = props->Distortion.EQBandwidth / (cutoff * 0.67f);
83 mBandpass.setParamsFromBandwidth(BiquadType::BandPass, cutoff/frequency/4.0f, 1.0f, bandwidth);
85 const auto coeffs = CalcDirectionCoeffs({0.0f, 0.0f, -1.0f}, 0.0f);
87 mOutTarget = target.Main->Buffer;
88 ComputePanGains(target.Main, coeffs.data(), slot->Params.Gain*props->Distortion.Gain, mGain);
91 void DistortionState::process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut)
93 const float fc{mEdgeCoeff};
94 for(size_t base{0u};base < samplesToDo;)
96 /* Perform 4x oversampling to avoid aliasing. Oversampling greatly
97 * improves distortion quality and allows to implement lowpass and
98 * bandpass filters using high frequencies, at which classic IIR
99 * filters became unstable.
101 size_t todo{minz(BUFFERSIZE, (samplesToDo-base) * 4)};
103 /* Fill oversample buffer using zero stuffing. Multiply the sample by
104 * the amount of oversampling to maintain the signal's power.
106 for(size_t i{0u};i < todo;i++)
107 mBuffer[0][i] = !(i&3) ? samplesIn[0][(i>>2)+base] * 4.0f : 0.0f;
109 /* First step, do lowpass filtering of original signal. Additionally
110 * perform buffer interpolation and lowpass cutoff for oversampling
111 * (which is fortunately first step of distortion). So combine three
112 * operations into the one.
114 mLowpass.process({mBuffer[0], todo}, mBuffer[1]);
116 /* Second step, do distortion using waveshaper function to emulate
117 * signal processing during tube overdriving. Three steps of
118 * waveshaping are intended to modify waveform without boost/clipping/
119 * attenuation process.
121 auto proc_sample = [fc](float smp) -> float
123 smp = (1.0f + fc) * smp/(1.0f + fc*std::abs(smp));
124 smp = (1.0f + fc) * smp/(1.0f + fc*std::abs(smp)) * -1.0f;
125 smp = (1.0f + fc) * smp/(1.0f + fc*std::abs(smp));
126 return smp;
128 std::transform(std::begin(mBuffer[1]), std::begin(mBuffer[1])+todo, std::begin(mBuffer[0]),
129 proc_sample);
131 /* Third step, do bandpass filtering of distorted signal. */
132 mBandpass.process({mBuffer[0], todo}, mBuffer[1]);
134 todo >>= 2;
135 const float *outgains{mGain};
136 for(FloatBufferLine &output : samplesOut)
138 /* Fourth step, final, do attenuation and perform decimation,
139 * storing only one sample out of four.
141 const float gain{*(outgains++)};
142 if(!(std::fabs(gain) > GAIN_SILENCE_THRESHOLD))
143 continue;
145 for(size_t i{0u};i < todo;i++)
146 output[base+i] += gain * mBuffer[1][i*4];
149 base += todo;
154 void Distortion_setParami(EffectProps*, ALenum param, int)
155 { throw effect_exception{AL_INVALID_ENUM, "Invalid distortion integer property 0x%04x", param}; }
156 void Distortion_setParamiv(EffectProps*, ALenum param, const int*)
158 throw effect_exception{AL_INVALID_ENUM, "Invalid distortion integer-vector property 0x%04x",
159 param};
161 void Distortion_setParamf(EffectProps *props, ALenum param, float val)
163 switch(param)
165 case AL_DISTORTION_EDGE:
166 if(!(val >= AL_DISTORTION_MIN_EDGE && val <= AL_DISTORTION_MAX_EDGE))
167 throw effect_exception{AL_INVALID_VALUE, "Distortion edge out of range"};
168 props->Distortion.Edge = val;
169 break;
171 case AL_DISTORTION_GAIN:
172 if(!(val >= AL_DISTORTION_MIN_GAIN && val <= AL_DISTORTION_MAX_GAIN))
173 throw effect_exception{AL_INVALID_VALUE, "Distortion gain out of range"};
174 props->Distortion.Gain = val;
175 break;
177 case AL_DISTORTION_LOWPASS_CUTOFF:
178 if(!(val >= AL_DISTORTION_MIN_LOWPASS_CUTOFF && val <= AL_DISTORTION_MAX_LOWPASS_CUTOFF))
179 throw effect_exception{AL_INVALID_VALUE, "Distortion low-pass cutoff out of range"};
180 props->Distortion.LowpassCutoff = val;
181 break;
183 case AL_DISTORTION_EQCENTER:
184 if(!(val >= AL_DISTORTION_MIN_EQCENTER && val <= AL_DISTORTION_MAX_EQCENTER))
185 throw effect_exception{AL_INVALID_VALUE, "Distortion EQ center out of range"};
186 props->Distortion.EQCenter = val;
187 break;
189 case AL_DISTORTION_EQBANDWIDTH:
190 if(!(val >= AL_DISTORTION_MIN_EQBANDWIDTH && val <= AL_DISTORTION_MAX_EQBANDWIDTH))
191 throw effect_exception{AL_INVALID_VALUE, "Distortion EQ bandwidth out of range"};
192 props->Distortion.EQBandwidth = val;
193 break;
195 default:
196 throw effect_exception{AL_INVALID_ENUM, "Invalid distortion float property 0x%04x", param};
199 void Distortion_setParamfv(EffectProps *props, ALenum param, const float *vals)
200 { Distortion_setParamf(props, param, vals[0]); }
202 void Distortion_getParami(const EffectProps*, ALenum param, int*)
203 { throw effect_exception{AL_INVALID_ENUM, "Invalid distortion integer property 0x%04x", param}; }
204 void Distortion_getParamiv(const EffectProps*, ALenum param, int*)
206 throw effect_exception{AL_INVALID_ENUM, "Invalid distortion integer-vector property 0x%04x",
207 param};
209 void Distortion_getParamf(const EffectProps *props, ALenum param, float *val)
211 switch(param)
213 case AL_DISTORTION_EDGE:
214 *val = props->Distortion.Edge;
215 break;
217 case AL_DISTORTION_GAIN:
218 *val = props->Distortion.Gain;
219 break;
221 case AL_DISTORTION_LOWPASS_CUTOFF:
222 *val = props->Distortion.LowpassCutoff;
223 break;
225 case AL_DISTORTION_EQCENTER:
226 *val = props->Distortion.EQCenter;
227 break;
229 case AL_DISTORTION_EQBANDWIDTH:
230 *val = props->Distortion.EQBandwidth;
231 break;
233 default:
234 throw effect_exception{AL_INVALID_ENUM, "Invalid distortion float property 0x%04x", param};
237 void Distortion_getParamfv(const EffectProps *props, ALenum param, float *vals)
238 { Distortion_getParamf(props, param, vals); }
240 DEFINE_ALEFFECT_VTABLE(Distortion);
243 struct DistortionStateFactory final : public EffectStateFactory {
244 EffectState *create() override { return new DistortionState{}; }
245 EffectProps getDefaultProps() const noexcept override;
246 const EffectVtable *getEffectVtable() const noexcept override { return &Distortion_vtable; }
249 EffectProps DistortionStateFactory::getDefaultProps() const noexcept
251 EffectProps props{};
252 props.Distortion.Edge = AL_DISTORTION_DEFAULT_EDGE;
253 props.Distortion.Gain = AL_DISTORTION_DEFAULT_GAIN;
254 props.Distortion.LowpassCutoff = AL_DISTORTION_DEFAULT_LOWPASS_CUTOFF;
255 props.Distortion.EQCenter = AL_DISTORTION_DEFAULT_EQCENTER;
256 props.Distortion.EQBandwidth = AL_DISTORTION_DEFAULT_EQBANDWIDTH;
257 return props;
260 } // namespace
262 EffectStateFactory *DistortionStateFactory_getFactory()
264 static DistortionStateFactory DistortionFactory{};
265 return &DistortionFactory;