Skip to content

Clamp float samples to [-1, 1] before scaling to short - #5

Open
austek wants to merge 1 commit into
espeak-ng:masterfrom
ZirekHQ:fix/float-sample-clamping-espeak
Open

Clamp float samples to [-1, 1] before scaling to short#5
austek wants to merge 1 commit into
espeak-ng:masterfrom
ZirekHQ:fix/float-sample-clamping-espeak

Conversation

@austek

@austek austek commented Aug 23, 2026

Copy link
Copy Markdown

Summary

addFloatSamplesToInputBuffer multiplied each input float by 32767.0f and assigned the result directly into a short, with no range check. sonic.h documents that values must be in [-1, 1], but nothing enforced it, and converting an out-of-range float to short is undefined behavior in C, not just lossy truncation. Every other input path in this file (volume, speed, pitch, rate, sample rate, channel count, and scaleSamples' int16 output) clamps defensively instead of trusting the caller; this path was the exception.

Clamps with the existing CLAMP macro before the multiply.

Same bug, same fix as waywardgeek/sonic#63 — this repo's addFloatSamplesToInputBuffer is byte-identical to what that file had upstream, so the fix ports directly.

Test plan

  • cd tests && make runtests && ./runtests — passes, adds sonicTestFloatSampleClamping to tests/input_clamping_test.c
  • Same build under -fsanitize=address,undefined — no finding from this path; only the separate, already-known findSincCoefficient left-shift issue remains

addFloatSamplesToInputBuffer multiplied each input float by 32767.0f
and assigned the result directly into a short, with no range check.
sonic.h documents that values must be in [-1, 1], but nothing
enforced it, and converting an out-of-range float to short is
undefined behavior in C, not just lossy truncation. Every other input
path in this file (volume, speed, pitch, rate, sample rate, channel
count, and scaleSamples' int16 output) clamps defensively instead of
trusting the caller; this path was the exception.

Clamp with the existing CLAMP macro before the multiply.

Adds sonicTestFloatSampleClamping to tests/input_clamping_test.c,
writing out-of-range floats and checking the output stays within
[-32767, 32767] via the bit-exact passthrough path that default
stream settings take.

Ported from waywardgeek/sonic#63, which fixes the same bug (also
present here, byte-identical addFloatSamplesToInputBuffer) upstream.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant