X-Git-Url: https://git.sesse.net/?p=pitch;a=blobdiff_plain;f=pitch.cpp;h=91afda5fb0618d7f0e611223f1089980f1a123ee;hp=13efaf8a5660f9b955c7d9d29cf15e9e9ba03c0c;hb=1a261eee89e163b53a334eeb57850f16d476c2df;hpb=2921b00f987d93f2ccc8c918da196158c2f90906 diff --git a/pitch.cpp b/pitch.cpp index 13efaf8..91afda5 100644 --- a/pitch.cpp +++ b/pitch.cpp @@ -46,7 +46,7 @@ int main() in = reinterpret_cast (fftw_malloc(sizeof(double) * FFT_LENGTH / PAD_FACTOR)); in_windowed = reinterpret_cast (fftw_malloc(sizeof(double) * FFT_LENGTH)); out = reinterpret_cast *> (fftw_malloc(sizeof(std::complex) * (FFT_LENGTH / 2 + 1))); - bins = reinterpret_cast (fftw_malloc(sizeof(double) * FFT_LENGTH / 2 + 1)); + bins = reinterpret_cast (fftw_malloc(sizeof(double) * (FFT_LENGTH / 2 + 1))); memset(in, 0, sizeof(double) * FFT_LENGTH / PAD_FACTOR); @@ -60,7 +60,8 @@ int main() fftw_execute(p); find_peak_magnitudes(out, bins, FFT_LENGTH); std::pair peak = find_peak(bins, FFT_LENGTH); - peak = adjust_for_overtones(peak, bins, FFT_LENGTH); + if (peak.first > 0.0) + peak = adjust_for_overtones(peak, bins, FFT_LENGTH); if (peak.first < 50.0 || peak.second - log10(FFT_LENGTH) < 0.0) { #if TUNING == WELL_TEMPERED_GUITAR @@ -224,9 +225,9 @@ std::pair find_peak(double *in, unsigned num_samples) best_bin /= i; // consider sliding one bin up or down - if (best_bin > 0 && in[best_bin - 1] > in[best_bin] && in[best_bin - 1] > in[best_bin - 2]) { + if (best_bin > 1 && in[best_bin - 1] > in[best_bin] && in[best_bin - 1] > in[best_bin - 2]) { --best_bin; - } else if (best_bin < num_samples / 2 && in[best_bin + 1] > in[best_bin] && in[best_bin + 1] > in[best_bin + 2]) { + } else if (best_bin < num_samples / 2 - 1 && in[best_bin + 1] > in[best_bin] && in[best_bin + 1] > in[best_bin + 2]) { ++best_bin; } @@ -234,6 +235,9 @@ std::pair find_peak(double *in, unsigned num_samples) } } + if (best_bin == 0 || best_bin == num_samples / 2) { + return std::make_pair(-1.0, 0.0); + } std::pair peak = interpolate_peak(in[best_bin - 1], in[best_bin], @@ -248,6 +252,8 @@ std::pair find_peak(double *in, unsigned num_samples) std::pair adjust_for_overtones(std::pair base, double *in, unsigned num_samples) { double mu = base.first, var = 1.0 / (base.second * base.second); + + //printf("Base at %.2f (amp=%5.2fdB)\n", base.first, base.second); for (unsigned i = 2; i < 10; ++i) { unsigned middle = unsigned(floor(freq_to_bin(base.first, num_samples) * i + 0.5));