Skip to content

ASIO, WASAPI: don't let stopStream block for good on a driver that stops calling back - #496

Merged
garyscavone merged 2 commits into
thestk:masterfrom
webprofusion-chrisc:asio-wasapi-bounded-stop-waits
Nov 30, 2026
Merged

garyscavone merged 2 commits into
thestk:masterfrom
webprofusion-chrisc:asio-wasapi-bounded-stop-waits

Conversation

@webprofusion-chrisc

Copy link
Copy Markdown
Contributor

Problem

RtApiAsio::stopStream() sets drainCounter = 2 and waits INFINITE on handle->condition,
which only the driver's bufferSwitch callback signals. If the driver never calls back (it did
not really start, or lost its device), stopStream() never returns, and neither does the thread
that called it. In an app that is usually the UI thread, during a device change.

We hit this in a stress test of an app built on clap-wrapper's standalone host. Switching the
driver to ASIO (ASIO4ALL) and straight back to WASAPI froze the UI thread:

KERNELBASE!WaitForSingleObjectEx+0xaf
App!RtApiAsio::stopStream+0xa4
App!RtAudio::stopStream+0x6
App!freeaudio::clap_wrapper::standalone::StandaloneHost::stopAudioThread+0x55
App!freeaudio::clap_wrapper::standalone::StandaloneHost::setAudioApi+0x4b

ASIO4ALL's thread was idle in GetMessageA and never called back.

RtApiWasapi has the same weakness: wasapiThread waits INFINITE for the capture and render
events, and stopStream() waits INFINITE for that thread while holding stream_.mutex.

Reproduction

stop_hang.cpp (below) opens the default output device, starts it, then calls stopStream()
under a watchdog. With inject, it first calls ASIOStop() directly so the driver stops calling
back. That gives the same state as a failed driver, on demand and with any ASIO driver.

master 8ce4f26 callbacks before stop stopStream()
ASIO4ALL, natural (2nd cycle) 0 never returned
ASIO4ALL, inject 20 never returned (watchdog killed the process at 10 s)
this PR callbacks before stop stopStream()
ASIO4ALL, inject ×3 20 1021.2 / 1021.5 / 1022.0 ms, with a warning
ASIO4ALL, normal ×3 20 12.9 – 16.3 ms (unchanged)
WASAPI (Steinberg UR12), normal ×5 49 – 62 5.6 – 11.0 ms (unchanged)

Windows 11, MSVC 19.52 x64, 48 kHz, 256 frames.

Change

  • ASIO: wait 1 s plus four buffers for the drain. On a timeout, report
    RTAUDIO_WARNING ("the driver did not drain the stream, stopping it anyway") and go on to
    ASIOStop() as before. A driver that does call back drains in two or three buffers, so this
    only changes the stuck case.
  • WASAPI: wait at most 2 s for each device event. This is the timeout Microsoft's own
    event-driven sample uses
    (Exclusive-Mode Streams).
    After a timeout the loop carries on: GetBuffer returns no frames (or fails for a removed
    device and the thread exits), and the loop sees STREAM_STOPPING.

The two commits are independent. The WASAPI one comes from reading the code, not from a captured
hang. I couldn't make a WASAPI device stop signaling on demand, so if you'd rather take only the
ASIO commit, that's fine.

Not touched: DirectSound's drain wait is signaled from RtAudio's own thread, not a driver
callback. Core Audio and JACK use a condition variable in the same way, but I can't test those
here.

stop_hang.cpp — the reproduction
// Reproduces RtApiAsio::stopStream blocking for good when the driver never calls back,
// and RtApiWasapi with the same pattern: open, start, run briefly, stop, with a watchdog.
// Usage: stop_hang <api: asio|wasapi> <run ms> <cycles> [switch|inject]
//   switch: alternate WASAPI and ASIO each cycle, as an app's device page does.
//   inject: ASIO only. Stop the driver behind RtAudio's back (ASIOStop), so it no
//           longer calls back, then stop the stream: what a driver that failed to
//           start or lost its device does, on demand and with any ASIO driver.
#include "RtAudio.h"
#include "asio.h"
#include <windows.h>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <future>
#include <string>
#include <thread>

static std::atomic<long> callbacks{0};
static bool inject = false;

static int silence(void* out, void*, unsigned int frames, double, RtAudioStreamStatus, void*)
{
   ++callbacks;
   std::memset(out, 0, frames * 2 * sizeof(float));
   return 0;
}

static RtAudio::Api api_of(std::string const& name)
{
   return name == "asio" ? RtAudio::WINDOWS_ASIO : RtAudio::WINDOWS_WASAPI;
}

// One cycle. Returns false when stopStream did not return within the watchdog.
static bool cycle(RtAudio::Api api, int run_ms)
{
   char const* name = api == RtAudio::WINDOWS_ASIO ? "ASIO" : "WASAPI";
   auto* audio = new RtAudio(api);
   RtAudio::StreamParameters out;
   out.deviceId = audio->getDefaultOutputDevice();
   out.nChannels = 2;
   if (out.deviceId == 0)
   {
      std::printf("%-6s no output device\n", name);
      delete audio;
      return true;
   }
   auto const info = audio->getDeviceInfo(out.deviceId);
   unsigned int frames = 256;
   callbacks = 0;
   if (audio->openStream(&out, nullptr, RTAUDIO_FLOAT32, 48000, &frames, &silence))
   {
      std::printf("%-6s open failed: %s\n", name, audio->getErrorText().c_str());
      delete audio;
      return true;
   }
   if (audio->startStream())
      std::printf("%-6s start failed: %s\n", name, audio->getErrorText().c_str());
   std::this_thread::sleep_for(std::chrono::milliseconds(run_ms));
   if (inject && api == RtAudio::WINDOWS_ASIO)
   {
      ASIOStop();
      std::this_thread::sleep_for(std::chrono::milliseconds(50));
   }
   long const before_stop = callbacks;

   auto const t0 = std::chrono::steady_clock::now();
   auto stopped = std::async(std::launch::async, [audio] { audio->stopStream(); });
   if (stopped.wait_for(std::chrono::seconds(10)) != std::future_status::ready)
   {
      std::printf("%-6s \"%s\": %ld callbacks in %d ms, stopStream HUNG (no return in 10 s)\n",
                  name, info.name.c_str(), before_stop, run_ms);
      std::fflush(stdout);
      TerminateProcess(GetCurrentProcess(), 3);
   }
   double const ms = std::chrono::duration<double, std::milli>(
      std::chrono::steady_clock::now() - t0).count();
   std::printf("%-6s \"%s\": %ld callbacks in %d ms, stopStream took %.1f ms\n",
               name, info.name.c_str(), before_stop, run_ms, ms);
   audio->closeStream();
   delete audio;
   return true;
}

int main(int argc, char** argv)
{
   std::string const which = argc > 1 ? argv[1] : "asio";
   int const run_ms = argc > 2 ? std::atoi(argv[2]) : 500;
   int const cycles = argc > 3 ? std::atoi(argv[3]) : 3;
   bool const alternate = argc > 4 && std::string(argv[4]) == "switch";
   inject = argc > 4 && std::string(argv[4]) == "inject";
   for (int i = 0; i < cycles; ++i)
   {
      if (alternate)
      {
         cycle(RtAudio::WINDOWS_WASAPI, run_ms);
         cycle(RtAudio::WINDOWS_ASIO, run_ms);
      }
      else
      {
         cycle(api_of(which), run_ms);
      }
      std::fflush(stdout);
   }
   return 0;
}
build.cmd — from an MSVC x64 prompt
@echo off
rem build.cmd <rtaudio checkout> <exe name>
rem Builds stop_hang.cpp against an RtAudio checkout with ASIO and WASAPI, from an MSVC x64 prompt.
cl /nologo /O2 /EHsc /std:c++17 /MD /D__WINDOWS_ASIO__ /D__WINDOWS_WASAPI__ /D_CRT_SECURE_NO_WARNINGS ^
   /I%1 /I%1/include %1/RtAudio.cpp %1/include/asio.cpp %1/include/asiodrivers.cpp %1/include/asiolist.cpp ^
   %1/include/iasiothiscallresolver.cpp stop_hang.cpp /Fe:%2 ^
   ole32.lib winmm.lib ksuser.lib mfplat.lib mfuuid.lib wmcodecdspuuid.lib user32.lib advapi32.lib

The drain is signaled from the driver's buffer switch callback, so a
driver that never calls back (one that did not start, or lost its
device) blocked stopStream, and the thread that called it, for good.
Wait one second plus four buffers, warn, and stop the driver anyway.
The stream thread waited without limit for the capture and render
events, so a device that stopped signaling left the thread, and
stopStream waiting for it, blocked for good. Wait two seconds, as
Microsoft's event-driven samples do; the loop then sees the stream
stopping, or GetBuffer fails for a device that is gone.
@garyscavone
garyscavone merged commit f028430 into thestk:master Nov 30, 2026
16 of 24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants