FFT plugin: Use worker thread only on multiprocessor targets.
[kugel-rb.git] / apps / plugins / fft / fft.c
blob3884f2c4135c3f602dff893d9d1de799802eb27f
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 #if (LCD_WIDTH < LCD_HEIGHT)
251 #define LCD_SIZE LCD_HEIGHT
252 #else
253 #define LCD_SIZE LCD_WIDTH
254 #endif
256 #if (LCD_SIZE < 512)
257 #define FFT_SIZE 2048 /* 512*4 */
258 #elif (LCD_SIZE < 1024)
259 #define FFT_SIZE 4096 /* 1024*4 */
260 #else
261 #define FFT_SIZE 8192 /* 2048*4 */
262 #endif
264 #ifdef HAVE_LCD_COLOR
265 #define lcd_(fn) rb->lcd_##fn
266 #define lcd_scroll_up xlcd_scroll_up
267 #define lcd_scroll_left xlcd_scroll_left
268 #else
269 #define lcd_(fn) grey_##fn
270 #define lcd_scroll_up grey_scroll_up
271 #define lcd_scroll_left grey_scroll_left
272 #endif
274 #define ARRAYLEN_IN (FFT_SIZE)
275 #define ARRAYLEN_OUT (FFT_SIZE/2)
276 #define ARRAYLEN_PLOT ((FFT_SIZE/4)-1) /* -1 to ignore DC bin */
277 #define BUFSIZE_FFT (sizeof(struct kiss_fft_state)+sizeof(kiss_fft_cpx)*(FFT_SIZE-1))
278 #define BUFSIZE_FFTR (BUFSIZE_FFT+sizeof(struct kiss_fftr_state)+sizeof(kiss_fft_cpx)*(FFT_SIZE*3/2))
279 #define BUFSIZE BUFSIZE_FFTR
280 #define FFT_ALLOC kiss_fftr_alloc
281 #define FFT_FFT kiss_fftr
282 #define FFT_CFG kiss_fftr_cfg
284 #define __COEFF(type,size) type##_##size
285 #define _COEFF(x, y) __COEFF(x,y) /* force the preprocessor to evaluate FFT_SIZE) */
286 #define HANN_COEFF _COEFF(hann, FFT_SIZE)
287 #define HAMMING_COEFF _COEFF(hamming, FFT_SIZE)
289 /****************************** Globals ****************************/
290 /* cacheline-aligned buffers with COP, otherwise word-aligned */
291 /* CPU/COP only applies when compiled for more than one core */
293 #define CACHEALIGN_UP_SIZE(type, len) \
294 (CACHEALIGN_UP((len)*sizeof(type) + (sizeof(type)-1)) / sizeof(type))
295 /* Shared */
296 /* COP + CPU PCM */
297 static kiss_fft_scalar input[CACHEALIGN_UP_SIZE(kiss_fft_scalar, ARRAYLEN_IN)]
298 CACHEALIGN_AT_LEAST_ATTR(4);
299 /* CPU+COP */
300 #if NUM_CORES > 1
301 /* Output queue indexes */
302 static volatile int output_head SHAREDBSS_ATTR = 0;
303 static volatile int output_tail SHAREDBSS_ATTR = 0;
304 /* The result is nfft/2+1 complex frequency bins from DC to Nyquist. */
305 static kiss_fft_cpx output[2][CACHEALIGN_UP_SIZE(kiss_fft_cpx, ARRAYLEN_OUT+1)]
306 SHAREDBSS_ATTR;
307 #else
308 /* Only one output buffer */
309 #define output_head 0
310 #define output_tail 0
311 /* The result is nfft/2+1 complex frequency bins from DC to Nyquist. */
312 static kiss_fft_cpx output[1][ARRAYLEN_OUT+1];
313 #endif
315 /* Unshared */
316 /* COP */
317 static FFT_CFG fft_state SHAREDBSS_ATTR;
318 static char buffer[CACHEALIGN_UP_SIZE(char, BUFSIZE)]
319 CACHEALIGN_AT_LEAST_ATTR(4);
320 /* CPU */
321 static int32_t plot_history[ARRAYLEN_PLOT];
322 static int32_t plot[ARRAYLEN_PLOT];
323 static struct
325 int16_t bin; /* integer bin number */
326 uint16_t frac; /* interpolation fraction */
327 } binlog[ARRAYLEN_PLOT] __attribute__((aligned(4)));
329 enum fft_window_func
331 FFT_WF_FIRST = 0,
332 FFT_WF_HAMMING = 0,
333 FFT_WF_HANN,
335 #define FFT_WF_COUNT (FFT_WF_HANN+1)
337 enum fft_display_mode
339 FFT_DM_FIRST = 0,
340 FFT_DM_LINES = 0,
341 FFT_DM_BARS,
342 FFT_DM_SPECTROGRAPH,
344 #define FFT_DM_COUNT (FFT_DM_SPECTROGRAPH+1)
346 static const unsigned char* const modes_text[FFT_DM_COUNT] =
347 { "Lines", "Bars", "Spectrogram" };
349 static const unsigned char* const amp_scales_text[2] =
350 { "Linear amplitude", "Logarithmic amplitude" };
352 static const unsigned char* const freq_scales_text[2] =
353 { "Linear frequency", "Logarithmic frequency" };
355 static const unsigned char* const window_text[FFT_WF_COUNT] =
356 { "Hamming window", "Hann window" };
358 static struct {
359 bool orientation_vertical;
360 enum fft_display_mode mode;
361 bool logarithmic_amp;
362 bool logarithmic_freq;
363 enum fft_window_func window_func;
364 int spectrogram_pos; /* row or column - only used by one at a time */
365 union
367 struct
369 bool orientation : 1;
370 bool mode : 1;
371 bool amp_scale : 1;
372 bool freq_scale : 1;
373 bool window_func : 1;
374 bool do_clear : 1;
376 bool clear_all; /* Write 'false' to clear all above */
377 } changed;
378 } graph_settings SHAREDDATA_ATTR =
380 /* Defaults */
381 .orientation_vertical = true,
382 .mode = FFT_DM_LINES,
383 .logarithmic_amp = true,
384 .logarithmic_freq = true,
385 .window_func = FFT_WF_HAMMING,
386 .spectrogram_pos = 0,
387 .changed = { .clear_all = false },
390 #ifdef HAVE_LCD_COLOR
391 #define SHADES BMPWIDTH_fft_colors
392 #define SPECTROGRAPH_PALETTE(index) (fft_colors[index])
393 #else
394 #define SHADES 256
395 #define SPECTROGRAPH_PALETTE(index) (255 - (index))
396 #endif
398 /************************* End of globals *************************/
400 /************************* Math functions *************************/
402 /* Based on playing back a 0dB sweep tone */
403 #define QLOG_MAX 0x000865EF
404 /* fudge it a little or it's not very visbile */
405 #define QLIN_MAX (0x00001157 >> 1)
407 /* Apply window function to input */
408 void apply_window_func(enum fft_window_func mode)
410 int i;
412 switch(mode)
414 case FFT_WF_HAMMING:
415 for(i = 0; i < ARRAYLEN_IN; ++i)
417 input[i] = (input[i] * HAMMING_COEFF[i] + 16384) >> 15;
419 break;
421 case FFT_WF_HANN:
422 for(i = 0; i < ARRAYLEN_IN; ++i)
424 input[i] = (input[i] * HANN_COEFF[i] + 16384) >> 15;
426 break;
430 /* Calculates the magnitudes from complex numbers and returns the maximum */
431 int32_t calc_magnitudes(bool logarithmic_amp)
433 /* A major assumption made when calculating the Q*MAX constants
434 * is that the maximum magnitude is 29 bits long. */
435 uint32_t max = 0;
436 kiss_fft_cpx *this_output = output[output_head] + 1; /* skip DC */
437 int i;
439 /* Calculate the magnitude, discarding the phase. */
440 for(i = 0; i < ARRAYLEN_PLOT; ++i)
442 int32_t re = this_output[i].r;
443 int32_t im = this_output[i].i;
445 uint32_t tmp = re*re + im*im;
447 if(tmp > 0)
449 if(tmp > 0x7FFFFFFF) /* clip */
451 tmp = 0x7FFFFFFF; /* if our assumptions are correct,
452 this should never happen. It's just
453 a safeguard. */
456 if(logarithmic_amp)
458 if(tmp < 0x8000) /* be more precise */
460 /* ln(x ^ .5) = .5*ln(x) */
461 tmp = fp16_log(tmp << 16) >> 1;
463 else
465 tmp = isqrt(tmp); /* linear scaling, nothing
466 bad should happen */
467 tmp = fp16_log(tmp << 16); /* the log function
468 expects s15.16 values */
471 else
473 tmp = isqrt(tmp); /* linear scaling, nothing
474 bad should happen */
478 /* Length 2 moving average - last transform and this one */
479 tmp = (plot_history[i] + tmp) >> 1;
480 plot[i] = tmp;
481 plot_history[i] = tmp;
483 if(tmp > max)
484 max = tmp;
487 return max;
490 /* Move plot bins into a logarithmic scale by sliding them towards the
491 * Nyquist bin according to the translation in the binlog array. */
492 void logarithmic_plot_translate(void)
494 int i;
496 for(i = ARRAYLEN_PLOT-1; i > 0; --i)
498 int bin;
499 int s = binlog[i].bin;
500 int e = binlog[i-1].bin;
501 int frac = binlog[i].frac;
503 bin = plot[s];
505 if(frac)
507 /* slope < 1, Interpolate stretched bins (linear for now) */
508 int diff = plot[s+1] - bin;
512 plot[i] = bin + FRACMUL(frac << 15, diff);
513 frac = binlog[--i].frac;
515 while(frac);
517 else
519 /* slope > 1, Find peak of two or more bins */
520 while(--s > e)
522 int val = plot[s];
524 if (val > bin)
525 bin = val;
529 plot[i] = bin;
533 /* Calculates the translation for logarithmic plot bins */
534 void logarithmic_plot_init(void)
536 int i, j;
538 * log: y = round(n * ln(x) / ln(n))
539 * anti: y = round(exp(x * ln(n) / n))
541 j = fp16_log((ARRAYLEN_PLOT - 1) << 16);
542 for(i = 0; i < ARRAYLEN_PLOT; ++i)
544 binlog[i].bin = (fp16_exp(i * j / (ARRAYLEN_PLOT - 1)) + 32768) >> 16;
547 /* setup fractions for interpolation of stretched bins */
548 for(i = 0; i < ARRAYLEN_PLOT-1; i = j)
550 j = i + 1;
552 /* stop when we have two different values */
553 while(binlog[j].bin == binlog[i].bin)
554 j++; /* if here, local slope of curve is < 1 */
556 if(j > i + 1)
558 /* distribute pieces evenly over stretched interval */
559 int diff = j - i;
560 int x = 0;
563 binlog[i].frac = (x++ << 16) / diff;
565 while(++i < j);
570 /************************ End of math functions ***********************/
572 /********************* Plotting functions (modes) *********************/
573 void draw_lines_vertical(void);
574 void draw_lines_horizontal(void);
575 void draw_bars_vertical(void);
576 void draw_bars_horizontal(void);
577 void draw_spectrogram_vertical(void);
578 void draw_spectrogram_horizontal(void);
580 #ifdef HAVE_LCD_COLOR
581 #define COLOR_DEFAULT_FG LCD_DEFAULT_FG
582 #define COLOR_DEFAULT_BG LCD_DEFAULT_BG
583 #define COLOR_MESSAGE_FRAME LCD_RGBPACK(0xc6, 0x00, 0x00)
584 #define COLOR_MESSAGE_BG LCD_BLACK
585 #define COLOR_MESSAGE_FG LCD_WHITE
586 #else
587 #define COLOR_DEFAULT_FG GREY_BLACK
588 #define COLOR_DEFAULT_BG GREY_WHITE
589 #define COLOR_MESSAGE_FRAME GREY_DARKGRAY
590 #define COLOR_MESSAGE_BG GREY_WHITE
591 #define COLOR_MESSAGE_FG GREY_BLACK
592 #endif
594 #define POPUP_HPADDING 3 /* 3 px of horizontal padding and */
595 #define POPUP_VPADDING 2 /* 2 px of vertical padding */
597 void draw_message_string(const unsigned char *message, bool active)
599 int x, y;
600 lcd_(getstringsize)(message, &x, &y);
602 /* x and y give the size of the box for the popup */
603 x += POPUP_HPADDING*2;
604 y += POPUP_VPADDING*2;
606 /* In vertical spectrogram mode, leave space for the popup
607 * before actually drawing it (if space is needed) */
608 if(active &&
609 graph_settings.mode == FFT_DM_SPECTROGRAPH &&
610 graph_settings.orientation_vertical &&
611 graph_settings.spectrogram_pos >= LCD_WIDTH - x)
613 lcd_scroll_left(graph_settings.spectrogram_pos -
614 LCD_WIDTH + x);
615 graph_settings.spectrogram_pos = LCD_WIDTH - x - 1;
618 lcd_(set_foreground)(COLOR_MESSAGE_FRAME);
619 lcd_(fillrect)(LCD_WIDTH - x, 0, LCD_WIDTH - 1, y);
621 lcd_(set_foreground)(COLOR_MESSAGE_FG);
622 lcd_(set_background)(COLOR_MESSAGE_BG);
623 lcd_(putsxy)(LCD_WIDTH - x + POPUP_HPADDING,
624 POPUP_VPADDING, message);
625 lcd_(set_foreground)(COLOR_DEFAULT_FG);
626 lcd_(set_background)(COLOR_DEFAULT_BG);
629 void draw(const unsigned char* message)
631 static long show_message_tick = 0;
632 static const unsigned char* last_message = 0;
634 if(message != NULL)
636 last_message = message;
637 show_message_tick = (*rb->current_tick + HZ) | 1;
640 /* maybe take additional actions depending upon the changed setting */
641 if(graph_settings.changed.orientation)
643 graph_settings.changed.amp_scale = true;
644 graph_settings.changed.do_clear = true;
647 if(graph_settings.changed.mode)
649 graph_settings.changed.amp_scale = true;
650 graph_settings.changed.do_clear = true;
653 if(graph_settings.changed.amp_scale)
654 memset(plot_history, 0, sizeof (plot_history));
656 if(graph_settings.changed.freq_scale)
657 graph_settings.changed.freq_scale = true;
659 lcd_(set_foreground)(COLOR_DEFAULT_FG);
660 lcd_(set_background)(COLOR_DEFAULT_BG);
662 switch (graph_settings.mode)
664 default:
665 case FFT_DM_LINES: {
667 lcd_(clear_display)();
669 if (graph_settings.orientation_vertical)
670 draw_lines_vertical();
671 else
672 draw_lines_horizontal();
673 break;
675 case FFT_DM_BARS: {
677 lcd_(clear_display());
679 if(graph_settings.orientation_vertical)
680 draw_bars_vertical();
681 else
682 draw_bars_horizontal();
684 break;
686 case FFT_DM_SPECTROGRAPH: {
688 if(graph_settings.changed.do_clear)
690 graph_settings.spectrogram_pos = 0;
691 lcd_(clear_display)();
694 if(graph_settings.orientation_vertical)
695 draw_spectrogram_vertical();
696 else
697 draw_spectrogram_horizontal();
698 break;
702 if(show_message_tick != 0)
704 if(TIME_BEFORE(*rb->current_tick, show_message_tick))
706 /* We have a message to show */
707 draw_message_string(last_message, true);
709 else
711 /* Stop drawing message */
712 show_message_tick = 0;
715 else if(last_message != NULL)
717 if(graph_settings.mode == FFT_DM_SPECTROGRAPH)
719 /* Spectrogram mode - need to erase the popup */
720 int x, y;
721 lcd_(getstringsize)(last_message, &x, &y);
722 /* Recalculate the size */
723 x += POPUP_HPADDING*2;
724 y += POPUP_VPADDING*2;
726 if(!graph_settings.orientation_vertical)
728 /* In horizontal spectrogram mode, just scroll up by Y lines */
729 lcd_scroll_up(y);
730 graph_settings.spectrogram_pos -= y;
731 if(graph_settings.spectrogram_pos < 0)
732 graph_settings.spectrogram_pos = 0;
734 else
736 /* In vertical spectrogram mode, erase the popup */
737 lcd_(set_foreground)(COLOR_DEFAULT_BG);
738 lcd_(fillrect)(graph_settings.spectrogram_pos + 1, 0,
739 LCD_WIDTH, y);
740 lcd_(set_foreground)(COLOR_DEFAULT_FG);
743 /* else These modes clear the screen themselves */
745 last_message = NULL;
748 lcd_(update)();
750 graph_settings.changed.clear_all = false;
753 void draw_lines_vertical(void)
755 static int max = 0;
757 #if LCD_WIDTH < ARRAYLEN_PLOT /* graph compression */
758 const int offset = 0;
759 const int plotwidth = LCD_WIDTH;
760 #else
761 const int offset = (LCD_HEIGHT - ARRAYLEN_PLOT) / 2;
762 const int plotwidth = ARRAYLEN_PLOT;
763 #endif
765 int this_max;
766 int i, x;
768 if(graph_settings.changed.amp_scale)
769 max = 0; /* reset the graph on scaling mode change */
771 this_max = calc_magnitudes(graph_settings.logarithmic_amp);
773 if(this_max == 0)
775 lcd_(hline)(0, LCD_WIDTH - 1, LCD_HEIGHT - 1); /* Draw all "zero" */
776 return;
779 if(graph_settings.logarithmic_freq)
780 logarithmic_plot_translate();
782 /* take the maximum of neighboring bins if we have to scale the graph
783 * horizontally */
784 if(LCD_WIDTH < ARRAYLEN_PLOT) /* graph compression */
786 int bins_acc = LCD_WIDTH / 2;
787 int bins_max = 0;
789 i = 0, x = 0;
791 for(;;)
793 int bin = plot[i++];
795 if(bin > bins_max)
796 bins_max = bin;
798 bins_acc += LCD_WIDTH;
800 if(bins_acc >= ARRAYLEN_PLOT)
802 plot[x] = bins_max;
804 if(bins_max > max)
805 max = bins_max;
807 if(++x >= LCD_WIDTH)
808 break;
810 bins_acc -= ARRAYLEN_PLOT;
811 bins_max = 0;
815 else
817 if(this_max > max)
818 max = this_max;
821 for(x = 0; x < plotwidth; ++x)
823 int h = LCD_HEIGHT*plot[x] / max;
824 lcd_(vline)(x + offset, LCD_HEIGHT - h, LCD_HEIGHT-1);
828 void draw_lines_horizontal(void)
830 static int max = 0;
832 #if LCD_WIDTH < ARRAYLEN_PLOT /* graph compression */
833 const int offset = 0;
834 const int plotwidth = LCD_HEIGHT;
835 #else
836 const int offset = (LCD_HEIGHT - ARRAYLEN_PLOT) / 2;
837 const int plotwidth = ARRAYLEN_PLOT;
838 #endif
840 int this_max;
841 int y;
843 if(graph_settings.changed.amp_scale)
844 max = 0; /* reset the graph on scaling mode change */
846 this_max = calc_magnitudes(graph_settings.logarithmic_amp);
848 if(this_max == 0)
850 lcd_(vline)(0, 0, LCD_HEIGHT-1); /* Draw all "zero" */
851 return;
854 if(graph_settings.logarithmic_freq)
855 logarithmic_plot_translate();
857 /* take the maximum of neighboring bins if we have to scale the graph
858 * horizontally */
859 if(LCD_HEIGHT < ARRAYLEN_PLOT) /* graph compression */
861 int bins_acc = LCD_HEIGHT / 2;
862 int bins_max = 0;
863 int i = 0;
865 y = 0;
867 for(;;)
869 int bin = plot[i++];
871 if (bin > bins_max)
872 bins_max = bin;
874 bins_acc += LCD_HEIGHT;
876 if(bins_acc >= ARRAYLEN_PLOT)
878 plot[y] = bins_max;
880 if(bins_max > max)
881 max = bins_max;
883 if(++y >= LCD_HEIGHT)
884 break;
886 bins_acc -= ARRAYLEN_PLOT;
887 bins_max = 0;
891 else
893 if(this_max > max)
894 max = this_max;
897 for(y = 0; y < plotwidth; ++y)
899 int w = LCD_WIDTH*plot[y] / max;
900 lcd_(hline)(0, w - 1, y + offset);
904 void draw_bars_vertical(void)
906 static int max = 0;
908 #if LCD_WIDTH < LCD_HEIGHT
909 const int bars = 15;
910 #else
911 const int bars = 20;
912 #endif
913 const int border = 2;
914 const int barwidth = LCD_WIDTH / (bars + border);
915 const int width = barwidth - border;
916 const int offset = (LCD_WIDTH - bars*barwidth) / 2;
918 if(graph_settings.changed.amp_scale)
919 max = 0; /* reset the graph on scaling mode change */
921 lcd_(hline)(0, LCD_WIDTH-1, LCD_HEIGHT-1); /* Draw baseline */
923 if(calc_magnitudes(graph_settings.logarithmic_amp) == 0)
924 return; /* nothing more to draw */
926 if(graph_settings.logarithmic_freq)
927 logarithmic_plot_translate();
929 int bins_acc = bars / 2;
930 int bins_max = 0;
931 int x = 0, i = 0;
933 for(;;)
935 int bin = plot[i++];
937 if(bin > bins_max)
938 bins_max = bin;
940 bins_acc += bars;
942 if(bins_acc >= ARRAYLEN_PLOT)
944 plot[x] = bins_max;
946 if(bins_max > max)
947 max = bins_max;
949 if(++x >= bars)
950 break;
952 bins_acc -= ARRAYLEN_PLOT;
953 bins_max = 0;
957 for(i = 0, x = offset; i < bars; ++i, x += barwidth)
959 int h = LCD_HEIGHT * plot[i] / max;
960 lcd_(fillrect)(x, LCD_HEIGHT - h, width, h - 1);
964 void draw_bars_horizontal(void)
966 static int max = 0;
968 #if LCD_WIDTH < LCD_HEIGHT
969 const int bars = 20;
970 #else
971 const int bars = 15;
972 #endif
973 const int border = 2;
974 const int barwidth = LCD_HEIGHT / (bars + border);
975 const int height = barwidth - border;
976 const int offset = (LCD_HEIGHT - bars*barwidth) / 2;
978 if(graph_settings.changed.amp_scale)
979 max = 0; /* reset the graph on scaling mode change */
981 lcd_(vline)(0, 0, LCD_HEIGHT-1); /* Draw baseline */
983 if(calc_magnitudes(graph_settings.logarithmic_amp) == 0)
984 return; /* nothing more to draw */
986 if(graph_settings.logarithmic_freq)
987 logarithmic_plot_translate();
989 int bins_acc = bars / 2;
990 int bins_max = 0;
991 int y = 0, i = 0;
993 for(;;)
995 int bin = plot[i++];
997 if (bin > bins_max)
998 bins_max = bin;
1000 bins_acc += bars;
1002 if(bins_acc >= ARRAYLEN_PLOT)
1004 plot[y] = bins_max;
1006 if(bins_max > max)
1007 max = bins_max;
1009 if(++y >= bars)
1010 break;
1012 bins_acc -= ARRAYLEN_PLOT;
1013 bins_max = 0;
1017 for(i = 0, y = offset; i < bars; ++i, y += barwidth)
1019 int w = LCD_WIDTH * plot[i] / max;
1020 lcd_(fillrect)(1, y, w, height);
1024 void draw_spectrogram_vertical(void)
1026 const int32_t scale_factor = MIN(LCD_HEIGHT, ARRAYLEN_PLOT);
1028 calc_magnitudes(graph_settings.logarithmic_amp);
1030 if(graph_settings.logarithmic_freq)
1031 logarithmic_plot_translate();
1033 int bins_acc = scale_factor / 2;
1034 int bins_max = 0;
1035 int y = 0, i = 0;
1037 for(;;)
1039 int bin = plot[i++];
1041 if(bin > bins_max)
1042 bins_max = bin;
1044 bins_acc += scale_factor;
1046 if(bins_acc >= ARRAYLEN_PLOT)
1048 unsigned index;
1050 if(graph_settings.logarithmic_amp)
1051 index = (SHADES-1)*bins_max / QLOG_MAX;
1052 else
1053 index = (SHADES-1)*bins_max / QLIN_MAX;
1055 /* These happen because we exaggerate the graph a little for
1056 * linear mode */
1057 if(index >= SHADES)
1058 index = SHADES-1;
1060 lcd_(set_foreground)(SPECTROGRAPH_PALETTE(index));
1061 lcd_(drawpixel)(graph_settings.spectrogram_pos,
1062 scale_factor-1 - y);
1064 if(++y >= scale_factor)
1065 break;
1067 bins_acc -= ARRAYLEN_PLOT;
1068 bins_max = 0;
1072 if(graph_settings.spectrogram_pos < LCD_WIDTH-1)
1073 graph_settings.spectrogram_pos++;
1074 else
1075 lcd_scroll_left(1);
1078 void draw_spectrogram_horizontal(void)
1080 const int32_t scale_factor = MIN(LCD_WIDTH, ARRAYLEN_PLOT);
1082 calc_magnitudes(graph_settings.logarithmic_amp);
1084 if(graph_settings.logarithmic_freq)
1085 logarithmic_plot_translate();
1087 int bins_acc = scale_factor / 2;
1088 int bins_max = 0;
1089 int x = 0, i = 0;
1091 for(;;)
1093 int bin = plot[i++];
1095 if(bin > bins_max)
1096 bins_max = bin;
1098 bins_acc += scale_factor;
1100 if(bins_acc >= ARRAYLEN_PLOT)
1102 unsigned index;
1104 if(graph_settings.logarithmic_amp)
1105 index = (SHADES-1)*bins_max / QLOG_MAX;
1106 else
1107 index = (SHADES-1)*bins_max / QLIN_MAX;
1109 /* These happen because we exaggerate the graph a little for
1110 * linear mode */
1111 if(index >= SHADES)
1112 index = SHADES-1;
1114 lcd_(set_foreground)(SPECTROGRAPH_PALETTE(index));
1115 lcd_(drawpixel)(x, graph_settings.spectrogram_pos);
1117 if(++x >= scale_factor)
1118 break;
1120 bins_acc -= ARRAYLEN_PLOT;
1121 bins_max = 0;
1125 if(graph_settings.spectrogram_pos < LCD_HEIGHT-1)
1126 graph_settings.spectrogram_pos++;
1127 else
1128 lcd_scroll_up(1);
1131 /********************* End of plotting functions (modes) *********************/
1133 /****************************** FFT functions ********************************/
1135 /** functions use in single/multi configuration **/
1136 static inline bool fft_init_fft_lib(void)
1138 size_t size = sizeof(buffer);
1139 fft_state = FFT_ALLOC(FFT_SIZE, 0, buffer, &size);
1141 if(fft_state == NULL)
1143 DEBUGF("needed data: %i", (int) size);
1144 return false;
1147 return true;
1150 static inline bool fft_get_fft(void)
1152 int count;
1153 int16_t *value = (int16_t *) rb->pcm_get_peak_buffer(&count);
1154 /* This block can introduce discontinuities in our data. Meaning, the
1155 * FFT will not be done a continuous segment of the signal. Which can
1156 * be bad. Or not.
1158 * Anyway, this is a demo, not a scientific tool. If you want accuracy,
1159 * do a proper spectrum analysis.*/
1161 /* there are cases when we don't have enough data to fill the buffer */
1162 if(count != ARRAYLEN_IN/2)
1164 if(count < ARRAYLEN_IN/2)
1165 return false;
1167 count = ARRAYLEN_IN/2; /* too much - limit */
1170 int fft_idx = 0; /* offset in 'input' */
1174 kiss_fft_scalar left = *value++;
1175 kiss_fft_scalar right = *value++;
1176 input[fft_idx++] = (left + right) >> 1; /* to mono */
1177 input[fft_idx++] = 0;
1178 } while (--count > 0);
1180 apply_window_func(graph_settings.window_func);
1182 rb->yield();
1184 FFT_FFT(fft_state, input, output[output_tail]);
1186 rb->yield();
1188 return true;
1191 #if NUM_CORES > 1
1192 /* use a worker thread if there is another processor core */
1193 static volatile bool fft_thread_run SHAREDDATA_ATTR = false;
1194 static unsigned long fft_thread;
1196 static long fft_thread_stack[CACHEALIGN_UP(DEFAULT_STACK_SIZE*4/sizeof(long))]
1197 CACHEALIGN_AT_LEAST_ATTR(4);
1199 static void fft_thread_entry(void)
1201 if (!fft_init_fft_lib())
1203 output_tail = -1; /* tell that we bailed */
1204 fft_thread_run = true;
1205 return;
1208 fft_thread_run = true;
1210 while(fft_thread_run)
1212 if (!rb->pcm_is_playing())
1214 rb->sleep(HZ/5);
1215 continue;
1218 if (!fft_get_fft())
1220 rb->sleep(0); /* not enough - ease up */
1221 continue;
1224 #if NUM_CORES > 1
1225 /* write back output for other processor and invalidate for next frame read */
1226 rb->cpucache_invalidate();
1227 #endif
1228 int new_tail = output_tail ^ 1;
1230 /* if full, block waiting until reader has freed a slot */
1231 while(fft_thread_run)
1233 if(new_tail != output_head)
1235 output_tail = new_tail;
1236 break;
1239 rb->sleep(0);
1244 static bool fft_have_fft(void)
1246 return output_head != output_tail;
1249 /* Call only after fft_have_fft() has returned true */
1250 static inline void fft_free_fft_output(void)
1252 output_head ^= 1; /* finished with this */
1255 static bool fft_init_fft(void)
1257 /* create worker thread - on the COP for dual-core targets */
1258 fft_thread = rb->create_thread(fft_thread_entry,
1259 fft_thread_stack, sizeof(fft_thread_stack), 0, "fft output thread"
1260 IF_PRIO(, PRIORITY_USER_INTERFACE+1) IF_COP(, COP));
1262 if(fft_thread == 0)
1264 rb->splash(HZ, "FFT thread failed create");
1265 return false;
1268 /* wait for it to indicate 'ready' */
1269 while(fft_thread_run == false)
1270 rb->sleep(0);
1272 if(output_tail == -1)
1274 /* FFT thread bailed-out like The Fed */
1275 rb->thread_wait(fft_thread);
1276 rb->splash(HZ, "FFT thread failed to init");
1277 return false;
1280 return true;
1283 static void fft_close_fft(void)
1285 /* Handle our FFT thread. */
1286 fft_thread_run = false;
1287 rb->thread_wait(fft_thread);
1288 #if NUM_CORES > 1
1289 rb->cpucache_invalidate();
1290 #endif
1292 #else /* NUM_CORES == 1 */
1293 /* everything serialize on single-core and FFT gets to use IRAM main stack if
1294 * target uses IRAM */
1295 static bool fft_have_fft(void)
1297 return fft_get_fft();
1300 static inline void fft_free_fft_output(void)
1302 /* nothing to do */
1305 static bool fft_init_fft(void)
1307 return fft_init_fft_lib();
1310 static inline void fft_close_fft(void)
1312 /* nothing to do */
1314 #endif /* NUM_CORES */
1315 /*************************** End of FFT functions ****************************/
1317 enum plugin_status plugin_start(const void* parameter)
1319 /* Defaults */
1320 bool run = true;
1321 bool showing_warning = false;
1323 if (!fft_init_fft())
1324 return PLUGIN_ERROR;
1326 #ifndef HAVE_LCD_COLOR
1327 unsigned char *gbuf;
1328 size_t gbuf_size = 0;
1329 /* get the remainder of the plugin buffer */
1330 gbuf = (unsigned char *) rb->plugin_get_buffer(&gbuf_size);
1332 /* initialize the greyscale buffer.*/
1333 if (!grey_init(gbuf, gbuf_size, GREY_ON_COP | GREY_BUFFERED,
1334 LCD_WIDTH, LCD_HEIGHT, NULL))
1336 rb->splash(HZ, "Couldn't init greyscale display");
1337 fft_close_fft();
1338 return PLUGIN_ERROR;
1340 grey_show(true);
1341 #endif
1343 logarithmic_plot_init();
1345 #if LCD_DEPTH > 1
1346 rb->lcd_set_backdrop(NULL);
1347 lcd_(clear_display)();
1348 lcd_(update)();
1349 #endif
1350 backlight_force_on();
1352 #ifdef HAVE_ADJUSTABLE_CPU_FREQ
1353 rb->cpu_boost(true);
1354 #endif
1356 while (run)
1358 int button;
1360 while (!fft_have_fft())
1362 int timeout;
1364 if(!rb->pcm_is_playing())
1366 showing_warning = true;
1367 lcd_(clear_display)();
1368 draw_message_string("No audio playing", false);
1369 lcd_(update)();
1370 timeout = HZ/5;
1372 else
1374 if(showing_warning)
1376 showing_warning = false;
1377 lcd_(clear_display)();
1378 lcd_(update)();
1381 timeout = HZ/100;
1384 /* Make sure the input thread has produced something before doing
1385 * anything but watching for buttons. Music might not be playing
1386 * or things just aren't going well for picking up buffers so keys
1387 * are scanned to avoid lockup. */
1388 button = rb->button_get_w_tmo(timeout);
1389 if (button != BUTTON_NONE)
1390 goto read_button;
1393 draw(NULL);
1395 fft_free_fft_output(); /* COP only */
1397 rb->yield();
1399 button = rb->button_get(false);
1400 read_button:
1401 switch (button)
1403 case FFT_QUIT:
1404 run = false;
1405 break;
1406 case FFT_PREV_GRAPH: {
1407 if (graph_settings.mode-- <= FFT_DM_FIRST)
1408 graph_settings.mode = FFT_DM_COUNT-1;
1409 graph_settings.changed.mode = true;
1410 draw(modes_text[graph_settings.mode]);
1411 break;
1413 case FFT_NEXT_GRAPH: {
1414 if (++graph_settings.mode >= FFT_DM_COUNT)
1415 graph_settings.mode = FFT_DM_FIRST;
1416 graph_settings.changed.mode = true;
1417 draw(modes_text[graph_settings.mode]);
1418 break;
1420 case FFT_WINDOW: {
1421 if(++graph_settings.window_func >= FFT_WF_COUNT)
1422 graph_settings.window_func = FFT_WF_FIRST;
1423 graph_settings.changed.window_func = true;
1424 draw(window_text[graph_settings.window_func]);
1425 break;
1427 case FFT_AMP_SCALE: {
1428 graph_settings.logarithmic_amp = !graph_settings.logarithmic_amp;
1429 graph_settings.changed.amp_scale = true;
1430 draw(amp_scales_text[graph_settings.logarithmic_amp ? 1 : 0]);
1431 break;
1433 #ifdef FFT_FREQ_SCALE /* 'Till all keymaps are defined */
1434 case FFT_FREQ_SCALE: {
1435 graph_settings.logarithmic_freq = !graph_settings.logarithmic_freq;
1436 graph_settings.changed.freq_scale = true;
1437 draw(freq_scales_text[graph_settings.logarithmic_freq ? 1 : 0]);
1438 break;
1440 #endif
1441 case FFT_ORIENTATION: {
1442 graph_settings.orientation_vertical =
1443 !graph_settings.orientation_vertical;
1444 graph_settings.changed.orientation = true;
1445 draw(NULL);
1446 break;
1448 default: {
1449 if (rb->default_event_handler(button) == SYS_USB_CONNECTED)
1450 return PLUGIN_USB_CONNECTED;
1456 fft_close_fft();
1458 #ifdef HAVE_ADJUSTABLE_CPU_FREQ
1459 rb->cpu_boost(false);
1460 #endif
1461 #ifndef HAVE_LCD_COLOR
1462 grey_release();
1463 #endif
1464 backlight_use_settings();
1465 return PLUGIN_OK;
1466 (void)parameter;