Skip to content

Instantly share code, notes, and snippets.

@greed9
Created October 8, 2022 20:17
Show Gist options
  • Save greed9/8dea608aea78e21f2cf48e3c1c66b494 to your computer and use it in GitHub Desktop.
Save greed9/8dea608aea78e21f2cf48e3c1c66b494 to your computer and use it in GitHub Desktop.
Display integer fft results from stdin as ascii chars using ncurses. Ugly but fast
#include <stdio.h>
#include <errno.h>
#include <string.h>
// based in part on: https://www.linuxjournal.com/content/getting-started-ncurses
#include <curses.h>
#include <stdlib.h>
#define FFT_SIZE (256)
#define ABS(x) ( (x )< 0 ? -(x) : (x))
// pipe from: arecord -D plughw:1,0 -c 1 -V mono -f S16_LE -t wav -r 44100 tmp.out
const char* intensity_map = " .:-=+*#%@" ;
static short fft_buf[FFT_SIZE] = {0};
int fft_size = 256 ;
short map( short x, short in_min, short in_max, short out_min, short out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
int choose_color(short mapped_val )
{
switch( mapped_val)
{
case 0:
return COLOR_BLACK ;
case 1:
return COLOR_RED ;
case 2:
return COLOR_GREEN ;
case 3:
return COLOR_YELLOW;
case 4:
return COLOR_BLUE ;
case 5:
return COLOR_MAGENTA;
case 6:
return COLOR_GREEN ;
case 7:
return COLOR_WHITE ;
default:
return COLOR_BLACK ;
}
}
int main( )
{
int maxlines = 20;
int maxcols = FFT_SIZE / 2;
/* initialize curses */
initscr();
start_color( ) ;
cbreak();
noecho();
WINDOW *fft_win = newwin(50, FFT_SIZE / 2, 0, 0);
wclear(fft_win);
scrollok(fft_win, 1) ;
init_pair(1, COLOR_RED, COLOR_BLACK);
init_pair(2, COLOR_GREEN, COLOR_BLACK);
init_pair(3, COLOR_YELLOW, COLOR_BLACK);
init_pair(4, COLOR_BLUE, COLOR_BLACK);
init_pair(5, COLOR_MAGENTA, COLOR_BLACK);
init_pair(6, COLOR_CYAN, COLOR_BLACK);
init_pair(7, COLOR_WHITE, COLOR_BLACK);
init_pair(8, COLOR_BLACK, COLOR_BLACK) ;
if (!freopen(NULL, "rb", stdin))
{
fprintf(stderr, "freopen failed. error: %s\n", strerror(errno));
getch( ) ;
endwin( ) ;
return 1 ;
}
int scaled_value = 0 ;
int color_number = 0 ;
int x = 0 ;
int y = 0 ;
size_t n_read = fread( fft_buf, 1, FFT_SIZE, stdin) ;
while( n_read )
{
for( int y = 0 ; y < FFT_SIZE / 2 ; y++)
{
scaled_value = map( ABS(fft_buf[y]), ( short) 0, (short) 100, (short) 0, (short) 7 );
if( scaled_value > 7)
{
scaled_value = 7 ;
}
color_number = choose_color(scaled_value) ;
wattron( fft_win, COLOR_PAIR(color_number));
waddch( fft_win, intensity_map[scaled_value]) ;
wattroff( fft_win, COLOR_PAIR(8));
}
wrefresh( fft_win) ;
n_read = fread( fft_buf, 1, FFT_SIZE, stdin) ;
//scroll(fft_win) ;
}
wrefresh(fft_win) ;
endwin( ) ;
return 0 ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment