From e2225d60988d46af309a850c5c875d05daf0b45f Mon Sep 17 00:00:00 2001 From: Kamal Mostafa Date: Mon, 13 Aug 2012 21:09:24 -0700 Subject: [PATCH] simple-tone: sin() lookup tables --- src/simple-tone-generator.c | 90 +++++++++++++++++++++++++++++++++---- src/simpleaudio.h | 4 +- 2 files changed, 85 insertions(+), 9 deletions(-) diff --git a/src/simple-tone-generator.c b/src/simple-tone-generator.c index c9badbf..1fa033a 100644 --- a/src/simple-tone-generator.c +++ b/src/simple-tone-generator.c @@ -1,7 +1,7 @@ /* * simple-tone-generator.c * - * Copyright (C) 2011 Kamal Mostafa + * Copyright (C) 2011-2012 Kamal Mostafa * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -26,6 +26,67 @@ #include "simpleaudio.h" + +static unsigned int sin_table_len; +static short *sin_table_short; +static float *sin_table_float; + +void +simpleaudio_tone_init( unsigned int new_sin_table_len ) +{ + sin_table_len = new_sin_table_len; + + if ( sin_table_len != 0 ) { + sin_table_short = realloc(sin_table_short, sin_table_len * sizeof(short)); + sin_table_float = realloc(sin_table_float, sin_table_len * sizeof(float)); + if ( !sin_table_short || !sin_table_float ) { + perror("malloc"); + assert(0); + } + + unsigned int i; + for ( i=0; i= 0 && t < sin_table_len ); + return sin_table_short[t]; +} + +/* + * in: turns (0.0 to 1.0) out: -1.0 to +1.0 + */ +static inline float +sin_lu_float( float turns ) +{ + turns = fmodf(turns, 1.0); + int t = (float)sin_table_len * turns; + // assert ( t >= 0 && t < sin_table_len ); + return sin_table_float[t]; +} + + /* "current" phase state of the tone generator */ static float sa_tone_cphase = 0.0; @@ -48,25 +109,38 @@ simpleaudio_tone(simpleaudio *sa_out, float tone_freq, size_t nsamples_dur) float wave_nsamples = simpleaudio_get_rate(sa_out) / tone_freq; size_t i; -#define SINE_PHASE_ANGLE ( M_PI*2.0*(i/wave_nsamples + sa_tone_cphase) ) +#define TURNS_TO_RADIANS(t) ( M_PI*2.0 * (t) ) + +#define SINE_PHASE_TURNS ( (float)i/wave_nsamples + sa_tone_cphase ) +#define SINE_PHASE_RADIANS TURNS_TO_RADIANS(SINE_PHASE_TURNS) switch ( simpleaudio_get_format(sa_out) ) { case SA_SAMPLE_FORMAT_FLOAT: { float *float_buf = buf; - for ( i=0; i + * Copyright (C) 2011-2012 Kamal Mostafa * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -95,5 +95,7 @@ simpleaudio_tone_reset(); void simpleaudio_tone(simpleaudio *sa_out, float tone_freq, size_t nsamples_dur); +void +simpleaudio_tone_init( unsigned int new_sin_table_len ); #endif