]> git.sesse.net Git - pitch/blob - pitch.cpp
8aff1485a1e9e44091263aef52b7195cf12479e2
[pitch] / pitch.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 <sys/ioctl.h>
10 #include <linux/soundcard.h>
11
12 #define SAMPLE_RATE     22050
13 #define FFT_LENGTH      4096     /* in samples */
14 #define PAD_FACTOR      2        /* 1/pf of the FFT samples are real samples, the rest are padding */
15 #define OVERLAP         4        /* 1/ol samples will be replaced in the buffer every frame. Should be
16                                   * a multiple of 2 for the Hamming window (see
17                                   * http://www-ccrma.stanford.edu/~jos/parshl/Choice_Hop_Size.html).
18                                   */
19
20 #define EQUAL_TEMPERAMENT     0
21 #define WELL_TEMPERED_GUITAR  1
22
23 #define TUNING WELL_TEMPERED_GUITAR
24
25 int get_dsp_fd();
26 void read_chunk(int fd, double *in, unsigned num_samples);
27 void apply_window(double *in, double *out, unsigned num_samples);
28 std::pair<double, double> find_peak(double *in, unsigned num_samples);
29 void find_peak_magnitudes(std::complex<double> *in, double *out, unsigned num_samples);
30 std::pair<double, double> adjust_for_overtones(std::pair<double, double> base, double *in, unsigned num_samples);
31 double bin_to_freq(double bin, unsigned num_samples);
32 double freq_to_bin(double freq, unsigned num_samples);
33 std::string freq_to_tonename(double freq);
34 std::pair<double, double> interpolate_peak(double ym1, double y0, double y1);
35 void print_spectrogram(double freq, double amp);
36 void write_sine(int dsp_fd, double freq, unsigned num_samples);
37
38 int main()
39 {
40         double *in, *in_windowed;
41         std::complex<double> *out;
42         double *bins;
43         fftw_plan p;
44
45         // allocate memory
46         in = reinterpret_cast<double *> (fftw_malloc(sizeof(double) * FFT_LENGTH / PAD_FACTOR));
47         in_windowed = reinterpret_cast<double *> (fftw_malloc(sizeof(double) * FFT_LENGTH));
48         out = reinterpret_cast<std::complex<double> *> (fftw_malloc(sizeof(std::complex<double>) * (FFT_LENGTH / 2 + 1)));
49         bins = reinterpret_cast<double *> (fftw_malloc(sizeof(double) * (FFT_LENGTH / 2 + 1)));
50
51         memset(in, 0, sizeof(double) * FFT_LENGTH / PAD_FACTOR);
52
53         // init FFTW
54         p = fftw_plan_dft_r2c_1d(FFT_LENGTH, in_windowed, reinterpret_cast<fftw_complex *> (out), FFTW_ESTIMATE);
55         
56         int fd = get_dsp_fd();
57         for ( ;; ) {
58                 read_chunk(fd, in, FFT_LENGTH);
59                 apply_window(in, in_windowed, FFT_LENGTH);
60                 fftw_execute(p);
61                 find_peak_magnitudes(out, bins, FFT_LENGTH);
62                 std::pair<double, double> peak = find_peak(bins, FFT_LENGTH);
63                 if (peak.first > 0.0)
64                         peak = adjust_for_overtones(peak, bins, FFT_LENGTH);
65
66                 if (peak.first < 50.0 || peak.second - log10(FFT_LENGTH) < 0.0) {
67 #if TUNING == WELL_TEMPERED_GUITAR
68                         printf("......\n");
69 #else           
70                         printf("............\n");
71 #endif
72                 } else {
73                         print_spectrogram(peak.first, peak.second - log10(FFT_LENGTH));
74                 }
75         }
76 }
77
78 int get_dsp_fd()
79 {
80         int fd = open("/dev/dsp", O_RDWR);
81         if (fd == -1) {
82                 perror("/dev/dsp");
83                 exit(1);
84         }
85         
86         ioctl(3, SNDCTL_DSP_RESET, 0);
87         
88         int fmt = AFMT_S16_LE;   // FIXME
89         ioctl(fd, SNDCTL_DSP_SETFMT, &fmt);
90
91         int chan = 1;
92         ioctl(fd, SOUND_PCM_WRITE_CHANNELS, &chan);
93         
94         int rate = SAMPLE_RATE;
95         ioctl(fd, SOUND_PCM_WRITE_RATE, &rate);
96
97         int max_fragments = 2;
98         int frag_shift = ffs(FFT_LENGTH / OVERLAP) - 1;
99         int fragments = (max_fragments << 16) | frag_shift;
100         ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &fragments);
101         
102         ioctl(3, SNDCTL_DSP_SYNC, 0);
103         
104         return fd;
105 }
106
107 #if 1
108 void read_chunk(int fd, double *in, unsigned num_samples)
109 {
110         int ret;
111         unsigned to_read = num_samples / PAD_FACTOR / OVERLAP;
112         short buf[to_read];
113
114         memmove(in, in + to_read, (num_samples / PAD_FACTOR - to_read) * sizeof(double));
115         
116         ret = read(fd, buf, to_read * sizeof(short));
117         if (ret == 0) {
118                 printf("EOF\n");
119                 exit(0);
120         }
121
122         if (ret != int(to_read * sizeof(short))) {
123                 // blah
124                 perror("read");
125                 exit(1);
126         }
127         
128         for (unsigned i = 0; i < to_read; ++i)
129                 in[i + (num_samples / PAD_FACTOR - to_read)] = double(buf[i]);
130 }
131 #else
132 // make a pure 440hz sine for testing
133 void read_chunk(int fd, double *in, unsigned num_samples)
134 {
135         static double theta = 0.0;
136         for (unsigned i = 0; i < num_samples; ++i) {
137                 in[i] = cos(theta);
138                 theta += 2.0 * M_PI * 440.0 / double(SAMPLE_RATE);
139         }
140 }
141 #endif
142
143 void write_sine(int dsp_fd, double freq, unsigned num_samples) 
144 {
145         static double theta = 0.0;
146         short buf[num_samples];
147         
148         for (unsigned i = 0; i < num_samples; ++i) {
149                 buf[i] = short(cos(theta) * 16384.0);
150                 theta += 2.0 * M_PI * freq / double(SAMPLE_RATE);
151         }
152
153         write(dsp_fd, buf, num_samples * sizeof(short));
154 }
155
156 // Apply a standard Hamming window to our input data.
157 void apply_window(double *in, double *out, unsigned num_samples)
158 {
159         static double *win_data;
160         static unsigned win_len;
161         static bool win_inited = false;
162
163         // Initialize the window for the first time
164         if (!win_inited) {
165                 win_len = num_samples / PAD_FACTOR;
166                 win_data = new double[win_len];
167
168                 for (unsigned i = 0; i < win_len; ++i) {
169                         win_data[i] = 0.54 - 0.46 * cos(2.0 * M_PI * double(i) / double(win_len - 1));
170                 }
171
172                 win_inited = true;
173         }
174
175         assert(win_len == num_samples / PAD_FACTOR);
176         
177         for (unsigned i = 0; i < win_len; ++i) {
178                 out[i] = in[i] * win_data[i];
179         }
180         for (unsigned i = win_len; i < num_samples; ++i) {
181                 out[i] = 0.0;
182         }
183 }
184
185 void find_peak_magnitudes(std::complex<double> *in, double *out, unsigned num_samples)
186 {
187         for (unsigned i = 0; i < num_samples / 2 + 1; ++i)
188                 out[i] = abs(in[i]);
189 }
190
191 std::pair<double, double> find_peak(double *in, unsigned num_samples)
192 {
193         double best_peak = in[0];
194         unsigned best_bin = 0;
195
196         for (unsigned i = 1; i < num_samples / 2 + 1; ++i) {
197                 if (in[i] > best_peak) {
198                         best_peak = in[i];
199                         best_bin = i;
200                 }
201         }
202         
203         if (best_bin == 0 || best_bin == num_samples / 2) {
204                 return std::make_pair(-1.0, 0.0);
205         }
206
207 #if 0
208         printf("undertone strength: %+4.2f %+4.2f %+4.2f [%+4.2f] %+4.2f %+4.2f %+4.2f\n",
209                 20.0 * log10(in[best_bin*4] / FFT_LENGTH),
210                 20.0 * log10(in[best_bin*3] / FFT_LENGTH),
211                 20.0 * log10(in[best_bin*2] / FFT_LENGTH),
212                 20.0 * log10(in[best_bin] / FFT_LENGTH),
213                 20.0 * log10(in[best_bin/2] / FFT_LENGTH),
214                 20.0 * log10(in[best_bin/3] / FFT_LENGTH),
215                 20.0 * log10(in[best_bin/4] / FFT_LENGTH));
216 #endif
217
218         // see if we might have hit an overtone (set a limit of 5dB)
219         for (unsigned i = 4; i >= 1; --i) {
220                 if (best_bin != best_bin / i &&
221                     20.0 * log10(in[best_bin] / in[best_bin / i]) < 5.0f) {
222 #if 0
223                         printf("Overtone of degree %u!\n", i);
224 #endif
225                         best_bin /= i;
226
227                         // consider sliding one bin up or down
228                         if (best_bin > 0 && in[best_bin - 1] > in[best_bin] && in[best_bin - 1] > in[best_bin - 2]) {
229                                 --best_bin;
230                         } else if (best_bin < num_samples / 2 && in[best_bin + 1] > in[best_bin] && in[best_bin + 1] > in[best_bin + 2]) {
231                                 ++best_bin;
232                         }
233                            
234                         break;
235                 }
236         }
237
238         if (best_bin == 0 || best_bin == num_samples / 2) {
239                 return std::make_pair(-1.0, 0.0);
240         }
241         std::pair<double, double> peak = 
242                 interpolate_peak(in[best_bin - 1],
243                                  in[best_bin],
244                                  in[best_bin + 1]);
245                 
246         return std::make_pair(bin_to_freq(double(best_bin) + peak.first, num_samples), peak.second);
247 }
248
249 // it's perhaps not ideal to _first_ find the peak and _then_ the harmonics --
250 // ideally, one should find the set of all peaks and then determine the likely
251 // base from that... something for later. :-)
252 std::pair<double, double> adjust_for_overtones(std::pair<double, double> base, double *in, unsigned num_samples)
253 {
254         double mu = base.first, var = 1.0 / (base.second * base.second);
255                 
256         //printf("Base at %.2f (amp=%5.2fdB)\n", base.first, base.second);
257
258         for (unsigned i = 2; i < 10; ++i) {
259                 unsigned middle = unsigned(floor(freq_to_bin(base.first, num_samples) * i + 0.5));
260                 unsigned lower = middle - (i+1)/2, upper = middle + (i+1)/2;
261
262                 if (upper >= num_samples)
263                         upper = num_samples - 2;
264
265                 // printf("Searching in [%u,%u] = %f..%f\n", lower, upper, bin_to_freq(lower, num_samples), bin_to_freq(upper, num_samples));
266
267                 // search for a peak in this interval
268                 double best_harmonics_freq = -1.0;
269                 double best_harmonics_amp = -1.0;
270                 for (unsigned j = lower; j <= upper; ++j) {
271                         if (in[j] > in[j-1] && in[j] > in[j+1]) {
272                                 std::pair<double, double> peak =
273                                         interpolate_peak(in[j - 1],
274                                                 in[j],
275                                                 in[j + 1]);
276                                 
277                                 if (peak.second > best_harmonics_amp) {
278                                         best_harmonics_freq = bin_to_freq(j + peak.first, num_samples);
279                                         best_harmonics_amp = peak.second;
280                                 }
281                         }
282                 }
283
284                 if (best_harmonics_amp <= 0.0)
285                         continue;
286
287                 //printf("Found overtone %u at %.2f (amp=%5.2fdB)\n", i, best_harmonics_freq,
288                 //       best_harmonics_amp);
289
290                 double this_mu = best_harmonics_freq / double(i);
291                 double this_var = 1.0 / (best_harmonics_amp * best_harmonics_amp);
292
293                 double k = var / (var + this_var);
294                 mu = (1.0 - k) * mu + k * this_mu;
295                 var *= (1.0 - k);
296         }
297         return std::make_pair(mu, base.second);
298 }
299
300 double bin_to_freq(double bin, unsigned num_samples)
301 {
302         return bin * SAMPLE_RATE / double(num_samples);
303 }
304 double freq_to_bin(double freq, unsigned num_samples)
305 {
306         return freq * double(num_samples) / double(SAMPLE_RATE);
307 }
308
309 /*
310  * Given three bins, find the interpolated real peak based
311  * on their magnitudes. To do this, we execute the following
312  * plan:
313  * 
314  * Fit a polynomial of the form ax^2 + bx + c = 0 to the data
315  * we have. Maple readily yields our coefficients, assuming
316  * that we have the values at x=-1, x=0 and x=1:
317  *
318  * > f := x -> a*x^2 + b*x + c;                                
319  * 
320  *                               2
321  *           f := x -> a x  + b x + c
322  * 
323  * > cf := solve({ f(-1) = ym1, f(0) = y0, f(1) = y1 }, { a, b, c });
324  * 
325  *                            y1    ym1       y1    ym1
326  *        cf := {c = y0, b = ---- - ---, a = ---- + --- - y0}
327  *                            2      2        2      2
328  *
329  * Now let's find the maximum point for the polynomial (it has to be
330  * a maximum, since y0 is the greatest value):
331  *
332  * > xmax := solve(subs(cf, diff(f(x), x)) = 0, x);
333  * 
334  *                                -y1 + ym1
335  *                   xmax := -------------------
336  *                           2 (y1 + ym1 - 2 y0)
337  *
338  * We could go further and insert {fmax,a,b,c} into the original
339  * polynomial, but it just gets hairy. We calculate a, b and c separately
340  * instead.
341  *
342  * http://www-ccrma.stanford.edu/~jos/parshl/Peak_Detection_Steps_3.html
343  * claims that detection is almost twice as good when using dB scale instead
344  * of linear scale for the input values, so we use that. (As a tiny bonus,
345  * we get back dB scale from the function.)
346  */
347 std::pair<double, double> interpolate_peak(double ym1, double y0, double y1)
348 {
349         ym1 = log10(ym1);
350         y0 = log10(y0);
351         y1 = log10(y1);
352
353 #if 0
354         assert(y0 >= y1);
355         assert(y0 >= ym1);
356 #endif
357         
358         double a = 0.5 * y1 + 0.5 * ym1 - y0;
359         double b = 0.5 * y1 - 0.5 * ym1;
360         double c = y0;
361         
362         double xmax = (ym1 - y1) / (2.0 * (y1 + ym1 - 2.0 * y0));
363         double ymax = 20.0 * (a * xmax * xmax + b * xmax + c) - 90.0;
364
365         return std::make_pair(xmax, ymax);
366 }
367
368 std::string freq_to_tonename(double freq)
369 {
370         std::string notenames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
371         double half_notes_away = 12.0 * log2(freq / 440.0) - 3.0;
372         int hnai = int(floor(half_notes_away + 0.5));
373         int octave = (hnai + 48) / 12;
374
375         char buf[256];
376         sprintf(buf, "%s%d + %.2f [%d]", notenames[((hnai % 12) + 12) % 12].c_str(), octave, half_notes_away - hnai, hnai);
377         return buf;
378 }
379
380 #if TUNING == EQUAL_TEMPERAMENT
381 void print_spectrogram(double freq, double amp)
382 {
383         std::string notenames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
384         double half_notes_away = 12.0 * log2(freq / 440.0) - 3.0;
385         int hnai = int(floor(half_notes_away + 0.5));
386         int octave = (hnai + 48) / 12;
387
388         for (int i = 0; i < 12; ++i)
389                 if (i == ((hnai % 12) + 12) % 12)
390                         printf("#");
391                 else
392                         printf(".");
393
394         printf(" (%-2s%d %+.2f, %5.2fHz) [%5.2fdB]  [", notenames[((hnai % 12) + 12) % 12].c_str(), octave, half_notes_away - hnai,
395                 freq, amp);
396
397         double off = half_notes_away - hnai;
398         for (int i = -10; i <= 10; ++i) {
399                 if (off >= (i-0.5) * 0.05 && off < (i+0.5) * 0.05) {
400                         printf("#");
401                 } else {
402                         if (i == 0) {
403                                 printf("|");
404                         } else {
405                                 printf("-");
406                         }
407                 }
408         }
409         printf("]\n");
410
411 }
412 #else
413 struct note {
414         char notename[16];
415         double freq;
416 };
417 static note notes[] = {
418         { "E-3", 110.0 * (3.0/4.0) },
419         { "A-3", 110.0 },
420         { "D-4", 110.0 * (4.0/3.0) },
421         { "G-4", 110.0 * (4.0/3.0)*(4.0/3.0) },
422         { "B-4", 440.0 * (3.0/4.0)*(3.0/4.0) },
423         { "E-5", 440.0 * (3.0/4.0) }
424 };
425
426 void print_spectrogram(double freq, double amp)
427 {
428         double best_away = 999999999.9;
429         unsigned best_away_ind = 0;
430         
431         for (unsigned i = 0; i < sizeof(notes)/sizeof(note); ++i) {
432                 double half_notes_away = 12.0 * log2(freq / notes[i].freq);
433                 if (fabs(half_notes_away) < fabs(best_away)) {
434                         best_away = half_notes_away;
435                         best_away_ind = i;
436                 }
437         }
438         
439         for (unsigned i = 0; i < sizeof(notes)/sizeof(note); ++i)
440                 if (i == best_away_ind)
441                         printf("#");
442                 else
443                         printf(".");
444
445         printf(" (%s %+.2f, %5.2fHz) [%5.2fdB]  [", notes[best_away_ind].notename, best_away, freq, amp);
446
447         for (int i = -10; i <= 10; ++i) {
448                 if (best_away >= (i-0.5) * 0.05 && best_away < (i+0.5) * 0.05) {
449                         printf("#");
450                 } else {
451                         if (i == 0) {
452                                 printf("|");
453                         } else {
454                                 printf("-");
455                         }
456                 }
457         }
458         printf("]\n");
459 }
460 #endif