From 82db14c6d132512d63770ea51e30d26f31d6d446 Mon Sep 17 00:00:00 2001 From: Honza Pokorny Date: Wed, 15 Apr 2026 19:00:21 -0300 Subject: [PATCH] Constrain ALSA buffer size and start_threshold in fallback path When buffer/period negotiation fails and we fall back to the device's defaults, some devices (e.g. USB audio via the `front:` plugin) end up with enormous buffers (1M+ frames at 44.1 kHz = ~23 seconds of audio). This causes two user-visible problems: 1. Playback start is delayed because start_threshold is set to buffer_size - period_size, so ALSA waits for ~23 seconds of data to be written before producing any output. 2. Track changes block because drain() must wait for the entire buffer to play out before the sink can be reopened for the next track. Fix both by: - Calling set_buffer_size_near(MAX_BUFFER) on the fallback hw params so the device picks a buffer close to 500 ms instead of its unconstrained default. This is best-effort (errors are ignored) and does not change behavior for devices that already negotiate successfully. - Capping start_threshold to at most SAMPLE_RATE frames (1 second) so that even if the buffer is still large, playback begins promptly. Co-Authored-By: Claude Opus 4.6 --- playback/src/audio_backend/alsa.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/playback/src/audio_backend/alsa.rs b/playback/src/audio_backend/alsa.rs index 49cc579e9..bd7fab9b3 100644 --- a/playback/src/audio_backend/alsa.rs +++ b/playback/src/audio_backend/alsa.rs @@ -362,6 +362,11 @@ fn open_device(dev_name: &str, format: AudioFormat) -> SinkResult<(PCM, usize)> trace!("You may experience higher than normal CPU usage and/or audio issues."); + // Still try to constrain the buffer size. Some devices default to + // very large buffers (e.g. 1M+ frames) which delays playback start + // (due to start_threshold) and blocks track changes (due to drain). + let _ = hwp_clone.set_buffer_size_near(MAX_BUFFER); + pcm.hw_params(&hwp_clone).map_err(AlsaError::Pcm)?; } else { pcm.hw_params(&hwp).map_err(AlsaError::Pcm)?; @@ -376,7 +381,11 @@ fn open_device(dev_name: &str, format: AudioFormat) -> SinkResult<(PCM, usize)> let swp = pcm.sw_params_current().map_err(AlsaError::Pcm)?; - swp.set_start_threshold(frames_per_buffer - frames_per_period) + // Cap start_threshold so that playback begins promptly even if the + // device ended up with a large buffer (e.g. after the fallback path). + // One second of latency is a reasonable upper bound. + let start_threshold = (frames_per_buffer - frames_per_period).min(SAMPLE_RATE as Frames); + swp.set_start_threshold(start_threshold) .map_err(AlsaError::SwParams)?; pcm.sw_params(&swp).map_err(AlsaError::Pcm)?;