#include #include #include #include #include #include #include #include #include #include "scope.h" // Pitch detection of singing voice using autocorrelation. (The class is // called "piano" because the result is shown on a piano keyboard.) // // The fundamental frequency is found with the McLeod Pitch Method: // 1) the autocorrelation r(tau) of the window is computed with an FFT // 2) it is normalised into the NSDF n(tau) = 2 r(tau) / m(tau) // where m(tau) = sum x[j]^2 + x[j+tau]^2 ; n is in the range -1 .. 1 // 3) the first NSDF peak that is close to the highest peak gives the // period; parabolic interpolation refines it to a fraction of a sample // 4) frequency = SAMPLE_RATE / period, which is mapped to a note // 5) the note is smoothed for the display: median of the last few // estimates, hysteresis against vibrato, and a short hold so that a // consonant or breath does not blank the display immediately // // The analysis window slides: every new read buffer is shifted in and a new // estimate is made once the window has filled. // // Define PIANO_DEBUG to write the input waveform and NSDF to files for gnuplot. piano_process_class::piano_process_class() { acf_time = NULL; acf_freq = NULL; acf_forward_plan = NULL; acf_inverse_plan = NULL; } piano_process_class::~piano_process_class() { if (acf_forward_plan != NULL) { fftw_destroy_plan(acf_forward_plan); } if (acf_inverse_plan != NULL) { fftw_destroy_plan(acf_inverse_plan); } if (acf_time != NULL) { fftw_free(acf_time); } if (acf_freq != NULL) { fftw_free(acf_freq); } } // Fill nsdf[0 .. PIANO_MAX_LAG + 1] from window_samples int piano_process_class::compute_nsdf() { int counter; int lag; double scale; double m; double re, im; // Zero padded copy of the window into the FFT input for (counter = 0; counter < PIANO_WINDOW_SIZE; counter += 1) { acf_time[counter] = window_samples[counter]; } for (counter = PIANO_WINDOW_SIZE; counter < ACF_FFT_SIZE; counter += 1) { acf_time[counter] = 0.0; } // Autocorrelation = inverse FFT of the power spectrum fftw_execute(acf_forward_plan); for (counter = 0; counter < (ACF_FFT_SIZE / 2) + 1; counter += 1) { re = acf_freq[counter][0]; im = acf_freq[counter][1]; acf_freq[counter][0] = (re * re) + (im * im); acf_freq[counter][1] = 0.0; } fftw_execute(acf_inverse_plan); // fftw does not normalise; acf_time[lag] is now r(lag) * ACF_FFT_SIZE scale = 1.0 / (double)ACF_FFT_SIZE; // m(0) = 2 * sum x^2 ; m(lag) = m(lag - 1) - x[lag - 1]^2 - x[N - lag]^2 m = 0.0; for (counter = 0; counter < PIANO_WINDOW_SIZE; counter += 1) { m += window_samples[counter] * window_samples[counter]; } m = 2.0 * m; for (lag = 0; lag < PIANO_MAX_LAG + 2; lag += 1) { if (lag > 0) { m -= (window_samples[lag - 1] * window_samples[lag - 1]) + (window_samples[PIANO_WINDOW_SIZE - lag] * window_samples[PIANO_WINDOW_SIZE - lag]); } if (m > 0.0) { nsdf[lag] = (2.0 * acf_time[lag] * scale) / m; } else { nsdf[lag] = 0.0; } } return 0; } // Returns the fundamental period in (fractional) samples, or -1.0 if the // sound is not clearly pitched double piano_process_class::find_fundamental_lag() { int peak_lags[PIANO_MAX_PEAKS]; int number_peaks; int lag; int current_peak_lag; int in_positive_region; int counter; int chosen_lag; double highest_peak; double threshold; double a, b, c, denominator, delta; number_peaks = 0; current_peak_lag = -1; in_positive_region = 0; // Skip the lobe around lag 0: wait for the NSDF to first go negative. // Then, in each positive region, remember the highest point (a "key // maximum"). Searching from lag 1 rather than from PIANO_MIN_LAG makes // sure the first period of a high note is not skipped. lag = 1; while ((lag <= PIANO_MAX_LAG) && (nsdf[lag] > 0.0)) { lag += 1; } for (; lag <= PIANO_MAX_LAG; lag += 1) { if ((nsdf[lag] > 0.0) && (nsdf[lag - 1] <= 0.0)) { // positive going zero crossing; start of a new region in_positive_region = 1; current_peak_lag = lag; } else if ((nsdf[lag] <= 0.0) && in_positive_region) { // negative going zero crossing; region done, record its peak in_positive_region = 0; if (number_peaks < PIANO_MAX_PEAKS) { peak_lags[number_peaks] = current_peak_lag; number_peaks += 1; } } else if (in_positive_region && (nsdf[lag] > nsdf[current_peak_lag])) { current_peak_lag = lag; } } // A region still open at the end of the search range counts too if (in_positive_region && (number_peaks < PIANO_MAX_PEAKS)) { peak_lags[number_peaks] = current_peak_lag; number_peaks += 1; } if (number_peaks == 0) { return -1.0; } highest_peak = 0.0; for (counter = 0; counter < number_peaks; counter += 1) { if (nsdf[peak_lags[counter]] > highest_peak) { highest_peak = nsdf[peak_lags[counter]]; } } if (highest_peak < PIANO_CLARITY_THRESHOLD) { return -1.0; } // Take the first (shortest period) peak that is nearly as strong as the // highest; this avoids picking a multiple of the period (octave too low) threshold = PIANO_PEAK_THRESHOLD * highest_peak; chosen_lag = -1; for (counter = 0; counter < number_peaks; counter += 1) { if ((peak_lags[counter] >= PIANO_MIN_LAG) && (nsdf[peak_lags[counter]] >= threshold)) { chosen_lag = peak_lags[counter]; break; } } if (chosen_lag < 1) { return -1.0; } // Parabolic interpolation through the peak and its neighbours a = nsdf[chosen_lag - 1]; b = nsdf[chosen_lag]; c = nsdf[chosen_lag + 1]; denominator = a - (2.0 * b) + c; delta = 0.0; if (denominator < 0.0) { delta = 0.5 * (a - c) / denominator; if ((delta > 0.5) || (delta < -0.5)) { delta = 0.0; } } return (double)chosen_lag + delta; } // Median of the fractional note numbers in note_history double piano_process_class::median_of_history() { double sorted[PIANO_MEDIAN_SIZE]; double hold; int outer, inner; for (outer = 0; outer < note_history_count; outer += 1) { sorted[outer] = note_history[outer]; } // insertion sort; only a handful of entries for (outer = 1; outer < note_history_count; outer += 1) { hold = sorted[outer]; inner = outer - 1; while ((inner >= 0) && (sorted[inner] > hold)) { sorted[inner + 1] = sorted[inner]; inner -= 1; } sorted[inner + 1] = hold; } if ((note_history_count % 2) == 1) { return sorted[note_history_count / 2]; } return 0.5 * (sorted[(note_history_count / 2) - 1] + sorted[note_history_count / 2]); } // Map a note number (0 = C1) to keyboard key (0 = C .. 11 = B) and // octive (0 = octave 1). Returns 0 on success, -1 if outside the display range int piano_process_class::note_to_key_and_octive(int note_number, int *keyboard_key, int *octive) { if ((note_number < 0) || (note_number >= TOTAL_NOTES)) { return -1; } *keyboard_key = note_number % NOTES_PER_OCTIVE; *octive = note_number / NOTES_PER_OCTIVE; return 0; } struct piano_data_struct *piano_process_class::process_piano_data(Sint16 *input_buffer) { int counter; int voiced; int candidate_note; int keyboard_key; int octive; double mean; double sum_squares; double rms; double lag; double note_number; double smoothed_note; // Slide the window: drop the oldest read buffer, append the new one memmove(full_size_buffer, full_size_buffer + READ_BUFFER_SIZE, sizeof(Sint16) * (PIANO_WINDOW_SIZE - READ_BUFFER_SIZE)); memcpy(full_size_buffer + (PIANO_WINDOW_SIZE - READ_BUFFER_SIZE), input_buffer, sizeof(Sint16) * READ_BUFFER_SIZE); // Wait until the window has been filled once if (main_buffer_read_count < (PIANO_WINDOW_SIZE / READ_BUFFER_SIZE)) { main_buffer_read_count += 1; if (main_buffer_read_count < (PIANO_WINDOW_SIZE / READ_BUFFER_SIZE)) { return NULL; } } // Convert to double and remove DC mean = 0.0; for (counter = 0; counter < PIANO_WINDOW_SIZE; counter += 1) { mean += (double)full_size_buffer[counter]; } mean = mean / (double)PIANO_WINDOW_SIZE; sum_squares = 0.0; for (counter = 0; counter < PIANO_WINDOW_SIZE; counter += 1) { window_samples[counter] = (double)full_size_buffer[counter] - mean; sum_squares += window_samples[counter] * window_samples[counter]; } rms = sqrt(sum_squares / (double)PIANO_WINDOW_SIZE); // Find the pitch of this frame (if loud enough and clearly pitched) voiced = 0; lag = -1.0; note_number = 0.0; if (rms >= PIANO_MIN_RMS) { compute_nsdf(); lag = find_fundamental_lag(); if (lag > 0.0) { voiced = 1; note_number = 12.0 * log2(((double)SAMPLE_RATE / lag) / PIANO_REFERENCE_FREQ); } } #ifdef PIANO_DEBUG FILE *debug_file; debug_file = fopen("waveform_of_input", "w"); if (debug_file != NULL) { for (counter = 0; counter < PIANO_WINDOW_SIZE; counter += 1) { fprintf(debug_file, "%d %f\n", counter, window_samples[counter]); } fclose(debug_file); } if (rms >= PIANO_MIN_RMS) { debug_file = fopen("nsdf_data_for_gnuplot", "w"); if (debug_file != NULL) { for (counter = 0; counter < PIANO_MAX_LAG + 2; counter += 1) { fprintf(debug_file, "%d %f\n", counter, nsdf[counter]); } fclose(debug_file); } } printf("voice: rms %f lag %f freq %f note %f\n", rms, lag, (lag > 0.0) ? (double)SAMPLE_RATE / lag : 0.0, note_number); #endif // Smooth the result for the display if (voiced) { unvoiced_frames = 0; note_history[note_history_index] = note_number; note_history_index = (note_history_index + 1) % PIANO_MEDIAN_SIZE; if (note_history_count < PIANO_MEDIAN_SIZE) { note_history_count += 1; } smoothed_note = median_of_history(); // Hysteresis: only move off the current note once clearly away from it if ((current_note < 0) || (fabs(smoothed_note - (double)current_note) > PIANO_HYSTERESIS_SEMITONES)) { candidate_note = (int)lround(smoothed_note); if ((candidate_note >= 0) && (candidate_note < TOTAL_NOTES)) { current_note = candidate_note; } else { current_note = -1; } } my_piano_data_struct.frequency = PIANO_REFERENCE_FREQ * pow(2.0, smoothed_note / 12.0); } else { // Hold the last note briefly through consonants and breaths unvoiced_frames += 1; if (unvoiced_frames > PIANO_HOLD_FRAMES) { current_note = -1; note_history_count = 0; note_history_index = 0; my_piano_data_struct.frequency = 0.0; } } my_piano_data_struct.done = 1; if ((current_note >= 0) && (note_to_key_and_octive(current_note, &keyboard_key, &octive) == 0)) { my_piano_data_struct.valid = 1; my_piano_data_struct.keyboard_key = keyboard_key; my_piano_data_struct.octive = octive; } else { my_piano_data_struct.valid = 0; my_piano_data_struct.keyboard_key = 0; my_piano_data_struct.octive = 0; } return &my_piano_data_struct; } int piano_process_class::initialize_piano_data() { int array_counter; // initialize full_size_buffer for (array_counter = 0; array_counter < PIANO_FULL_ARRAY_SIZE; array_counter += 1) { full_size_buffer[array_counter] = (Sint16)0; } main_buffer_read_count = 0; my_piano_data_struct.keyboard_key = 0; my_piano_data_struct.octive = 0; my_piano_data_struct.done = 0; my_piano_data_struct.valid = 0; my_piano_data_struct.frequency = 0.0; // Smoothing state for (array_counter = 0; array_counter < PIANO_MEDIAN_SIZE; array_counter += 1) { note_history[array_counter] = 0.0; } note_history_count = 0; note_history_index = 0; current_note = -1; unvoiced_frames = 0; // Buffers and plans for the FFT based autocorrelation acf_time = (double *)fftw_malloc(sizeof(double) * ACF_FFT_SIZE); acf_freq = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * ((ACF_FFT_SIZE / 2) + 1)); if ((acf_time == NULL) || (acf_freq == NULL)) { printf("cannot allocate voice autocorrelation buffers\n"); return -1; } // FFTW_MEASURE overwrites the arrays while planning; fine, nothing is in them yet acf_forward_plan = fftw_plan_dft_r2c_1d(ACF_FFT_SIZE, acf_time, acf_freq, FFTW_MEASURE); acf_inverse_plan = fftw_plan_dft_c2r_1d(ACF_FFT_SIZE, acf_freq, acf_time, FFTW_MEASURE); if ((acf_forward_plan == NULL) || (acf_inverse_plan == NULL)) { printf("cannot create voice autocorrelation fft plans\n"); return -1; } printf("voice autocorrelation: window %d fft %d lag range %d - %d\n", PIANO_WINDOW_SIZE, ACF_FFT_SIZE, PIANO_MIN_LAG, PIANO_MAX_LAG); printf ("done initialize \n"); return 0; }