2
0

alcomplex.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "config.h"
  2. #include "alcomplex.h"
  3. #include <algorithm>
  4. #include <cmath>
  5. #include <cstddef>
  6. #include <utility>
  7. #include "math_defs.h"
  8. void complex_fft(const al::span<std::complex<double>> buffer, const double sign)
  9. {
  10. const size_t fftsize{buffer.size()};
  11. /* Bit-reversal permutation applied to a sequence of FFTSize items */
  12. for(size_t i{1u};i < fftsize-1;i++)
  13. {
  14. size_t j{0u};
  15. for(size_t mask{1u};mask < fftsize;mask <<= 1)
  16. {
  17. if((i&mask) != 0)
  18. j++;
  19. j <<= 1;
  20. }
  21. j >>= 1;
  22. if(i < j)
  23. std::swap(buffer[i], buffer[j]);
  24. }
  25. /* Iterative form of Danielson–Lanczos lemma */
  26. size_t step{2u};
  27. for(size_t i{1u};i < fftsize;i<<=1, step<<=1)
  28. {
  29. const size_t step2{step >> 1};
  30. double arg{al::MathDefs<double>::Pi() / static_cast<double>(step2)};
  31. std::complex<double> w{std::cos(arg), std::sin(arg)*sign};
  32. std::complex<double> u{1.0, 0.0};
  33. for(size_t j{0};j < step2;j++)
  34. {
  35. for(size_t k{j};k < fftsize;k+=step)
  36. {
  37. std::complex<double> temp{buffer[k+step2] * u};
  38. buffer[k+step2] = buffer[k] - temp;
  39. buffer[k] += temp;
  40. }
  41. u *= w;
  42. }
  43. }
  44. }
  45. void complex_hilbert(const al::span<std::complex<double>> buffer)
  46. {
  47. complex_fft(buffer, 1.0);
  48. const double inverse_size = 1.0/static_cast<double>(buffer.size());
  49. auto bufiter = buffer.begin();
  50. const auto halfiter = bufiter + (buffer.size()>>1);
  51. *bufiter *= inverse_size; ++bufiter;
  52. bufiter = std::transform(bufiter, halfiter, bufiter,
  53. [inverse_size](const std::complex<double> &c) -> std::complex<double>
  54. { return c * (2.0*inverse_size); });
  55. *bufiter *= inverse_size; ++bufiter;
  56. std::fill(bufiter, buffer.end(), std::complex<double>{});
  57. complex_fft(buffer, -1.0);
  58. }