Skip to content

fix(output): never lose an audio-toolbox buffer on an empty read - #447

Merged
devgianlu merged 1 commit into
devgianlu:masterfrom
isnogudus:fix/audio-toolbox-lost-buffers
Nov 18, 2026
Merged

devgianlu merged 1 commit into
devgianlu:masterfrom
isnogudus:fix/audio-toolbox-lost-buffers

Conversation

@isnogudus

Copy link
Copy Markdown
Contributor

On macOS, playback can turn distorted after a few track changes and stay that way until the daemon restarts. The log then shows:

error queuing samples for output: -66686

-66686 is kAudioQueueErr_BufferEmpty.

Cause

The audio queue owns three buffers and hands each one back only through the output callback. Two reads lose a buffer for good:

  • An empty read. SwitchingAudioSource.readDirect returns (0, nil) when it switches to a prefetched track and the old decoder had no samples left. The buffer is enqueued with zero bytes, and the queue rejects it.
  • A failed read. The callback returns without enqueueing the buffer at all.

After two such switches only one buffer is left. The queue then underruns on every buffer, which sounds like distortion on every output device.

Fix

readSamples now does the reading.

  • After an empty or failed read, it fills the whole buffer with silence, so the callback always enqueues a non-empty buffer.
  • Samples that come back together with an error, such as the last ones before io.EOF, still play.
  • Read errors are still reported on the Error() channel.

Testing

  • TestAudioToolboxEveryReadFillsTheBuffer covers five reads: full, partial, empty at a track switch, failed, and the last samples before EOF. It needs no audio device.
  • go test -race -tags "test_unit test_integration" ./... passes, and so does TestAudioToolboxDefaultDevice with GO_LIBRESPOT_TEST_AUDIO_DEVICE=1.
  • The fix is running in my daemon. Before it, the distortion followed the two -66686 errors at track switches in the log.

🤖 Generated with Claude Code

The audio queue owns three buffers and hands each back only through the
output callback. When the reader returned no samples, as it does at a
switch to a prefetched track, or failed, the buffer was enqueued empty
(rejected with kAudioQueueErr_BufferEmpty, -66686) or not at all, and was
never seen again. After two such track switches a single buffer was left
and playback stuttered into audible distortion until the daemon restarted.

Enqueue a buffer of silence instead, and keep samples read along with an
error, like the last ones before io.EOF.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@devgianlu
devgianlu merged commit fdfa7ee into devgianlu:master Nov 18, 2026
11 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