fix(audio): borne amplitude tone_gen a int16
Sature s dans [-32768, 32767] avant le cast int16_t pour eviter l'UB C99. Documente le contrat dans l'en-tete. Ajoute assertion 5/5 : amplitude 40000 ne deborde pas.
This commit is contained in:
@@ -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);
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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 */
|
||||
|
||||
Reference in New Issue
Block a user