More FFT fun: No point in computing and combining the 2nd FFT if it's just being...
[kugel-rb.git] / apps / plugins / fft / fft.c
blob28e775a9c156315a0e1dcd60e217d529b06e2151
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2009 Delyan Kratunov
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
21 #include "plugin.h"
23 #include "lib/helper.h"
24 #include "lib/xlcd.h"
25 #include "math.h"
26 #include "fracmul.h"
28 #ifndef HAVE_LCD_COLOR
29 #include "lib/grey.h"
30 #endif
32 PLUGIN_HEADER
34 #ifndef HAVE_LCD_COLOR
35 GREY_INFO_STRUCT
36 #endif
38 #if CONFIG_KEYPAD == ARCHOS_AV300_PAD
39 # define FFT_PREV_GRAPH BUTTON_LEFT
40 # define FFT_NEXT_GRAPH BUTTON_RIGHT
41 # define FFT_ORIENTATION BUTTON_F3
42 # define FFT_WINDOW BUTTON_F1
43 # define FFT_AMP_SCALE BUTTON_UP
44 # define FFT_QUIT BUTTON_OFF
46 #elif (CONFIG_KEYPAD == IRIVER_H100_PAD) || \
47 (CONFIG_KEYPAD == IRIVER_H300_PAD)
48 # define FFT_PREV_GRAPH BUTTON_LEFT
49 # define FFT_NEXT_GRAPH BUTTON_RIGHT
50 # define FFT_ORIENTATION BUTTON_REC
51 # define FFT_WINDOW BUTTON_SELECT
52 # define FFT_AMP_SCALE BUTTON_UP
53 # define FFT_FREQ_SCALE BUTTON_DOWN
54 # define FFT_QUIT BUTTON_OFF
56 #elif (CONFIG_KEYPAD == IPOD_4G_PAD) || \
57 (CONFIG_KEYPAD == IPOD_3G_PAD) || \
58 (CONFIG_KEYPAD == IPOD_1G2G_PAD)
59 # define MINESWP_SCROLLWHEEL
60 # define FFT_PREV_GRAPH BUTTON_LEFT
61 # define FFT_NEXT_GRAPH BUTTON_RIGHT
62 # define FFT_ORIENTATION (BUTTON_SELECT | BUTTON_LEFT)
63 # define FFT_WINDOW (BUTTON_SELECT | BUTTON_RIGHT)
64 # define FFT_AMP_SCALE BUTTON_MENU
65 # define FFT_FREQ_SCALE BUTTON_PLAY
66 # define FFT_QUIT (BUTTON_SELECT | BUTTON_MENU)
68 #elif (CONFIG_KEYPAD == IAUDIO_X5M5_PAD)
69 # define FFT_PREV_GRAPH BUTTON_LEFT
70 # define FFT_NEXT_GRAPH BUTTON_RIGHT
71 # define FFT_ORIENTATION BUTTON_SELECT
72 # define FFT_WINDOW BUTTON_PLAY
73 # define FFT_AMP_SCALE BUTTON_UP
74 # define FFT_FREQ_SCALE BUTTON_DOWN
75 # define FFT_QUIT BUTTON_POWER
77 #elif (CONFIG_KEYPAD == GIGABEAT_PAD)
78 # define FFT_PREV_GRAPH BUTTON_LEFT
79 # define FFT_NEXT_GRAPH BUTTON_RIGHT
80 # define FFT_AMP_SCALE BUTTON_UP
81 # define FFT_FREQ_SCALE BUTTON_DOWN
82 # define FFT_ORIENTATION BUTTON_SELECT
83 # define FFT_WINDOW BUTTON_A
84 # define FFT_QUIT BUTTON_POWER
86 #elif (CONFIG_KEYPAD == SANSA_E200_PAD)
87 # define FFT_PREV_GRAPH BUTTON_LEFT
88 # define FFT_NEXT_GRAPH BUTTON_RIGHT
89 # define FFT_ORIENTATION BUTTON_SELECT
90 # define FFT_WINDOW BUTTON_REC
91 # define FFT_AMP_SCALE BUTTON_UP
92 # define FFT_FREQ_SCALE BUTTON_DOWN
93 # define FFT_QUIT BUTTON_POWER
95 #elif (CONFIG_KEYPAD == SANSA_FUZE_PAD)
96 # define FFT_PREV_GRAPH BUTTON_LEFT
97 # define FFT_NEXT_GRAPH BUTTON_RIGHT
98 # define FFT_ORIENTATION (BUTTON_SELECT | BUTTON_LEFT)
99 # define FFT_WINDOW (BUTTON_SELECT | BUTTON_RIGHT)
100 # define FFT_AMP_SCALE BUTTON_UP
101 # define FFT_FREQ_SCALE BUTTON_DOWN
102 # define FFT_QUIT (BUTTON_HOME|BUTTON_REPEAT)
104 #elif (CONFIG_KEYPAD == SANSA_C200_PAD)
105 # define FFT_PREV_GRAPH BUTTON_LEFT
106 # define FFT_NEXT_GRAPH BUTTON_RIGHT
107 # define FFT_ORIENTATION BUTTON_UP
108 # define FFT_WINDOW BUTTON_REC
109 # define FFT_AMP_SCALE BUTTON_SELECT
110 # define FFT_QUIT BUTTON_POWER
111 #elif (CONFIG_KEYPAD == SANSA_M200_PAD)
112 # define FFT_PREV_GRAPH BUTTON_LEFT
113 # define FFT_NEXT_GRAPH BUTTON_RIGHT
114 # define FFT_ORIENTATION BUTTON_UP
115 # define FFT_WINDOW BUTTON_DOWN
116 # define FFT_AMP_SCALE BUTTON_SELECT
117 # define FFT_QUIT BUTTON_POWER
118 #elif (CONFIG_KEYPAD == SANSA_CLIP_PAD)
119 # define FFT_PREV_GRAPH BUTTON_LEFT
120 # define FFT_NEXT_GRAPH BUTTON_RIGHT
121 # define FFT_ORIENTATION BUTTON_UP
122 # define FFT_WINDOW BUTTON_HOME
123 # define FFT_AMP_SCALE BUTTON_SELECT
124 # define FFT_QUIT BUTTON_POWER
126 #elif (CONFIG_KEYPAD == IRIVER_H10_PAD)
127 # define FFT_PREV_GRAPH BUTTON_LEFT
128 # define FFT_NEXT_GRAPH BUTTON_RIGHT
129 # define FFT_ORIENTATION BUTTON_FF
130 # define FFT_WINDOW BUTTON_SCROLL_UP
131 # define FFT_AMP_SCALE BUTTON_REW
132 # define FFT_FREQ_SCALE BUTTON_PLAY
133 # define FFT_QUIT BUTTON_POWER
135 #elif (CONFIG_KEYPAD == GIGABEAT_S_PAD)
136 # define FFT_PREV_GRAPH BUTTON_LEFT
137 # define FFT_NEXT_GRAPH BUTTON_RIGHT
138 # define FFT_ORIENTATION BUTTON_MENU
139 # define FFT_WINDOW BUTTON_PREV
140 # define FFT_AMP_SCALE BUTTON_UP
141 # define FFT_FREQ_SCALE BUTTON_DOWN
142 # define FFT_QUIT BUTTON_BACK
144 #elif (CONFIG_KEYPAD == MROBE100_PAD)
145 # define FFT_PREV_GRAPH BUTTON_LEFT
146 # define FFT_NEXT_GRAPH BUTTON_RIGHT
147 # define FFT_ORIENTATION BUTTON_PLAY
148 # define FFT_WINDOW BUTTON_SELECT
149 # define FFT_AMP_SCALE BUTTON_UP
150 # define FFT_FREQ_SCALE BUTTON_DOWN
151 # define FFT_QUIT BUTTON_POWER
153 #elif CONFIG_KEYPAD == IAUDIO_M3_PAD
154 # define FFT_PREV_GRAPH BUTTON_RC_REW
155 # define FFT_NEXT_GRAPH BUTTON_RC_FF
156 # define FFT_ORIENTATION BUTTON_RC_MODE
157 # define FFT_WINDOW BUTTON_RC_PLAY
158 # define FFT_AMP_SCALE BUTTON_RC_VOL_UP
159 # define FFT_QUIT BUTTON_RC_REC
161 #elif (CONFIG_KEYPAD == COWON_D2_PAD)
162 # define FFT_QUIT BUTTON_POWER
163 # define FFT_PREV_GRAPH BUTTON_PLUS
164 # define FFT_NEXT_GRAPH BUTTON_MINUS
166 #elif CONFIG_KEYPAD == CREATIVEZVM_PAD
167 # define FFT_PREV_GRAPH BUTTON_LEFT
168 # define FFT_NEXT_GRAPH BUTTON_RIGHT
169 # define FFT_ORIENTATION BUTTON_MENU
170 # define FFT_WINDOW BUTTON_SELECT
171 # define FFT_AMP_SCALE BUTTON_UP
172 # define FFT_FREQ_SCALE BUTTON_DOWN
173 # define FFT_QUIT BUTTON_BACK
175 #elif CONFIG_KEYPAD == PHILIPS_HDD1630_PAD
176 # define FFT_PREV_GRAPH BUTTON_LEFT
177 # define FFT_NEXT_GRAPH BUTTON_RIGHT
178 # define FFT_ORIENTATION BUTTON_SELECT
179 # define FFT_WINDOW BUTTON_MENU
180 # define FFT_AMP_SCALE BUTTON_UP
181 # define FFT_FREQ_SCALE BUTTON_DOWN
182 # define FFT_QUIT BUTTON_POWER
184 #elif (CONFIG_KEYPAD == SAMSUNG_YH_PAD)
185 # define FFT_PREV_GRAPH BUTTON_LEFT
186 # define FFT_NEXT_GRAPH BUTTON_RIGHT
187 # define FFT_ORIENTATION BUTTON_UP
188 # define FFT_WINDOW BUTTON_DOWN
189 # define FFT_AMP_SCALE BUTTON_FFWD
190 # define FFT_QUIT BUTTON_PLAY
192 #elif (CONFIG_KEYPAD == MROBE500_PAD)
193 # define FFT_QUIT BUTTON_POWER
195 #elif (CONFIG_KEYPAD == ONDAVX747_PAD)
196 # define FFT_QUIT BUTTON_POWER
198 #elif (CONFIG_KEYPAD == ONDAVX777_PAD)
199 # define FFT_QUIT BUTTON_POWER
201 #elif (CONFIG_KEYPAD == PBELL_VIBE500_PAD)
202 # define FFT_PREV_GRAPH BUTTON_PREV
203 # define FFT_NEXT_GRAPH BUTTON_NEXT
204 # define FFT_ORIENTATION BUTTON_MENU
205 # define FFT_WINDOW BUTTON_OK
206 # define FFT_AMP_SCALE BUTTON_PLAY
207 # define FFT_QUIT BUTTON_REC
209 #elif CONFIG_KEYPAD == MPIO_HD200_PAD
210 # define FFT_PREV_GRAPH BUTTON_PREV
211 # define FFT_NEXT_GRAPH BUTTON_NEXT
212 # define FFT_ORIENTATION BUTTON_REC
213 # define FFT_WINDOW BUTTON_SELECT
214 # define FFT_AMP_SCALE BUTTON_PLAY
215 # define FFT_QUIT (BUTTON_REC | BUTTON_PLAY)
217 #else
218 #error No keymap defined!
219 #endif
221 #ifdef HAVE_TOUCHSCREEN
222 #ifndef FFT_PREV_GRAPH
223 # define FFT_PREV_GRAPH BUTTON_MIDLEFT
224 #endif
225 #ifndef FFT_NEXT_GRAPH
226 # define FFT_NEXT_GRAPH BUTTON_MIDRIGHT
227 #endif
228 #ifndef FFT_ORIENTATION
229 # define FFT_ORIENTATION BUTTON_CENTER
230 #endif
231 #ifndef FFT_WINDOW
232 # define FFT_WINDOW BUTTON_TOPLEFT
233 #endif
234 #ifndef FFT_AMP_SCALE
235 # define FFT_AMP_SCALE BUTTON_TOPRIGHT
236 #endif
237 #ifndef FFT_QUIT
238 # define FFT_QUIT BUTTON_BOTTOMLEFT
239 #endif
240 #endif /* HAVE_TOUCHSCREEN */
242 #ifdef HAVE_LCD_COLOR
243 #include "pluginbitmaps/fft_colors.h"
244 #endif
246 #include "kiss_fftr.h"
247 #include "_kiss_fft_guts.h" /* sizeof(struct kiss_fft_state) */
248 #include "const.h"
250 #define LCD_SIZE MAX(LCD_WIDTH, LCD_HEIGHT)
252 #if (LCD_SIZE <= 511)
253 #define FFT_SIZE 1024 /* 512*2 */
254 #elif (LCD_SIZE <= 1023)
255 #define FFT_SIZE 2048 /* 1024*2 */
256 #else
257 #define FFT_SIZE 4096 /* 2048*2 */
258 #endif
260 #ifdef HAVE_LCD_COLOR
261 #define lcd_(fn) rb->lcd_##fn
262 #define lcd_scroll_up xlcd_scroll_up
263 #define lcd_scroll_left xlcd_scroll_left
264 #else
265 #define lcd_(fn) grey_##fn
266 #define lcd_scroll_up grey_scroll_up
267 #define lcd_scroll_left grey_scroll_left
268 #endif
270 #define ARRAYLEN_IN (FFT_SIZE)
271 #define ARRAYLEN_OUT (FFT_SIZE)
272 #define ARRAYLEN_PLOT (FFT_SIZE/2-1) /* FFT is symmetric, ignore DC */
273 #define BUFSIZE_FFT (sizeof(struct kiss_fft_state)+sizeof(kiss_fft_cpx)*(FFT_SIZE-1))
275 #define __COEFF(type,size) type##_##size
276 #define _COEFF(x, y) __COEFF(x,y) /* force the preprocessor to evaluate FFT_SIZE) */
277 #define HANN_COEFF _COEFF(hann, FFT_SIZE)
278 #define HAMMING_COEFF _COEFF(hamming, FFT_SIZE)
280 /****************************** Globals ****************************/
281 /* cacheline-aligned buffers with COP, otherwise word-aligned */
282 /* CPU/COP only applies when compiled for more than one core */
284 #define CACHEALIGN_UP_SIZE(type, len) \
285 (CACHEALIGN_UP((len)*sizeof(type) + (sizeof(type)-1)) / sizeof(type))
286 /* Shared */
287 /* COP + CPU PCM */
288 static kiss_fft_cpx input[CACHEALIGN_UP_SIZE(kiss_fft_scalar, ARRAYLEN_IN)]
289 CACHEALIGN_AT_LEAST_ATTR(4);
290 /* CPU+COP */
291 #if NUM_CORES > 1
292 /* Output queue indexes */
293 static volatile int output_head SHAREDBSS_ATTR = 0;
294 static volatile int output_tail SHAREDBSS_ATTR = 0;
295 /* The result is nfft/2 complex frequency bins from DC to Nyquist. */
296 static kiss_fft_cpx output[2][CACHEALIGN_UP_SIZE(kiss_fft_cpx, ARRAYLEN_OUT)]
297 SHAREDBSS_ATTR;
298 #else
299 /* Only one output buffer */
300 #define output_head 0
301 #define output_tail 0
302 /* The result is nfft/2 complex frequency bins from DC to Nyquist. */
303 static kiss_fft_cpx output[1][ARRAYLEN_OUT];
304 #endif
306 /* Unshared */
307 /* COP */
308 static kiss_fft_cfg fft_state SHAREDBSS_ATTR;
309 static char fft_buffer[CACHEALIGN_UP_SIZE(char, BUFSIZE_FFT)]
310 CACHEALIGN_AT_LEAST_ATTR(4);
311 /* CPU */
312 static int32_t plot_history[ARRAYLEN_PLOT];
313 static int32_t plot[ARRAYLEN_PLOT];
314 static struct
316 int16_t bin; /* integer bin number */
317 uint16_t frac; /* interpolation fraction */
318 } binlog[ARRAYLEN_PLOT] __attribute__((aligned(4)));
320 enum fft_window_func
322 FFT_WF_FIRST = 0,
323 FFT_WF_HAMMING = 0,
324 FFT_WF_HANN,
326 #define FFT_WF_COUNT (FFT_WF_HANN+1)
328 enum fft_display_mode
330 FFT_DM_FIRST = 0,
331 FFT_DM_LINES = 0,
332 FFT_DM_BARS,
333 FFT_DM_SPECTROGRAPH,
335 #define FFT_DM_COUNT (FFT_DM_SPECTROGRAPH+1)
337 static const unsigned char* const modes_text[FFT_DM_COUNT] =
338 { "Lines", "Bars", "Spectrogram" };
340 static const unsigned char* const amp_scales_text[2] =
341 { "Linear amplitude", "Logarithmic amplitude" };
343 static const unsigned char* const freq_scales_text[2] =
344 { "Linear frequency", "Logarithmic frequency" };
346 static const unsigned char* const window_text[FFT_WF_COUNT] =
347 { "Hamming window", "Hann window" };
349 static struct {
350 bool orientation_vertical;
351 enum fft_display_mode mode;
352 bool logarithmic_amp;
353 bool logarithmic_freq;
354 enum fft_window_func window_func;
355 int spectrogram_pos; /* row or column - only used by one at a time */
356 union
358 struct
360 bool orientation : 1;
361 bool mode : 1;
362 bool amp_scale : 1;
363 bool freq_scale : 1;
364 bool window_func : 1;
365 bool do_clear : 1;
367 bool clear_all; /* Write 'false' to clear all above */
368 } changed;
369 } graph_settings SHAREDDATA_ATTR =
371 /* Defaults */
372 .orientation_vertical = true,
373 .mode = FFT_DM_LINES,
374 .logarithmic_amp = true,
375 .logarithmic_freq = true,
376 .window_func = FFT_WF_HAMMING,
377 .spectrogram_pos = 0,
378 .changed = { .clear_all = false },
381 #ifdef HAVE_LCD_COLOR
382 #define SHADES BMPWIDTH_fft_colors
383 #define SPECTROGRAPH_PALETTE(index) (fft_colors[index])
384 #else
385 #define SHADES 256
386 #define SPECTROGRAPH_PALETTE(index) (255 - (index))
387 #endif
389 /************************* End of globals *************************/
391 /************************* Math functions *************************/
393 /* Based on feeding-in a 0db sinewave at FS/4 */
394 #define QLOG_MAX 0x0009154B
395 /* fudge it a little or it's not very visbile */
396 #define QLIN_MAX (0x00002266 >> 1)
398 /* Apply window function to input */
399 static void apply_window_func(enum fft_window_func mode)
401 int i;
403 switch(mode)
405 case FFT_WF_HAMMING:
406 for(i = 0; i < ARRAYLEN_IN; ++i)
408 input[i].r = (input[i].r * HAMMING_COEFF[i] + 16384) >> 15;
410 break;
412 case FFT_WF_HANN:
413 for(i = 0; i < ARRAYLEN_IN; ++i)
415 input[i].r = (input[i].r * HANN_COEFF[i] + 16384) >> 15;
417 break;
421 /* Calculates the magnitudes from complex numbers and returns the maximum */
422 static int32_t calc_magnitudes(bool logarithmic_amp)
424 /* A major assumption made when calculating the Q*MAX constants
425 * is that the maximum magnitude is 29 bits long. */
426 uint32_t max = 0;
427 kiss_fft_cpx *this_output = output[output_head] + 1; /* skip DC */
428 int i;
430 /* Calculate the magnitude, discarding the phase. */
431 for(i = 0; i < ARRAYLEN_PLOT; ++i)
433 int32_t re = this_output[i].r;
434 int32_t im = this_output[i].i;
436 uint32_t tmp = re*re + im*im;
438 if(tmp > 0)
440 if(tmp > 0x7FFFFFFF) /* clip */
442 tmp = 0x7FFFFFFF; /* if our assumptions are correct,
443 this should never happen. It's just
444 a safeguard. */
447 if(logarithmic_amp)
449 if(tmp < 0x8000) /* be more precise */
451 /* ln(x ^ .5) = .5*ln(x) */
452 tmp = fp16_log(tmp << 16) >> 1;
454 else
456 tmp = isqrt(tmp); /* linear scaling, nothing
457 bad should happen */
458 tmp = fp16_log(tmp << 16); /* the log function
459 expects s15.16 values */
462 else
464 tmp = isqrt(tmp); /* linear scaling, nothing
465 bad should happen */
469 /* Length 2 moving average - last transform and this one */
470 tmp = (plot_history[i] + tmp) >> 1;
471 plot[i] = tmp;
472 plot_history[i] = tmp;
474 if(tmp > max)
475 max = tmp;
478 return max;
481 /* Move plot bins into a logarithmic scale by sliding them towards the
482 * Nyquist bin according to the translation in the binlog array. */
483 static void logarithmic_plot_translate(void)
485 int i;
487 for(i = ARRAYLEN_PLOT-1; i > 0; --i)
489 int bin;
490 int s = binlog[i].bin;
491 int e = binlog[i-1].bin;
492 int frac = binlog[i].frac;
494 bin = plot[s];
496 if(frac)
498 /* slope < 1, Interpolate stretched bins (linear for now) */
499 int diff = plot[s+1] - bin;
503 plot[i] = bin + FRACMUL(frac << 15, diff);
504 frac = binlog[--i].frac;
506 while(frac);
508 else
510 /* slope > 1, Find peak of two or more bins */
511 while(--s > e)
513 int val = plot[s];
515 if (val > bin)
516 bin = val;
520 plot[i] = bin;
524 /* Calculates the translation for logarithmic plot bins */
525 static void logarithmic_plot_init(void)
527 int i, j;
529 * log: y = round(n * ln(x) / ln(n))
530 * anti: y = round(exp(x * ln(n) / n))
532 j = fp16_log((ARRAYLEN_PLOT - 1) << 16);
533 for(i = 0; i < ARRAYLEN_PLOT; ++i)
535 binlog[i].bin = (fp16_exp(i * j / (ARRAYLEN_PLOT - 1)) + 32768) >> 16;
538 /* setup fractions for interpolation of stretched bins */
539 for(i = 0; i < ARRAYLEN_PLOT-1; i = j)
541 j = i + 1;
543 /* stop when we have two different values */
544 while(binlog[j].bin == binlog[i].bin)
545 j++; /* if here, local slope of curve is < 1 */
547 if(j > i + 1)
549 /* distribute pieces evenly over stretched interval */
550 int diff = j - i;
551 int x = 0;
554 binlog[i].frac = (x++ << 16) / diff;
556 while(++i < j);
561 /************************ End of math functions ***********************/
563 /********************* Plotting functions (modes) *********************/
564 static void draw_lines_vertical(void);
565 static void draw_lines_horizontal(void);
566 static void draw_bars_vertical(void);
567 static void draw_bars_horizontal(void);
568 static void draw_spectrogram_vertical(void);
569 static void draw_spectrogram_horizontal(void);
571 #ifdef HAVE_LCD_COLOR
572 #define COLOR_DEFAULT_FG LCD_DEFAULT_FG
573 #define COLOR_DEFAULT_BG LCD_DEFAULT_BG
574 #define COLOR_MESSAGE_FRAME LCD_RGBPACK(0xc6, 0x00, 0x00)
575 #define COLOR_MESSAGE_BG LCD_BLACK
576 #define COLOR_MESSAGE_FG LCD_WHITE
577 #else
578 #define COLOR_DEFAULT_FG GREY_BLACK
579 #define COLOR_DEFAULT_BG GREY_WHITE
580 #define COLOR_MESSAGE_FRAME GREY_DARKGRAY
581 #define COLOR_MESSAGE_BG GREY_WHITE
582 #define COLOR_MESSAGE_FG GREY_BLACK
583 #endif
585 #define POPUP_HPADDING 3 /* 3 px of horizontal padding and */
586 #define POPUP_VPADDING 2 /* 2 px of vertical padding */
588 static void draw_message_string(const unsigned char *message, bool active)
590 int x, y;
591 lcd_(getstringsize)(message, &x, &y);
593 /* x and y give the size of the box for the popup */
594 x += POPUP_HPADDING*2;
595 y += POPUP_VPADDING*2;
597 /* In vertical spectrogram mode, leave space for the popup
598 * before actually drawing it (if space is needed) */
599 if(active &&
600 graph_settings.mode == FFT_DM_SPECTROGRAPH &&
601 graph_settings.orientation_vertical &&
602 graph_settings.spectrogram_pos >= LCD_WIDTH - x)
604 lcd_scroll_left(graph_settings.spectrogram_pos -
605 LCD_WIDTH + x);
606 graph_settings.spectrogram_pos = LCD_WIDTH - x - 1;
609 lcd_(set_foreground)(COLOR_MESSAGE_FRAME);
610 lcd_(fillrect)(LCD_WIDTH - x, 0, LCD_WIDTH - 1, y);
612 lcd_(set_foreground)(COLOR_MESSAGE_FG);
613 lcd_(set_background)(COLOR_MESSAGE_BG);
614 lcd_(putsxy)(LCD_WIDTH - x + POPUP_HPADDING,
615 POPUP_VPADDING, message);
616 lcd_(set_foreground)(COLOR_DEFAULT_FG);
617 lcd_(set_background)(COLOR_DEFAULT_BG);
620 static void draw(const unsigned char* message)
622 static long show_message_tick = 0;
623 static const unsigned char* last_message = 0;
625 if(message != NULL)
627 last_message = message;
628 show_message_tick = (*rb->current_tick + HZ) | 1;
631 /* maybe take additional actions depending upon the changed setting */
632 if(graph_settings.changed.orientation)
634 graph_settings.changed.amp_scale = true;
635 graph_settings.changed.do_clear = true;
638 if(graph_settings.changed.mode)
640 graph_settings.changed.amp_scale = true;
641 graph_settings.changed.do_clear = true;
644 if(graph_settings.changed.amp_scale)
645 memset(plot_history, 0, sizeof (plot_history));
647 if(graph_settings.changed.freq_scale)
648 graph_settings.changed.freq_scale = true;
650 lcd_(set_foreground)(COLOR_DEFAULT_FG);
651 lcd_(set_background)(COLOR_DEFAULT_BG);
653 switch (graph_settings.mode)
655 default:
656 case FFT_DM_LINES: {
658 lcd_(clear_display)();
660 if (graph_settings.orientation_vertical)
661 draw_lines_vertical();
662 else
663 draw_lines_horizontal();
664 break;
666 case FFT_DM_BARS: {
668 lcd_(clear_display());
670 if(graph_settings.orientation_vertical)
671 draw_bars_vertical();
672 else
673 draw_bars_horizontal();
675 break;
677 case FFT_DM_SPECTROGRAPH: {
679 if(graph_settings.changed.do_clear)
681 graph_settings.spectrogram_pos = 0;
682 lcd_(clear_display)();
685 if(graph_settings.orientation_vertical)
686 draw_spectrogram_vertical();
687 else
688 draw_spectrogram_horizontal();
689 break;
693 if(show_message_tick != 0)
695 if(TIME_BEFORE(*rb->current_tick, show_message_tick))
697 /* We have a message to show */
698 draw_message_string(last_message, true);
700 else
702 /* Stop drawing message */
703 show_message_tick = 0;
706 else if(last_message != NULL)
708 if(graph_settings.mode == FFT_DM_SPECTROGRAPH)
710 /* Spectrogram mode - need to erase the popup */
711 int x, y;
712 lcd_(getstringsize)(last_message, &x, &y);
713 /* Recalculate the size */
714 x += POPUP_HPADDING*2;
715 y += POPUP_VPADDING*2;
717 if(!graph_settings.orientation_vertical)
719 /* In horizontal spectrogram mode, just scroll up by Y lines */
720 lcd_scroll_up(y);
721 graph_settings.spectrogram_pos -= y;
722 if(graph_settings.spectrogram_pos < 0)
723 graph_settings.spectrogram_pos = 0;
725 else
727 /* In vertical spectrogram mode, erase the popup */
728 lcd_(set_foreground)(COLOR_DEFAULT_BG);
729 lcd_(fillrect)(graph_settings.spectrogram_pos + 1, 0,
730 LCD_WIDTH, y);
731 lcd_(set_foreground)(COLOR_DEFAULT_FG);
734 /* else These modes clear the screen themselves */
736 last_message = NULL;
739 lcd_(update)();
741 graph_settings.changed.clear_all = false;
744 static void draw_lines_vertical(void)
746 static int max = 0;
748 #if LCD_WIDTH < ARRAYLEN_PLOT /* graph compression */
749 const int offset = 0;
750 const int plotwidth = LCD_WIDTH;
751 #else
752 const int offset = (LCD_HEIGHT - ARRAYLEN_PLOT) / 2;
753 const int plotwidth = ARRAYLEN_PLOT;
754 #endif
756 int this_max;
757 int i, x;
759 if(graph_settings.changed.amp_scale)
760 max = 0; /* reset the graph on scaling mode change */
762 this_max = calc_magnitudes(graph_settings.logarithmic_amp);
764 if(this_max == 0)
766 lcd_(hline)(0, LCD_WIDTH - 1, LCD_HEIGHT - 1); /* Draw all "zero" */
767 return;
770 if(graph_settings.logarithmic_freq)
771 logarithmic_plot_translate();
773 /* take the maximum of neighboring bins if we have to scale the graph
774 * horizontally */
775 if(LCD_WIDTH < ARRAYLEN_PLOT) /* graph compression */
777 int bins_acc = LCD_WIDTH / 2;
778 int bins_max = 0;
780 i = 0, x = 0;
782 for(;;)
784 int bin = plot[i++];
786 if(bin > bins_max)
787 bins_max = bin;
789 bins_acc += LCD_WIDTH;
791 if(bins_acc >= ARRAYLEN_PLOT)
793 plot[x] = bins_max;
795 if(bins_max > max)
796 max = bins_max;
798 if(++x >= LCD_WIDTH)
799 break;
801 bins_acc -= ARRAYLEN_PLOT;
802 bins_max = 0;
806 else
808 if(this_max > max)
809 max = this_max;
812 for(x = 0; x < plotwidth; ++x)
814 int h = LCD_HEIGHT*plot[x] / max;
815 lcd_(vline)(x + offset, LCD_HEIGHT - h, LCD_HEIGHT-1);
819 static void draw_lines_horizontal(void)
821 static int max = 0;
823 #if LCD_WIDTH < ARRAYLEN_PLOT /* graph compression */
824 const int offset = 0;
825 const int plotwidth = LCD_HEIGHT;
826 #else
827 const int offset = (LCD_HEIGHT - ARRAYLEN_PLOT) / 2;
828 const int plotwidth = ARRAYLEN_PLOT;
829 #endif
831 int this_max;
832 int y;
834 if(graph_settings.changed.amp_scale)
835 max = 0; /* reset the graph on scaling mode change */
837 this_max = calc_magnitudes(graph_settings.logarithmic_amp);
839 if(this_max == 0)
841 lcd_(vline)(0, 0, LCD_HEIGHT-1); /* Draw all "zero" */
842 return;
845 if(graph_settings.logarithmic_freq)
846 logarithmic_plot_translate();
848 /* take the maximum of neighboring bins if we have to scale the graph
849 * horizontally */
850 if(LCD_HEIGHT < ARRAYLEN_PLOT) /* graph compression */
852 int bins_acc = LCD_HEIGHT / 2;
853 int bins_max = 0;
854 int i = 0;
856 y = 0;
858 for(;;)
860 int bin = plot[i++];
862 if (bin > bins_max)
863 bins_max = bin;
865 bins_acc += LCD_HEIGHT;
867 if(bins_acc >= ARRAYLEN_PLOT)
869 plot[y] = bins_max;
871 if(bins_max > max)
872 max = bins_max;
874 if(++y >= LCD_HEIGHT)
875 break;
877 bins_acc -= ARRAYLEN_PLOT;
878 bins_max = 0;
882 else
884 if(this_max > max)
885 max = this_max;
888 for(y = 0; y < plotwidth; ++y)
890 int w = LCD_WIDTH*plot[y] / max;
891 lcd_(hline)(0, w - 1, y + offset);
895 static void draw_bars_vertical(void)
897 static int max = 0;
899 #if LCD_WIDTH < LCD_HEIGHT
900 const int bars = 15;
901 #else
902 const int bars = 20;
903 #endif
904 const int border = 2;
905 const int barwidth = LCD_WIDTH / (bars + border);
906 const int width = barwidth - border;
907 const int offset = (LCD_WIDTH - bars*barwidth) / 2;
909 if(graph_settings.changed.amp_scale)
910 max = 0; /* reset the graph on scaling mode change */
912 lcd_(hline)(0, LCD_WIDTH-1, LCD_HEIGHT-1); /* Draw baseline */
914 if(calc_magnitudes(graph_settings.logarithmic_amp) == 0)
915 return; /* nothing more to draw */
917 if(graph_settings.logarithmic_freq)
918 logarithmic_plot_translate();
920 int bins_acc = bars / 2;
921 int bins_max = 0;
922 int x = 0, i = 0;
924 for(;;)
926 int bin = plot[i++];
928 if(bin > bins_max)
929 bins_max = bin;
931 bins_acc += bars;
933 if(bins_acc >= ARRAYLEN_PLOT)
935 plot[x] = bins_max;
937 if(bins_max > max)
938 max = bins_max;
940 if(++x >= bars)
941 break;
943 bins_acc -= ARRAYLEN_PLOT;
944 bins_max = 0;
948 for(i = 0, x = offset; i < bars; ++i, x += barwidth)
950 int h = LCD_HEIGHT * plot[i] / max;
951 lcd_(fillrect)(x, LCD_HEIGHT - h, width, h - 1);
955 static void draw_bars_horizontal(void)
957 static int max = 0;
959 #if LCD_WIDTH < LCD_HEIGHT
960 const int bars = 20;
961 #else
962 const int bars = 15;
963 #endif
964 const int border = 2;
965 const int barwidth = LCD_HEIGHT / (bars + border);
966 const int height = barwidth - border;
967 const int offset = (LCD_HEIGHT - bars*barwidth) / 2;
969 if(graph_settings.changed.amp_scale)
970 max = 0; /* reset the graph on scaling mode change */
972 lcd_(vline)(0, 0, LCD_HEIGHT-1); /* Draw baseline */
974 if(calc_magnitudes(graph_settings.logarithmic_amp) == 0)
975 return; /* nothing more to draw */
977 if(graph_settings.logarithmic_freq)
978 logarithmic_plot_translate();
980 int bins_acc = bars / 2;
981 int bins_max = 0;
982 int y = 0, i = 0;
984 for(;;)
986 int bin = plot[i++];
988 if (bin > bins_max)
989 bins_max = bin;
991 bins_acc += bars;
993 if(bins_acc >= ARRAYLEN_PLOT)
995 plot[y] = bins_max;
997 if(bins_max > max)
998 max = bins_max;
1000 if(++y >= bars)
1001 break;
1003 bins_acc -= ARRAYLEN_PLOT;
1004 bins_max = 0;
1008 for(i = 0, y = offset; i < bars; ++i, y += barwidth)
1010 int w = LCD_WIDTH * plot[i] / max;
1011 lcd_(fillrect)(1, y, w, height);
1015 static void draw_spectrogram_vertical(void)
1017 const int32_t scale_factor = MIN(LCD_HEIGHT, ARRAYLEN_PLOT);
1019 calc_magnitudes(graph_settings.logarithmic_amp);
1021 if(graph_settings.logarithmic_freq)
1022 logarithmic_plot_translate();
1024 int bins_acc = scale_factor / 2;
1025 int bins_max = 0;
1026 int y = 0, i = 0;
1028 for(;;)
1030 int bin = plot[i++];
1032 if(bin > bins_max)
1033 bins_max = bin;
1035 bins_acc += scale_factor;
1037 if(bins_acc >= ARRAYLEN_PLOT)
1039 unsigned index;
1041 if(graph_settings.logarithmic_amp)
1042 index = (SHADES-1)*bins_max / QLOG_MAX;
1043 else
1044 index = (SHADES-1)*bins_max / QLIN_MAX;
1046 /* These happen because we exaggerate the graph a little for
1047 * linear mode */
1048 if(index >= SHADES)
1049 index = SHADES-1;
1051 lcd_(set_foreground)(SPECTROGRAPH_PALETTE(index));
1052 lcd_(drawpixel)(graph_settings.spectrogram_pos,
1053 scale_factor-1 - y);
1055 if(++y >= scale_factor)
1056 break;
1058 bins_acc -= ARRAYLEN_PLOT;
1059 bins_max = 0;
1063 if(graph_settings.spectrogram_pos < LCD_WIDTH-1)
1064 graph_settings.spectrogram_pos++;
1065 else
1066 lcd_scroll_left(1);
1069 static void draw_spectrogram_horizontal(void)
1071 const int32_t scale_factor = MIN(LCD_WIDTH, ARRAYLEN_PLOT);
1073 calc_magnitudes(graph_settings.logarithmic_amp);
1075 if(graph_settings.logarithmic_freq)
1076 logarithmic_plot_translate();
1078 int bins_acc = scale_factor / 2;
1079 int bins_max = 0;
1080 int x = 0, i = 0;
1082 for(;;)
1084 int bin = plot[i++];
1086 if(bin > bins_max)
1087 bins_max = bin;
1089 bins_acc += scale_factor;
1091 if(bins_acc >= ARRAYLEN_PLOT)
1093 unsigned index;
1095 if(graph_settings.logarithmic_amp)
1096 index = (SHADES-1)*bins_max / QLOG_MAX;
1097 else
1098 index = (SHADES-1)*bins_max / QLIN_MAX;
1100 /* These happen because we exaggerate the graph a little for
1101 * linear mode */
1102 if(index >= SHADES)
1103 index = SHADES-1;
1105 lcd_(set_foreground)(SPECTROGRAPH_PALETTE(index));
1106 lcd_(drawpixel)(x, graph_settings.spectrogram_pos);
1108 if(++x >= scale_factor)
1109 break;
1111 bins_acc -= ARRAYLEN_PLOT;
1112 bins_max = 0;
1116 if(graph_settings.spectrogram_pos < LCD_HEIGHT-1)
1117 graph_settings.spectrogram_pos++;
1118 else
1119 lcd_scroll_up(1);
1122 /********************* End of plotting functions (modes) *********************/
1124 /****************************** FFT functions ********************************/
1126 /** functions use in single/multi configuration **/
1127 static inline bool fft_init_fft_lib(void)
1129 size_t size = sizeof(fft_buffer);
1130 fft_state = kiss_fft_alloc(FFT_SIZE, 0, fft_buffer, &size);
1132 if(fft_state == NULL)
1134 DEBUGF("needed data: %i", (int) size);
1135 return false;
1138 return true;
1141 static inline bool fft_get_fft(void)
1143 int count;
1144 int16_t *value = (int16_t *) rb->pcm_get_peak_buffer(&count);
1145 /* This block can introduce discontinuities in our data. Meaning, the
1146 * FFT will not be done a continuous segment of the signal. Which can
1147 * be bad. Or not.
1149 * Anyway, this is a demo, not a scientific tool. If you want accuracy,
1150 * do a proper spectrum analysis.*/
1152 /* there are cases when we don't have enough data to fill the buffer */
1153 if(count != ARRAYLEN_IN)
1155 if(count < ARRAYLEN_IN)
1156 return false;
1158 count = ARRAYLEN_IN; /* too much - limit */
1161 int fft_idx = 0; /* offset in 'input' */
1165 kiss_fft_scalar left = *value++;
1166 kiss_fft_scalar right = *value++;
1167 input[fft_idx].r = (left + right) >> 1; /* to mono */
1168 } while (fft_idx++, --count > 0);
1170 apply_window_func(graph_settings.window_func);
1172 rb->yield();
1174 kiss_fft(fft_state, input, output[output_tail]);
1176 rb->yield();
1178 return true;
1181 #if NUM_CORES > 1
1182 /* use a worker thread if there is another processor core */
1183 static volatile bool fft_thread_run SHAREDDATA_ATTR = false;
1184 static unsigned long fft_thread;
1186 static long fft_thread_stack[CACHEALIGN_UP(DEFAULT_STACK_SIZE*4/sizeof(long))]
1187 CACHEALIGN_AT_LEAST_ATTR(4);
1189 static void fft_thread_entry(void)
1191 if (!fft_init_fft_lib())
1193 output_tail = -1; /* tell that we bailed */
1194 fft_thread_run = true;
1195 return;
1198 fft_thread_run = true;
1200 while(fft_thread_run)
1202 if (!rb->pcm_is_playing())
1204 rb->sleep(HZ/5);
1205 continue;
1208 if (!fft_get_fft())
1210 rb->sleep(0); /* not enough - ease up */
1211 continue;
1214 #if NUM_CORES > 1
1215 /* write back output for other processor and invalidate for next frame read */
1216 rb->cpucache_invalidate();
1217 #endif
1218 int new_tail = output_tail ^ 1;
1220 /* if full, block waiting until reader has freed a slot */
1221 while(fft_thread_run)
1223 if(new_tail != output_head)
1225 output_tail = new_tail;
1226 break;
1229 rb->sleep(0);
1234 static bool fft_have_fft(void)
1236 return output_head != output_tail;
1239 /* Call only after fft_have_fft() has returned true */
1240 static inline void fft_free_fft_output(void)
1242 output_head ^= 1; /* finished with this */
1245 static bool fft_init_fft(void)
1247 /* create worker thread - on the COP for dual-core targets */
1248 fft_thread = rb->create_thread(fft_thread_entry,
1249 fft_thread_stack, sizeof(fft_thread_stack), 0, "fft output thread"
1250 IF_PRIO(, PRIORITY_USER_INTERFACE+1) IF_COP(, COP));
1252 if(fft_thread == 0)
1254 rb->splash(HZ, "FFT thread failed create");
1255 return false;
1258 /* wait for it to indicate 'ready' */
1259 while(fft_thread_run == false)
1260 rb->sleep(0);
1262 if(output_tail == -1)
1264 /* FFT thread bailed-out like The Fed */
1265 rb->thread_wait(fft_thread);
1266 rb->splash(HZ, "FFT thread failed to init");
1267 return false;
1270 return true;
1273 static void fft_close_fft(void)
1275 /* Handle our FFT thread. */
1276 fft_thread_run = false;
1277 rb->thread_wait(fft_thread);
1278 #if NUM_CORES > 1
1279 rb->cpucache_invalidate();
1280 #endif
1282 #else /* NUM_CORES == 1 */
1283 /* everything serialize on single-core and FFT gets to use IRAM main stack if
1284 * target uses IRAM */
1285 static bool fft_have_fft(void)
1287 return rb->pcm_is_playing() && fft_get_fft();
1290 static inline void fft_free_fft_output(void)
1292 /* nothing to do */
1295 static bool fft_init_fft(void)
1297 return fft_init_fft_lib();
1300 static inline void fft_close_fft(void)
1302 /* nothing to do */
1304 #endif /* NUM_CORES */
1305 /*************************** End of FFT functions ****************************/
1307 enum plugin_status plugin_start(const void* parameter)
1309 /* Defaults */
1310 bool run = true;
1311 bool showing_warning = false;
1313 if (!fft_init_fft())
1314 return PLUGIN_ERROR;
1316 #ifndef HAVE_LCD_COLOR
1317 unsigned char *gbuf;
1318 size_t gbuf_size = 0;
1319 /* get the remainder of the plugin buffer */
1320 gbuf = (unsigned char *) rb->plugin_get_buffer(&gbuf_size);
1322 /* initialize the greyscale buffer.*/
1323 if (!grey_init(gbuf, gbuf_size, GREY_ON_COP | GREY_BUFFERED,
1324 LCD_WIDTH, LCD_HEIGHT, NULL))
1326 rb->splash(HZ, "Couldn't init greyscale display");
1327 fft_close_fft();
1328 return PLUGIN_ERROR;
1330 grey_show(true);
1331 #endif
1333 logarithmic_plot_init();
1335 #if LCD_DEPTH > 1
1336 rb->lcd_set_backdrop(NULL);
1337 lcd_(clear_display)();
1338 lcd_(update)();
1339 #endif
1340 backlight_force_on();
1342 #ifdef HAVE_ADJUSTABLE_CPU_FREQ
1343 rb->cpu_boost(true);
1344 #endif
1346 while (run)
1348 /* Unless otherwise specified, HZ/50 is around the window length
1349 * and quite fast. We want to be done with drawing by this time. */
1350 long next_frame_tick = *rb->current_tick + HZ/50;
1351 int button;
1353 while (!fft_have_fft())
1355 int timeout;
1357 if(!rb->pcm_is_playing())
1359 showing_warning = true;
1360 lcd_(clear_display)();
1361 draw_message_string("No audio playing", false);
1362 lcd_(update)();
1363 timeout = HZ/5;
1365 else
1367 if(showing_warning)
1369 showing_warning = false;
1370 lcd_(clear_display)();
1371 lcd_(update)();
1374 timeout = HZ/100; /* 'till end of curent tick, don't use 100% CPU */
1377 /* Make sure the FFT has produced something before doing anything
1378 * but watching for buttons. Music might not be playing or things
1379 * just aren't going well for picking up buffers so keys are
1380 * scanned to avoid lockup. */
1381 button = rb->button_get_w_tmo(timeout);
1382 if (button != BUTTON_NONE)
1383 goto read_button;
1386 draw(NULL);
1388 fft_free_fft_output(); /* COP only */
1390 long tick = *rb->current_tick;
1391 if(TIME_BEFORE(tick, next_frame_tick))
1393 tick = next_frame_tick - tick;
1395 else
1397 rb->yield(); /* tmo = 0 won't yield */
1398 tick = 0;
1401 button = rb->button_get_w_tmo(tick);
1402 read_button:
1403 switch (button)
1405 case FFT_QUIT:
1406 run = false;
1407 break;
1408 case FFT_PREV_GRAPH: {
1409 if (graph_settings.mode-- <= FFT_DM_FIRST)
1410 graph_settings.mode = FFT_DM_COUNT-1;
1411 graph_settings.changed.mode = true;
1412 draw(modes_text[graph_settings.mode]);
1413 break;
1415 case FFT_NEXT_GRAPH: {
1416 if (++graph_settings.mode >= FFT_DM_COUNT)
1417 graph_settings.mode = FFT_DM_FIRST;
1418 graph_settings.changed.mode = true;
1419 draw(modes_text[graph_settings.mode]);
1420 break;
1422 case FFT_WINDOW: {
1423 if(++graph_settings.window_func >= FFT_WF_COUNT)
1424 graph_settings.window_func = FFT_WF_FIRST;
1425 graph_settings.changed.window_func = true;
1426 draw(window_text[graph_settings.window_func]);
1427 break;
1429 case FFT_AMP_SCALE: {
1430 graph_settings.logarithmic_amp = !graph_settings.logarithmic_amp;
1431 graph_settings.changed.amp_scale = true;
1432 draw(amp_scales_text[graph_settings.logarithmic_amp ? 1 : 0]);
1433 break;
1435 #ifdef FFT_FREQ_SCALE /* 'Till all keymaps are defined */
1436 case FFT_FREQ_SCALE: {
1437 graph_settings.logarithmic_freq = !graph_settings.logarithmic_freq;
1438 graph_settings.changed.freq_scale = true;
1439 draw(freq_scales_text[graph_settings.logarithmic_freq ? 1 : 0]);
1440 break;
1442 #endif
1443 case FFT_ORIENTATION: {
1444 graph_settings.orientation_vertical =
1445 !graph_settings.orientation_vertical;
1446 graph_settings.changed.orientation = true;
1447 draw(NULL);
1448 break;
1450 default: {
1451 if (rb->default_event_handler(button) == SYS_USB_CONNECTED)
1452 return PLUGIN_USB_CONNECTED;
1458 fft_close_fft();
1460 #ifdef HAVE_ADJUSTABLE_CPU_FREQ
1461 rb->cpu_boost(false);
1462 #endif
1463 #ifndef HAVE_LCD_COLOR
1464 grey_release();
1465 #endif
1466 backlight_use_settings();
1467 return PLUGIN_OK;
1468 (void)parameter;