From cb2b7af8fd8d33226c02c6f2e33dc4bd67ef5bc8 Mon Sep 17 00:00:00 2001 From: Wim Taymans Date: Tue, 6 Feb 2024 11:34:27 +0100 Subject: [PATCH] tutorial: fix s16 scale and add some docs The float -> s16 scale value is 32767 or 32768 with clamping. Fix this and add some docs. Fixes #3838 --- doc/examples/tutorial4.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/doc/examples/tutorial4.c b/doc/examples/tutorial4.c index bc445868b..0b691fefd 100644 --- a/doc/examples/tutorial4.c +++ b/doc/examples/tutorial4.c @@ -50,7 +50,13 @@ static void on_process(void *userdata) if (data->accumulator >= M_PI_M2) data->accumulator -= M_PI_M2; - val = sin(data->accumulator) * DEFAULT_VOLUME * 16767.f; + /* sin() gives a value between -1.0 and 1.0, we first apply + * the volume and then scale with 32767.0 to get a 16 bits value + * between [-32767 32767]. + * Another common method to convert a double to + * 16 bits is to multiple by 32768.0 and then clamp to + * [-32768 32767] to get the full 16 bits range. */ + val = sin(data->accumulator) * DEFAULT_VOLUME * 32767.0; for (c = 0; c < DEFAULT_CHANNELS; c++) *dst++ = val; }