diff --git a/Makefile b/Makefile index 6520d49..2826b61 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,10 @@ CC = gcc CFLAGS = -g3 -Wall -Wextra -pedantic -Wconversion -Wdouble-promotion \ -Wno-unused-parameter -Wno-unused-function -Wno-sign-conversion \ - -fsanitize=undefined -fsanitize-trap -fanalyzer + -fsanitize=undefined -fsanitize=float-cast-overflow -fsanitize=float-divide-by-zero \ + -fsanitize=address +#CFLAGS += -fsanitize-trap +CFLAGS += -fanalyzer main: main.c synth.c $(CC) $(CFLAGS) -o main main.c synth.c -lasound -lm diff --git a/main.c b/main.c index 78c985d..0a626c2 100644 --- a/main.c +++ b/main.c @@ -6,6 +6,7 @@ #include #include "synth.h" +#define clamp(n, a, b) ((n) < (a) ? (a) : (n) > (b) ? (b) : (n)) #define ALSA_CHK(stmt, msg) do { \ int alsa_chk_err = (stmt); \ if (alsa_chk_err < 0) { \ @@ -221,10 +222,10 @@ int main(int argc, const char** argv) { // mix voices into playing buffer for (size_t i = 0; i < PLAYBACK_BUFFER_SIZE; i++) { // TODO: handle saturation (sum ouf of int16 range) - playing_buffer[i] = (int16_t) (mixing_buffer[i] * (float) INT16_MAX); + playing_buffer[i] = (int16_t) clamp((mixing_buffer[i] * (float) INT16_MAX), INT16_MIN, INT16_MAX); } - if (write_audio(handle, playing_buffer) < 0) { + if (write_audio(handle, playing_buffer) != 0) { return 1; } } diff --git a/synth.c b/synth.c index d01ec0d..d37a42b 100644 --- a/synth.c +++ b/synth.c @@ -5,7 +5,8 @@ void play_note(Note *note, float *buffer, int buffer_size) { for (int i = 0; i < buffer_size; i++) { // update phase counter - note->phase = fmodf(note->phase + note->freq / SAMPLE_RATE, 1.0f); + note->phase = note->phase + note->freq / SAMPLE_RATE; + if (note->phase >= 1.0f) { note->phase -= 1.0f; } // oscillator float sample = 0.0f; @@ -21,9 +22,11 @@ void play_note(Note *note, float *buffer, int buffer_size) { //sample = note->lp; // basic attack / release + float attack_sec = fmaxf(note->attack_ms / 1000.0f, 1e-6f); // apply minimum value to avoid division by zero + float release_sec = fmaxf(note->release_ms / 1000.0f, 1e-6f); // convert attack / release time to a number of steps to reach target gain - float attack_step = 0.2f / ((note->attack_ms / 1000.0f) * SAMPLE_RATE); - float release_step = 0.2f / ((note->release_ms / 1000.0f) * SAMPLE_RATE); + float attack_step = 0.2f / (attack_sec * SAMPLE_RATE); + float release_step = 0.2f / (release_sec * SAMPLE_RATE); note->gain = note->is_playing ? fminf(note->gain + attack_step, 0.2f) // attack : fmaxf(note->gain - release_step, 0); // release diff --git a/todo.txt b/todo.txt index a06c7ce..7692ae2 100644 --- a/todo.txt +++ b/todo.txt @@ -6,3 +6,4 @@ - filters - DSP - wavetables +- monophonic w/ legato