1 /**
2  * OpenAL cross platform audio library
3  * Copyright (C) 2018 by Raul Herraiz.
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.
8  *
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.
13  *
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
19  */
20 
21 #include "config.h"
22 
23 #include <cmath>
24 #include <cstdlib>
25 
26 #include <algorithm>
27 
28 #include "alcmain.h"
29 #include "alcontext.h"
30 #include "core/filters/biquad.h"
31 #include "effectslot.h"
32 #include "vecmat.h"
33 
34 namespace {
35 
36 constexpr float GainScale{31621.0f};
37 constexpr float MinFreq{20.0f};
38 constexpr float MaxFreq{2500.0f};
39 constexpr float QFactor{5.0f};
40 
41 struct AutowahState final : public EffectState {
42     /* Effect parameters */
43     float mAttackRate;
44     float mReleaseRate;
45     float mResonanceGain;
46     float mPeakGain;
47     float mFreqMinNorm;
48     float mBandwidthNorm;
49     float mEnvDelay;
50 
51     /* Filter components derived from the envelope. */
52     struct {
53         float cos_w0;
54         float alpha;
55     } mEnv[BufferLineSize];
56 
57     struct {
58         /* Effect filters' history. */
59         struct {
60             float z1, z2;
61         } Filter;
62 
63         /* Effect gains for each output channel */
64         float CurrentGains[MAX_OUTPUT_CHANNELS];
65         float TargetGains[MAX_OUTPUT_CHANNELS];
66     } mChans[MaxAmbiChannels];
67 
68     /* Effects buffers */
69     alignas(16) float mBufferOut[BufferLineSize];
70 
71 
72     void deviceUpdate(const ALCdevice *device, const Buffer &buffer) override;
73     void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props,
74         const EffectTarget target) override;
75     void process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn,
76         const al::span<FloatBufferLine> samplesOut) override;
77 
78     DEF_NEWDEL(AutowahState)
79 };
80 
deviceUpdate(const ALCdevice *,const Buffer &)81 void AutowahState::deviceUpdate(const ALCdevice*, const Buffer&)
82 {
83     /* (Re-)initializing parameters and clear the buffers. */
84 
85     mAttackRate    = 1.0f;
86     mReleaseRate   = 1.0f;
87     mResonanceGain = 10.0f;
88     mPeakGain      = 4.5f;
89     mFreqMinNorm   = 4.5e-4f;
90     mBandwidthNorm = 0.05f;
91     mEnvDelay      = 0.0f;
92 
93     for(auto &e : mEnv)
94     {
95         e.cos_w0 = 0.0f;
96         e.alpha = 0.0f;
97     }
98 
99     for(auto &chan : mChans)
100     {
101         std::fill(std::begin(chan.CurrentGains), std::end(chan.CurrentGains), 0.0f);
102         chan.Filter.z1 = 0.0f;
103         chan.Filter.z2 = 0.0f;
104     }
105 }
106 
update(const ALCcontext * context,const EffectSlot * slot,const EffectProps * props,const EffectTarget target)107 void AutowahState::update(const ALCcontext *context, const EffectSlot *slot,
108     const EffectProps *props, const EffectTarget target)
109 {
110     const ALCdevice *device{context->mDevice.get()};
111     const auto frequency = static_cast<float>(device->Frequency);
112 
113     const float ReleaseTime{clampf(props->Autowah.ReleaseTime, 0.001f, 1.0f)};
114 
115     mAttackRate    = std::exp(-1.0f / (props->Autowah.AttackTime*frequency));
116     mReleaseRate   = std::exp(-1.0f / (ReleaseTime*frequency));
117     /* 0-20dB Resonance Peak gain */
118     mResonanceGain = std::sqrt(std::log10(props->Autowah.Resonance)*10.0f / 3.0f);
119     mPeakGain      = 1.0f - std::log10(props->Autowah.PeakGain / GainScale);
120     mFreqMinNorm   = MinFreq / frequency;
121     mBandwidthNorm = (MaxFreq-MinFreq) / frequency;
122 
123     mOutTarget = target.Main->Buffer;
124     auto set_gains = [slot,target](auto &chan, al::span<const float,MaxAmbiChannels> coeffs)
125     { ComputePanGains(target.Main, coeffs.data(), slot->Gain, chan.TargetGains); };
126     SetAmbiPanIdentity(std::begin(mChans), slot->Wet.Buffer.size(), set_gains);
127 }
128 
process(const size_t samplesToDo,const al::span<const FloatBufferLine> samplesIn,const al::span<FloatBufferLine> samplesOut)129 void AutowahState::process(const size_t samplesToDo,
130     const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut)
131 {
132     const float attack_rate{mAttackRate};
133     const float release_rate{mReleaseRate};
134     const float res_gain{mResonanceGain};
135     const float peak_gain{mPeakGain};
136     const float freq_min{mFreqMinNorm};
137     const float bandwidth{mBandwidthNorm};
138 
139     float env_delay{mEnvDelay};
140     for(size_t i{0u};i < samplesToDo;i++)
141     {
142         float w0, sample, a;
143 
144         /* Envelope follower described on the book: Audio Effects, Theory,
145          * Implementation and Application.
146          */
147         sample = peak_gain * std::fabs(samplesIn[0][i]);
148         a = (sample > env_delay) ? attack_rate : release_rate;
149         env_delay = lerp(sample, env_delay, a);
150 
151         /* Calculate the cos and alpha components for this sample's filter. */
152         w0 = minf((bandwidth*env_delay + freq_min), 0.46f) * al::MathDefs<float>::Tau();
153         mEnv[i].cos_w0 = std::cos(w0);
154         mEnv[i].alpha = std::sin(w0)/(2.0f * QFactor);
155     }
156     mEnvDelay = env_delay;
157 
158     auto chandata = std::addressof(mChans[0]);
159     for(const auto &insamples : samplesIn)
160     {
161         /* This effectively inlines BiquadFilter_setParams for a peaking
162          * filter and BiquadFilter_processC. The alpha and cosine components
163          * for the filter coefficients were previously calculated with the
164          * envelope. Because the filter changes for each sample, the
165          * coefficients are transient and don't need to be held.
166          */
167         float z1{chandata->Filter.z1};
168         float z2{chandata->Filter.z2};
169 
170         for(size_t i{0u};i < samplesToDo;i++)
171         {
172             const float alpha{mEnv[i].alpha};
173             const float cos_w0{mEnv[i].cos_w0};
174             float input, output;
175             float a[3], b[3];
176 
177             b[0] =  1.0f + alpha*res_gain;
178             b[1] = -2.0f * cos_w0;
179             b[2] =  1.0f - alpha*res_gain;
180             a[0] =  1.0f + alpha/res_gain;
181             a[1] = -2.0f * cos_w0;
182             a[2] =  1.0f - alpha/res_gain;
183 
184             input = insamples[i];
185             output = input*(b[0]/a[0]) + z1;
186             z1 = input*(b[1]/a[0]) - output*(a[1]/a[0]) + z2;
187             z2 = input*(b[2]/a[0]) - output*(a[2]/a[0]);
188             mBufferOut[i] = output;
189         }
190         chandata->Filter.z1 = z1;
191         chandata->Filter.z2 = z2;
192 
193         /* Now, mix the processed sound data to the output. */
194         MixSamples({mBufferOut, samplesToDo}, samplesOut, chandata->CurrentGains,
195             chandata->TargetGains, samplesToDo, 0);
196         ++chandata;
197     }
198 }
199 
200 
201 struct AutowahStateFactory final : public EffectStateFactory {
create__anona9be4b1f0111::AutowahStateFactory202     al::intrusive_ptr<EffectState> create() override
203     { return al::intrusive_ptr<EffectState>{new AutowahState{}}; }
204 };
205 
206 } // namespace
207 
AutowahStateFactory_getFactory()208 EffectStateFactory *AutowahStateFactory_getFactory()
209 {
210     static AutowahStateFactory AutowahFactory{};
211     return &AutowahFactory;
212 }
213