Repository navigation
fix(audio): keep stream open across pause so DACs hold lock - #304
kiwipaulrob wants to merge 2 commits into
Conversation
Pause arrives as stream/end, which ran close_stream() and fully closed the PortAudio stream; resume then recreated it via set_format(). Each close/open drops USB lock, clicking muting relays on XMOS-based DACs (verified live: the click survives full digital silence, so no server-side mute or fade can suppress it). clear() and close_stream() now drain the queue but leave the stream running - the callback already renders silence while starved - and set_format() skips recreating the stream when the format is unchanged. The device releases on stop() (shutdown) and on real format changes only.
Resume-after-announce crashed the audio callback: set_format() swapped the shared format synchronously while the old stream closed async, so an in-flight old-stream callback sized its buffer from the new format (ValueError: memoryview assignment), leaving the client silent while the server showed playing. Seen live on a moOde Pi. Three guards: set_format() stops the old stream synchronously before swapping (stop blocks until in-flight callbacks finish; worker thread, never in-callback, and _call_stream logs internally) and drops the stale last-frame cache; the callback clamps bytes_needed and read frames to the actual buffer so any residual mismatch degrades to trailing silence; _fill_silence trims to the buffer. Release paths unchanged (stop(), real format changes).
maximmaxim345
left a comment
There was a problem hiding this comment.
Thanks for tracking this down!
Some users have amplifier power scripts that watch the ALSA state, which this would break. And many sound cards can only be opened by one app at a time.
I have a bit of an alternative idea: how about we keep the device open for 10 seconds after a stream ends and release it then? That covers short pauses for everyone.
A setting that's off by default, like --keep-device-open, can then skip the release entirely. "Adding a new configuration option" in CLAUDE.md lists what it needs (CLI flag, settings entry and README).
The synchronous stop in set_format() can stay outside the setting, since I think the same crash can happen on main when the format changes mid-stream.
Related:
| stream = self._stream | ||
| if stream is not None: | ||
| self._stream_executor.submit(self._call_stream, stream.stop) | ||
| # Keep the audio stream running: with the queue drained the callback |
There was a problem hiding this comment.
Since the stream now keeps running between streams, the callback also runs in INITIALIZING, where it plays queued audio instead of silence.
So the first chunk of the next stream can start playing before its scheduled start. Can it output silence in INITIALIZING too?
| # bounds them all (bulk reads are capped separately to keep cursor | ||
| # accounting consistent). | ||
| got = frames * self._format.frame_size | ||
| bytes_needed = got if got < len(output_buffer) else len(output_buffer) |
There was a problem hiding this comment.
With the synchronous stop in set_format(), I think no callback of the old stream can run after the format swap, so these guards can't trigger anymore.
Can we drop them and their test, to keep the callback as it is on main?
| pcm_format.channels, | ||
| ) | ||
| return | ||
| # Stop the old stream synchronously BEFORE swapping the format. The |
There was a problem hiding this comment.
Nit: Can you shorten the comments and test docstrings you added in this PR to one line on what the code does?
The crash history fits better in the PR description.
Why this PR exists
Greetings audiophiles. Pausing, resuming, seeking or skipping makes USB DACs with lock-loss muting relays click audibly on every transition. I hit this on an SMSL USB DAC (XMOS-based) behind a moOde Raspberry Pi: a sharp relay tick on pause, another on resume, another on every skip. That soft passive aggressive click drives me crazy.
Root cause, traced end to end:
stream/end)._on_stream_endhandler callsclose_stream(), which fully closed the PortAudio stream;clear()(seek path) stopped it. Either way the ALSA device was released.set_format()closed and recreated it unconditionally, even for an identical format), the DAC re-locks and ticks again.The key evidence that this is the right layer: the click sounds identical through full digital silence. I muted across the transition first - zero difference - which proves the click is not in the audio signal and no server-side mute, fade or crossfade can suppress it. Only whoever decides to close the device can fix it, and that decision lives in this client (
AudioPlayer).This is not SMSL-specific: any output that drops a lock when the stream closes (XMOS/Topping/Schiit USB DACs, HDMI/SPDIF relocks, Bluetooth renegotiation) clicks the same way, and all of them are fixed by the same change. Outputs with no lock concept are unaffected (silence costs nothing).
How it is implemented (
sendspin/audio.py, + regression tests)One principle - the stream stays open on silence; the device releases only when it must - plus guards so a stale callback can never crash:
clear()no longer stops the stream. It drains the queued chunks as before, but instead of submittingstream.stopit leaves the stream running. The audio callback already renders silence while starved (_read_input_frames_bulkpads with zeros), so the device stays open and pause/seek become silent gaps in an ongoing stream. New chunks submitted afterwards play on the running stream (submit()restarts it only if never started).close_stream()no longer closes the stream either. Pause arrives asstream/end, which routes here - so without this half of the fix, pausing would still close the device (proven live: fixingclear()alone left the pause click intact). It now drains viaclear()and returns, keeping the device held.set_format()skips the close/recreate cycle when the format is unchanged (dataclass equality on the PCM format). Resume re-sends the identical format after a pause; previously that tore the stream down and rebuilt it - the resume click. Now it is a logged no-op and music continues on the held-open stream.set_format()swapped the shared format while the old stream closed async, so an in-flight old-stream callback sized its buffer from the new format and crashed (ValueError: memoryview assignment), leaving the client silent while the server showed playing. Nowset_format()stops the old stream synchronously before swapping (safe: worker thread, never in-callback, internally logged), drops the stale last-frame cache, and the callback clamps reads to the actual buffer with a trailing silence pad - any residual mismatch degrades to silence, never an exception._fill_silencetrims to the buffer as final insurance.Explicitly untouched, so the device still releases exactly when it should:
stop()(daemon shutdown) fully closes - handing the device back (e.g. to MPD) still works; verified live by stopping the service and watching the ALSA state goclosed.set_format()on a real format change still closes and recreates - sample-rate switches still re-lock (correct; that tick is unavoidable and honest).Verification
tests/test_audio.py:clear()/close_stream()drain without stopping/closing; identical-formatset_format()keeps the stream; changed-formatset_format()stops the old stream synchronously and resets the frame cache; a stale-format callback degrades to silence without raising (replays the live crash).ruff format,ruff check,mypy sendspinall clean.RUNNINGacross pause, resume and skip; MA states correct throughout; zero callback errors across the matrix.Known cosmetic trade-off, disclosed: while paused with the stream held open, DAC-derived playback position keeps advancing (silence still ticks the clock). It resyncs on resume. Deliberately kept out of this change to stay out of the callback hot path - happy to add a cursor freeze as a follow-up if preferred.
Maintainers - this is a real quality of life improvement so please consider merging.
Types of changes
bugfix