fix: use rounding for float-to-integer conversions - #191
Conversation
0d048b3 to
78bf2c3
Compare
|
Rebased and passing the CI now. |
Replace truncating casts with proper rounding in float-to-integer sample conversions to eliminate bias and preserve small signals. Changes: - Use f32::round() and f64::round() instead of truncating `as` casts - Eliminates bias towards zero from truncation behavior - Preserves small audio signals that would otherwise be truncated to zero - Removes nonlinear distortion caused by signal values in (-1.0, 1.0) all mapping to zero, creating an interval twice as large as any other Inlines sqrt and round functions for performance. Additional tests verify proper rounding behavior for cases that would fail with truncation.
78bf2c3 to
4ce63ed
Compare
|
Reproduced on dasp_sample 0.11.0 from crates.io, through the documented The last line is a sweep of 4001 evenly spaced f32 values across (-2 LSB, +2 LSB) into i16. The zero bin holds twice as many inputs as the -1 or +1 bin. That matches the two effects the PR description names: values inside (-1 LSB, +1 LSB) collapse to zero, and everything else is biased toward zero by up to one LSB. This path runs in published consumers. web-audio-api calls Could this get a review and merge, followed by a dasp_sample release? The only version on crates.io is 0.11.0 from 2020, so no published build carries the fix yet. |
This PR replaces truncating casts with proper rounding in float-to-integer sample conversions to eliminate systematic bias and nonlinear distortion.
Problem
The current implementation uses truncating casts (e.g.
as i16), which creates two issues:Nonlinear distortion: All signal values in the interval (-1.0, 1.0) map to zero, creating an output bin twice as large as any other integer value. This violates the uniform quantization assumption and introduces harmonic distortion.
Systematic bias towards zero: Small signals that should map to ±1 are instead lost to zero, introducing DC bias and reducing effective dynamic range by about 8 dB.
One publication that documents this is Dannenberg's "Danger in Floating-Point-to-Integer Conversion" letter to Computer Music Journal in 2002, which warns against truncation in audio applications.
Solution
Replace
(s * scale) as {integer}with(s * scale).round() as {integer}for float-to-integer conversions.Before (truncation):
After (rounding):
The performance impact is minimal, because LLVM generates efficient code for
round()intrinsics with dedicated instructions on most targets.