realnc / SDL_audiolib

An audio decoding, resampling and mixing library for SDL.
GNU Lesser General Public License v3.0
43 stars 8 forks source link

Eliminate audio delay on second frame of stream playback #28

Closed StephenCWills closed 3 years ago

StephenCWills commented 3 years ago

Based on the issue reported in devilutionX: diasurgical/devilutionX#2888

On my Debian Bullseye system, it seems that a buffer length of 2048 at 22 kHz will result in a buffer duration of ~46 milliseconds. The timer that invokes the audio callback on that system seems to operate at a 25-millisecond resolution, so the interval between callbacks will typically be around either 52 milliseconds or 27 milliseconds. If the delay on the first frame happens to be rather small--for example, 6 milliseconds--and the interval between the first and second frame happens to be 27 milliseconds, the ticks_since_play_start on the second frame works out to be less than the 46-millisecond buffer duration--33 milliseconds in our example. In this case, the logic will cause the second frame to be delayed as well, causing a blip in the audio.

In other words, we need a more reliable way to determine whether the delay for a given stream should be applied to the current audio frame. That's the idea behind this PR.

FYI, this also suggests that the delay is only consistent up to to the resolution of the system timer. This could perhaps be improved by capturing the time of the first callback and the total number of callbacks, although that logic could instead be dependent on system performance. Regardless, I deemed it to be out of scope for this fix.

realnc commented 3 years ago

Thanks!