# SPDX-FileCopyrightText: 2026 Brad Barnett
#
# SPDX-License-Identifier: MIT
"""WASAPI queued PCM backend for Windows CPython (via ``uwin32``).
Playback and capture use shared-mode ``IAudioClient`` with
``AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM``. There is no Python audio-thread
callback. Import fails unless ``uwin32`` loads.
"""
try:
import asyncio
except ImportError: # pragma: no cover
try:
import uasyncio as asyncio
except ImportError:
asyncio = None
import time
from audiodev import AudioFormat, PCMInput, PCMOutput, check_latency
from audiodev.bytequeue import ByteQueue
import uwin32 as win
DEFAULT_PLAY_SAMPLES = 4096
DEFAULT_PLAY_QUEUE_MS = 2000
DEFAULT_COALESCE_MS = 100
PREBUFFER_MS = 100
# Same WSLg Pulse/RDP WASAPI stall as sdl2_audio: the sink keeps accepting
# PCM at 5-30% of realtime after a minute or two. Recycle the IAudioClient.
# Do not drop coalesce on overflow — that removes backpressure and decode
# runs unbounded (measured ~2.6× realtime).
STALL_WINDOW_MS = 1500
STALL_RATIO = 0.5
STALL_SAMPLE_MS = 100
RECOVER_GRACE_MS = 1500
RECOVER_SETTLE_MS = 800
# Fourth field: prebuffer_ms (see sdl2_audio._PLAY_PROFILES for why a small
# prime matters for note-to-sound latency). None falls back to PREBUFFER_MS.
_PLAY_PROFILES = {
None: (DEFAULT_PLAY_SAMPLES, DEFAULT_PLAY_QUEUE_MS, DEFAULT_COALESCE_MS, None),
"buffered": (DEFAULT_PLAY_SAMPLES, DEFAULT_PLAY_QUEUE_MS, DEFAULT_COALESCE_MS, None),
"low": (256, 250, 5, 25),
}
_CAPTURE_PROFILES = {
None: (512, 500),
"buffered": (512, 500),
"low": (256, 100),
}
WRITE_WAIT_MS = 500
def _sleep_ms(milliseconds):
# Do not use multimer here: a pumping sleep re-enters Device.service while
# write() holds the WASAPI client mid-recycle and deadlocks the pump.
if hasattr(time, "sleep_ms"):
time.sleep_ms(milliseconds)
else:
time.sleep(milliseconds / 1000)
def _monotonic_ms():
if hasattr(time, "ticks_ms"):
return time.ticks_ms()
return int(time.time() * 1000)
def _elapsed_ms(since):
if hasattr(time, "ticks_diff"):
return time.ticks_diff(_monotonic_ms(), since)
return _monotonic_ms() - since
def _diff_ms(later, earlier):
if hasattr(time, "ticks_diff"):
return time.ticks_diff(later, earlier)
return later - earlier
def _deadline_ms(milliseconds):
if hasattr(time, "ticks_add"):
return time.ticks_add(_monotonic_ms(), milliseconds)
return _monotonic_ms() + milliseconds
async def _asleep_ms(milliseconds):
await asyncio.sleep(milliseconds / 1000)
def _wave_format(fmt):
return win.WAVEFORMATEX_pcm(fmt.rate, fmt.channels, fmt.bits)
[docs]
class WinPCMOutput(PCMOutput):
def __init__(
self,
fmt,
*,
device=None,
samples=DEFAULT_PLAY_SAMPLES,
queue_ms=DEFAULT_PLAY_QUEUE_MS,
poll_ms=2,
coalesce_ms=DEFAULT_COALESCE_MS,
prebuffer_ms=None,
session=None,
):
super().__init__(fmt, session=session)
self.device_name = device
self.samples = int(samples)
self.queue_ms = int(queue_ms)
self.poll_ms = int(poll_ms)
self.coalesce_ms = int(coalesce_ms)
self._bytes_per_second = fmt.rate * fmt.frame_size
self._queue_limit = max(fmt.frame_size, self._bytes_per_second * self.queue_ms // 1000)
self._coalesce_bytes = max(
fmt.frame_size,
self._bytes_per_second * self.coalesce_ms // 1000,
)
_prebuffer_ms = PREBUFFER_MS if prebuffer_ms is None else int(prebuffer_ms)
self._prebuffer_bytes = min(
self._queue_limit // 4,
max(fmt.frame_size, self._bytes_per_second * _prebuffer_ms // 1000),
)
self._max_pending = 4 * self._queue_limit
# Chunked: a bytearray grown here needed one contiguous block the size of
# all pending audio, which a heap shared with a UI may not have.
self._coalesce = ByteQueue(2 * self._max_pending)
self._enumerator = None
self._endpoint = None
self._client = None
self._render = None
self._buffer_frames = 0
self._started = False
self._in_push = False
self._pushed_total = 0
self._samples = []
self._grace_until = None
self._recycling = False
self._min_depth_bytes = max(
self.format.frame_size,
self._bytes_per_second * 40 // 1000,
)
self._min_rate = max(1, int(self._bytes_per_second * STALL_RATIO))
self.recycles = 0
self.lost_bytes = 0
self.requeued_bytes = 0
self._last_push_ms = None
self._play_origin_ms = None
@property
def speaker_sink(self):
"""The firmware's name for this speaker, or None.
``"wasapi"`` for the default device: on an interpreter whose pump can
open it (`audiodev.pump.speaker`), `AudioOut
<audiodev.sample_out.AudioOut>` hands the graph to the pump, which
writes it to WASAPI from its own thread and never opens this
transport. A named ``device`` stays on this transport.
"""
return "wasapi" if self.device_name is None else None
def _hw_queued(self):
if not self._client:
return 0
return int(win.IAudioClient_GetCurrentPadding(self._client)) * self.format.frame_size
[docs]
def queued_size(self):
return self._hw_queued() + len(self._coalesce)
[docs]
def is_active(self):
return self.queued_size() > 0
[docs]
def clear(self):
self._coalesce.clear()
self._pushed_total = 0
self._samples = []
self._play_origin_ms = None
if self._client and self._started:
try:
win.IAudioClient_Stop(self._client)
win.IAudioClient_Reset(self._client)
except OSError:
pass
self._started = False
def _open(self):
win.CoInitializeEx()
self._enumerator = win.MMDeviceEnumerator_Create()
self._endpoint = win.IMMDeviceEnumerator_GetDefaultAudioEndpoint(
self._enumerator, win.eRender
)
self._client = win.IMMDevice_Activate_IAudioClient(self._endpoint)
wfx = _wave_format(self.format)
win.IAudioClient_Initialize_shared_pcm(self._client, wfx, self.queue_ms)
self._buffer_frames = win.IAudioClient_GetBufferSize(self._client)
self._render = win.IAudioClient_GetService(self._client, win.IID_IAudioRenderClient)
self._started = False
self._play_origin_ms = None
self._last_push_ms = _monotonic_ms()
def _close(self, keep_coalesce=False):
if self._client and self._started:
try:
win.IAudioClient_Stop(self._client)
except OSError:
pass
for punk in (self._render, self._client, self._endpoint, self._enumerator):
if punk:
win.IUnknown_Release(punk)
self._render = self._client = self._endpoint = self._enumerator = None
self._started = False
self._pushed_total = 0
self._samples = []
self._last_push_ms = None
self._play_origin_ms = None
if not keep_coalesce:
self._coalesce.clear()
def _available_frames(self):
if not self._client:
return 0
padding = win.IAudioClient_GetCurrentPadding(self._client)
return max(0, self._buffer_frames - padding)
def _recover_client(self):
if not self._client:
return
try:
win.IAudioClient_Stop(self._client)
except OSError:
pass
try:
win.IAudioClient_Reset(self._client)
except OSError:
pass
self._started = False
self._pushed_total = 0
self._play_origin_ms = None
def _push_budget(self):
if not self._started or self._play_origin_ms is None:
return self._pushed_total + self._queue_limit
elapsed = max(0, _diff_ms(_monotonic_ms(), self._play_origin_ms))
return self._bytes_per_second * (elapsed + self.queue_ms) // 1000
def _push_frames(self, data):
frame = self.format.frame_size
nbytes = len(data) - (len(data) % frame)
if nbytes <= 0 or not self._render or self._in_push:
return 0
frames = nbytes // frame
room = self._available_frames()
if room <= 0:
return 0
frames = min(frames, room)
self._in_push = True
got = False
try:
ptr = win.IAudioRenderClient_GetBuffer(self._render, frames)
got = True
win.memmove(ptr, data[: frames * frame], frames * frame)
win.IAudioRenderClient_ReleaseBuffer(self._render, frames)
got = False
written = frames * frame
self._pushed_total += written
self._last_push_ms = _monotonic_ms()
return written
except OSError as exc:
print("win_audio GetBuffer/Release failed", exc)
if got:
try:
win.IAudioRenderClient_ReleaseBuffer(self._render, frames)
except OSError:
pass
self._recover_client()
return 0
finally:
self._in_push = False
# ------------------------------------------------------------------
# Direct writes, for callers that keep their own low-latency queue
# ------------------------------------------------------------------
@property
def buffer_frames(self):
"""Frames the WASAPI buffer holds in all; 0 until the output is open."""
return int(self._buffer_frames) if self._client else 0
[docs]
def device_frames(self):
"""Frames written to the device and not yet played (its padding)."""
return self._hw_queued() // self.format.frame_size
[docs]
def write_now(self, buf, *, start=True):
"""Write *buf* straight into the WASAPI buffer, now, and return the
bytes written.
For a caller that runs its own short queue -- a synth or mixer that
renders a block at a time and decides itself how far ahead of the
device to stay. It skips `write`'s media queue and coalescing,
which batch PCM into 100 ms pieces and hold playback back until about
100 ms is queued: right for a decoder, far too much for a key-to-sound
path.
Whole frames only, as many as the device has room for; it never waits
and never keeps the rest, so a short count means the device is full
and the caller still holds the remainder. Volume and mute apply, as
they do to `write`. With *start* (the default) playback begins
as soon as anything has been written; pass ``start=False`` to prime
the buffer first and call `start` when it holds enough.
Use either this or `write` on one output, not both: they reach
the device by different paths, and nothing orders one against the
other. Pair it with `device_frames` to see how much the device
still has to play, and `buffer_frames` for its capacity.
"""
self.open()
source = self._prepare(buf)
written = self._push_frames(source)
if start and written:
self._start_if_primed(force=True)
return written
[docs]
def start(self):
"""Start playing what `write_now` has written; True once playing."""
self.open()
self._start_if_primed(force=True)
return self._started
def _start_if_primed(self, force=False):
if self._started or not self._client:
return
queued = self._hw_queued()
if queued <= 0:
return
if not force and queued < self._prebuffer_bytes:
return
try:
win.IAudioClient_Start(self._client)
self._started = True
queued_ms = queued * 1000 // max(1, self._bytes_per_second)
self._play_origin_ms = _monotonic_ms() - queued_ms
except OSError as exc:
print("win_audio Start failed", exc)
self._recover_client()
def _flush_coalesce(self, force=False):
frame = max(1, self.format.frame_size)
budget = self._push_budget()
while self._coalesce:
pending = len(self._coalesce)
if not force and pending < self._coalesce_bytes:
break
# One coalesce window at a time, forced or not, so no push copies
# more than that out of the ring.
take = min(pending, self._coalesce_bytes)
take -= take % frame
if take <= 0:
break
if not force and self._hw_queued() + take > self._queue_limit:
break
if not force and self._pushed_total >= budget:
break
written = self._push_frames(self._coalesce.head(take))
if written <= 0:
break
self._coalesce.consume(written)
self._start_if_primed(force=force)
def _write(self, buf):
if not buf:
return 0
waited = 0
# Bound the wait so Device.service can return and pcm.service can recycle.
# Forever-blocking write froze Tremor at 3:49 of Under Pressure.
while len(self._coalesce) >= self._max_pending and waited < WRITE_WAIT_MS:
self._flush_coalesce(force=False)
if len(self._coalesce) < self._max_pending:
break
_sleep_ms(self.poll_ms)
waited += self.poll_ms
taken = self._coalesce.write(buf)
if taken < len(buf):
# Full even after the wait: the caller is far ahead of realtime.
self.lost_bytes += len(buf) - taken
self._flush_coalesce(force=False)
return len(buf)
def _check_stall(self):
if self._recycling or not self._client:
return
if self._grace_until is not None and _elapsed_ms(self._grace_until) < 0:
self._samples = []
return
hw = self._hw_queued()
pending = len(self._coalesce)
now = _monotonic_ms()
# Room in the device but GetBuffer has not succeeded: WSLg gulp-then-wedge.
# Do not treat a full healthy WASAPI (no GetBuffer because it is full) as a stall.
if (
pending >= self._coalesce_bytes
and self._last_push_ms is not None
and hw + self._coalesce_bytes <= self._queue_limit
and _diff_ms(now, self._last_push_ms) >= STALL_WINDOW_MS
):
self._samples = []
self._recycle_client(stalled_bytes=hw, rate=0)
return
if not self._started or hw < self._min_depth_bytes:
self._samples = []
return
consumed = self._pushed_total - hw
samples = self._samples
if not samples or _diff_ms(now, samples[-1][0]) >= STALL_SAMPLE_MS:
samples.append((now, consumed))
while len(samples) > 1 and _diff_ms(now, samples[1][0]) >= STALL_WINDOW_MS:
samples.pop(0)
span = _diff_ms(now, samples[0][0])
if span < STALL_WINDOW_MS:
return
rate = (consumed - samples[0][1]) * 1000 // span
if rate >= self._min_rate:
return
self._samples = []
self._recycle_client(stalled_bytes=hw, rate=rate)
def _recycle_client(self, stalled_bytes=0, rate=None):
if self._recycling:
return
self._recycling = True
self.lost_bytes += int(stalled_bytes)
self.recycles += 1
pending = len(self._coalesce)
print(
"win_audio stall recycle rate=%s hw=%d pending=%d"
% (rate, int(stalled_bytes), pending)
)
try:
before = len(self._coalesce)
self._recover_client()
self._samples = []
self._flush_coalesce(force=False)
pushed = before - len(self._coalesce)
if pushed > 0:
print("win_audio stall recover inplace pushed=%d" % pushed)
else:
print("win_audio stall recover inplace no-push")
except OSError as exc:
print("win_audio stall recover failed", exc)
finally:
# Reopen (Close + Initialize) native-crashed 0xc0000005 on WSLg.
self._grace_until = _deadline_ms(RECOVER_GRACE_MS * 4)
self._recycling = False
[docs]
def service(self):
if self._recycling:
return self.queued_size()
self._flush_coalesce(force=False)
self._check_stall()
return self.queued_size()
def _drain(self):
self._flush_coalesce(force=True)
waited = 0
timeout_ms = 10000
while self.queued_size() > 0 and waited < timeout_ms:
self._flush_coalesce(force=True)
_sleep_ms(self.poll_ms)
waited += self.poll_ms
return self.queued_size() == 0
async def _awrite(self, buf):
await _asleep_ms(0)
while self._hw_queued() >= self._queue_limit:
await _asleep_ms(self.poll_ms)
return self._write(buf)
async def _adrain(self):
self._flush_coalesce(force=True)
waited = 0
timeout_ms = 10000
while self.queued_size() > 0 and waited < timeout_ms:
self._flush_coalesce(force=True)
await _asleep_ms(self.poll_ms)
waited += self.poll_ms
return self.queued_size() == 0
[docs]
def pcm_out(
format=None,
*,
device=None,
latency=None,
samples=None,
queue_ms=None,
coalesce_ms=None,
prebuffer_ms=None,
poll_ms=2,
):
"""Create a WASAPI-backed `PCMOutput`."""
check_latency(latency)
p_samples, p_queue_ms, p_coalesce_ms, p_prebuffer_ms = _PLAY_PROFILES[latency]
fmt = format or AudioFormat(16000, 2, 16)
return WinPCMOutput(
fmt,
device=device,
samples=p_samples if samples is None else samples,
queue_ms=p_queue_ms if queue_ms is None else queue_ms,
coalesce_ms=p_coalesce_ms if coalesce_ms is None else coalesce_ms,
prebuffer_ms=p_prebuffer_ms if prebuffer_ms is None else prebuffer_ms,
poll_ms=poll_ms,
)
[docs]
def pcm_in(
format=None,
*,
device=None,
latency=None,
samples=None,
queue_ms=None,
poll_ms=2,
):
"""Create a WASAPI-backed `PCMInput`."""
check_latency(latency)
default_samples, default_queue_ms = _CAPTURE_PROFILES[latency]
fmt = format or AudioFormat(16000, 1, 16)
return WinPCMInput(
fmt,
device=device,
samples=default_samples if samples is None else samples,
queue_ms=default_queue_ms if queue_ms is None else queue_ms,
poll_ms=poll_ms,
)