ALSA: Fix 100% CPU usage after underrun

With my previous patch, after an underrun occurred sometimes polling the
alsa FDs would always return POLLIN immediately, but avail_frames would
be zero. Eventually avail_frames would become nonzero and audio output
would work, but poll would still return immediately afterwards.

Calling `stream.prepare()` when this happens seems to fix the issue after
a few loops.
This commit is contained in:
Jacob Hughes 2020-09-01 12:31:06 -04:00
parent 119ada803e
commit 6b91485781

View file

@ -504,9 +504,11 @@ fn input_stream_worker(
.unwrap_or(PollDescriptorsFlow::Continue); .unwrap_or(PollDescriptorsFlow::Continue);
match flow { match flow {
PollDescriptorsFlow::Continue => continue, PollDescriptorsFlow::Continue => {
continue;
}
PollDescriptorsFlow::XRun => { PollDescriptorsFlow::XRun => {
stream.channel.prepare().unwrap(); report_error(stream.channel.prepare(), error_callback);
continue; continue;
} }
PollDescriptorsFlow::Return => return, PollDescriptorsFlow::Return => return,
@ -549,9 +551,12 @@ fn output_stream_worker(
.unwrap_or(PollDescriptorsFlow::Continue); .unwrap_or(PollDescriptorsFlow::Continue);
match flow { match flow {
PollDescriptorsFlow::Continue => continue, PollDescriptorsFlow::Continue => {
report_error(stream.channel.prepare(), error_callback);
continue;
}
PollDescriptorsFlow::XRun => { PollDescriptorsFlow::XRun => {
stream.channel.prepare().unwrap(); report_error(stream.channel.prepare(), error_callback);
continue; continue;
} }
PollDescriptorsFlow::Return => return, PollDescriptorsFlow::Return => return,
@ -665,7 +670,12 @@ fn poll_descriptors_and_prepare_buffer(
}; };
let status = stream.channel.status()?; let status = stream.channel.status()?;
let avail_frames = status.get_avail() as usize; let avail_frames = match stream.channel.avail() {
Err(err) if err.errno() == Some(nix::errno::Errno::EPIPE) => {
return Ok(PollDescriptorsFlow::XRun)
}
res => res,
}? as usize;
let delay_frames = match status.get_delay() { let delay_frames = match status.get_delay() {
// Buffer underrun. TODO: Notify the user. // Buffer underrun. TODO: Notify the user.
d if d < 0 => 0, d if d < 0 => 0,
@ -675,11 +685,7 @@ fn poll_descriptors_and_prepare_buffer(
// Only go on if there is at least `stream.period_len` samples. // Only go on if there is at least `stream.period_len` samples.
if available_samples < stream.period_len { if available_samples < stream.period_len {
return if status.get_state() == alsa::pcm::State::XRun { return Ok(PollDescriptorsFlow::Continue);
Ok(PollDescriptorsFlow::XRun)
} else {
Ok(PollDescriptorsFlow::Continue)
};
} }
// Prepare the data buffer. // Prepare the data buffer.