fix(audio): recover from a wedged CPAL output stream and rate-limit POLLERR (#660)

cpal 0.17's ALSA worker reports `alsa::poll() returned POLLERR` and polls
again immediately, without snd_pcm_recover: a PCM left in XRUN/SUSPENDED/
DISCONNECTED (CPU starvation at a track change on a Pi, a suspend, a pulled
cable) becomes a tight loop that never plays again until the stream is
dropped. rodio's default callback eprintln!s every one of them, which is the
POLLERR flood in the issue. The System default and PipeWire routes installed
no error callback at all, and nothing rebuilt a wedged stream.

- New qbz-audio::stream_health: classify (Wedged vs Transient), a flood
  limiter (one log line per 5s window with a suppressed count), a wedge
  latch, and one shared error_callback installed on every CPAL route
  (System default x4, PipeWire, ALSA) and the legacy player path.
- The audio thread checks the wedge latch at the TOP of its loop, every
  iteration, not in the recv_timeout Timeout arm: under QConnect the
  renderer-state command flow keeps recv returning Ok(...) and the Timeout
  arm barely runs, which left a wedged worker spinning a core for ~22s.
  On a wedge it drops the stream (joining cpal's worker), and when playing
  rebuilds and resumes at the current position; a second wedge within a 10s
  backoff releases the device and stops instead of looping.

Bit-perfect paths (ALSA Direct, DSD, WASAPI) are untouched; they never use
cpal's worker. The low-memory profile from 2.1.0 already addressed the exit
137 OOM; this is the separate flood/wedge half.

Verified on a Pi 4B + HiFiBerry DAC+ over the System default route with a
192 kHz 835 MB track and SIGSTOP-induced wedges: rebuild+resume in ~40 ms,
auto-recovery after the backoff, release+stop on a repeat wedge, and 7
POLLERR log lines instead of a flood. qbz-audio 125 and qbz-player 139 tests
pass; new stream_health and wedge_recovery tests included.

cc
This commit is contained in:
vicrodh committed 2026-09-10 01:35:38 -06:00
1 parent 1ff6df5bac
commit 9fdf53c3ea
6 files changed
+392 -11

No files matched your search

+2 -3
View File
@@ -1411,9 +1411,8 @@ impl AudioBackend for AlsaBackend {
})?
.with_supported_config(&supported_config)
.with_buffer_size(stream_config.buffer_size)
.with_error_callback(move |err| {
log::warn!("[ALSA Backend] Stream error at {}Hz: {}", effective_rate, err);
})
// #660: shared rate-limited callback + wedge latch (see stream_health).
.with_error_callback(crate::stream_health::error_callback("ALSA Backend"))
.open_stream()
.map_err(|e| {
if config.exclusive_mode {
+9 -1
View File
@@ -707,10 +707,15 @@ impl AudioBackend for CpalDefaultBackend {
.with_buffer_size(rodio::cpal::BufferSize::Fixed(
(config.sample_rate / 10).clamp(1024, 19200),
))
// #660: rodio's default callback eprintln!s every error of a
// wedged PCM (~1.7 M/s); the shared callback rate-limits it and
// latches the wedge for the audio thread to rebuild the stream.
.with_error_callback(crate::stream_health::error_callback("System default"))
.open_stream()
.map_err(|e| format!("Failed to create output stream: {}", e))?;
#[cfg(not(target_os = "linux"))]
let mixer_sink = builder
.with_error_callback(crate::stream_health::error_callback("System default"))
.open_stream()
.map_err(|e| format!("Failed to create output stream: {}", e))?;
@@ -814,9 +819,12 @@ impl CpalDefaultBackend {
builder
.with_supported_config(cfg)
.with_buffer_size(buffer_size)
.with_error_callback(crate::stream_health::error_callback("System default"))
.open_stream()
} else {
builder.open_stream()
builder
.with_error_callback(crate::stream_health::error_callback("System default"))
.open_stream()
};
let mixer_sink = match open_result {
+1
View File
@@ -60,6 +60,7 @@ pub mod pipewire_backend;
pub mod pulse_backend;
pub mod seek_waveform;
pub mod settings;
pub mod stream_health;
pub mod visualizer;
// Re-export commonly used types
+2
View File
@@ -877,6 +877,8 @@ impl AudioBackend for PipeWireBackend {
.map_err(|e| format!("Failed to create device sink builder: {}", e))?
.with_supported_config(&supported_config)
.with_buffer_size(cpal_buffer_size)
// #660: shared rate-limited callback + wedge latch (see stream_health).
.with_error_callback(crate::stream_health::error_callback("PipeWire"))
.open_stream()
.map_err(|e| {
format!(
+225
View File
@@ -0,0 +1,225 @@
//! Live-output-stream error triage shared by every CPAL route (#660).
//!
//! cpal 0.17's ALSA worker reports `alsa::poll() returned POLLERR` and then
//! polls again immediately, without `snd_pcm_recover`: a PCM left in XRUN /
//! SUSPENDED / DISCONNECTED state (CPU starvation at a track change on a Pi,
//! a system suspend, a pulled USB cable) becomes a tight loop — measured at
//! ~1.7 M error callbacks per second on a Fosi ZH3 over `front:CARD=` — that
//! never plays again until the stream is dropped. rodio's default callback
//! `eprintln!`s every one of them, which is the "15,000 lines in a few
//! seconds" of issue #660.
//!
//! This module gives the routes one shared callback that (a) classifies the
//! error, (b) rate-limits what reaches the log, and (c) latches a WEDGED
//! verdict the audio thread polls so it can drop and rebuild the stream.
use rodio::cpal::StreamError;
use std::sync::Mutex;
use std::time::{Duration, Instant};
/// One log line per window from a flooding callback (cpal can fire ~1.7 M/s).
pub const LOG_WINDOW: Duration = Duration::from_secs(5);
/// What a live stream error means for the stream's future.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StreamFault {
/// The PCM sits in an error state the worker never leaves on its own
/// (the POLLERR loop, a device that is gone): drop the stream and
/// rebuild it — cpal exposes no PCM handle, so that is the only recovery
/// available from this side.
Wedged(String),
/// A one-off the worker recovers from itself (an EPIPE underrun goes
/// through `try_recover`) or an error with no evidence of a stuck loop.
Transient(String),
}
/// Classify a cpal stream error. Kept free of side effects so every route
/// (System default, ALSA, PipeWire, the legacy CPAL path) judges alike.
pub fn classify(err: &StreamError) -> StreamFault {
let text = err.to_string();
match err {
StreamError::DeviceNotAvailable => StreamFault::Wedged(text),
StreamError::BackendSpecific { err } if err.description.contains("POLLERR") => {
StreamFault::Wedged(text)
}
_ => StreamFault::Transient(text),
}
}
/// Admits at most one event per window and counts what it swallowed in
/// between, so a flood becomes "one line every 5 s with a suppressed count"
/// instead of one line per iteration of a spinning worker.
#[derive(Debug)]
pub struct FloodLimiter {
window: Duration,
last_admitted: Option<Instant>,
suppressed: u64,
}
impl FloodLimiter {
pub fn new(window: Duration) -> Self {
Self {
window,
last_admitted: None,
suppressed: 0,
}
}
/// `Some(n)` when the caller should act on this event, where `n` is how
/// many events were suppressed since the previous admitted one.
pub fn admit(&mut self, now: Instant) -> Option<u64> {
match self.last_admitted {
Some(last) if now.duration_since(last) < self.window => {
self.suppressed += 1;
None
}
_ => {
self.last_admitted = Some(now);
Some(std::mem::take(&mut self.suppressed))
}
}
}
}
/// Process-wide "the live output stream is wedged" latch. Raised from the
/// cpal worker thread by the shared callback, taken by the audio thread on
/// its idle tick. The first reason wins while latched; a rebuilt stream
/// starts from a cleared latch (its predecessor's worker is joined on drop,
/// so nothing raises it late).
static WEDGED: Mutex<Option<String>> = Mutex::new(None);
pub fn raise_wedged(reason: String) {
if let Ok(mut latch) = WEDGED.lock() {
if latch.is_none() {
*latch = Some(reason);
}
}
}
pub fn take_wedged() -> Option<String> {
WEDGED.lock().ok().and_then(|mut latch| latch.take())
}
pub fn clear_wedged() {
if let Ok(mut latch) = WEDGED.lock() {
*latch = None;
}
}
/// The error callback every CPAL route installs
/// (`DeviceSinkBuilder::with_error_callback`). Logs the first error of a
/// burst and then one line per [`LOG_WINDOW`] with the suppressed count, and
/// latches a wedge exactly once per stream.
pub fn error_callback(route: &'static str) -> impl FnMut(StreamError) + Send + 'static {
let mut limiter = FloodLimiter::new(LOG_WINDOW);
let mut latched = false;
move |err: StreamError| {
let fault = classify(&err);
if let Some(suppressed) = limiter.admit(Instant::now()) {
if suppressed == 0 {
log::warn!("[{route}] Stream error: {err}");
} else {
log::warn!(
"[{route}] Stream error: {err} ({suppressed} more suppressed in the last {}s)",
LOG_WINDOW.as_secs()
);
}
}
if let StreamFault::Wedged(reason) = fault {
if !latched {
latched = true;
raise_wedged(format!("{route}: {reason}"));
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use rodio::cpal::{BackendSpecificError, StreamError};
use std::sync::Mutex;
use std::time::{Duration, Instant};
/// The wedge latch is process-wide; serialise the tests that touch it.
static LATCH_TESTS: Mutex<()> = Mutex::new(());
fn pollerr() -> StreamError {
StreamError::BackendSpecific {
err: BackendSpecificError {
description: "`alsa::poll()` returned POLLERR".to_string(),
},
}
}
#[test]
fn pollerr_is_a_wedged_stream() {
assert!(matches!(classify(&pollerr()), StreamFault::Wedged(_)));
}
#[test]
fn device_loss_is_a_wedged_stream() {
assert!(matches!(
classify(&StreamError::DeviceNotAvailable),
StreamFault::Wedged(_)
));
}
#[test]
fn underrun_and_other_backend_errors_are_transient() {
// cpal recovers an EPIPE underrun itself (try_recover); a one-off
// backend error is not a reason to rebuild the stream.
assert!(matches!(
classify(&StreamError::BufferUnderrun),
StreamFault::Transient(_)
));
let other = StreamError::BackendSpecific {
err: BackendSpecificError {
description: "snd_pcm_writei returned EAGAIN".to_string(),
},
};
assert!(matches!(classify(&other), StreamFault::Transient(_)));
}
#[test]
fn limiter_admits_the_first_then_one_per_window_with_the_suppressed_count() {
let t0 = Instant::now();
let mut limiter = FloodLimiter::new(Duration::from_secs(5));
assert_eq!(limiter.admit(t0), Some(0));
for i in 1..=10_000u64 {
assert_eq!(limiter.admit(t0 + Duration::from_micros(i)), None);
}
assert_eq!(limiter.admit(t0 + Duration::from_secs(5)), Some(10_000));
assert_eq!(
limiter.admit(t0 + Duration::from_secs(5) + Duration::from_millis(1)),
None
);
assert_eq!(limiter.admit(t0 + Duration::from_secs(10)), Some(1));
}
#[test]
fn wedged_latch_is_raised_once_and_taken_once() {
let _guard = LATCH_TESTS.lock().unwrap();
clear_wedged();
assert_eq!(take_wedged(), None);
raise_wedged("POLLERR".to_string());
raise_wedged("a later reason".to_string()); // first reason wins while latched
assert_eq!(take_wedged().as_deref(), Some("POLLERR"));
assert_eq!(take_wedged(), None);
}
#[test]
fn error_callback_latches_a_wedge_exactly_once_under_a_flood() {
let _guard = LATCH_TESTS.lock().unwrap();
clear_wedged();
let mut callback = error_callback("test route");
for _ in 0..100_000 {
callback(pollerr());
}
assert!(take_wedged().is_some());
assert_eq!(take_wedged(), None);
// A transient error never latches.
callback(StreamError::BufferUnderrun);
assert_eq!(take_wedged(), None);
}
}
+153 -7
View File
@@ -565,17 +565,36 @@ fn create_output_stream_with_config(
// a PlaybackError. Rate-limited: ALSA can repeat EPIPE every
// period on a wedged device, and each recorded message is one
// bus event (and one forked hook script) after the drain.
let mut last_reported: Option<std::time::Instant> = None;
//
// #660: the same limiter also caps the LOG line (cpal fires the
// POLLERR error ~1.7 M times per second on a wedged PCM), and a
// wedge is latched once for the audio thread to rebuild the
// stream — see qbz_audio::stream_health.
let mut limiter = qbz_audio::stream_health::FloodLimiter::new(
qbz_audio::stream_health::LOG_WINDOW,
);
let mut wedge_latched = false;
match builder
.with_supported_config(&supported_config)
.with_buffer_size(cpal_buffer_size)
.with_error_callback(move |err| {
log::error!("Audio stream error: {err}");
let now = std::time::Instant::now();
if last_reported.map_or(true, |t| now.duration_since(t).as_secs() >= 5) {
last_reported = Some(now);
let fault = qbz_audio::stream_health::classify(&err);
if let Some(suppressed) = limiter.admit(std::time::Instant::now()) {
if suppressed == 0 {
log::error!("Audio stream error: {err}");
} else {
log::error!(
"Audio stream error: {err} ({suppressed} more suppressed)"
);
}
state.record_stream_error(format!("Audio stream error: {err}"));
}
if let qbz_audio::stream_health::StreamFault::Wedged(reason) = fault {
if !wedge_latched {
wedge_latched = true;
qbz_audio::stream_health::raise_wedged(format!("CPAL: {reason}"));
}
}
})
.open_stream()
{
@@ -875,6 +894,28 @@ fn coreaudio_shared_rate_mismatch(
(stream_rate != nominal_rate).then_some((stream_rate, nominal_rate))
}
/// How the audio thread answers a wedged output stream (#660): cpal's ALSA
/// worker spins on `alsa::poll() returned POLLERR` (a PCM left in XRUN /
/// SUSPENDED / DISCONNECTED state after CPU starvation, a suspend, or a
/// device that went away) and never recovers; dropping the stream is the only
/// exit. The first wedge is rebuilt at once; a second one inside the backoff
/// window means the device itself is broken, so the thread releases it and
/// stops instead of rebuilding in a loop.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WedgeRecovery {
Rebuild,
Stop,
}
const WEDGE_REBUILD_BACKOFF: Duration = Duration::from_secs(10);
fn wedge_recovery(last_rebuild: Option<Instant>, now: Instant) -> WedgeRecovery {
match last_rebuild {
Some(last) if now.duration_since(last) < WEDGE_REBUILD_BACKOFF => WedgeRecovery::Stop,
_ => WedgeRecovery::Rebuild,
}
}
/// Inputs needed by both `Play` and `Stream` handlers to decide whether the
/// current output stream must be torn down and recreated.
struct StreamRecreateDecision {
@@ -2305,6 +2346,8 @@ impl Player {
const PAUSE_SUSPEND_DELAY_MS: u64 = 2000;
let mut pause_suspend_deadline: Option<Instant> = None;
let mut last_empty_check = Instant::now();
// #660: when the last wedged-stream rebuild happened (backoff input).
let mut last_wedge_rebuild: Option<Instant> = None;
// Latch so the low-memory oversized-track promotion skip logs
// once per track instead of on every 500 ms idle tick. Reset
// whenever the streaming source is absent or still downloading
@@ -4867,6 +4910,85 @@ impl Player {
};
loop {
// #660: observe a wedged output stream at the TOP of every loop
// iteration, before the command wait. Under QConnect the
// renderer-state command flow keeps recv_timeout returning
// Ok(...), so the Timeout arm (where this used to live) never
// fired — on the Pi a wedged cpal worker spun a core for 20+ s
// until an unrelated command arrived. Here it runs regardless of
// command flow and of is_playing. The stream is always dropped
// (that joins cpal's spinning worker); we only rebuild when we
// were actually playing.
if let Some(reason) = qbz_audio::stream_health::take_wedged() {
let now = Instant::now();
let was_playing = thread_state.is_playing.load(Ordering::SeqCst);
let resume_at = thread_state.current_position();
if let Some(engine) = current_engine.take() {
engine.stop();
}
drop(stream_opt.take());
qbz_audio::stream_health::clear_wedged();
gapless_pending = None;
gapless_request_armed = false;
if !was_playing {
log::warn!(
"Audio thread: output stream wedged while stopped ({reason}); released it"
);
} else {
match wedge_recovery(last_wedge_rebuild, now) {
WedgeRecovery::Rebuild => {
last_wedge_rebuild = Some(now);
log::warn!(
"Audio thread: output stream wedged ({reason}); rebuilding it and resuming at {resume_at}s"
);
let sr = current_track_sample_rate.unwrap_or(48000);
let ch = current_track_channels.unwrap_or(2);
stream_opt =
init_device(&current_device_name, &thread_state, sr, ch);
if stream_opt.is_some() {
consecutive_sink_failures = 0;
handle_command(
AudioCommand::Seek(resume_at),
&mut current_engine,
&mut current_audio_data,
&mut current_streaming_source,
&mut current_direct_dsd,
&mut stream_opt,
&mut current_device_name,
&mut consecutive_sink_failures,
&mut pause_suspend_deadline,
&mut current_track_sample_rate,
&mut current_track_channels,
&mut current_normalization_gain,
&mut current_gain_atomic,
&mut gapless_pending,
&mut gapless_request_armed,
);
}
if current_engine.is_none() {
log::error!(
"Audio thread: could not rebuild the output stream after it wedged ({reason})"
);
thread_state
.record_stream_error(format!("Audio output stopped: {reason}"));
thread_state.pause_playback_timer();
thread_state.is_playing.store(false, Ordering::SeqCst);
}
}
WedgeRecovery::Stop => {
last_wedge_rebuild = Some(now);
log::error!(
"Audio thread: output stream wedged again within {}s ({reason}); releasing the device and stopping",
WEDGE_REBUILD_BACKOFF.as_secs()
);
thread_state
.record_stream_error(format!("Audio output stopped: {reason}"));
thread_state.pause_playback_timer();
thread_state.is_playing.store(false, Ordering::SeqCst);
}
}
}
}
thread_state.publish_output_stream_format(stream_opt.as_ref());
if thread_state.is_playing.load(Ordering::SeqCst) {
match rx.recv_timeout(Duration::from_millis(100)) {
@@ -5291,7 +5413,11 @@ impl Player {
pause_suspend_deadline = None;
}
match rx.recv() {
// #660: a bounded wait (not a blocking recv) so the loop
// keeps iterating and the top-of-loop wedge check runs even
// while stopped — a stream can wedge with is_playing already
// false and cpal's worker would otherwise spin unseen.
match rx.recv_timeout(Duration::from_millis(250)) {
Ok(command) => handle_command(
command,
&mut current_engine,
@@ -5309,7 +5435,8 @@ impl Player {
&mut gapless_pending,
&mut gapless_request_armed,
),
Err(_) => {
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => {
log::info!("Audio thread: channel closed, exiting");
break;
}
@@ -7194,6 +7321,7 @@ pub fn external_content_type(mime: &str, format_id: u32) -> String {
#[cfg(test)]
mod tests {
use super::compute_needs_new_stream;
use super::{wedge_recovery, WedgeRecovery, WEDGE_REBUILD_BACKOFF};
use super::external_content_type;
#[cfg(target_os = "linux")]
use super::{hardware_volume_event_callback, reported_volume_after_command};
@@ -7455,6 +7583,24 @@ mod tests {
}
}
#[test]
fn wedge_recovery_rebuilds_once_then_backs_off() {
// #660: a wedged CPAL stream (POLLERR loop) is rebuilt at once; a
// second wedge inside the backoff window means the device itself is
// gone or broken, so the thread releases it and stops instead of
// rebuilding in a loop.
let t0 = std::time::Instant::now();
assert_eq!(wedge_recovery(None, t0), WedgeRecovery::Rebuild);
assert_eq!(
wedge_recovery(Some(t0), t0 + std::time::Duration::from_secs(3)),
WedgeRecovery::Stop
);
assert_eq!(
wedge_recovery(Some(t0), t0 + WEDGE_REBUILD_BACKOFF),
WedgeRecovery::Rebuild
);
}
#[test]
fn dsd_error_report_surfaces_io_error_at_stream_end() {
let state = SharedState::new();