]> git.sesse.net Git - pitch/blob - pitchdetector.cpp
Don't choose impossible tones as undertones.
[pitch] / pitchdetector.cpp
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <fcntl.h>
5 #include <complex>
6 #include <cassert>
7 #include <algorithm>
8 #include <fftw3.h>
9 #include "pitchdetector.h"
10
11 PitchDetector::PitchDetector(unsigned sample_rate, unsigned fft_length, unsigned pad_factor, unsigned overlap)
12         : sample_rate(sample_rate), fft_length(fft_length), pad_factor(pad_factor), overlap(overlap)
13 {
14         in = reinterpret_cast<double *> (fftw_malloc(sizeof(double) * fft_length / pad_factor));
15         in_windowed = reinterpret_cast<double *> (fftw_malloc(sizeof(double) * fft_length));
16         out = reinterpret_cast<std::complex<double> *> (fftw_malloc(sizeof(std::complex<double>) * (fft_length / 2 + 1)));
17         bins = reinterpret_cast<double *> (fftw_malloc(sizeof(double) * (fft_length / 2 + 1)));
18
19         memset(in, 0, sizeof(double) * fft_length / pad_factor);
20
21         plan = fftw_plan_dft_r2c_1d(fft_length, in_windowed, reinterpret_cast<fftw_complex *> (out), FFTW_ESTIMATE);
22         
23         // Initialize the Hamming window
24         window_data = new double[fft_length / pad_factor];
25         for (unsigned i = 0; i < fft_length / pad_factor; ++i) {
26                 window_data[i] = 0.54 - 0.46 * cos(2.0 * M_PI * double(i) / double(fft_length/pad_factor - 1));
27         }
28 }
29
30 PitchDetector::~PitchDetector()
31 {
32         fftw_free(in);
33         fftw_free(in_windowed);
34         fftw_free(out);
35         fftw_free(bins);
36 }
37
38 std::pair<double, double> PitchDetector::detect_pitch(short *buf)
39 {
40         unsigned buf_len = fft_length / pad_factor / overlap;
41         memmove(in, in + buf_len, (fft_length / pad_factor - buf_len) * sizeof(double));
42         
43         for (unsigned i = 0; i < buf_len; ++i)
44                 in[i + (fft_length / pad_factor - buf_len)] = double(buf[i]);
45
46         apply_window(in, in_windowed, fft_length);
47         fftw_execute(plan);
48         find_peak_magnitudes(out, bins, fft_length);
49         std::pair<double, double> peak = find_peak(bins, fft_length);
50         if (peak.first > 0.0)
51                 peak = adjust_for_overtones(peak, bins, fft_length);
52
53         return peak;
54 }
55
56 // Apply a standard Hamming window to our input data.
57 void PitchDetector::apply_window(double *in, double *out, unsigned num_samples)
58 {
59         for (unsigned i = 0; i < num_samples / pad_factor; ++i) {
60                 out[i] = in[i] * window_data[i];
61         }
62         for (unsigned i = num_samples / pad_factor; i < num_samples; ++i) {
63                 out[i] = 0.0;
64         }
65 }
66
67 void PitchDetector::find_peak_magnitudes(std::complex<double> *in, double *out, unsigned num_samples)
68 {
69         for (unsigned i = 0; i < num_samples / 2 + 1; ++i)
70                 out[i] = abs(in[i]);
71 }
72
73 std::pair<double, double> PitchDetector::find_peak(double *in, unsigned num_samples)
74 {
75         double best_peak = in[5];
76         unsigned best_bin = 5;
77
78         for (unsigned i = 6; i < num_samples / 2 + 1; ++i) {
79                 if (in[i] > best_peak) {
80                         best_peak = in[i];
81                         best_bin = i;
82                 }
83 #if 0
84                 if (20.0 * log10(in[i] / fft_length) > 0.0) {
85                         printf("PEAK: %+4.2f dB   %5.2f Hz\n",
86                                 20.0 * log10(in[i] / fft_length),
87                                 bin_to_freq(i, num_samples));
88                 }
89 #endif
90         }
91         
92         if (best_bin == 0 || best_bin == num_samples / 2) {
93                 return std::make_pair(-1.0, 0.0);
94         }
95
96 #if 0
97         printf("undertone strength: %+4.2f %+4.2f %+4.2f [%+4.2f] %+4.2f %+4.2f %+4.2f\n",
98                 20.0 * log10(in[best_bin*4] / fft_length),
99                 20.0 * log10(in[best_bin*3] / fft_length),
100                 20.0 * log10(in[best_bin*2] / fft_length),
101                 20.0 * log10(in[best_bin] / fft_length),
102                 20.0 * log10(in[best_bin/2] / fft_length),
103                 20.0 * log10(in[best_bin/3] / fft_length),
104                 20.0 * log10(in[best_bin/4] / fft_length));
105 #endif
106
107         // see if we might have hit an overtone (set a limit of 10dB)
108         for (unsigned i = 6; i >= 1; --i) {
109                 if (best_bin != best_bin / i &&
110                     20.0 * log10(in[best_bin] / in[best_bin / i]) < 10.0f &&
111                     best_bin / i >= 5) {
112 #if 0
113                         printf("Overtone of degree %u!\n", i);
114 #endif
115                         best_bin /= i;
116
117                         // consider sliding one bin up or down
118                         if (best_bin > 1 && in[best_bin - 1] > in[best_bin] && in[best_bin - 1] > in[best_bin - 2]) {
119                                 --best_bin;
120                         } else if (best_bin < num_samples / 2 - 1 && in[best_bin + 1] > in[best_bin] && in[best_bin + 1] > in[best_bin + 2]) {
121                                 ++best_bin;
122                         }
123                            
124                         break;
125                 }
126         }
127
128         if (best_bin == 0 || best_bin == num_samples / 2) {
129                 return std::make_pair(-1.0, 0.0);
130         }
131         std::pair<double, double> peak = 
132                 interpolate_peak(in[best_bin - 1],
133                                  in[best_bin],
134                                  in[best_bin + 1]);
135                 
136         return std::make_pair(bin_to_freq(double(best_bin) + peak.first, num_samples), peak.second);
137 }
138
139 // it's perhaps not ideal to _first_ find the peak and _then_ the harmonics --
140 // ideally, one should find the set of all peaks and then determine the likely
141 // base from that... something for later. :-)
142 std::pair<double, double> PitchDetector::adjust_for_overtones(std::pair<double, double> base, double *in, unsigned num_samples)
143 {
144         double mu = base.first, var = 1.0 / (base.second * base.second);
145                 
146         //printf("Base at %.2f (amp=%5.2fdB)\n", base.first, base.second);
147
148         for (unsigned i = 2; i < 10; ++i) {
149                 unsigned middle = unsigned(floor(freq_to_bin(base.first, num_samples) * i + 0.5));
150                 unsigned lower = middle - (i+1)/2, upper = middle + (i+1)/2;
151
152                 if (lower < 1)
153                         lower = 1;
154                 if (upper >= num_samples)
155                         upper = num_samples - 2;
156
157                 // printf("Searching in [%u,%u] = %f..%f\n", lower, upper, bin_to_freq(lower, num_samples), bin_to_freq(upper, num_samples));
158
159                 // search for a peak in this interval
160                 double best_harmonics_freq = -1.0;
161                 double best_harmonics_amp = -1.0;
162                 for (unsigned j = lower; j <= upper; ++j) {
163                         if (in[j] > in[j-1] && in[j] > in[j+1]) {
164                                 std::pair<double, double> peak =
165                                         interpolate_peak(in[j - 1],
166                                                 in[j],
167                                                 in[j + 1]);
168                                 
169                                 if (peak.second > best_harmonics_amp) {
170                                         best_harmonics_freq = bin_to_freq(j + peak.first, num_samples);
171                                         best_harmonics_amp = peak.second;
172                                 }
173                         }
174                 }
175
176                 if (best_harmonics_amp <= 0.0)
177                         continue;
178
179                 //printf("Found overtone %u at %.2f (amp=%5.2fdB)\n", i, best_harmonics_freq,
180                 //       best_harmonics_amp);
181
182                 double this_mu = best_harmonics_freq / double(i);
183                 double this_var = 1.0 / (best_harmonics_amp * best_harmonics_amp);
184
185                 double k = var / (var + this_var);
186                 mu = (1.0 - k) * mu + k * this_mu;
187                 var *= (1.0 - k);
188         }
189         return std::make_pair(mu, base.second);
190 }
191
192 double PitchDetector::bin_to_freq(double bin, unsigned num_samples)
193 {
194         return bin * sample_rate / double(num_samples);
195 }
196 double PitchDetector::freq_to_bin(double freq, unsigned num_samples)
197 {
198         return freq * double(num_samples) / double(sample_rate);
199 }
200
201 /*
202  * Given three bins, find the interpolated real peak based
203  * on their magnitudes. To do this, we execute the following
204  * plan:
205  * 
206  * Fit a polynomial of the form ax^2 + bx + c = 0 to the data
207  * we have. Maple readily yields our coefficients, assuming
208  * that we have the values at x=-1, x=0 and x=1:
209  *
210  * > f := x -> a*x^2 + b*x + c;                                
211  * 
212  *                               2
213  *           f := x -> a x  + b x + c
214  * 
215  * > cf := solve({ f(-1) = ym1, f(0) = y0, f(1) = y1 }, { a, b, c });
216  * 
217  *                            y1    ym1       y1    ym1
218  *        cf := {c = y0, b = ---- - ---, a = ---- + --- - y0}
219  *                            2      2        2      2
220  *
221  * Now let's find the maximum point for the polynomial (it has to be
222  * a maximum, since y0 is the greatest value):
223  *
224  * > xmax := solve(subs(cf, diff(f(x), x)) = 0, x);
225  * 
226  *                                -y1 + ym1
227  *                   xmax := -------------------
228  *                           2 (y1 + ym1 - 2 y0)
229  *
230  * We could go further and insert {fmax,a,b,c} into the original
231  * polynomial, but it just gets hairy. We calculate a, b and c separately
232  * instead.
233  *
234  * http://www-ccrma.stanford.edu/~jos/parshl/Peak_Detection_Steps_3.html
235  * claims that detection is almost twice as good when using dB scale instead
236  * of linear scale for the input values, so we use that. (As a tiny bonus,
237  * we get back dB scale from the function.)
238  */
239 std::pair<double, double> PitchDetector::interpolate_peak(double ym1, double y0, double y1)
240 {
241         ym1 = log10(ym1);
242         y0 = log10(y0);
243         y1 = log10(y1);
244
245 #if 0
246         assert(y0 >= y1);
247         assert(y0 >= ym1);
248 #endif
249         
250         double a = 0.5 * y1 + 0.5 * ym1 - y0;
251         double b = 0.5 * y1 - 0.5 * ym1;
252         double c = y0;
253         
254         double xmax = (ym1 - y1) / (2.0 * (y1 + ym1 - 2.0 * y0));
255         double ymax = 20.0 * (a * xmax * xmax + b * xmax + c) - 80.0;
256
257         return std::make_pair(xmax, ymax);
258 }
259