Persistent audio discontinuity in WASAPI loopback capture when debugging

Yellow Van 25 Reputation points
2023-03-10T12:28:49.9166667+00:00

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 to eRender in GetDefaultAudioEndpoint
  • Change eCapture to eRender in EnumAudioEndpoints
  • Add AUDCLNT_STREAMFLAGS_LOOPBACK to IAudioClient::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?

Windows development | Windows API - Win32
{count} votes

Answer accepted by question author
  1. Xiaopo Yang - MSFT 12,736 Reputation points Microsoft External Staff
    2023-03-14T01:46:40.7733333+00:00

    @Yellow Van You can report the CaptureSharedEventDriven sample's issue at Windows-classic-samples Issues, which may not take into consideration the situation where the audio engine can be reasonably expected to have accumulated about that much audio data. You may also refer to the dedicated loopback sample ApplicationLoopback.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.