FFT.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. * Copyright (c) 2021, Cesar Torres <shortanemoia@protonmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Complex.h>
  8. #include <AK/Math.h>
  9. #include <AK/Span.h>
  10. namespace DSP {
  11. constexpr void fft(Span<Complex<float>> sample_data, bool invert = false)
  12. {
  13. int n = sample_data.size();
  14. for (int i = 1, j = 0; i < n; i++) {
  15. int bit = n >> 1;
  16. for (; j & bit; bit >>= 1)
  17. j ^= bit;
  18. j ^= bit;
  19. if (i < j)
  20. swap(sample_data[i], sample_data[j]);
  21. }
  22. for (int len = 2; len <= n; len <<= 1) {
  23. float ang = 2 * AK::Pi<float> / static_cast<float>(len * (invert ? -1 : 1));
  24. Complex<float> wlen = Complex<float>::from_polar(1.f, ang);
  25. for (int i = 0; i < n; i += len) {
  26. Complex<float> w = { 1., 0. };
  27. for (int j = 0; j < len / 2; j++) {
  28. Complex<float> u = sample_data[i + j];
  29. Complex<float> v = sample_data[i + j + len / 2] * w;
  30. sample_data[i + j] = u + v;
  31. sample_data[i + j + len / 2] = u - v;
  32. w *= wlen;
  33. }
  34. }
  35. }
  36. if (invert) {
  37. for (int i = 0; i < n; i++)
  38. sample_data[i] /= n;
  39. }
  40. }
  41. }