pshifter.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 <variant>
  27. #include "alc/effects/base.h"
  28. #include "alnumbers.h"
  29. #include "alnumeric.h"
  30. #include "alspan.h"
  31. #include "core/ambidefs.h"
  32. #include "core/bufferline.h"
  33. #include "core/device.h"
  34. #include "core/effects/base.h"
  35. #include "core/effectslot.h"
  36. #include "core/mixer.h"
  37. #include "core/mixer/defs.h"
  38. #include "intrusive_ptr.h"
  39. #include "pffft.h"
  40. struct BufferStorage;
  41. struct ContextBase;
  42. namespace {
  43. using uint = unsigned int;
  44. using complex_f = std::complex<float>;
  45. constexpr size_t StftSize{1024};
  46. constexpr size_t StftHalfSize{StftSize >> 1};
  47. constexpr size_t OversampleFactor{8};
  48. static_assert(StftSize%OversampleFactor == 0, "Factor must be a clean divisor of the size");
  49. constexpr size_t StftStep{StftSize / OversampleFactor};
  50. /* Define a Hann window, used to filter the STFT input and output. */
  51. struct Windower {
  52. alignas(16) std::array<float,StftSize> mData{};
  53. Windower()
  54. {
  55. /* Create lookup table of the Hann window for the desired size. */
  56. for(size_t i{0};i < StftHalfSize;i++)
  57. {
  58. constexpr double scale{al::numbers::pi / double{StftSize}};
  59. const double val{std::sin((static_cast<double>(i)+0.5) * scale)};
  60. mData[i] = mData[StftSize-1-i] = static_cast<float>(val * val);
  61. }
  62. }
  63. };
  64. const Windower gWindow{};
  65. struct FrequencyBin {
  66. float Magnitude;
  67. float FreqBin;
  68. };
  69. struct PshifterState final : public EffectState {
  70. /* Effect parameters */
  71. size_t mCount{};
  72. size_t mPos{};
  73. uint mPitchShiftI{};
  74. float mPitchShift{};
  75. /* Effects buffers */
  76. std::array<float,StftSize> mFIFO{};
  77. std::array<float,StftHalfSize+1> mLastPhase{};
  78. std::array<float,StftHalfSize+1> mSumPhase{};
  79. std::array<float,StftSize> mOutputAccum{};
  80. PFFFTSetup mFft;
  81. alignas(16) std::array<float,StftSize> mFftBuffer{};
  82. alignas(16) std::array<float,StftSize> mFftWorkBuffer{};
  83. std::array<FrequencyBin,StftHalfSize+1> mAnalysisBuffer{};
  84. std::array<FrequencyBin,StftHalfSize+1> mSynthesisBuffer{};
  85. alignas(16) FloatBufferLine mBufferOut{};
  86. /* Effect gains for each output channel */
  87. std::array<float,MaxAmbiChannels> mCurrentGains{};
  88. std::array<float,MaxAmbiChannels> mTargetGains{};
  89. void deviceUpdate(const DeviceBase *device, const BufferStorage *buffer) override;
  90. void update(const ContextBase *context, const EffectSlot *slot, const EffectProps *props,
  91. const EffectTarget target) override;
  92. void process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn,
  93. const al::span<FloatBufferLine> samplesOut) override;
  94. };
  95. void PshifterState::deviceUpdate(const DeviceBase*, const BufferStorage*)
  96. {
  97. /* (Re-)initializing parameters and clear the buffers. */
  98. mCount = 0;
  99. mPos = StftSize - StftStep;
  100. mPitchShiftI = MixerFracOne;
  101. mPitchShift = 1.0f;
  102. mFIFO.fill(0.0f);
  103. mLastPhase.fill(0.0f);
  104. mSumPhase.fill(0.0f);
  105. mOutputAccum.fill(0.0f);
  106. mFftBuffer.fill(0.0f);
  107. mAnalysisBuffer.fill(FrequencyBin{});
  108. mSynthesisBuffer.fill(FrequencyBin{});
  109. mCurrentGains.fill(0.0f);
  110. mTargetGains.fill(0.0f);
  111. if(!mFft)
  112. mFft = PFFFTSetup{StftSize, PFFFT_REAL};
  113. }
  114. void PshifterState::update(const ContextBase*, const EffectSlot *slot,
  115. const EffectProps *props_, const EffectTarget target)
  116. {
  117. auto &props = std::get<PshifterProps>(*props_);
  118. const int tune{props.CoarseTune*100 + props.FineTune};
  119. const float pitch{std::pow(2.0f, static_cast<float>(tune) / 1200.0f)};
  120. mPitchShiftI = std::clamp(fastf2u(pitch*MixerFracOne), uint{MixerFracHalf},
  121. uint{MixerFracOne}*2u);
  122. mPitchShift = static_cast<float>(mPitchShiftI) * float{1.0f/MixerFracOne};
  123. static constexpr auto coeffs = CalcDirectionCoeffs(std::array{0.0f, 0.0f, -1.0f});
  124. mOutTarget = target.Main->Buffer;
  125. ComputePanGains(target.Main, coeffs, slot->Gain, mTargetGains);
  126. }
  127. void PshifterState::process(const size_t samplesToDo,
  128. const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut)
  129. {
  130. /* Pitch shifter engine based on the work of Stephan Bernsee.
  131. * http://blogs.zynaptiq.com/bernsee/pitch-shifting-using-the-ft/
  132. */
  133. /* Cycle offset per update expected of each frequency bin (bin 0 is none,
  134. * bin 1 is x1, bin 2 is x2, etc).
  135. */
  136. constexpr float expected_cycles{al::numbers::pi_v<float>*2.0f / OversampleFactor};
  137. for(size_t base{0u};base < samplesToDo;)
  138. {
  139. const size_t todo{std::min(StftStep-mCount, samplesToDo-base)};
  140. /* Retrieve the output samples from the FIFO and fill in the new input
  141. * samples.
  142. */
  143. auto fifo_iter = mFIFO.begin()+mPos + mCount;
  144. std::copy_n(fifo_iter, todo, mBufferOut.begin()+base);
  145. std::copy_n(samplesIn[0].begin()+base, todo, fifo_iter);
  146. mCount += todo;
  147. base += todo;
  148. /* Check whether FIFO buffer is filled with new samples. */
  149. if(mCount < StftStep) break;
  150. mCount = 0;
  151. mPos = (mPos+StftStep) & (mFIFO.size()-1);
  152. /* Time-domain signal windowing, store in FftBuffer, and apply a
  153. * forward FFT to get the frequency-domain signal.
  154. */
  155. for(size_t src{mPos}, k{0u};src < StftSize;++src,++k)
  156. mFftBuffer[k] = mFIFO[src] * gWindow.mData[k];
  157. for(size_t src{0u}, k{StftSize-mPos};src < mPos;++src,++k)
  158. mFftBuffer[k] = mFIFO[src] * gWindow.mData[k];
  159. mFft.transform_ordered(mFftBuffer.data(), mFftBuffer.data(), mFftWorkBuffer.data(),
  160. PFFFT_FORWARD);
  161. /* Analyze the obtained data. Since the real FFT is symmetric, only
  162. * StftHalfSize+1 samples are needed.
  163. */
  164. for(size_t k{0u};k < StftHalfSize+1;++k)
  165. {
  166. const auto cplx = (k == 0) ? complex_f{mFftBuffer[0]} :
  167. (k == StftHalfSize) ? complex_f{mFftBuffer[1]} :
  168. complex_f{mFftBuffer[k*2], mFftBuffer[k*2 + 1]};
  169. const float magnitude{std::abs(cplx)};
  170. const float phase{std::arg(cplx)};
  171. /* Compute the phase difference from the last update and subtract
  172. * the expected phase difference for this bin.
  173. *
  174. * When oversampling, the expected per-update offset increments by
  175. * 1/OversampleFactor for every frequency bin. So, the offset wraps
  176. * every 'OversampleFactor' bin.
  177. */
  178. const auto bin_offset = static_cast<float>(k % OversampleFactor);
  179. float tmp{(phase - mLastPhase[k]) - bin_offset*expected_cycles};
  180. /* Store the actual phase for the next update. */
  181. mLastPhase[k] = phase;
  182. /* Normalize from pi, and wrap the delta between -1 and +1. */
  183. tmp *= al::numbers::inv_pi_v<float>;
  184. int qpd{float2int(tmp)};
  185. tmp -= static_cast<float>(qpd + (qpd%2));
  186. /* Get deviation from bin frequency (-0.5 to +0.5), and account for
  187. * oversampling.
  188. */
  189. tmp *= 0.5f * OversampleFactor;
  190. /* Compute the k-th partials' frequency bin target and store the
  191. * magnitude and frequency bin in the analysis buffer. We don't
  192. * need the "true frequency" since it's a linear relationship with
  193. * the bin.
  194. */
  195. mAnalysisBuffer[k].Magnitude = magnitude;
  196. mAnalysisBuffer[k].FreqBin = static_cast<float>(k) + tmp;
  197. }
  198. /* Shift the frequency bins according to the pitch adjustment,
  199. * accumulating the magnitudes of overlapping frequency bins.
  200. */
  201. std::fill(mSynthesisBuffer.begin(), mSynthesisBuffer.end(), FrequencyBin{});
  202. static constexpr size_t bin_limit{((StftHalfSize+1)<<MixerFracBits) - MixerFracHalf - 1};
  203. const size_t bin_count{std::min(StftHalfSize+1, bin_limit/mPitchShiftI + 1)};
  204. for(size_t k{0u};k < bin_count;k++)
  205. {
  206. const size_t j{(k*mPitchShiftI + MixerFracHalf) >> MixerFracBits};
  207. /* If more than two bins end up together, use the target frequency
  208. * bin for the one with the dominant magnitude. There might be a
  209. * better way to handle this, but it's better than last-index-wins.
  210. */
  211. if(mAnalysisBuffer[k].Magnitude > mSynthesisBuffer[j].Magnitude)
  212. mSynthesisBuffer[j].FreqBin = mAnalysisBuffer[k].FreqBin * mPitchShift;
  213. mSynthesisBuffer[j].Magnitude += mAnalysisBuffer[k].Magnitude;
  214. }
  215. /* Reconstruct the frequency-domain signal from the adjusted frequency
  216. * bins.
  217. */
  218. for(size_t k{0u};k < StftHalfSize+1;k++)
  219. {
  220. /* Calculate the actual delta phase for this bin's target frequency
  221. * bin, and accumulate it to get the actual bin phase.
  222. */
  223. float tmp{mSumPhase[k] + mSynthesisBuffer[k].FreqBin*expected_cycles};
  224. /* Wrap between -pi and +pi for the sum. If mSumPhase is left to
  225. * grow indefinitely, it will lose precision and produce less exact
  226. * phase over time.
  227. */
  228. tmp *= al::numbers::inv_pi_v<float>;
  229. int qpd{float2int(tmp)};
  230. tmp -= static_cast<float>(qpd + (qpd%2));
  231. mSumPhase[k] = tmp * al::numbers::pi_v<float>;
  232. const complex_f cplx{std::polar(mSynthesisBuffer[k].Magnitude, mSumPhase[k])};
  233. if(k == 0)
  234. mFftBuffer[0] = cplx.real();
  235. else if(k == StftHalfSize)
  236. mFftBuffer[1] = cplx.real();
  237. else
  238. {
  239. mFftBuffer[k*2 + 0] = cplx.real();
  240. mFftBuffer[k*2 + 1] = cplx.imag();
  241. }
  242. }
  243. /* Apply an inverse FFT to get the time-domain signal, and accumulate
  244. * for the output with windowing.
  245. */
  246. mFft.transform_ordered(mFftBuffer.data(), mFftBuffer.data(), mFftWorkBuffer.data(),
  247. PFFFT_BACKWARD);
  248. static constexpr float scale{3.0f / OversampleFactor / StftSize};
  249. for(size_t dst{mPos}, k{0u};dst < StftSize;++dst,++k)
  250. mOutputAccum[dst] += gWindow.mData[k]*mFftBuffer[k] * scale;
  251. for(size_t dst{0u}, k{StftSize-mPos};dst < mPos;++dst,++k)
  252. mOutputAccum[dst] += gWindow.mData[k]*mFftBuffer[k] * scale;
  253. /* Copy out the accumulated result, then clear for the next iteration. */
  254. std::copy_n(mOutputAccum.begin() + mPos, StftStep, mFIFO.begin() + mPos);
  255. std::fill_n(mOutputAccum.begin() + mPos, StftStep, 0.0f);
  256. }
  257. /* Now, mix the processed sound data to the output. */
  258. MixSamples(al::span{mBufferOut}.first(samplesToDo), samplesOut, mCurrentGains, mTargetGains,
  259. std::max(samplesToDo, 512_uz), 0);
  260. }
  261. struct PshifterStateFactory final : public EffectStateFactory {
  262. al::intrusive_ptr<EffectState> create() override
  263. { return al::intrusive_ptr<EffectState>{new PshifterState{}}; }
  264. };
  265. } // namespace
  266. EffectStateFactory *PshifterStateFactory_getFactory()
  267. {
  268. static PshifterStateFactory PshifterFactory{};
  269. return &PshifterFactory;
  270. }