audiodev.sdl2_audio

SDL2 audio backend for audiodev (pure Python, queued audio only).

Playback pushes PCM with SDL_QueueAudio and never installs an audio callback: SDL’s audio thread is not registered with the Python/MicroPython interpreter, so calling back into it from it is unsafe (it segfaults under MicroPython and fights the GIL under CPython/LVGL).

Four behaviors keep queued playback smooth, all established by measurement on WSLg/PulseAudio rather than by preference:

  • small writes are coalesced (coalesce_ms, 100ms by default) before being handed to SDL;

  • the device stays paused until PREBUFFER_MS is queued, because starting on a nearly empty queue and then starving it makes PulseAudio stop asking for data;

  • if the device falls far behind realtime, it is reopened and the unplayed PCM is re-queued (see STALL_WINDOW_MS);

  • that reopen runs on a worker thread, because closing a wedged device blocks for over a second and the caller is usually driving a UI.

Before simplifying any of this

Each rule below replaced an obvious, simpler version that measurably failed. The failure is named so it can be re-tested instead of rediscovered:

  • Detect stalls by consumption rate over a window, never by watching queue depth. A caller that tops the queue up replaces every consumed period before the next check sees it, so depth does not fall even when the sink has died.

  • Gate the prebuffer on SDLPCMOutput._hw_queued, never on SDLPCMOutput.queued_size. Counting bytes still sitting in the software buffer let the device start on ~40ms of audio, underrun, and wedge again immediately after every recovery.

  • Keep the reopen off the caller’s thread, and keep RECOVER_SETTLE_MS between close and open. A synchronous rebuild stalled the caller’s tick for ~1.8s; reopening with no gap handed back the same wedged sink and re-stalled within seconds, in pairs.

  • Size _shadow to cover everything SDL may still hold. Anything smaller silently drops audio during recovery.

  • Do not let “the device is unpaused” mean playing in SDLPCMOutput.is_active – it stays unpaused for the life of the device, so callers would wait forever for playback that already finished.

The recycles, lost_bytes and requeued_bytes counters exist to keep those claims checkable: a healthy long run recycles rarely and loses nothing. README.md in this directory has the full account, including how to measure a change before making it.

This module also runs on MicroPython (unix and micropython.exe) and CircuitPython, so it avoids CPython-only APIs – notably it consumes buffers with buf[:n] = b"" rather than del buf[:n], which those interpreters reject at runtime, not at import. See “Portability” in README.md; verify changes by running examples/audio_out_test.py under all three interpreters.

audiodev.sdl2_audio.list_audio_devices(capture=False)[source]

Return SDL playback or capture device names.

class audiodev.sdl2_audio.SDLPCMOutput(fmt, *, device=None, samples=512, queue_ms=250, poll_ms=2, coalesce_ms=100, prebuffer_ms=None, session=None)[source]

Bases: PCMOutput

SDL playback via SDL_QueueAudio (no audio callback, no mixer).

PCM travels through two buffers: writes land in _coalesce (software) and are handed to SDL in coalesce_ms pieces up to _queue_limit (hardware). queued_size reports both, so a caller can treat “queued_size() == 0” as end of playback without knowing which buffer holds what.

Callers must call service from their tick. Without it, a partial write can sit in _coalesce unqueued and a wedged device is never noticed.

queued_size()[source]

Bytes still waiting to play, including what has not been handed to SDL.

Both buffers count, so audio parked in _coalesce during a rebuild is not mistaken for silence. Use _hw_queued instead when the question is what the device is doing.

is_active()[source]

True while PCM is still queued anywhere.

Deliberately ignores pause state: the device stays unpaused for its whole life, so testing that instead would report playback as active forever and hang callers that wait for idle.

clear()[source]

Drop queued PCM now (abort); keep the device and re-prime on next write.

service()[source]

Call from the app’s tick: flush partial writes and watch for stalls.

Required, not optional – stall recovery only happens here and in drain. A no-op during a rebuild, since the worker owns the device and the pending PCM is queued on the next tick.

Re-entrancy: a MicroPython mp_sched callback (spremote’s pump) can fire between bytecodes on this same thread and call service() again while we are mid-_check_stall. Both would mutate self._samples and the inner one leaves the outer indexing an emptied list. The guard makes the nested call a no-op; the outer call finishes the tick.

drain(timeout_ms=None)[source]

Block until queued PCM has played out. False if it timed out.

Keeps servicing the stall detector while it waits, and grants a fresh playout budget whenever a recycle happens, so recovering mid-drain does not truncate the tail it just re-queued.

async adrain(timeout_ms=None)[source]

Async drain; identical rules, yields instead of sleeping.

class audiodev.sdl2_audio.SDLPCMInput(fmt, *, device=None, samples=512, queue_ms=250, poll_ms=2, timeout_ms=100)[source]

Bases: PCMInput

audiodev.sdl2_audio.pcm_out(format=None, *, device=None, latency=None, samples=None, queue_ms=None, coalesce_ms=None, prebuffer_ms=None, poll_ms=2)[source]

Create an SDL-backed PCMOutput.

latency picks a profile (see audiodev.LATENCIES); pass "low" for interactive callers such as a synth. Any of samples, queue_ms, coalesce_ms and prebuffer_ms given explicitly override the profile.

audiodev.sdl2_audio.pcm_in(format=None, *, device=None, latency=None, samples=None, queue_ms=None, poll_ms=2, timeout_ms=100)[source]

Create an SDL-backed PCMInput using real host capture.

latency picks a profile as in audio_out; samples and queue_ms given explicitly override it. A read returns after timeout_ms with no samples rather than waiting for them.