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_MSis 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 onSDLPCMOutput.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_MSbetween 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
_shadowto 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:
PCMOutputSDL playback via
SDL_QueueAudio(no audio callback, no mixer).PCM travels through two buffers: writes land in
_coalesce(software) and are handed to SDL incoalesce_mspieces up to_queue_limit(hardware).queued_sizereports both, so a caller can treat “queued_size() == 0” as end of playback without knowing which buffer holds what.Callers must call
servicefrom their tick. Without it, a partial write can sit in_coalesceunqueued 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
_coalesceduring a rebuild is not mistaken for silence. Use_hw_queuedinstead 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.
- 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_schedcallback (spremote’s pump) can fire between bytecodes on this same thread and callservice()again while we are mid-_check_stall. Both would mutateself._samplesand 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.
- 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.latencypicks a profile (seeaudiodev.LATENCIES); pass"low"for interactive callers such as a synth. Any ofsamples,queue_ms,coalesce_msandprebuffer_msgiven 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
PCMInputusing real host capture.latencypicks a profile as inaudio_out;samplesandqueue_msgiven explicitly override it. A read returns aftertimeout_mswith no samples rather than waiting for them.