FFT.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright (c) 2021, Cesar Torres <shortanemoia@protonmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "FFT.h"
  7. #include <AK/Complex.h>
  8. #include <AK/Math.h>
  9. namespace LibDSP {
  10. // This function uses the input vector as output too. therefore, if you wish to
  11. // leave it intact, pass a copy to this function
  12. //
  13. // The sampling frequency must be more than twice the frequency to resolve.
  14. // The sample window must be at least large enough to reflect the periodicity
  15. // of the smallest frequency to be resolved.
  16. //
  17. // For example, to resolve a 10 KHz and a 2 Hz sine waves we need at least
  18. // a samplerate of 20 KHz and a window of 0.5 seconds
  19. //
  20. // If invert is true, this function computes the inverse discrete fourier transform.
  21. //
  22. // The data vector must be a power of 2
  23. // Adapted from https://cp-algorithms.com/algebra/fft.html
  24. void fft(Vector<Complex<double>>& sample_data, bool invert)
  25. {
  26. int n = sample_data.size();
  27. auto data = sample_data.data();
  28. for (int i = 1, j = 0; i < n; i++) {
  29. int bit = n >> 1;
  30. for (; j & bit; bit >>= 1)
  31. j ^= bit;
  32. j ^= bit;
  33. if (i < j)
  34. swap(data[i], data[j]);
  35. }
  36. for (int len = 2; len <= n; len <<= 1) {
  37. double ang = 2 * AK::Pi<double> / len * (invert ? -1 : 1);
  38. Complex<double> wlen(AK::cos(ang), AK::sin(ang));
  39. for (int i = 0; i < n; i += len) {
  40. Complex<double> w = { 1., 0. };
  41. for (int j = 0; j < len / 2; j++) {
  42. Complex<double> u = data[i + j], v = data[i + j + len / 2] * w;
  43. data[i + j] = u + v;
  44. data[i + j + len / 2] = u - v;
  45. w *= wlen;
  46. }
  47. }
  48. }
  49. if (invert) {
  50. for (int i = 0; i < n; i++)
  51. data[i] /= n;
  52. }
  53. }
  54. }