In day 8, Casey tries to always have the sound buffer filled with audio.
On the first frame, since no audio is playing, BytesToWrite
equal the size of the buffer. So he will fill the complete buffer with sample, and RunningSampleIndex
will be a full buffer worth of sample. He will then start to play the buffer.
On the second frame, Casey compute ByteToLock
based on the RunningSampleIndex
which will be zero, since we filled the complete buffer and it's a circular buffer (we do a % SecondaryBufferSize
). You can see ByteToLock
here has 1 past the last byte we have written in the buffer on the previous frame
. He compares that to the current value of the PlayCursor
to get BytesToWrite
. So BytesToWrite
here is how much of the audio has been played already and thus contains audio that we need to replace. That also means that he always adds audio at the "end" (in quotes because it's a circular buffer) of the buffer, so there is always about 1 second of audio latency.
On day 9, Casey changes the code so that instead of writing at the "end" of the buffer, he writes at the "start" of the buffer but still a little ahead (LatencySampleCount
) of the PlayCursor
. That implies to not write a full buffer worth of samples (both at startup and during gameplay), so that RunningSampleIndex
isn't far ahead of the PlayCursor
. In later episodes, he will improve the latency by overwriting some samples to be closer to the PlayCursor
.
In theory you shouldn't write samples between the PlayCursor
and the WriteCursor
, you should only write after the WriteCursor
. This is because there is some sort of memory copy from the secondary buffer and the actual sound card memory, and if you write between the PlayCursor
and the WriteCursor
some of the memory might already have been copied. I said in theory, because DirectSound in Windows Vista and later is emulated on top of other Windows API (Core audio API such as Windows Audio Session API (WASAPI)). So in theory the best latency you'd get using DirectSound would be WriteCursor - PlayCursor
bytes, and if I remember correctly, on modern Windows this is always 30ms.
If you search these forums you'll find some implementation of the audio code using WASAPI and there are also a lot of subject about the audio latency in handmade hero.