diff --git a/piano_class.cpp b/piano_class.cpp index 4b88aa3..0173559 100644 --- a/piano_class.cpp +++ b/piano_class.cpp @@ -23,26 +23,24 @@ int piano_window_class::draw_trace(piano_data_struct *input_piano_data) my_piano_data = input_piano_data; - // point to piano_key_texture - if (my_piano_data->keyboard_key == 0) + // Light the detected key and octive; blank when no note was detected. + // keyboard_key is 0 - 11 and octive is 0 based (0 = octave 1) + texture_current_piano_light = texture_key_blank; + texture_current_octive_light = texture_octive_blank; + if (my_piano_data->valid) { - texture_current_piano_light = texture_key_blank; + if ((my_piano_data->keyboard_key >= 0) && + (my_piano_data->keyboard_key < NUMBER_KEY_LIGHTS)) + { + texture_current_piano_light = texture_keys[my_piano_data->keyboard_key]; + } + if ((my_piano_data->octive >= 0) && + (my_piano_data->octive < NUMBER_OCTIVE_LIGHTS)) + { + texture_current_octive_light = texture_octives[my_piano_data->octive]; + } } - else - { - texture_current_piano_light = texture_keys[my_piano_data->keyboard_key - 1]; - } - - // point to octive_texture - if (my_piano_data->octive == 0) - { - texture_current_octive_light = texture_octive_blank; - } - else - { - texture_current_octive_light = texture_octives[my_piano_data->octive - 1]; - } - + // Put on screen SDL_RenderCopy(renderer_for_piano, texture_current_piano_light, NULL, &rect_for_keys); SDL_RenderCopy(renderer_for_piano, texture_current_octive_light, NULL, &rect_for_octives); diff --git a/piano_process.cpp b/piano_process.cpp index 8a911ed..ed13b05 100644 --- a/piano_process.cpp +++ b/piano_process.cpp @@ -3,302 +3,479 @@ #include #include #include +#include #include #include #include #include "scope.h" -// Functions to try to process Constant Q transform +// 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); + } } -double piano_process_class::goertzel(int num_samples, int target_frequency, int sample_rate, - Sint16 *input_buffer) +// Fill nsdf[0 .. PIANO_MAX_LAG + 1] from window_samples +int piano_process_class::compute_nsdf() { - double dinput_buffer; - double magnatude; - int k, i; - double doublenumsamples; - double omega, sine, cosine, coeff, q0, q1, q2, real, imag; - double scalingfactor; - - // Initialize constant stuff + int counter; + int lag; + double scale; + double m; + double re, im; - doublenumsamples = (double)num_samples; - scalingfactor = doublenumsamples / 2.0; - k = (int)(0.5 + ((doublenumsamples * (double)(target_frequency)) / (double)sample_rate)); - omega = (2.0 * M_PI * (double)k) / doublenumsamples; - sine = sin(omega); - cosine= cos(omega); - coeff = 2.0 * cosine; - - // Init q's - q0 = 0; - q1 = 0; - q2 = 0; - - - // First stage (2nd order IIR filter) - for (i = 0; i < num_samples; i += 1) + // Zero padded copy of the window into the FFT input + for (counter = 0; counter < PIANO_WINDOW_SIZE; counter += 1) { - dinput_buffer = 3.0 * (double)*(input_buffer + i); - q2 = q1; - q1 = q0; - q0 = coeff * q1 - q2 + dinput_buffer; + acf_time[counter] = window_samples[counter]; + } + for (counter = PIANO_WINDOW_SIZE; counter < ACF_FFT_SIZE; counter += 1) + { + acf_time[counter] = 0.0; } - // Seconod stage (FIR filter) - real = (q0 - q1 *cosine) / scalingfactor; - imag = (-q1 * sine) / scalingfactor; - magnatude = sqrt((real * real) + (imag * imag)); - + // 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); - // Test Prints + // 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; - // printf("goertzel done\n"); - return magnatude; + 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 bucket_counter; - bucket_data_struct *current_bucket; - FILE *result_plot_file; - FILE *input_waveform_file; - FILE *note_result_plot_file; - Sint16 *current_read_buffer_in; - Sint16 *current_read_buffer_out; - int print_file_counter; - int count_for_transfering_buffers; - struct piano_note_struct *working_note; - struct piano_note_struct *strongest_note; - int note_counter; + 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); - // Before doing anything, we need to 1) update the full size buffer - // and ensure that it is full before processing, - // Otherwize return NULL if not. - - if (main_buffer_read_count < FFT_NUMBER_READ_BUFFERS) + // Wait until the window has been filled once + if (main_buffer_read_count < (PIANO_WINDOW_SIZE / READ_BUFFER_SIZE)) { - current_read_buffer_in = input_buffer; - current_read_buffer_out = full_size_buffer + READ_BUFFER_SIZE * main_buffer_read_count; - for (count_for_transfering_buffers = 0; count_for_transfering_buffers < READ_BUFFER_SIZE; - count_for_transfering_buffers += 1) - { - *current_read_buffer_out = *current_read_buffer_in; - current_read_buffer_out += 1; - current_read_buffer_in += 1; - } - main_buffer_read_count += 1; - return NULL; + 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 { - main_buffer_read_count = 0; - } - - input_waveform_file = fopen("waveform_of_input","w"); - if (input_waveform_file == NULL) - { - printf("cant open input waveform_file\n"); - exit (0); - } - - for (print_file_counter = 0; print_file_counter < READ_BUFFER_SIZE * FFT_NUMBER_READ_BUFFERS; - print_file_counter += 2) - { - fprintf(input_waveform_file, "%d %d\n", print_file_counter, *(full_size_buffer + print_file_counter)); - // printf("%d %f\n", print_file_counter, (double)*(full_size_buffer + print_file_counter)); - } - - fclose (input_waveform_file); - - // Go through all of the buckets to get their strenght using Goertzel - // Test plotfile - result_plot_file = fopen("result_data_for_gnuplot", "w"); - if (result_plot_file == NULL) - { - printf("oops cant open result file\n"); - perror("cant open file\n"); - exit(0); - } - - note_result_plot_file = fopen("note_data_for_gnuplot", "w"); - if (note_result_plot_file == NULL) - { - printf("oops cant open note result file\n"); - perror("cant open file\n"); - exit(0); - } - - //clear the strengh in all notes - working_note = my_piano_notes; - for (note_counter = 0; note_counter < TOTAL_NOTES; note_counter += 1) - { - (working_note + note_counter)->note_strength = (double)0.0; - } - - for (bucket_counter = 0; bucket_counter < TOTAL_BUCKETS; bucket_counter += 1) - { - current_bucket = my_bucket_data + bucket_counter; - current_bucket->bucket_strength = goertzel(current_bucket->buffer_size, - current_bucket->bucket_frequency, - SAMPLE_RATE, - full_size_buffer); - current_bucket->this_piano_note->note_strength += current_bucket->bucket_strength; - - //Test print - fprintf(result_plot_file, - "%d %f\n", - bucket_counter, current_bucket->bucket_strength); - } - - working_note = my_piano_notes; - for (note_counter = 0; note_counter < TOTAL_NOTES; note_counter += 1) - { - fprintf(note_result_plot_file, "%d %f\n", note_counter, (working_note + note_counter)->note_strength); - } - - fclose (note_result_plot_file); - - //now find the strongest note - strongest_note = my_piano_notes; - working_note = my_piano_notes; - - // Update - first first strong note that stronger than 100. - - for (note_counter = 0; note_counter < TOTAL_NOTES; note_counter += 1) - { - if (working_note->note_strength > PIANO_MIN_VOLUME) + // Hold the last note briefly through consonants and breaths + unvoiced_frames += 1; + if (unvoiced_frames > PIANO_HOLD_FRAMES) { - strongest_note = working_note; - break; + current_note = -1; + note_history_count = 0; + note_history_index = 0; + my_piano_data_struct.frequency = 0.0; } - working_note += 1; } - my_piano_data_struct.keyboard_key = strongest_note->keyboard_key; - my_piano_data_struct.octive = strongest_note->octive; - my_piano_data_struct.done = 1; - - fclose (result_plot_file); - - // printf ("done process \n"); + 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() { - double current_bucket_frequency; - double previous_bucket_frequency; - int current_octive; - int current_bucket; - int current_note; - int bucket_in_note; - int note_in_octive; - double semi_interval; - struct bucket_data_struct *current_bucket_pointer; - struct piano_note_struct *current_note_pointer; - FILE *print_records; int array_counter; - - note_in_octive = 0; - current_bucket_frequency = (double)32.0; - previous_bucket_frequency = (double)32.0; - current_note = 0; - current_octive = 0; - bucket_in_note = 0; - - semi_interval = (double)(pow(2.0, 1.0/(double(BUCKETS_PER_OCTIVE)))); - - // printf("semi is %f\n", semi_interval); - - print_records = fopen("my_bucket_record","w"); - if (print_records == NULL) - { - printf ("cannot open records file \n"); - } // 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; - for (current_bucket = 0; current_bucket < TOTAL_BUCKETS; current_bucket += 1) + 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) { - // Set pointers to bucket structure - current_bucket_pointer = my_bucket_data + current_bucket; - // Set pointer to note - current_note_pointer = my_piano_notes + (int)(current_bucket / BUCKETS_PER_NOTE) + bucket_in_note; - // Fill out both bucket and note structures - current_bucket_pointer->this_piano_note = current_note_pointer; - current_bucket_pointer->bucket_strength = 0.0; - current_note_pointer->note_strength = 0.0; - current_note_pointer->keyboard_key = note_in_octive; - current_note_pointer->octive = current_octive; + note_history[array_counter] = 0.0; + } + note_history_count = 0; + note_history_index = 0; + current_note = -1; + unvoiced_frames = 0; - //Set current bucket frequency - //First is handled differently - if (current_bucket == 0) - { - current_bucket_pointer->bucket_frequency = current_bucket_frequency; - previous_bucket_frequency = current_bucket_frequency; - } - - else - { - current_bucket_frequency = previous_bucket_frequency * semi_interval; - previous_bucket_frequency = current_bucket_frequency; - } - - current_bucket_pointer->bucket_frequency = current_bucket_frequency; - - // Radians on cycle per sample - current_bucket_pointer->radians_per_sample = (double)RADIANS_PER_SAMPLE_AT_1_HZ * - (double)current_bucket_pointer->bucket_frequency; - - // Buffer size for this bucket's frequency - current_bucket_pointer->buffer_size = (int)((double)(SAMPLE_RATE)/ - current_bucket_pointer->bucket_frequency) * Q_QUALITY; - - //Verification prints - fprintf (print_records, "current bucket - %d; bucket in note - %d; note in octive - %d; current note %d; current octive - %d ; bucket_frequency - %f ; degree per sample - %f; buffer size - %d; which note - %d\n", - current_bucket, bucket_in_note, note_in_octive, current_note, current_octive, - current_bucket_pointer->bucket_frequency, current_bucket_pointer->radians_per_sample, - current_bucket_pointer->buffer_size, - (int)(current_bucket / BUCKETS_PER_NOTE)); - - // Bump up for next; reset if necessary - // Note frequency - - // Update bucket in note and note in octive - bucket_in_note += 1; - if (bucket_in_note == BUCKETS_PER_NOTE) - { - bucket_in_note = 0; - current_note += 1; - note_in_octive += 1; - if (note_in_octive == NOTES_PER_OCTIVE) - { - note_in_octive = 0; - current_octive += 1; - } - } + // 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; } - fclose(print_records); + // 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; } - diff --git a/scope.h b/scope.h index 1efaf56..fe3e75e 100644 --- a/scope.h +++ b/scope.h @@ -19,7 +19,6 @@ #define AUDIO_BUFFER_SIZE 6000 #define FFT_START_BUCKET 0 #define MAIN_VOLUME .01 -#define PIANO_MIN_VOLUME 100. #define SPECTRUM_VOLUME .1 #define PIANO_SIZE_MULTIPLY .35 #define KEYBOARD_POSITION_X 50 @@ -28,38 +27,52 @@ #define OCTIVE_POSITION_Y 10 #define NUMBER_KEY_LIGHTS 12 #define NUMBER_OCTIVE_LIGHTS 8 -#define RADIANS_PER_SAMPLE_AT_1_HZ (double)6.28319/(double)SAMPLE_RATE #define NUMBER_OCTIVES 6 -#define BUCKETS_PER_NOTE 2 #define NOTES_PER_OCTIVE 12 -#define BUCKETS_PER_OCTIVE BUCKETS_PER_NOTE*NOTES_PER_OCTIVE -#define TOTAL_BUCKETS BUCKETS_PER_OCTIVE*NUMBER_OCTIVES #define TOTAL_NOTES NOTES_PER_OCTIVE*NUMBER_OCTIVES -#define Q_QUALITY 6 -#define FIRST_FREQUENCY 32 -#define PIANO_FULL_ARRAY_SIZE FFT_BUFFER_SIZE -//Structure for piano notes -struct piano_note_struct { -double note_strength; -int keyboard_key; -int octive;; -}; - -//Structure for processing buckets -struct bucket_data_struct { -double bucket_frequency; -double bucket_strength; -int buffer_size; -double radians_per_sample; -struct piano_note_struct *this_piano_note; -}; +// Autocorrelation (McLeod NSDF) pitch detection settings, tuned for +// singing voice (the "piano" classes show the sung note on a keyboard) +// Analysis window: number of samples examined per pitch estimate. +// Must be a multiple of READ_BUFFER_SIZE and at least 2 * PIANO_MAX_LAG. +// It slides: each new read buffer shifts in and a new estimate is made. +#define PIANO_WINDOW_SIZE 4096 +#define PIANO_FULL_ARRAY_SIZE PIANO_WINDOW_SIZE +// FFT size for autocorrelation; power of 2 and >= 2 * PIANO_WINDOW_SIZE +// so that the circular correlation does not wrap around +#define ACF_FFT_SIZE 8192 +// Frequency of C1; note 0 (keyboard key 0, octive 0) is C1 +#define PIANO_REFERENCE_FREQ 32.70319566 +// Search range covering singing voice, low bass (~C2) to high soprano (~C6) +#define PIANO_MIN_FREQ 60.0 +#define PIANO_MAX_FREQ 1100.0 +#define PIANO_MIN_LAG ((int)((double)SAMPLE_RATE / PIANO_MAX_FREQ)) +#define PIANO_MAX_LAG ((int)((double)SAMPLE_RATE / PIANO_MIN_FREQ) + 1) +// Max number of candidate peaks tracked in the NSDF +#define PIANO_MAX_PEAKS 128 +// Silence gate: RMS of the (MAIN_VOLUME scaled) samples below this = no note +#define PIANO_MIN_RMS 5.0 +// Highest NSDF peak must reach this for the sound to count as pitched (0..1); +// rejects breath and unvoiced consonants (s, sh, f) +#define PIANO_CLARITY_THRESHOLD 0.8 +// Pick the first NSDF peak that is at least this fraction of the highest peak +#define PIANO_PEAK_THRESHOLD 0.9 +// Smoothing: median of the last few voiced estimates (removes single frame +// octave jumps) +#define PIANO_MEDIAN_SIZE 3 +// Hysteresis in semitones: the displayed note only changes once the sung +// pitch is more than this far from it (keeps vibrato from flickering) +#define PIANO_HYSTERESIS_SEMITONES 0.6 +// Keep showing the note through this many unvoiced frames before blanking +#define PIANO_HOLD_FRAMES 2 // Structure used by both piano and main classes struct piano_data_struct { -int keyboard_key; -int octive; +int keyboard_key; // 0 - 11 (C .. B); only meaningful when valid +int octive; // 0 - 5 (octave 1 .. 6); only meaningful when valid int done; +int valid; // 1 if a pitched note was detected, 0 for silence/noise +double frequency; // detected fundamental in Hz (0 when not valid) }; class main_window_class { @@ -282,16 +295,27 @@ class piano_process_class { ~piano_process_class(); int initialize_piano_data(); struct piano_data_struct *process_piano_data(Sint16 *input_buffer); - double goertzel(int num_samples, int target_frequency, int sample_rate, Sint16 *input_buffer); private: + int compute_nsdf(); + double find_fundamental_lag(); + double median_of_history(); + int note_to_key_and_octive(int note_number, int *keyboard_key, int *octive); + struct piano_data_struct my_piano_data_struct; - Sint16 *local_main_buffer; - int ctr1; - struct piano_note_struct my_piano_notes[TOTAL_NOTES]; - struct bucket_data_struct my_bucket_data[TOTAL_BUCKETS]; Sint16 full_size_buffer[PIANO_FULL_ARRAY_SIZE]; int main_buffer_read_count; - + double window_samples[PIANO_WINDOW_SIZE]; + double nsdf[PIANO_MAX_LAG + 2]; + double *acf_time; + fftw_complex *acf_freq; + fftw_plan acf_forward_plan; + fftw_plan acf_inverse_plan; + // Smoothing state + double note_history[PIANO_MEDIAN_SIZE]; // fractional note numbers + int note_history_count; + int note_history_index; + int current_note; // displayed note, -1 = none + int unvoiced_frames; }; #endif