diff --git a/components/tone_gen/include/tone_gen.h b/components/tone_gen/include/tone_gen.h index eb81c2d..2e433b3 100644 --- a/components/tone_gen/include/tone_gen.h +++ b/components/tone_gen/include/tone_gen.h @@ -8,7 +8,8 @@ extern "C" { /* Fill `buf` with n_frames stereo frames (L == R) of a sine wave. * buf must hold n_frames*2 int16_t. *phase is the running mono sample index, - * advanced by n_frames. amplitude is the peak amplitude in int16 units. */ + * advanced by n_frames. amplitude is the peak amplitude (the output is clamped + * to the int16 range [-32768, 32767], so values above 32767 saturate). */ void tone_gen_fill_stereo(int16_t *buf, int n_frames, uint32_t *phase, float freq_hz, float amplitude, uint32_t sample_rate); diff --git a/components/tone_gen/test_tone_gen.c b/components/tone_gen/test_tone_gen.c index 0d06ac8..3cc4625 100644 --- a/components/tone_gen/test_tone_gen.c +++ b/components/tone_gen/test_tone_gen.c @@ -32,6 +32,16 @@ int main(void) int16_t got = buf2[4 * 2]; assert(fabsf((float)got - expected) < 2.0f); - printf("tone_gen: 4/4 assertions OK\n"); + /* 5. Saturation : une amplitude > 32767 ne doit jamais déborder l'int16. */ + uint32_t ph3 = 0; + int16_t buf3[256 * 2]; + tone_gen_fill_stereo(buf3, 256, &ph3, 440.0f, 40000.0f, 16000); + for (int i = 0; i < 256; i++) { + assert(buf3[i*2] <= 32767); + assert(buf3[i*2] >= -32768); + assert(buf3[i*2] == buf3[i*2+1]); + } + + printf("tone_gen: 5/5 assertions OK\n"); return 0; } diff --git a/components/tone_gen/tone_gen.c b/components/tone_gen/tone_gen.c index 753357a..5e4be77 100644 --- a/components/tone_gen/tone_gen.c +++ b/components/tone_gen/tone_gen.c @@ -11,6 +11,8 @@ void tone_gen_fill_stereo(int16_t *buf, int n_frames, uint32_t *phase, for (int i = 0; i < n_frames; i++) { float s = amplitude * sinf(2.0f * (float)M_PI * freq_hz * (float)(*phase) / (float)sample_rate); + if (s > 32767.0f) s = 32767.0f; + if (s < -32768.0f) s = -32768.0f; int16_t v = (int16_t)s; buf[i * 2] = v; /* L */ buf[i * 2 + 1] = v; /* R */