| 1 |
#ifndef AUTOCORRELATION_HH |
| 2 |
#define AUTOCORRELATION_HH |
| 3 |
|
| 4 |
#include "FFTReal.hh" |
| 5 |
|
| 6 |
#include <algorithm> |
| 7 |
#include <array> |
| 8 |
#include <cassert> |
| 9 |
#include <span> |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
template<unsigned SIGNAL_LEN_L2, bool NORMALIZE = true> |
| 35 |
void autocorrelation(std::span<const float> signal, std::span<float> output) |
| 36 |
{ |
| 37 |
static_assert(SIGNAL_LEN_L2 >= 2); |
| 38 |
static_assert(SIGNAL_LEN_L2 <= 15); |
| 39 |
static constexpr unsigned SIGNAL_LEN = 1 << SIGNAL_LEN_L2; |
| 40 |
static constexpr unsigned FFT_LEN = 2 * SIGNAL_LEN; |
| 41 |
|
| 42 |
const auto N = signal.size(); |
| 43 |
assert(N <= SIGNAL_LEN); |
| 44 |
assert(N == output.size()); |
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
std::array<float, FFT_LEN> paddedSignal; |
| 50 |
std::ranges::copy(signal, paddedSignal.begin()); |
| 51 |
std::ranges::fill(std::span(paddedSignal).subspan(N), 0.0f); |
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
std::array<float, FFT_LEN> spectrum; |
| 56 |
std::array<float, FFT_LEN> fftWork; |
| 57 |
FFTReal<SIGNAL_LEN_L2 + 1>::execute(paddedSignal, spectrum, fftWork); |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
spectrum[0] = spectrum[0] * spectrum[0]; |
| 64 |
|
| 65 |
spectrum[SIGNAL_LEN] = spectrum[SIGNAL_LEN] * spectrum[SIGNAL_LEN]; |
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
for (unsigned i = 1; i < SIGNAL_LEN; ++i) { |
| 70 |
const float re = spectrum[i]; |
| 71 |
const float im = spectrum[SIGNAL_LEN + i]; |
| 72 |
spectrum[i] = re * re + im * im; |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
for (unsigned i = 1; i < SIGNAL_LEN; ++i) { |
| 81 |
spectrum[FFT_LEN - i] = spectrum[i]; |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
auto& autocorr = paddedSignal; |
| 96 |
FFTReal<SIGNAL_LEN_L2 + 1>::execute(spectrum, autocorr, fftWork); |
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
if constexpr (NORMALIZE) { |
| 103 |
const float norm = 1.0f / FFT_LEN; |
| 104 |
for (unsigned i = 0; i < N; ++i) { |
| 105 |
autocorr[i] *= norm; |
| 106 |
} |
| 107 |
} |
| 108 |
|
| 109 |
|
| 110 |
std::ranges::copy_n(autocorr.begin(), N, output.begin()); |
| 111 |
} |
| 112 |
|
| 113 |
#endif |