pshifter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. #include "config.h"
  21. #ifdef HAVE_SSE_INTRINSICS
  22. #include <emmintrin.h>
  23. #endif
  24. #include <cmath>
  25. #include <cstdlib>
  26. #include <array>
  27. #include <complex>
  28. #include <algorithm>
  29. #include "al/auxeffectslot.h"
  30. #include "alcmain.h"
  31. #include "alcomplex.h"
  32. #include "alcontext.h"
  33. #include "alnumeric.h"
  34. #include "alu.h"
  35. namespace {
  36. using complex_d = std::complex<double>;
  37. #define STFT_SIZE 1024
  38. #define STFT_HALF_SIZE (STFT_SIZE>>1)
  39. #define OVERSAMP (1<<2)
  40. #define STFT_STEP (STFT_SIZE / OVERSAMP)
  41. #define FIFO_LATENCY (STFT_STEP * (OVERSAMP-1))
  42. /* Define a Hann window, used to filter the STFT input and output. */
  43. /* Making this constexpr seems to require C++14. */
  44. std::array<ALdouble,STFT_SIZE> InitHannWindow()
  45. {
  46. std::array<ALdouble,STFT_SIZE> ret;
  47. /* Create lookup table of the Hann window for the desired size, i.e. HIL_SIZE */
  48. for(size_t i{0};i < STFT_SIZE>>1;i++)
  49. {
  50. constexpr double scale{al::MathDefs<double>::Pi() / double{STFT_SIZE-1}};
  51. const double val{std::sin(static_cast<double>(i) * scale)};
  52. ret[i] = ret[STFT_SIZE-1-i] = val * val;
  53. }
  54. return ret;
  55. }
  56. alignas(16) const std::array<ALdouble,STFT_SIZE> HannWindow = InitHannWindow();
  57. struct ALphasor {
  58. ALdouble Amplitude;
  59. ALdouble Phase;
  60. };
  61. struct ALfrequencyDomain {
  62. ALdouble Amplitude;
  63. ALdouble Frequency;
  64. };
  65. /* Converts complex to ALphasor */
  66. inline ALphasor rect2polar(const complex_d &number)
  67. {
  68. ALphasor polar;
  69. polar.Amplitude = std::abs(number);
  70. polar.Phase = std::arg(number);
  71. return polar;
  72. }
  73. /* Converts ALphasor to complex */
  74. inline complex_d polar2rect(const ALphasor &number)
  75. { return std::polar<double>(number.Amplitude, number.Phase); }
  76. struct PshifterState final : public EffectState {
  77. /* Effect parameters */
  78. size_t mCount;
  79. ALuint mPitchShiftI;
  80. ALfloat mPitchShift;
  81. ALfloat mFreqPerBin;
  82. /* Effects buffers */
  83. ALfloat mInFIFO[STFT_SIZE];
  84. ALfloat mOutFIFO[STFT_STEP];
  85. ALdouble mLastPhase[STFT_HALF_SIZE+1];
  86. ALdouble mSumPhase[STFT_HALF_SIZE+1];
  87. ALdouble mOutputAccum[STFT_SIZE];
  88. complex_d mFFTbuffer[STFT_SIZE];
  89. ALfrequencyDomain mAnalysis_buffer[STFT_HALF_SIZE+1];
  90. ALfrequencyDomain mSyntesis_buffer[STFT_HALF_SIZE+1];
  91. alignas(16) ALfloat mBufferOut[BUFFERSIZE];
  92. /* Effect gains for each output channel */
  93. ALfloat mCurrentGains[MAX_OUTPUT_CHANNELS];
  94. ALfloat mTargetGains[MAX_OUTPUT_CHANNELS];
  95. ALboolean deviceUpdate(const ALCdevice *device) override;
  96. void update(const ALCcontext *context, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target) override;
  97. void process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut) override;
  98. DEF_NEWDEL(PshifterState)
  99. };
  100. ALboolean PshifterState::deviceUpdate(const ALCdevice *device)
  101. {
  102. /* (Re-)initializing parameters and clear the buffers. */
  103. mCount = FIFO_LATENCY;
  104. mPitchShiftI = FRACTIONONE;
  105. mPitchShift = 1.0f;
  106. mFreqPerBin = static_cast<float>(device->Frequency) / float{STFT_SIZE};
  107. std::fill(std::begin(mInFIFO), std::end(mInFIFO), 0.0f);
  108. std::fill(std::begin(mOutFIFO), std::end(mOutFIFO), 0.0f);
  109. std::fill(std::begin(mLastPhase), std::end(mLastPhase), 0.0);
  110. std::fill(std::begin(mSumPhase), std::end(mSumPhase), 0.0);
  111. std::fill(std::begin(mOutputAccum), std::end(mOutputAccum), 0.0);
  112. std::fill(std::begin(mFFTbuffer), std::end(mFFTbuffer), complex_d{});
  113. std::fill(std::begin(mAnalysis_buffer), std::end(mAnalysis_buffer), ALfrequencyDomain{});
  114. std::fill(std::begin(mSyntesis_buffer), std::end(mSyntesis_buffer), ALfrequencyDomain{});
  115. std::fill(std::begin(mCurrentGains), std::end(mCurrentGains), 0.0f);
  116. std::fill(std::begin(mTargetGains), std::end(mTargetGains), 0.0f);
  117. return AL_TRUE;
  118. }
  119. void PshifterState::update(const ALCcontext*, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target)
  120. {
  121. const float pitch{std::pow(2.0f,
  122. static_cast<ALfloat>(props->Pshifter.CoarseTune*100 + props->Pshifter.FineTune) / 1200.0f
  123. )};
  124. mPitchShiftI = fastf2u(pitch*FRACTIONONE);
  125. mPitchShift = static_cast<float>(mPitchShiftI) * (1.0f/FRACTIONONE);
  126. ALfloat coeffs[MAX_AMBI_CHANNELS];
  127. CalcDirectionCoeffs({0.0f, 0.0f, -1.0f}, 0.0f, coeffs);
  128. mOutTarget = target.Main->Buffer;
  129. ComputePanGains(target.Main, coeffs, slot->Params.Gain, mTargetGains);
  130. }
  131. void PshifterState::process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut)
  132. {
  133. /* Pitch shifter engine based on the work of Stephan Bernsee.
  134. * http://blogs.zynaptiq.com/bernsee/pitch-shifting-using-the-ft/
  135. */
  136. static constexpr ALdouble expected{al::MathDefs<double>::Tau() / OVERSAMP};
  137. const ALdouble freq_per_bin{mFreqPerBin};
  138. ALfloat *RESTRICT bufferOut{mBufferOut};
  139. size_t count{mCount};
  140. for(size_t i{0u};i < samplesToDo;)
  141. {
  142. do {
  143. /* Fill FIFO buffer with samples data */
  144. mInFIFO[count] = samplesIn[0][i];
  145. bufferOut[i] = mOutFIFO[count - FIFO_LATENCY];
  146. count++;
  147. } while(++i < samplesToDo && count < STFT_SIZE);
  148. /* Check whether FIFO buffer is filled */
  149. if(count < STFT_SIZE) break;
  150. count = FIFO_LATENCY;
  151. /* Real signal windowing and store in FFTbuffer */
  152. for(ALuint k{0u};k < STFT_SIZE;k++)
  153. {
  154. mFFTbuffer[k].real(mInFIFO[k] * HannWindow[k]);
  155. mFFTbuffer[k].imag(0.0);
  156. }
  157. /* ANALYSIS */
  158. /* Apply FFT to FFTbuffer data */
  159. complex_fft(mFFTbuffer, -1.0);
  160. /* Analyze the obtained data. Since the real FFT is symmetric, only
  161. * STFT_HALF_SIZE+1 samples are needed.
  162. */
  163. for(ALuint k{0u};k < STFT_HALF_SIZE+1;k++)
  164. {
  165. /* Compute amplitude and phase */
  166. ALphasor component{rect2polar(mFFTbuffer[k])};
  167. /* Compute phase difference and subtract expected phase difference */
  168. double tmp{(component.Phase - mLastPhase[k]) - k*expected};
  169. /* Map delta phase into +/- Pi interval */
  170. int qpd{double2int(tmp / al::MathDefs<double>::Pi())};
  171. tmp -= al::MathDefs<double>::Pi() * (qpd + (qpd%2));
  172. /* Get deviation from bin frequency from the +/- Pi interval */
  173. tmp /= expected;
  174. /* Compute the k-th partials' true frequency, twice the amplitude
  175. * for maintain the gain (because half of bins are used) and store
  176. * amplitude and true frequency in analysis buffer.
  177. */
  178. mAnalysis_buffer[k].Amplitude = 2.0 * component.Amplitude;
  179. mAnalysis_buffer[k].Frequency = (k + tmp) * freq_per_bin;
  180. /* Store actual phase[k] for the calculations in the next frame*/
  181. mLastPhase[k] = component.Phase;
  182. }
  183. /* PROCESSING */
  184. /* pitch shifting */
  185. for(ALuint k{0u};k < STFT_HALF_SIZE+1;k++)
  186. {
  187. mSyntesis_buffer[k].Amplitude = 0.0;
  188. mSyntesis_buffer[k].Frequency = 0.0;
  189. }
  190. for(size_t k{0u};k < STFT_HALF_SIZE+1;k++)
  191. {
  192. size_t j{(k*mPitchShiftI) >> FRACTIONBITS};
  193. if(j >= STFT_HALF_SIZE+1) break;
  194. mSyntesis_buffer[j].Amplitude += mAnalysis_buffer[k].Amplitude;
  195. mSyntesis_buffer[j].Frequency = mAnalysis_buffer[k].Frequency * mPitchShift;
  196. }
  197. /* SYNTHESIS */
  198. /* Synthesis the processing data */
  199. for(ALuint k{0u};k < STFT_HALF_SIZE+1;k++)
  200. {
  201. ALphasor component;
  202. ALdouble tmp;
  203. /* Compute bin deviation from scaled freq */
  204. tmp = mSyntesis_buffer[k].Frequency/freq_per_bin - k;
  205. /* Calculate actual delta phase and accumulate it to get bin phase */
  206. mSumPhase[k] += (k + tmp) * expected;
  207. component.Amplitude = mSyntesis_buffer[k].Amplitude;
  208. component.Phase = mSumPhase[k];
  209. /* Compute phasor component to cartesian complex number and storage it into FFTbuffer*/
  210. mFFTbuffer[k] = polar2rect(component);
  211. }
  212. /* zero negative frequencies for recontruct a real signal */
  213. for(ALuint k{STFT_HALF_SIZE+1};k < STFT_SIZE;k++)
  214. mFFTbuffer[k] = complex_d{};
  215. /* Apply iFFT to buffer data */
  216. complex_fft(mFFTbuffer, 1.0);
  217. /* Windowing and add to output */
  218. for(ALuint k{0u};k < STFT_SIZE;k++)
  219. mOutputAccum[k] += HannWindow[k] * mFFTbuffer[k].real() /
  220. (0.5 * STFT_HALF_SIZE * OVERSAMP);
  221. /* Shift accumulator, input & output FIFO */
  222. size_t j, k;
  223. for(k = 0;k < STFT_STEP;k++) mOutFIFO[k] = static_cast<ALfloat>(mOutputAccum[k]);
  224. for(j = 0;k < STFT_SIZE;k++,j++) mOutputAccum[j] = mOutputAccum[k];
  225. for(;j < STFT_SIZE;j++) mOutputAccum[j] = 0.0;
  226. for(k = 0;k < FIFO_LATENCY;k++)
  227. mInFIFO[k] = mInFIFO[k+STFT_STEP];
  228. }
  229. mCount = count;
  230. /* Now, mix the processed sound data to the output. */
  231. MixSamples({bufferOut, samplesToDo}, samplesOut, mCurrentGains, mTargetGains,
  232. maxz(samplesToDo, 512), 0);
  233. }
  234. void Pshifter_setParamf(EffectProps*, ALCcontext *context, ALenum param, ALfloat)
  235. { context->setError(AL_INVALID_ENUM, "Invalid pitch shifter float property 0x%04x", param); }
  236. void Pshifter_setParamfv(EffectProps*, ALCcontext *context, ALenum param, const ALfloat*)
  237. { context->setError(AL_INVALID_ENUM, "Invalid pitch shifter float-vector property 0x%04x", param); }
  238. void Pshifter_setParami(EffectProps *props, ALCcontext *context, ALenum param, ALint val)
  239. {
  240. switch(param)
  241. {
  242. case AL_PITCH_SHIFTER_COARSE_TUNE:
  243. if(!(val >= AL_PITCH_SHIFTER_MIN_COARSE_TUNE && val <= AL_PITCH_SHIFTER_MAX_COARSE_TUNE))
  244. SETERR_RETURN(context, AL_INVALID_VALUE,,"Pitch shifter coarse tune out of range");
  245. props->Pshifter.CoarseTune = val;
  246. break;
  247. case AL_PITCH_SHIFTER_FINE_TUNE:
  248. if(!(val >= AL_PITCH_SHIFTER_MIN_FINE_TUNE && val <= AL_PITCH_SHIFTER_MAX_FINE_TUNE))
  249. SETERR_RETURN(context, AL_INVALID_VALUE,,"Pitch shifter fine tune out of range");
  250. props->Pshifter.FineTune = val;
  251. break;
  252. default:
  253. context->setError(AL_INVALID_ENUM, "Invalid pitch shifter integer property 0x%04x",
  254. param);
  255. }
  256. }
  257. void Pshifter_setParamiv(EffectProps *props, ALCcontext *context, ALenum param, const ALint *vals)
  258. { Pshifter_setParami(props, context, param, vals[0]); }
  259. void Pshifter_getParami(const EffectProps *props, ALCcontext *context, ALenum param, ALint *val)
  260. {
  261. switch(param)
  262. {
  263. case AL_PITCH_SHIFTER_COARSE_TUNE:
  264. *val = props->Pshifter.CoarseTune;
  265. break;
  266. case AL_PITCH_SHIFTER_FINE_TUNE:
  267. *val = props->Pshifter.FineTune;
  268. break;
  269. default:
  270. context->setError(AL_INVALID_ENUM, "Invalid pitch shifter integer property 0x%04x",
  271. param);
  272. }
  273. }
  274. void Pshifter_getParamiv(const EffectProps *props, ALCcontext *context, ALenum param, ALint *vals)
  275. { Pshifter_getParami(props, context, param, vals); }
  276. void Pshifter_getParamf(const EffectProps*, ALCcontext *context, ALenum param, ALfloat*)
  277. { context->setError(AL_INVALID_ENUM, "Invalid pitch shifter float property 0x%04x", param); }
  278. void Pshifter_getParamfv(const EffectProps*, ALCcontext *context, ALenum param, ALfloat*)
  279. { context->setError(AL_INVALID_ENUM, "Invalid pitch shifter float vector-property 0x%04x", param); }
  280. DEFINE_ALEFFECT_VTABLE(Pshifter);
  281. struct PshifterStateFactory final : public EffectStateFactory {
  282. EffectState *create() override;
  283. EffectProps getDefaultProps() const noexcept override;
  284. const EffectVtable *getEffectVtable() const noexcept override { return &Pshifter_vtable; }
  285. };
  286. EffectState *PshifterStateFactory::create()
  287. { return new PshifterState{}; }
  288. EffectProps PshifterStateFactory::getDefaultProps() const noexcept
  289. {
  290. EffectProps props{};
  291. props.Pshifter.CoarseTune = AL_PITCH_SHIFTER_DEFAULT_COARSE_TUNE;
  292. props.Pshifter.FineTune = AL_PITCH_SHIFTER_DEFAULT_FINE_TUNE;
  293. return props;
  294. }
  295. } // namespace
  296. EffectStateFactory *PshifterStateFactory_getFactory()
  297. {
  298. static PshifterStateFactory PshifterFactory{};
  299. return &PshifterFactory;
  300. }