flysight/flysight — pull request #27 by crwper (2014-03-23 20:29:00+00:00)
Title: Change to circular audio buffer

Previously, we used a double buffer for audio. While one half of the buffer was being output as audio, the other half would be read from a WAV file on disk. The problem with a double buffer, however, is that we are never more than half a buffer away from running out of data.

With a [circular buffer](http://en.wikipedia.org/wiki/Circular_buffer), effectively the entire buffer can be used. In particular, the buffer that's used here is [this one](http://en.wikipedia.org/wiki/Circular_buffer#Absolute_indices). For a given amount of memory, we now have twice as much time to deal with, e.g., log writes.

With a circular buffer, we are also able to deal with log writes at a finer scale. Instead of squeezing them between large reads, we can insert them whenever the circular buffer is "mostly" full. This gives us more opportunities to write, and as a result it seems that logging becomes much more robust.

Finally, a limit has been added on how much can be read into the circular buffer at once, Because we can't update ```Tone_write``` until we have read all of the samples and adjusted their volume, we sometimes run into a problem where a large log write occurs followed by a lengthy read to fill the circular buffer. The combined delays can cause the buffer to overflow when it could have been avoided. To avoid this problem, we limit reads ```TONE_BUFFER_CHUNK``` bytes. This creates a compromise between efficiency (filling the entire buffer at once) and rapid update (reading a large number of small chunks).