I am writing a program that captures the output on a Windows device using WASAPI loopback capture. In principle it works correctly, but it breaks whenever I try to debug it, after continuing from a breakpoint.
I can reproduce this in Windows' own example code: I'm using the CaptureSharedEventDriven sample.
Then I followed the instructions to change this demo to use loopback, which is simply:
- Change
eCapture
toeRender
inGetDefaultAudioEndpoint
- Change
eCapture
toeRender
inEnumAudioEndpoints
- Add
AUDCLNT_STREAMFLAGS_LOOPBACK
toIAudioClient::Initialize
call
This now correctly captures the audio output. However, when I breakpoint at the end of CWASAPICapture::Start(...)
(line 262 in the sample) and then continue, the capture turns into rubbish from then onwards. The captured audio shows discontinuities every 1056 samples (this is also the buffer size of the IAudioClient) and misses 384 samples every iteration.
I can prove this by adding the following debug code:
[WASAPICapture.cpp, line 358]
hr = _CaptureClient->GetBuffer(&pData, &framesAvailable, &flags, NULL, NULL);
if (SUCCEEDED(hr))
{
UINT32 framesToCopy = min(framesAvailable, static_cast<UINT32>((_CaptureBufferSize - _CurrentCaptureIndex) / _FrameSize));
if (framesToCopy != 0)
{
//
// Adding this in order to trace the output issue:
//
if (flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) {
printf("Discontinuity detected, writing %d samples\n", framesAvailable);
}
else {
printf("Correct render, writing %d samples\n", framesAvailable);
}
After hitting the breakpoint, for the rest of the capture the output will now be:
Discontinuity detected, writing 480 samples
Correct render, writing 480 samples
Discontinuity detected, writing 96 samples
Discontinuity detected, writing 480 samples
Correct render, writing 480 samples
Discontinuity detected, writing 96 samples
Correct render, writing 480 samples
Correct render, writing 480 samples
Discontinuity detected, writing 96 samples
etc...
How do I make WASAPI recover from this error?