01dfef25cad7c46caf1b47b498d0a0f8ec500057
[kugel-rb.git] / apps / plugins / pitch_detector.c
blob01dfef25cad7c46caf1b47b498d0a0f8ec500057
1 /**************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2008 Lechner Michael / smoking gnu
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 * ----------------------------------------------------------------------------
20 * INTRODUCTION:
21 * OK, this is an attempt to write an instrument tuner for rockbox.
22 * It uses a Schmitt trigger algorithm, which I copied from
23 * tuneit [ (c) 2004 Mario Lang <mlang@delysid.org> ], for detecting the
24 * fundamental freqency of a sound. A FFT algorithm would be more accurate
25 * but also much slower.
27 * TODO:
28 * - Adapt the Yin FFT algorithm, which would reduce complexity from O(n^2)
29 * to O(nlogn), theoretically reducing latency by a factor of ~10. -David
31 * MAJOR CHANGES:
32 * 08.03.2008 Started coding
33 * 21.03.2008 Pitch detection works more or less
34 * Button definitions for most targets added
35 * 02.04.2008 Proper GUI added
36 * Todo, Major Changes and Current Limitations added
37 * 08.19.2009 Brought the code up to date with current plugin standards
38 * Made it work more nicely with color, BW and grayscale
39 * Changed pitch detection to use the Yin algorithm (better
40 * detection, but slower -- would be ~4x faster with
41 * fixed point math, I think). Code was poached from the
42 * Aubio sound processing library (aubio.org). -David
43 * 08.31.2009 Lots of changes:
44 * Added a menu to tweak settings
45 * Converted everything to fixed point (greatly improving
46 * latency)
47 * Improved the display
48 * Improved efficiency with judicious use of cpu_boost, the
49 * backlight, and volume detection to limit unneeded
50 * calculation
51 * Fixed a problem that caused an octave-off error
52 * -David
53 * 05.14.2010 Multibuffer continuous recording with two buffers
56 * CURRENT LIMITATIONS:
57 * - No gapless recording. Strictly speaking true gappless isn't possible,
58 * since the algorithm takes longer to calculate than the length of the
59 * sample, but latency could be improved a bit with proper use of the DMA
60 * recording functions.
61 * - Due to how the Yin algorithm works, latency is higher for lower
62 * frequencies.
65 #include "plugin.h"
66 #include "lib/pluginlib_actions.h"
67 #include "lib/picture.h"
68 #include "lib/helper.h"
69 #include "pluginbitmaps/pitch_notes.h"
71 PLUGIN_HEADER
73 /* Some fixed point calculation stuff */
74 typedef int32_t fixed_data;
75 struct _fixed
77 fixed_data a;
79 typedef struct _fixed fixed;
80 #define FIXED_PRECISION 18
81 #define FP_MAX ((fixed) {0x7fffffff})
82 #define FP_MIN ((fixed) {-0x80000000})
83 #define int2fixed(x) ((fixed){(x) << FIXED_PRECISION})
84 #define int2mantissa(x) ((fixed){x})
85 #define fixed2int(x) ((int)((x).a >> FIXED_PRECISION))
86 #define fixed2float(x) (((float)(x).a) / ((float)(1 << FIXED_PRECISION)))
87 #define float2fixed(x) \
88 ((fixed){(fixed_data)(x * (float)(1 << FIXED_PRECISION))})
89 /* I adapted these ones from the Rockbox fixed point library */
90 #define fp_mul(x, y) \
91 ((fixed){(((int64_t)((x).a)) * ((int64_t)((y).a))) >> (FIXED_PRECISION)})
92 #define fp_div(x, y) \
93 ((fixed){(((int64_t)((x).a)) << (FIXED_PRECISION)) / ((int64_t)((y).a))})
94 /* Operators for fixed point */
95 #define fp_add(x, y) ((fixed){(x).a + (y).a})
96 #define fp_sub(x, y) ((fixed){(x).a - (y).a})
97 #define fp_shl(x, y) ((fixed){(x).a << y})
98 #define fp_shr(x, y) ((fixed){(x).a >> y})
99 #define fp_neg(x) ((fixed){-(x).a})
100 #define fp_gt(x, y) ((x).a > (y).a)
101 #define fp_gte(x, y) ((x).a >= (y).a)
102 #define fp_lt(x, y) ((x).a < (y).a)
103 #define fp_lte(x, y) ((x).a <= (y).a)
104 #define fp_sqr(x) fp_mul((x), (x))
105 #define fp_equal(x, y) ((x).a == (y).a)
106 #define fp_round(x) (fixed2int(fp_add((x), float2fixed(0.5))))
107 #define fp_data(x) ((x).a)
108 #define fp_frac(x) (fp_sub((x), int2fixed(fixed2int(x))))
109 #define FP_ZERO ((fixed){0})
110 #define FP_LOW ((fixed){2})
112 /* Some defines for converting between period and frequency */
114 /* I introduce some divisors in this because the fixed point */
115 /* variables aren't big enough to hold higher than a certain */
116 /* value. This loses a bit of precision but it means we */
117 /* don't have to use 32.32 variables (yikes). */
118 /* With an 18-bit decimal precision, the max value in the */
119 /* integer part is 8192. Divide 44100 by 7 and it'll fit in */
120 /* that variable. */
121 #define fp_period2freq(x) fp_div(int2fixed(sample_rate / 7), \
122 fp_div((x),int2fixed(7)))
123 #define fp_freq2period(x) fp_period2freq(x)
124 #define period2freq(x) (sample_rate / (x))
125 #define freq2period(x) period2freq(x)
127 #define sqr(x) ((x)*(x))
129 /* Some constants for tuning */
130 #define A_FREQ float2fixed(440.0f)
131 #define D_NOTE float2fixed(1.059463094359f)
132 #define LOG_D_NOTE float2fixed(1.0f/12.0f)
133 #define D_NOTE_SQRT float2fixed(1.029302236643f)
134 #define LOG_2 float2fixed(1.0f)
136 /* The recording buffer size */
137 /* This is how much is sampled at a time. */
138 /* It also determines latency -- if BUFFER_SIZE == sample_rate then */
139 /* there'll be one sample per second, or a latency of one second. */
140 /* Furthermore, the lowest detectable frequency will be about twice */
141 /* the number of reads per second */
142 /* If we ever switch to Yin FFT algorithm then this needs to be
143 a power of 2 */
144 #define BUFFER_SIZE 4096
145 #define SAMPLE_SIZE 4096
146 #define SAMPLE_SIZE_MIN 1024
147 #define YIN_BUFFER_SIZE (BUFFER_SIZE / 4)
149 #define LCD_FACTOR (fp_div(int2fixed(LCD_WIDTH), int2fixed(100)))
150 /* The threshold for the YIN algorithm */
151 #define DEFAULT_YIN_THRESHOLD 5 /* 0.10 */
152 const fixed yin_threshold_table[] =
154 float2fixed(0.01),
155 float2fixed(0.02),
156 float2fixed(0.03),
157 float2fixed(0.04),
158 float2fixed(0.05),
159 float2fixed(0.10),
160 float2fixed(0.15),
161 float2fixed(0.20),
162 float2fixed(0.25),
163 float2fixed(0.30),
164 float2fixed(0.35),
165 float2fixed(0.40),
166 float2fixed(0.45),
167 float2fixed(0.50),
170 /* Structure for the reference frequency (frequency of A)
171 * It's used for scaling the frequency before finding out
172 * the note. The frequency is scaled in a way that the main
173 * algorithm can assume the frequency of A to be 440 Hz.
175 struct freq_A_entry
177 const int frequency; /* Frequency in Hz */
178 const fixed ratio; /* 440/frequency */
179 const fixed logratio; /* log2(factor) */
182 const struct freq_A_entry freq_A[] =
184 {435, float2fixed(1.011363636), float2fixed( 0.016301812)},
185 {436, float2fixed(1.009090909), float2fixed( 0.013056153)},
186 {437, float2fixed(1.006818182), float2fixed( 0.009803175)},
187 {438, float2fixed(1.004545455), float2fixed( 0.006542846)},
188 {439, float2fixed(1.002272727), float2fixed( 0.003275132)},
189 {440, float2fixed(1.000000000), float2fixed( 0.000000000)},
190 {441, float2fixed(0.997727273), float2fixed(-0.003282584)},
191 {442, float2fixed(0.995454545), float2fixed(-0.006572654)},
192 {443, float2fixed(0.993181818), float2fixed(-0.009870244)},
193 {444, float2fixed(0.990909091), float2fixed(-0.013175389)},
194 {445, float2fixed(0.988636364), float2fixed(-0.016488123)},
197 /* Index of the entry for 440 Hz in the table (default frequency for A) */
198 #define DEFAULT_FREQ_A 5
199 #define NUM_FREQ_A (sizeof(freq_A)/sizeof(freq_A[0]))
201 /* How loud the audio has to be to start displaying pitch */
202 /* Must be between 0 and 100 */
203 #define VOLUME_THRESHOLD (50)
205 /* Change to AUDIO_SRC_LINEIN if you want to record from line-in */
206 #ifdef HAVE_MIC_IN
207 #define INPUT_TYPE AUDIO_SRC_MIC
208 #else
209 #define INPUT_TYPE AUDIO_SRC_LINEIN
210 #endif
212 /* How many decimal places to display for the Hz value */
213 #define DISPLAY_HZ_PRECISION 100
215 /* Where to put the various GUI elements */
216 int note_y;
217 int bar_grad_y;
218 #define LCD_RES_MIN (LCD_HEIGHT < LCD_WIDTH ? LCD_HEIGHT : LCD_WIDTH)
219 #define BAR_PADDING (LCD_RES_MIN / 32)
220 #define BAR_Y (LCD_HEIGHT * 3 / 4)
221 #define BAR_HEIGHT (LCD_RES_MIN / 4 - BAR_PADDING)
222 #define BAR_HLINE_Y (BAR_Y - BAR_PADDING)
223 #define BAR_HLINE_Y2 (BAR_Y + BAR_HEIGHT + BAR_PADDING - 1)
224 #define HZ_Y 0
225 #define GRADUATION 10 /* Subdivisions of the whole 100-cent scale */
227 /* Bitmaps for drawing the note names. These need to have height
228 <= (bar_grad_y - note_y), or 15/32 * LCD_HEIGHT
230 #define NUM_NOTE_IMAGES 9
231 #define NOTE_INDEX_A 0
232 #define NOTE_INDEX_B 1
233 #define NOTE_INDEX_C 2
234 #define NOTE_INDEX_D 3
235 #define NOTE_INDEX_E 4
236 #define NOTE_INDEX_F 5
237 #define NOTE_INDEX_G 6
238 #define NOTE_INDEX_SHARP 7
239 #define NOTE_INDEX_FLAT 8
240 const struct picture note_bitmaps =
242 pitch_notes,
243 BMPWIDTH_pitch_notes,
244 BMPHEIGHT_pitch_notes,
245 BMPHEIGHT_pitch_notes/NUM_NOTE_IMAGES
249 static unsigned int sample_rate;
250 static int audio_head = 0; /* which of the two buffers to use? */
251 static volatile int audio_tail = 0; /* which of the two buffers to record? */
252 /* It's stereo, so make the buffer twice as big */
253 #ifndef SIMULATOR
254 static int16_t audio_data[2][BUFFER_SIZE] __attribute__((aligned(CACHEALIGN_SIZE)));
255 static fixed yin_buffer[YIN_BUFFER_SIZE];
256 #endif
258 /* Description of a note of scale */
259 struct note_entry
261 const char *name; /* Name of the note, e.g. "A#" */
262 const fixed freq; /* Note frequency, Hz */
263 const fixed logfreq; /* log2(frequency) */
266 /* Notes within one (reference) scale */
267 static const struct note_entry notes[] =
269 {"A" , float2fixed(440.0000000f), float2fixed(8.781359714f)},
270 {"A#", float2fixed(466.1637615f), float2fixed(8.864693047f)},
271 {"B" , float2fixed(493.8833013f), float2fixed(8.948026380f)},
272 {"C" , float2fixed(523.2511306f), float2fixed(9.031359714f)},
273 {"C#", float2fixed(554.3652620f), float2fixed(9.114693047f)},
274 {"D" , float2fixed(587.3295358f), float2fixed(9.198026380f)},
275 {"D#", float2fixed(622.2539674f), float2fixed(9.281359714f)},
276 {"E" , float2fixed(659.2551138f), float2fixed(9.364693047f)},
277 {"F" , float2fixed(698.4564629f), float2fixed(9.448026380f)},
278 {"F#", float2fixed(739.9888454f), float2fixed(9.531359714f)},
279 {"G" , float2fixed(783.9908720f), float2fixed(9.614693047f)},
280 {"G#", float2fixed(830.6093952f), float2fixed(9.698026380f)},
283 /* GUI */
284 #if LCD_DEPTH > 1
285 static unsigned front_color;
286 #endif
287 static int font_w,font_h;
288 static int bar_x_0;
289 static int lbl_x_minus_50, lbl_x_minus_20, lbl_x_0, lbl_x_20, lbl_x_50;
291 /* Settings for the plugin */
292 struct tuner_settings
294 unsigned volume_threshold;
295 unsigned record_gain;
296 unsigned sample_size;
297 unsigned lowest_freq;
298 unsigned yin_threshold;
299 int freq_A; /* Index of the frequency of A */
300 bool use_sharps;
301 bool display_hz;
302 } tuner_settings;
304 /*=================================================================*/
305 /* Settings loading and saving(adapted from the clock plugin) */
306 /*=================================================================*/
308 #define SETTINGS_FILENAME PLUGIN_APPS_DIR "/.pitch_settings"
310 enum message
312 MESSAGE_LOADING,
313 MESSAGE_LOADED,
314 MESSAGE_ERRLOAD,
315 MESSAGE_SAVING,
316 MESSAGE_SAVED,
317 MESSAGE_ERRSAVE
320 enum settings_file_status
322 LOADED, ERRLOAD,
323 SAVED, ERRSAVE
326 /* The settings as they exist on the hard disk, so that
327 * we can know at saving time if changes have been made */
328 struct tuner_settings hdd_tuner_settings;
330 /*---------------------------------------------------------------------*/
332 bool settings_needs_saving(struct tuner_settings* settings)
334 return(rb->memcmp(settings, &hdd_tuner_settings, sizeof(*settings)));
337 /*---------------------------------------------------------------------*/
339 void tuner_settings_reset(struct tuner_settings* settings)
341 settings->volume_threshold = VOLUME_THRESHOLD;
342 settings->record_gain = rb->global_settings->rec_mic_gain;
343 settings->sample_size = BUFFER_SIZE;
344 settings->lowest_freq = period2freq(BUFFER_SIZE / 4);
345 settings->yin_threshold = DEFAULT_YIN_THRESHOLD;
346 settings->freq_A = DEFAULT_FREQ_A;
347 settings->use_sharps = true;
348 settings->display_hz = false;
351 /*---------------------------------------------------------------------*/
353 enum settings_file_status tuner_settings_load(struct tuner_settings* settings,
354 char* filename)
356 int fd = rb->open(filename, O_RDONLY);
357 if(fd >= 0){ /* does file exist? */
358 /* basic consistency check */
359 if(rb->filesize(fd) == sizeof(*settings)){
360 rb->read(fd, settings, sizeof(*settings));
361 rb->close(fd);
362 rb->memcpy(&hdd_tuner_settings, settings, sizeof(*settings));
363 return(LOADED);
366 /* Initializes the settings with default values at least */
367 tuner_settings_reset(settings);
368 return(ERRLOAD);
371 /*---------------------------------------------------------------------*/
373 enum settings_file_status tuner_settings_save(struct tuner_settings* settings,
374 char* filename)
376 int fd = rb->creat(filename, 0666);
377 if(fd >= 0){ /* does file exist? */
378 rb->write (fd, settings, sizeof(*settings));
379 rb->close(fd);
380 return(SAVED);
382 return(ERRSAVE);
385 /*---------------------------------------------------------------------*/
387 void load_settings(void)
389 tuner_settings_load(&tuner_settings, SETTINGS_FILENAME);
391 rb->storage_sleep();
394 /*---------------------------------------------------------------------*/
396 void save_settings(void)
398 if(!settings_needs_saving(&tuner_settings))
399 return;
401 tuner_settings_save(&tuner_settings, SETTINGS_FILENAME);
404 /*=================================================================*/
405 /* MENU */
406 /*=================================================================*/
408 /* Keymaps */
409 const struct button_mapping* plugin_contexts[]={
410 generic_actions,
411 generic_increase_decrease,
412 generic_directions,
413 #if NB_SCREENS == 2
414 remote_directions
415 #endif
417 #define PLA_ARRAY_COUNT sizeof(plugin_contexts)/sizeof(plugin_contexts[0])
419 /* Option strings */
421 /* This has to match yin_threshold_table */
422 static const struct opt_items yin_threshold_text[] =
424 { "0.01", -1 },
425 { "0.02", -1 },
426 { "0.03", -1 },
427 { "0.04", -1 },
428 { "0.05", -1 },
429 { "0.10", -1 },
430 { "0.15", -1 },
431 { "0.20", -1 },
432 { "0.25", -1 },
433 { "0.30", -1 },
434 { "0.35", -1 },
435 { "0.40", -1 },
436 { "0.45", -1 },
437 { "0.50", -1 },
440 static const struct opt_items accidental_text[] =
442 { "Flat", -1 },
443 { "Sharp", -1 },
446 void set_min_freq(int new_freq)
448 tuner_settings.sample_size = freq2period(new_freq) * 4;
450 /* clamp the sample size between min and max */
451 if(tuner_settings.sample_size <= SAMPLE_SIZE_MIN)
452 tuner_settings.sample_size = SAMPLE_SIZE_MIN;
453 else if(tuner_settings.sample_size >= BUFFER_SIZE)
454 tuner_settings.sample_size = BUFFER_SIZE;
456 /* sample size must be divisible by 4 - round up */
457 tuner_settings.sample_size = (tuner_settings.sample_size + 3) & ~3;
460 bool main_menu(void)
462 int selection = 0;
463 bool done = false;
464 bool exit_tuner = false;
465 int choice;
466 int freq_val;
467 bool reset;
469 backlight_use_settings();
470 #ifdef HAVE_SCHEDULER_BOOSTCTRL
471 rb->cancel_cpu_boost();
472 #endif
474 MENUITEM_STRINGLIST(menu,"Tuner Settings",NULL,
475 "Return to Tuner",
476 "Volume Threshold",
477 "Listening Volume",
478 "Lowest Frequency",
479 "Algorithm Pickiness",
480 "Accidentals",
481 "Display Frequency (Hz)",
482 "Frequency of A (Hz)",
483 "Reset Settings",
484 "Quit");
486 while(!done)
488 choice = rb->do_menu(&menu, &selection, NULL, false);
489 switch(choice)
491 case 1:
492 rb->set_int("Volume Threshold", "%", UNIT_INT,
493 &tuner_settings.volume_threshold,
494 NULL, 5, 5, 95, NULL);
495 break;
496 case 2:
497 rb->set_int("Listening Volume", "%", UNIT_INT,
498 &tuner_settings.record_gain,
499 NULL, 1, rb->sound_min(SOUND_MIC_GAIN),
500 rb->sound_max(SOUND_MIC_GAIN), NULL);
501 break;
502 case 3:
503 rb->set_int("Lowest Frequency", "Hz", UNIT_INT,
504 &tuner_settings.lowest_freq, set_min_freq, 1,
505 /* Range depends on the size of the buffer */
506 sample_rate / (BUFFER_SIZE / 4),
507 sample_rate / (SAMPLE_SIZE_MIN / 4), NULL);
508 break;
509 case 4:
510 rb->set_option(
511 "Algorithm Pickiness (Lower -> more discriminating)",
512 &tuner_settings.yin_threshold,
513 INT, yin_threshold_text,
514 sizeof(yin_threshold_text) / sizeof(yin_threshold_text[0]),
515 NULL);
516 break;
517 case 5:
518 rb->set_option("Display Accidentals As",
519 &tuner_settings.use_sharps,
520 BOOL, accidental_text, 2, NULL);
521 break;
522 case 6:
523 rb->set_bool("Display Frequency (Hz)",
524 &tuner_settings.display_hz);
525 break;
526 case 7:
527 freq_val = freq_A[tuner_settings.freq_A].frequency;
528 rb->set_int("Frequency of A (Hz)",
529 "Hz", UNIT_INT, &freq_val, NULL,
530 1, freq_A[0].frequency, freq_A[NUM_FREQ_A-1].frequency,
531 NULL);
532 tuner_settings.freq_A = freq_val - freq_A[0].frequency;
533 break;
534 case 8:
535 reset = false;
536 rb->set_bool("Reset Tuner Settings?", &reset);
537 if (reset)
538 tuner_settings_reset(&tuner_settings);
539 break;
540 case 9:
541 exit_tuner = true;
542 done = true;
543 break;
544 case 0:
545 default:
546 /* Return to the tuner */
547 done = true;
548 break;
552 backlight_force_on();
553 return exit_tuner;
556 /*=================================================================*/
557 /* Binary Log */
558 /*=================================================================*/
560 /* Fixed-point log base 2*/
561 /* Adapted from python code at
562 http://en.wikipedia.org/wiki/Binary_logarithm#Algorithm
564 fixed log(fixed inp)
566 fixed x = inp;
567 fixed fp = int2fixed(1);
568 fixed res = int2fixed(0);
570 if(fp_lte(x, FP_ZERO))
572 return FP_MIN;
575 /* Integer part*/
576 /* while x<1 */
577 while(fp_lt(x, int2fixed(1)))
579 res = fp_sub(res, int2fixed(1));
580 x = fp_shl(x, 1);
582 /* while x>=2 */
583 while(fp_gte(x, int2fixed(2)))
585 res = fp_add(res, int2fixed(1));
586 x = fp_shr(x, 1);
589 /* Fractional part */
590 /* while fp > 0 */
591 while(fp_gt(fp, FP_ZERO))
593 fp = fp_shr(fp, 1);
594 x = fp_mul(x, x);
595 /* if x >= 2 */
596 if(fp_gte(x, int2fixed(2)))
598 x = fp_shr(x, 1);
599 res = fp_add(res, fp);
603 return res;
606 /*=================================================================*/
607 /* GUI Stuff */
608 /*=================================================================*/
610 /* The function name is pretty self-explaining ;) */
611 void print_int_xy(int x, int y, int v)
613 char temp[20];
614 #if LCD_DEPTH > 1
615 rb->lcd_set_foreground(front_color);
616 #endif
617 rb->snprintf(temp,20,"%d",v);
618 rb->lcd_putsxy(x,y,temp);
621 /* Print out the frequency etc */
622 void print_str(char* s)
624 #if LCD_DEPTH > 1
625 rb->lcd_set_foreground(front_color);
626 #endif
627 rb->lcd_putsxy(0, HZ_Y, s);
630 /* What can I say? Read the function name... */
631 void print_char_xy(int x, int y, char c)
633 char temp[2];
635 temp[0]=c;
636 temp[1]=0;
637 #if LCD_DEPTH > 1
638 rb->lcd_set_foreground(front_color);
639 #endif
641 rb->lcd_putsxy(x, y, temp);
644 /* Draw the note bitmap */
645 void draw_note(const char *note)
647 int i;
648 int note_x = (LCD_WIDTH - BMPWIDTH_pitch_notes) / 2;
649 int accidental_index = NOTE_INDEX_SHARP;
651 i = note[0]-'A';
653 if(note[1] == '#')
655 if(!(tuner_settings.use_sharps))
657 i = (i + 1) % 7;
658 accidental_index = NOTE_INDEX_FLAT;
661 vertical_picture_draw_sprite(rb->screens[0],
662 &note_bitmaps,
663 accidental_index,
664 LCD_WIDTH / 2,
665 note_y);
666 note_x = LCD_WIDTH / 2 - BMPWIDTH_pitch_notes;
669 vertical_picture_draw_sprite(rb->screens[0], &note_bitmaps, i,
670 note_x,
671 note_y);
673 /* Draw the red bar and the white lines */
674 void draw_bar(fixed wrong_by_cents)
676 unsigned n;
677 int x;
679 #ifdef HAVE_LCD_COLOR
680 rb->lcd_set_foreground(LCD_RGBPACK(255,255,255)); /* Color screens */
681 #elif LCD_DEPTH > 1
682 rb->lcd_set_foreground(LCD_BLACK); /* Greyscale screens */
683 #endif
685 rb->lcd_hline(0,LCD_WIDTH-1, BAR_HLINE_Y);
686 rb->lcd_hline(0,LCD_WIDTH-1, BAR_HLINE_Y2);
688 /* Draw graduation lines on the off-by readout */
689 for(n = 0; n <= GRADUATION; n++)
691 x = (LCD_WIDTH * n + GRADUATION / 2) / GRADUATION;
692 if (x >= LCD_WIDTH)
693 x = LCD_WIDTH - 1;
694 rb->lcd_vline(x, BAR_HLINE_Y, BAR_HLINE_Y2);
697 print_int_xy(lbl_x_minus_50 ,bar_grad_y, -50);
698 print_int_xy(lbl_x_minus_20 ,bar_grad_y, -20);
699 print_int_xy(lbl_x_0 ,bar_grad_y, 0);
700 print_int_xy(lbl_x_20 ,bar_grad_y, 20);
701 print_int_xy(lbl_x_50 ,bar_grad_y, 50);
703 #ifdef HAVE_LCD_COLOR
704 rb->lcd_set_foreground(LCD_RGBPACK(255,0,0)); /* Color screens */
705 #elif LCD_DEPTH > 1
706 rb->lcd_set_foreground(LCD_DARKGRAY); /* Greyscale screens */
707 #endif
709 if (fp_gt(wrong_by_cents, FP_ZERO))
711 rb->lcd_fillrect(bar_x_0, BAR_Y,
712 fixed2int(fp_mul(wrong_by_cents, LCD_FACTOR)), BAR_HEIGHT);
714 else
716 rb->lcd_fillrect(bar_x_0 + fixed2int(fp_mul(wrong_by_cents,LCD_FACTOR)),
717 BAR_Y,
718 fixed2int(fp_mul(wrong_by_cents, LCD_FACTOR)) * -1,
719 BAR_HEIGHT);
723 /* Calculate how wrong the note is and draw the GUI */
724 void display_frequency (fixed freq)
726 fixed ldf, mldf;
727 fixed lfreq, nfreq;
728 fixed orig_freq;
729 int i, note = 0;
730 char str_buf[30];
732 if (fp_lt(freq, FP_LOW))
733 freq = FP_LOW;
735 /* We calculate the frequency and its log as if */
736 /* the reference frequency of A were 440 Hz. */
737 orig_freq = freq;
738 lfreq = fp_add(log(freq), freq_A[tuner_settings.freq_A].logratio);
739 freq = fp_mul(freq, freq_A[tuner_settings.freq_A].ratio);
741 /* This calculates a log freq offset for note A */
742 /* Get the frequency to within the range of our reference table, */
743 /* i.e. into the right octave. */
744 while (fp_lt(lfreq, fp_sub(notes[0].logfreq, fp_shr(LOG_D_NOTE, 1))))
745 lfreq = fp_add(lfreq, LOG_2);
746 while (fp_gte(lfreq, fp_sub(fp_add(notes[0].logfreq, LOG_2),
747 fp_shr(LOG_D_NOTE, 1))))
748 lfreq = fp_sub(lfreq, LOG_2);
749 mldf = LOG_D_NOTE;
750 for (i=0; i<12; i++)
752 ldf = fp_gt(fp_sub(lfreq,notes[i].logfreq), FP_ZERO) ?
753 fp_sub(lfreq,notes[i].logfreq) : fp_neg(fp_sub(lfreq,notes[i].logfreq));
754 if (fp_lt(ldf, mldf))
756 mldf = ldf;
757 note = i;
760 nfreq = notes[note].freq;
761 while (fp_gt(fp_div(nfreq, freq), D_NOTE_SQRT))
762 nfreq = fp_shr(nfreq, 1);
764 while (fp_gt(fp_div(freq, nfreq), D_NOTE_SQRT))
765 nfreq = fp_shl(nfreq, 1);
767 ldf = fp_mul(int2fixed(1200), log(fp_div(freq,nfreq)));
769 rb->lcd_clear_display();
770 draw_bar(ldf); /* The red bar */
771 if(fp_round(freq) != 0)
773 draw_note(notes[note].name);
774 if(tuner_settings.display_hz)
776 rb->snprintf(str_buf,30, "%s : %d cents (%d.%02dHz)",
777 notes[note].name, fp_round(ldf) ,fixed2int(orig_freq),
778 fp_round(fp_mul(fp_frac(orig_freq),
779 int2fixed(DISPLAY_HZ_PRECISION))));
780 print_str(str_buf);
783 rb->lcd_update();
786 /*-----------------------------------------------------------------------
787 * Functions for the Yin algorithm
789 * These were all adapted from the versions in Aubio v0.3.2
790 * Here's what the Aubio documentation has to say:
792 * This algorithm was developped by A. de Cheveigne and H. Kawahara and
793 * published in:
795 * de Cheveign?, A., Kawahara, H. (2002) "YIN, a fundamental frequency
796 * estimator for speech and music", J. Acoust. Soc. Am. 111, 1917-1930.
798 * see http://recherche.ircam.fr/equipes/pcm/pub/people/cheveign.html
799 -------------------------------------------------------------------------*/
801 /* Find the index of the minimum element of an array of floats */
802 unsigned vec_min_elem(fixed *s, unsigned buflen)
804 unsigned j, pos=0.0f;
805 fixed tmp = s[0];
806 for (j=0; j < buflen; j++)
808 if(fp_gt(tmp, s[j]))
810 pos = j;
811 tmp = s[j];
814 return pos;
818 fixed aubio_quadfrac(fixed s0, fixed s1, fixed s2, fixed pf)
820 /* Original floating point version: */
821 /* tmp = s0 + (pf/2.0f) * (pf * ( s0 - 2.0f*s1 + s2 ) -
822 3.0f*s0 + 4.0f*s1 - s2);*/
823 /* Converted to explicit operator precedence: */
824 /* tmp = s0 + ((pf/2.0f) * ((((pf * ((s0 - (2*s1)) + s2)) -
825 (3*s0)) + (4*s1)) - s2)); */
827 /* I made it look like this so I could easily track the precedence and */
828 /* make sure it matched the original expression */
829 /* Oy, this is when I really wish I could do C++ operator overloading */
830 fixed tmp = fp_add
833 fp_mul
835 fp_shr(pf, 1),
836 fp_sub
838 fp_add
840 fp_sub
842 fp_mul
845 fp_add
847 fp_sub
850 fp_shl(s1, 1)
855 fp_mul
857 float2fixed(3.0f),
861 fp_shl(s1, 2)
867 return tmp;
870 #define QUADINT_STEP float2fixed(1.0f/200.0f)
872 fixed vec_quadint_min(fixed *x, unsigned bufsize, unsigned pos, unsigned span)
874 fixed res, frac, s0, s1, s2;
875 fixed exactpos = int2fixed(pos);
876 /* init resold to something big (in case x[pos+-span]<0)) */
877 fixed resold = FP_MAX;
879 if ((pos > span) && (pos < bufsize-span))
881 s0 = x[pos-span];
882 s1 = x[pos] ;
883 s2 = x[pos+span];
884 /* increase frac */
885 for (frac = float2fixed(0.0f);
886 fp_lt(frac, float2fixed(2.0f));
887 frac = fp_add(frac, QUADINT_STEP))
889 res = aubio_quadfrac(s0, s1, s2, frac);
890 if (fp_lt(res, resold))
892 resold = res;
894 else
896 /* exactpos += (frac-QUADINT_STEP)*span - span/2.0f; */
897 exactpos = fp_add(exactpos,
898 fp_sub(
899 fp_mul(
900 fp_sub(frac, QUADINT_STEP),
901 int2fixed(span)
903 int2fixed(span)
906 break;
910 return exactpos;
914 /* Calculate the period of the note in the
915 buffer using the YIN algorithm */
916 /* The yin pointer is just a buffer that the algorithm uses as a work
917 space. It needs to be half the length of the input buffer. */
919 fixed pitchyin(int16_t *input, fixed *yin)
921 fixed retval;
922 unsigned j,tau = 0;
923 int period;
924 unsigned yin_size = tuner_settings.sample_size / 4;
926 fixed tmp = FP_ZERO, tmp2 = FP_ZERO;
927 yin[0] = int2fixed(1);
928 for (tau = 1; tau < yin_size; tau++)
930 yin[tau] = FP_ZERO;
931 for (j = 0; j < yin_size; j++)
933 tmp = fp_sub(int2mantissa(input[2 * j]),
934 int2mantissa(input[2 * (j + tau)]));
935 yin[tau] = fp_add(yin[tau], fp_mul(tmp, tmp));
937 tmp2 = fp_add(tmp2, yin[tau]);
938 if(!fp_equal(tmp2, FP_ZERO))
940 yin[tau] = fp_mul(yin[tau], fp_div(int2fixed(tau), tmp2));
942 period = tau - 3;
943 if(tau > 4 && fp_lt(yin[period],
944 yin_threshold_table[tuner_settings.yin_threshold])
945 && fp_lt(yin[period], yin[period+1]))
947 retval = vec_quadint_min(yin, yin_size, period, 1);
948 return retval;
951 retval = vec_quadint_min(yin, yin_size,
952 vec_min_elem(yin, yin_size), 1);
953 return retval;
954 /*return FP_ZERO;*/
957 /*-----------------------------------------------------------------*/
959 uint32_t buffer_magnitude(int16_t *input)
961 unsigned n;
962 uint64_t tally = 0;
964 /* Operate on only one channel of the stereo signal */
965 for(n = 0; n < tuner_settings.sample_size; n+=2)
967 int s = input[n];
968 tally += s * s;
971 tally /= tuner_settings.sample_size / 2;
973 /* now tally holds the average of the squares of all the samples */
974 /* It must be between 0 and 0x7fff^2, so it fits in 32 bits */
975 return (uint32_t)tally;
978 /* Stop the recording when the buffer is full */
979 #ifndef SIMULATOR
980 int recording_callback(int status)
982 int tail = audio_tail ^ 1;
984 /* Do not overrun the reader. Reuse current buffer if full. */
985 if (tail != audio_head)
986 audio_tail = tail;
988 /* Always record full buffer, even if not required */
989 rb->pcm_record_more(audio_data[tail],
990 BUFFER_SIZE * sizeof (int16_t));
992 return 0;
993 (void)status;
995 #endif
997 /* Start recording */
998 static void record_data(void)
1000 #ifndef SIMULATOR
1001 /* Always record full buffer, even if not required */
1002 rb->pcm_record_data(recording_callback, audio_data[audio_tail],
1003 BUFFER_SIZE * sizeof (int16_t));
1004 #endif
1007 /* The main program loop */
1008 void record_and_get_pitch(void)
1010 int quit=0, button;
1011 bool redraw = true;
1012 /* For tracking the latency */
1014 long timer;
1015 char debug_string[20];
1017 #ifndef SIMULATOR
1018 fixed period;
1019 bool waiting = false;
1020 #else
1021 audio_tail = 1;
1022 #endif
1024 backlight_force_on();
1026 record_data();
1028 while(!quit)
1030 while (audio_head == audio_tail && !quit) /* wait for the buffer to be filled */
1032 button=pluginlib_getaction(HZ/100, plugin_contexts, PLA_ARRAY_COUNT);
1034 switch(button)
1036 case PLA_QUIT:
1037 quit=true;
1038 break;
1040 case PLA_MENU:
1041 rb->pcm_stop_recording();
1042 quit = main_menu() != 0;
1043 if(!quit)
1045 redraw = true;
1046 record_data();
1048 break;
1050 break;
1054 if(!quit)
1056 #ifndef SIMULATOR
1057 /* Only do the heavy lifting if the volume is high enough */
1058 if(buffer_magnitude(audio_data[audio_head]) >
1059 sqr(tuner_settings.volume_threshold *
1060 rb->sound_max(SOUND_MIC_GAIN)))
1062 waiting = false;
1063 redraw = false;
1065 #ifdef HAVE_SCHEDULER_BOOSTCTRL
1066 rb->trigger_cpu_boost();
1067 #endif
1069 /* This returns the period of the detected pitch in samples */
1070 period = pitchyin(audio_data[audio_head], yin_buffer);
1071 /* Hz = sample rate / period */
1072 if(fp_gt(period, FP_ZERO))
1074 display_frequency(fp_period2freq(period));
1076 else
1078 display_frequency(FP_ZERO);
1081 else if(redraw || !waiting)
1083 waiting = true;
1084 redraw = false;
1085 display_frequency(FP_ZERO);
1086 #ifdef HAVE_ADJUSTABLE_CPU_FREQ
1087 rb->cancel_cpu_boost();
1088 #endif
1091 /* Move to next buffer if not empty (but empty *shouldn't* happen
1092 * here). */
1093 if (audio_head != audio_tail)
1094 audio_head ^= 1;
1095 #else /* SIMULATOR */
1096 /* Display a preselected frequency */
1097 display_frequency(int2fixed(445));
1098 #endif
1101 rb->pcm_close_recording();
1102 #ifdef HAVE_SCHEDULER_BOOSTCTRL
1103 rb->cancel_cpu_boost();
1104 #endif
1106 backlight_use_settings();
1109 /* Init recording, tuning, and GUI */
1110 void init_everything(void)
1112 load_settings();
1114 /* Stop all playback */
1115 rb->plugin_get_audio_buffer(NULL);
1117 /* --------- Init the audio recording ----------------- */
1118 rb->audio_set_output_source(AUDIO_SRC_PLAYBACK);
1119 rb->audio_set_input_source(INPUT_TYPE, SRCF_RECORDING);
1121 /* set to maximum gain */
1122 rb->audio_set_recording_gain(tuner_settings.record_gain,
1123 tuner_settings.record_gain,
1124 AUDIO_GAIN_MIC);
1126 /* Highest C on piano is approx 4.186 kHz, so we need just over
1127 * 8.372 kHz to pass it. */
1128 sample_rate = rb->round_value_to_list32(9000, rb->rec_freq_sampr,
1129 REC_NUM_FREQ, false);
1130 sample_rate = rb->rec_freq_sampr[sample_rate];
1131 rb->pcm_set_frequency(sample_rate);
1132 rb->pcm_init_recording();
1134 /* GUI */
1135 #if LCD_DEPTH > 1
1136 front_color = rb->lcd_get_foreground();
1137 #endif
1138 rb->lcd_getstringsize("X", &font_w, &font_h);
1140 bar_x_0 = LCD_WIDTH / 2;
1141 lbl_x_minus_50 = 0;
1142 lbl_x_minus_20 = (LCD_WIDTH / 2) -
1143 fixed2int(fp_mul(LCD_FACTOR, int2fixed(20))) - font_w;
1144 lbl_x_0 = (LCD_WIDTH - font_w) / 2;
1145 lbl_x_20 = (LCD_WIDTH / 2) +
1146 fixed2int(fp_mul(LCD_FACTOR, int2fixed(20))) - font_w;
1147 lbl_x_50 = LCD_WIDTH - 2 * font_w;
1149 bar_grad_y = BAR_Y - BAR_PADDING - font_h;
1150 /* Put the note right between the top and bottom text elements */
1151 note_y = ((font_h + bar_grad_y - note_bitmaps.slide_height) / 2);
1155 enum plugin_status plugin_start(const void* parameter) NO_PROF_ATTR
1157 (void)parameter;
1159 init_everything();
1160 record_and_get_pitch();
1161 save_settings();
1163 return 0;