]> git.sesse.net Git - pitch/blobdiff - pitch.cpp
Fix a possible segfault.
[pitch] / pitch.cpp
index 1f639d6a22340d0b34d43e74288ad4646c54668a..c8246dcf5f28436277ad51c6cff8bf94f145bc64 100644 (file)
--- a/pitch.cpp
+++ b/pitch.cpp
@@ -46,7 +46,7 @@ int main()
        in = reinterpret_cast<double *> (fftw_malloc(sizeof(double) * FFT_LENGTH / PAD_FACTOR));
        in_windowed = reinterpret_cast<double *> (fftw_malloc(sizeof(double) * FFT_LENGTH));
        out = reinterpret_cast<std::complex<double> *> (fftw_malloc(sizeof(std::complex<double>) * (FFT_LENGTH / 2 + 1)));
-       bins = reinterpret_cast<double *> (fftw_malloc(sizeof(double) * FFT_LENGTH / 2 + 1));
+       bins = reinterpret_cast<double *> (fftw_malloc(sizeof(double) * (FFT_LENGTH / 2 + 1)));
 
        memset(in, 0, sizeof(double) * FFT_LENGTH / PAD_FACTOR);
 
@@ -93,6 +93,11 @@ int get_dsp_fd()
        int rate = SAMPLE_RATE;
        ioctl(fd, SOUND_PCM_WRITE_RATE, &rate);
 
+       int max_fragments = 2;
+       int frag_shift = ffs(FFT_LENGTH / OVERLAP) - 1;
+       int fragments = (max_fragments << 16) | frag_shift;
+        ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &fragments);
+       
        ioctl(3, SNDCTL_DSP_SYNC, 0);
        
        return fd;
@@ -229,6 +234,9 @@ std::pair<double, double> 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<double, double> peak = 
                interpolate_peak(in[best_bin - 1],
                                 in[best_bin],
@@ -243,7 +251,8 @@ std::pair<double, double> find_peak(double *in, unsigned num_samples)
 std::pair<double, double> adjust_for_overtones(std::pair<double, double> base, double *in, unsigned num_samples)
 {
        double mu = base.first, var = 1.0 / (base.second * base.second);
-       printf("mu=%f, var=%f\n", mu, var);
+               
+       //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));
@@ -283,8 +292,6 @@ std::pair<double, double> adjust_for_overtones(std::pair<double, double> base, d
                double k = var / (var + this_var);
                mu = (1.0 - k) * mu + k * this_mu;
                var *= (1.0 - k);
-
-               printf("mu=%f, var=%f\n", mu, var);
        }
        return std::make_pair(mu, base.second);
 }