🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

274 lines
10 KiB

  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. #include <algorithm>
  22. #include <array>
  23. #include <cmath>
  24. #include <complex>
  25. #include <cstdlib>
  26. #include <iterator>
  27. #include "alc/effects/base.h"
  28. #include "alcomplex.h"
  29. #include "almalloc.h"
  30. #include "alnumbers.h"
  31. #include "alnumeric.h"
  32. #include "alspan.h"
  33. #include "core/bufferline.h"
  34. #include "core/devformat.h"
  35. #include "core/device.h"
  36. #include "core/effectslot.h"
  37. #include "core/mixer.h"
  38. #include "core/mixer/defs.h"
  39. #include "intrusive_ptr.h"
  40. struct ContextBase;
  41. namespace {
  42. using uint = unsigned int;
  43. using complex_d = std::complex<double>;
  44. #define STFT_SIZE 1024
  45. #define STFT_HALF_SIZE (STFT_SIZE>>1)
  46. #define OVERSAMP (1<<2)
  47. #define STFT_STEP (STFT_SIZE / OVERSAMP)
  48. #define FIFO_LATENCY (STFT_STEP * (OVERSAMP-1))
  49. /* Define a Hann window, used to filter the STFT input and output. */
  50. std::array<double,STFT_SIZE> InitHannWindow()
  51. {
  52. std::array<double,STFT_SIZE> ret;
  53. /* Create lookup table of the Hann window for the desired size, i.e. STFT_SIZE */
  54. for(size_t i{0};i < STFT_SIZE>>1;i++)
  55. {
  56. constexpr double scale{al::numbers::pi / double{STFT_SIZE}};
  57. const double val{std::sin(static_cast<double>(i+1) * scale)};
  58. ret[i] = ret[STFT_SIZE-1-i] = val * val;
  59. }
  60. return ret;
  61. }
  62. alignas(16) const std::array<double,STFT_SIZE> HannWindow = InitHannWindow();
  63. struct FrequencyBin {
  64. double Amplitude;
  65. double FreqBin;
  66. };
  67. struct PshifterState final : public EffectState {
  68. /* Effect parameters */
  69. size_t mCount;
  70. size_t mPos;
  71. uint mPitchShiftI;
  72. double mPitchShift;
  73. /* Effects buffers */
  74. std::array<double,STFT_SIZE> mFIFO;
  75. std::array<double,STFT_HALF_SIZE+1> mLastPhase;
  76. std::array<double,STFT_HALF_SIZE+1> mSumPhase;
  77. std::array<double,STFT_SIZE> mOutputAccum;
  78. std::array<complex_d,STFT_SIZE> mFftBuffer;
  79. std::array<FrequencyBin,STFT_HALF_SIZE+1> mAnalysisBuffer;
  80. std::array<FrequencyBin,STFT_HALF_SIZE+1> mSynthesisBuffer;
  81. alignas(16) FloatBufferLine mBufferOut;
  82. /* Effect gains for each output channel */
  83. float mCurrentGains[MAX_OUTPUT_CHANNELS];
  84. float mTargetGains[MAX_OUTPUT_CHANNELS];
  85. void deviceUpdate(const DeviceBase *device, const Buffer &buffer) override;
  86. void update(const ContextBase *context, const EffectSlot *slot, const EffectProps *props,
  87. const EffectTarget target) override;
  88. void process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn,
  89. const al::span<FloatBufferLine> samplesOut) override;
  90. DEF_NEWDEL(PshifterState)
  91. };
  92. void PshifterState::deviceUpdate(const DeviceBase*, const Buffer&)
  93. {
  94. /* (Re-)initializing parameters and clear the buffers. */
  95. mCount = 0;
  96. mPos = FIFO_LATENCY;
  97. mPitchShiftI = MixerFracOne;
  98. mPitchShift = 1.0;
  99. std::fill(mFIFO.begin(), mFIFO.end(), 0.0);
  100. std::fill(mLastPhase.begin(), mLastPhase.end(), 0.0);
  101. std::fill(mSumPhase.begin(), mSumPhase.end(), 0.0);
  102. std::fill(mOutputAccum.begin(), mOutputAccum.end(), 0.0);
  103. std::fill(mFftBuffer.begin(), mFftBuffer.end(), complex_d{});
  104. std::fill(mAnalysisBuffer.begin(), mAnalysisBuffer.end(), FrequencyBin{});
  105. std::fill(mSynthesisBuffer.begin(), mSynthesisBuffer.end(), FrequencyBin{});
  106. std::fill(std::begin(mCurrentGains), std::end(mCurrentGains), 0.0f);
  107. std::fill(std::begin(mTargetGains), std::end(mTargetGains), 0.0f);
  108. }
  109. void PshifterState::update(const ContextBase*, const EffectSlot *slot,
  110. const EffectProps *props, const EffectTarget target)
  111. {
  112. const int tune{props->Pshifter.CoarseTune*100 + props->Pshifter.FineTune};
  113. const float pitch{std::pow(2.0f, static_cast<float>(tune) / 1200.0f)};
  114. mPitchShiftI = fastf2u(pitch*MixerFracOne);
  115. mPitchShift = mPitchShiftI * double{1.0/MixerFracOne};
  116. const auto coeffs = CalcDirectionCoeffs({0.0f, 0.0f, -1.0f}, 0.0f);
  117. mOutTarget = target.Main->Buffer;
  118. ComputePanGains(target.Main, coeffs.data(), slot->Gain, mTargetGains);
  119. }
  120. void PshifterState::process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut)
  121. {
  122. /* Pitch shifter engine based on the work of Stephan Bernsee.
  123. * http://blogs.zynaptiq.com/bernsee/pitch-shifting-using-the-ft/
  124. */
  125. /* Cycle offset per update expected of each frequency bin (bin 0 is none,
  126. * bin 1 is x1, bin 2 is x2, etc).
  127. */
  128. constexpr double expected_cycles{al::numbers::pi*2.0 / OVERSAMP};
  129. for(size_t base{0u};base < samplesToDo;)
  130. {
  131. const size_t todo{minz(STFT_STEP-mCount, samplesToDo-base)};
  132. /* Retrieve the output samples from the FIFO and fill in the new input
  133. * samples.
  134. */
  135. auto fifo_iter = mFIFO.begin()+mPos + mCount;
  136. std::transform(fifo_iter, fifo_iter+todo, mBufferOut.begin()+base,
  137. [](double d) noexcept -> float { return static_cast<float>(d); });
  138. std::copy_n(samplesIn[0].begin()+base, todo, fifo_iter);
  139. mCount += todo;
  140. base += todo;
  141. /* Check whether FIFO buffer is filled with new samples. */
  142. if(mCount < STFT_STEP) break;
  143. mCount = 0;
  144. mPos = (mPos+STFT_STEP) & (mFIFO.size()-1);
  145. /* Time-domain signal windowing, store in FftBuffer, and apply a
  146. * forward FFT to get the frequency-domain signal.
  147. */
  148. for(size_t src{mPos}, k{0u};src < STFT_SIZE;++src,++k)
  149. mFftBuffer[k] = mFIFO[src] * HannWindow[k];
  150. for(size_t src{0u}, k{STFT_SIZE-mPos};src < mPos;++src,++k)
  151. mFftBuffer[k] = mFIFO[src] * HannWindow[k];
  152. forward_fft(mFftBuffer);
  153. /* Analyze the obtained data. Since the real FFT is symmetric, only
  154. * STFT_HALF_SIZE+1 samples are needed.
  155. */
  156. for(size_t k{0u};k < STFT_HALF_SIZE+1;k++)
  157. {
  158. const double amplitude{std::abs(mFftBuffer[k])};
  159. const double phase{std::arg(mFftBuffer[k])};
  160. /* Compute phase difference and subtract expected phase difference */
  161. double tmp{(phase - mLastPhase[k]) - static_cast<double>(k)*expected_cycles};
  162. /* Map delta phase into +/- Pi interval */
  163. int qpd{double2int(tmp / al::numbers::pi)};
  164. tmp -= al::numbers::pi * (qpd + (qpd%2));
  165. /* Get deviation from bin frequency from the +/- Pi interval */
  166. tmp /= expected_cycles;
  167. /* Compute the k-th partials' true frequency and store the
  168. * amplitude and frequency bin in the analysis buffer.
  169. */
  170. mAnalysisBuffer[k].Amplitude = amplitude;
  171. mAnalysisBuffer[k].FreqBin = static_cast<double>(k) + tmp;
  172. /* Store the actual phase[k] for the next frame. */
  173. mLastPhase[k] = phase;
  174. }
  175. /* Shift the frequency bins according to the pitch adjustment,
  176. * accumulating the amplitudes of overlapping frequency bins.
  177. */
  178. std::fill(mSynthesisBuffer.begin(), mSynthesisBuffer.end(), FrequencyBin{});
  179. const size_t bin_count{minz(STFT_HALF_SIZE+1,
  180. (((STFT_HALF_SIZE+1)<<MixerFracBits) - (MixerFracOne>>1) - 1)/mPitchShiftI + 1)};
  181. for(size_t k{0u};k < bin_count;k++)
  182. {
  183. const size_t j{(k*mPitchShiftI + (MixerFracOne>>1)) >> MixerFracBits};
  184. mSynthesisBuffer[j].Amplitude += mAnalysisBuffer[k].Amplitude;
  185. mSynthesisBuffer[j].FreqBin = mAnalysisBuffer[k].FreqBin * mPitchShift;
  186. }
  187. /* Reconstruct the frequency-domain signal from the adjusted frequency
  188. * bins.
  189. */
  190. for(size_t k{0u};k < STFT_HALF_SIZE+1;k++)
  191. {
  192. /* Calculate actual delta phase and accumulate it to get bin phase */
  193. mSumPhase[k] += mSynthesisBuffer[k].FreqBin * expected_cycles;
  194. mFftBuffer[k] = std::polar(mSynthesisBuffer[k].Amplitude, mSumPhase[k]);
  195. }
  196. for(size_t k{STFT_HALF_SIZE+1};k < STFT_SIZE;++k)
  197. mFftBuffer[k] = std::conj(mFftBuffer[STFT_SIZE-k]);
  198. /* Apply an inverse FFT to get the time-domain siganl, and accumulate
  199. * for the output with windowing.
  200. */
  201. inverse_fft(mFftBuffer);
  202. for(size_t dst{mPos}, k{0u};dst < STFT_SIZE;++dst,++k)
  203. mOutputAccum[dst] += HannWindow[k]*mFftBuffer[k].real() * (4.0/OVERSAMP/STFT_SIZE);
  204. for(size_t dst{0u}, k{STFT_SIZE-mPos};dst < mPos;++dst,++k)
  205. mOutputAccum[dst] += HannWindow[k]*mFftBuffer[k].real() * (4.0/OVERSAMP/STFT_SIZE);
  206. /* Copy out the accumulated result, then clear for the next iteration. */
  207. std::copy_n(mOutputAccum.begin() + mPos, STFT_STEP, mFIFO.begin() + mPos);
  208. std::fill_n(mOutputAccum.begin() + mPos, STFT_STEP, 0.0);
  209. }
  210. /* Now, mix the processed sound data to the output. */
  211. MixSamples({mBufferOut.data(), samplesToDo}, samplesOut, mCurrentGains, mTargetGains,
  212. maxz(samplesToDo, 512), 0);
  213. }
  214. struct PshifterStateFactory final : public EffectStateFactory {
  215. al::intrusive_ptr<EffectState> create() override
  216. { return al::intrusive_ptr<EffectState>{new PshifterState{}}; }
  217. };
  218. } // namespace
  219. EffectStateFactory *PshifterStateFactory_getFactory()
  220. {
  221. static PshifterStateFactory PshifterFactory{};
  222. return &PshifterFactory;
  223. }