Avoid class templates for the POPCNT64/CTZ64 macros
[openal-soft.git] / alc / effects / vmorpher.cpp
blob0ffe23e65c41e9f4c2cec430a05a789fbad33264
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 2019 by Anis A. Hireche
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 <cmath>
24 #include <cstdlib>
25 #include <algorithm>
26 #include <functional>
28 #include "al/auxeffectslot.h"
29 #include "alcmain.h"
30 #include "alcontext.h"
31 #include "alu.h"
33 namespace {
35 #define MAX_UPDATE_SAMPLES 256
36 #define NUM_FORMANTS 4
37 #define NUM_FILTERS 2
38 #define Q_FACTOR 5.0f
40 #define VOWEL_A_INDEX 0
41 #define VOWEL_B_INDEX 1
43 #define WAVEFORM_FRACBITS 24
44 #define WAVEFORM_FRACONE (1<<WAVEFORM_FRACBITS)
45 #define WAVEFORM_FRACMASK (WAVEFORM_FRACONE-1)
47 inline float Sin(ALuint index)
49 constexpr float scale{al::MathDefs<float>::Tau() / WAVEFORM_FRACONE};
50 return std::sin(static_cast<float>(index) * scale)*0.5f + 0.5f;
53 inline float Saw(ALuint index)
54 { return static_cast<float>(index) / float{WAVEFORM_FRACONE}; }
56 inline float Triangle(ALuint index)
57 { return std::fabs(static_cast<float>(index)*(2.0f/WAVEFORM_FRACONE) - 1.0f); }
59 inline float Half(ALuint) { return 0.5f; }
61 template<float (&func)(ALuint)>
62 void Oscillate(float *RESTRICT dst, ALuint index, const ALuint step, size_t todo)
64 for(size_t i{0u};i < todo;i++)
66 index += step;
67 index &= WAVEFORM_FRACMASK;
68 dst[i] = func(index);
72 struct FormantFilter
74 float mCoeff{0.0f};
75 float mGain{1.0f};
76 float mS1{0.0f};
77 float mS2{0.0f};
79 FormantFilter() = default;
80 FormantFilter(float f0norm, float gain)
81 : mCoeff{std::tan(al::MathDefs<float>::Pi() * f0norm)}, mGain{gain}
82 { }
84 inline void process(const float *samplesIn, float *samplesOut, const size_t numInput)
86 /* A state variable filter from a topology-preserving transform.
87 * Based on a talk given by Ivan Cohen: https://www.youtube.com/watch?v=esjHXGPyrhg
89 const float g{mCoeff};
90 const float gain{mGain};
91 const float h{1.0f / (1.0f + (g/Q_FACTOR) + (g*g))};
92 float s1{mS1};
93 float s2{mS2};
95 for(size_t i{0u};i < numInput;i++)
97 const float H{(samplesIn[i] - (1.0f/Q_FACTOR + g)*s1 - s2)*h};
98 const float B{g*H + s1};
99 const float L{g*B + s2};
101 s1 = g*H + B;
102 s2 = g*B + L;
104 // Apply peak and accumulate samples.
105 samplesOut[i] += B * gain;
107 mS1 = s1;
108 mS2 = s2;
111 inline void clear()
113 mS1 = 0.0f;
114 mS2 = 0.0f;
119 struct VmorpherState final : public EffectState {
120 struct {
121 /* Effect parameters */
122 FormantFilter Formants[NUM_FILTERS][NUM_FORMANTS];
124 /* Effect gains for each channel */
125 float CurrentGains[MAX_OUTPUT_CHANNELS]{};
126 float TargetGains[MAX_OUTPUT_CHANNELS]{};
127 } mChans[MAX_AMBI_CHANNELS];
129 void (*mGetSamples)(float*RESTRICT, ALuint, const ALuint, size_t){};
131 ALuint mIndex{0};
132 ALuint mStep{1};
134 /* Effects buffers */
135 alignas(16) float mSampleBufferA[MAX_UPDATE_SAMPLES]{};
136 alignas(16) float mSampleBufferB[MAX_UPDATE_SAMPLES]{};
137 alignas(16) float mLfo[MAX_UPDATE_SAMPLES]{};
139 void deviceUpdate(const ALCdevice *device) override;
140 void update(const ALCcontext *context, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target) override;
141 void process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut) override;
143 static std::array<FormantFilter,4> getFiltersByPhoneme(ALenum phoneme, float frequency, float pitch);
145 DEF_NEWDEL(VmorpherState)
148 std::array<FormantFilter,4> VmorpherState::getFiltersByPhoneme(ALenum phoneme, float frequency, float pitch)
150 /* Using soprano formant set of values to
151 * better match mid-range frequency space.
153 * See: https://www.classes.cs.uchicago.edu/archive/1999/spring/CS295/Computing_Resources/Csound/CsManual3.48b1.HTML/Appendices/table3.html
155 switch(phoneme)
157 case AL_VOCAL_MORPHER_PHONEME_A:
158 return {{
159 {( 800 * pitch) / frequency, 1.000000f}, /* std::pow(10.0f, 0 / 20.0f); */
160 {(1150 * pitch) / frequency, 0.501187f}, /* std::pow(10.0f, -6 / 20.0f); */
161 {(2900 * pitch) / frequency, 0.025118f}, /* std::pow(10.0f, -32 / 20.0f); */
162 {(3900 * pitch) / frequency, 0.100000f} /* std::pow(10.0f, -20 / 20.0f); */
164 case AL_VOCAL_MORPHER_PHONEME_E:
165 return {{
166 {( 350 * pitch) / frequency, 1.000000f}, /* std::pow(10.0f, 0 / 20.0f); */
167 {(2000 * pitch) / frequency, 0.100000f}, /* std::pow(10.0f, -20 / 20.0f); */
168 {(2800 * pitch) / frequency, 0.177827f}, /* std::pow(10.0f, -15 / 20.0f); */
169 {(3600 * pitch) / frequency, 0.009999f} /* std::pow(10.0f, -40 / 20.0f); */
171 case AL_VOCAL_MORPHER_PHONEME_I:
172 return {{
173 {( 270 * pitch) / frequency, 1.000000f}, /* std::pow(10.0f, 0 / 20.0f); */
174 {(2140 * pitch) / frequency, 0.251188f}, /* std::pow(10.0f, -12 / 20.0f); */
175 {(2950 * pitch) / frequency, 0.050118f}, /* std::pow(10.0f, -26 / 20.0f); */
176 {(3900 * pitch) / frequency, 0.050118f} /* std::pow(10.0f, -26 / 20.0f); */
178 case AL_VOCAL_MORPHER_PHONEME_O:
179 return {{
180 {( 450 * pitch) / frequency, 1.000000f}, /* std::pow(10.0f, 0 / 20.0f); */
181 {( 800 * pitch) / frequency, 0.281838f}, /* std::pow(10.0f, -11 / 20.0f); */
182 {(2830 * pitch) / frequency, 0.079432f}, /* std::pow(10.0f, -22 / 20.0f); */
183 {(3800 * pitch) / frequency, 0.079432f} /* std::pow(10.0f, -22 / 20.0f); */
185 case AL_VOCAL_MORPHER_PHONEME_U:
186 return {{
187 {( 325 * pitch) / frequency, 1.000000f}, /* std::pow(10.0f, 0 / 20.0f); */
188 {( 700 * pitch) / frequency, 0.158489f}, /* std::pow(10.0f, -16 / 20.0f); */
189 {(2700 * pitch) / frequency, 0.017782f}, /* std::pow(10.0f, -35 / 20.0f); */
190 {(3800 * pitch) / frequency, 0.009999f} /* std::pow(10.0f, -40 / 20.0f); */
193 return {};
197 void VmorpherState::deviceUpdate(const ALCdevice* /*device*/)
199 for(auto &e : mChans)
201 std::for_each(std::begin(e.Formants[VOWEL_A_INDEX]), std::end(e.Formants[VOWEL_A_INDEX]),
202 std::mem_fn(&FormantFilter::clear));
203 std::for_each(std::begin(e.Formants[VOWEL_B_INDEX]), std::end(e.Formants[VOWEL_B_INDEX]),
204 std::mem_fn(&FormantFilter::clear));
205 std::fill(std::begin(e.CurrentGains), std::end(e.CurrentGains), 0.0f);
209 void VmorpherState::update(const ALCcontext *context, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target)
211 const ALCdevice *device{context->mDevice.get()};
212 const float frequency{static_cast<float>(device->Frequency)};
213 const float step{props->Vmorpher.Rate / frequency};
214 mStep = fastf2u(clampf(step*WAVEFORM_FRACONE, 0.0f, float{WAVEFORM_FRACONE-1}));
216 if(mStep == 0)
217 mGetSamples = Oscillate<Half>;
218 else if(props->Vmorpher.Waveform == AL_VOCAL_MORPHER_WAVEFORM_SINUSOID)
219 mGetSamples = Oscillate<Sin>;
220 else if(props->Vmorpher.Waveform == AL_VOCAL_MORPHER_WAVEFORM_SAWTOOTH)
221 mGetSamples = Oscillate<Saw>;
222 else /*if(props->Vmorpher.Waveform == AL_VOCAL_MORPHER_WAVEFORM_TRIANGLE)*/
223 mGetSamples = Oscillate<Triangle>;
225 const float pitchA{std::pow(2.0f,
226 static_cast<float>(props->Vmorpher.PhonemeACoarseTuning) / 12.0f)};
227 const float pitchB{std::pow(2.0f,
228 static_cast<float>(props->Vmorpher.PhonemeBCoarseTuning) / 12.0f)};
230 auto vowelA = getFiltersByPhoneme(props->Vmorpher.PhonemeA, frequency, pitchA);
231 auto vowelB = getFiltersByPhoneme(props->Vmorpher.PhonemeB, frequency, pitchB);
233 /* Copy the filter coefficients to the input channels. */
234 for(size_t i{0u};i < slot->Wet.Buffer.size();++i)
236 std::copy(vowelA.begin(), vowelA.end(), std::begin(mChans[i].Formants[VOWEL_A_INDEX]));
237 std::copy(vowelB.begin(), vowelB.end(), std::begin(mChans[i].Formants[VOWEL_B_INDEX]));
240 mOutTarget = target.Main->Buffer;
241 auto set_gains = [slot,target](auto &chan, al::span<const float,MAX_AMBI_CHANNELS> coeffs)
242 { ComputePanGains(target.Main, coeffs.data(), slot->Params.Gain, chan.TargetGains); };
243 SetAmbiPanIdentity(std::begin(mChans), slot->Wet.Buffer.size(), set_gains);
246 void VmorpherState::process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut)
248 /* Following the EFX specification for a conformant implementation which describes
249 * the effect as a pair of 4-band formant filters blended together using an LFO.
251 for(size_t base{0u};base < samplesToDo;)
253 const size_t td{minz(MAX_UPDATE_SAMPLES, samplesToDo-base)};
255 mGetSamples(mLfo, mIndex, mStep, td);
256 mIndex += static_cast<ALuint>(mStep * td);
257 mIndex &= WAVEFORM_FRACMASK;
259 auto chandata = std::addressof(mChans[0]);
260 for(const auto &input : samplesIn)
262 auto& vowelA = chandata->Formants[VOWEL_A_INDEX];
263 auto& vowelB = chandata->Formants[VOWEL_B_INDEX];
265 /* Process first vowel. */
266 std::fill_n(std::begin(mSampleBufferA), td, 0.0f);
267 vowelA[0].process(&input[base], mSampleBufferA, td);
268 vowelA[1].process(&input[base], mSampleBufferA, td);
269 vowelA[2].process(&input[base], mSampleBufferA, td);
270 vowelA[3].process(&input[base], mSampleBufferA, td);
272 /* Process second vowel. */
273 std::fill_n(std::begin(mSampleBufferB), td, 0.0f);
274 vowelB[0].process(&input[base], mSampleBufferB, td);
275 vowelB[1].process(&input[base], mSampleBufferB, td);
276 vowelB[2].process(&input[base], mSampleBufferB, td);
277 vowelB[3].process(&input[base], mSampleBufferB, td);
279 alignas(16) float blended[MAX_UPDATE_SAMPLES];
280 for(size_t i{0u};i < td;i++)
281 blended[i] = lerp(mSampleBufferA[i], mSampleBufferB[i], mLfo[i]);
283 /* Now, mix the processed sound data to the output. */
284 MixSamples({blended, td}, samplesOut, chandata->CurrentGains, chandata->TargetGains,
285 samplesToDo-base, base);
286 ++chandata;
289 base += td;
294 void Vmorpher_setParami(EffectProps *props, ALenum param, int val)
296 switch(param)
298 case AL_VOCAL_MORPHER_WAVEFORM:
299 if(!(val >= AL_VOCAL_MORPHER_MIN_WAVEFORM && val <= AL_VOCAL_MORPHER_MAX_WAVEFORM))
300 throw effect_exception{AL_INVALID_VALUE, "Vocal morpher waveform out of range"};
301 props->Vmorpher.Waveform = val;
302 break;
304 case AL_VOCAL_MORPHER_PHONEMEA:
305 if(!(val >= AL_VOCAL_MORPHER_MIN_PHONEMEA && val <= AL_VOCAL_MORPHER_MAX_PHONEMEA))
306 throw effect_exception{AL_INVALID_VALUE, "Vocal morpher phoneme-a out of range"};
307 props->Vmorpher.PhonemeA = val;
308 break;
310 case AL_VOCAL_MORPHER_PHONEMEB:
311 if(!(val >= AL_VOCAL_MORPHER_MIN_PHONEMEB && val <= AL_VOCAL_MORPHER_MAX_PHONEMEB))
312 throw effect_exception{AL_INVALID_VALUE, "Vocal morpher phoneme-b out of range"};
313 props->Vmorpher.PhonemeB = val;
314 break;
316 case AL_VOCAL_MORPHER_PHONEMEA_COARSE_TUNING:
317 if(!(val >= AL_VOCAL_MORPHER_MIN_PHONEMEA_COARSE_TUNING && val <= AL_VOCAL_MORPHER_MAX_PHONEMEA_COARSE_TUNING))
318 throw effect_exception{AL_INVALID_VALUE, "Vocal morpher phoneme-a coarse tuning out of range"};
319 props->Vmorpher.PhonemeACoarseTuning = val;
320 break;
322 case AL_VOCAL_MORPHER_PHONEMEB_COARSE_TUNING:
323 if(!(val >= AL_VOCAL_MORPHER_MIN_PHONEMEB_COARSE_TUNING && val <= AL_VOCAL_MORPHER_MAX_PHONEMEB_COARSE_TUNING))
324 throw effect_exception{AL_INVALID_VALUE, "Vocal morpher phoneme-b coarse tuning out of range"};
325 props->Vmorpher.PhonemeBCoarseTuning = val;
326 break;
328 default:
329 throw effect_exception{AL_INVALID_ENUM, "Invalid vocal morpher integer property 0x%04x",
330 param};
333 void Vmorpher_setParamiv(EffectProps*, ALenum param, const int*)
335 throw effect_exception{AL_INVALID_ENUM, "Invalid vocal morpher integer-vector property 0x%04x",
336 param};
338 void Vmorpher_setParamf(EffectProps *props, ALenum param, float val)
340 switch(param)
342 case AL_VOCAL_MORPHER_RATE:
343 if(!(val >= AL_VOCAL_MORPHER_MIN_RATE && val <= AL_VOCAL_MORPHER_MAX_RATE))
344 throw effect_exception{AL_INVALID_VALUE, "Vocal morpher rate out of range"};
345 props->Vmorpher.Rate = val;
346 break;
348 default:
349 throw effect_exception{AL_INVALID_ENUM, "Invalid vocal morpher float property 0x%04x",
350 param};
353 void Vmorpher_setParamfv(EffectProps *props, ALenum param, const float *vals)
354 { Vmorpher_setParamf(props, param, vals[0]); }
356 void Vmorpher_getParami(const EffectProps *props, ALenum param, int* val)
358 switch(param)
360 case AL_VOCAL_MORPHER_PHONEMEA:
361 *val = props->Vmorpher.PhonemeA;
362 break;
364 case AL_VOCAL_MORPHER_PHONEMEB:
365 *val = props->Vmorpher.PhonemeB;
366 break;
368 case AL_VOCAL_MORPHER_PHONEMEA_COARSE_TUNING:
369 *val = props->Vmorpher.PhonemeACoarseTuning;
370 break;
372 case AL_VOCAL_MORPHER_PHONEMEB_COARSE_TUNING:
373 *val = props->Vmorpher.PhonemeBCoarseTuning;
374 break;
376 case AL_VOCAL_MORPHER_WAVEFORM:
377 *val = props->Vmorpher.Waveform;
378 break;
380 default:
381 throw effect_exception{AL_INVALID_ENUM, "Invalid vocal morpher integer property 0x%04x",
382 param};
385 void Vmorpher_getParamiv(const EffectProps*, ALenum param, int*)
387 throw effect_exception{AL_INVALID_ENUM, "Invalid vocal morpher integer-vector property 0x%04x",
388 param};
390 void Vmorpher_getParamf(const EffectProps *props, ALenum param, float *val)
392 switch(param)
394 case AL_VOCAL_MORPHER_RATE:
395 *val = props->Vmorpher.Rate;
396 break;
398 default:
399 throw effect_exception{AL_INVALID_ENUM, "Invalid vocal morpher float property 0x%04x",
400 param};
403 void Vmorpher_getParamfv(const EffectProps *props, ALenum param, float *vals)
404 { Vmorpher_getParamf(props, param, vals); }
406 DEFINE_ALEFFECT_VTABLE(Vmorpher);
409 struct VmorpherStateFactory final : public EffectStateFactory {
410 EffectState *create() override { return new VmorpherState{}; }
411 EffectProps getDefaultProps() const noexcept override;
412 const EffectVtable *getEffectVtable() const noexcept override { return &Vmorpher_vtable; }
415 EffectProps VmorpherStateFactory::getDefaultProps() const noexcept
417 EffectProps props{};
418 props.Vmorpher.Rate = AL_VOCAL_MORPHER_DEFAULT_RATE;
419 props.Vmorpher.PhonemeA = AL_VOCAL_MORPHER_DEFAULT_PHONEMEA;
420 props.Vmorpher.PhonemeB = AL_VOCAL_MORPHER_DEFAULT_PHONEMEB;
421 props.Vmorpher.PhonemeACoarseTuning = AL_VOCAL_MORPHER_DEFAULT_PHONEMEA_COARSE_TUNING;
422 props.Vmorpher.PhonemeBCoarseTuning = AL_VOCAL_MORPHER_DEFAULT_PHONEMEB_COARSE_TUNING;
423 props.Vmorpher.Waveform = AL_VOCAL_MORPHER_DEFAULT_WAVEFORM;
424 return props;
427 } // namespace
429 EffectStateFactory *VmorpherStateFactory_getFactory()
431 static VmorpherStateFactory VmorpherFactory{};
432 return &VmorpherFactory;