devkitPro / SDL

Simple Directmedia Layer
https://libsdl.org
zlib License
11 stars 12 forks source link

ogc: rework audio driver to avoid clicks and gaps #38

Closed mardy closed 6 months ago

mardy commented 6 months ago

When playing an audio stream the previous implementation was producing frequent clicks (also audible in the emulator). The reason is that SDL runs a thread that does these operations in a loop:

  1. Ask the driver for a buffer (GetDeviceBuf())
  2. Fill the buffer with audio data from the app
  3. Call PlayAudio() on the driver
  4. Call WaitDevice() on the driver

The clicks occurred because after a buffer had finished playing, our completion callback would set the condition variable, allowing the audio thread (which was blocking in point 4) to continue. However, since libaesnd does not offer an API to queue audio buffer, we were sending the next audio buffer only in PlayAudio(), that is after the points 1 and 2 were performed. And since point 2 involves copying buffers and possibly even converting them, this would often generate an audible delay.

The solution is to play the next buffer directly from the completion callback. The waiting logic has been rewritten to use a semaphore blocking on the availability of a buffer for writing (not for playback!).

The number of buffers has also been increase to protect against sudden spikes in CPU usage, although in the test applications 2 buffers are good enough too.