Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

A failing audio device's error is said once, then only how often it came back: the mixer's and raea voice's stream error callbacks printed a line for every call, and on Linux an ALSA device answering POLLERR filled app.log with 40 GB of one line in two days (#239)

shinyobjectz7595c8178257
diff --git a/apps/voice/src/audio.rs b/apps/voice/src/audio.rs
index 969e954d..4e8ccf73 100644
--- a/apps/voice/src/audio.rs
+++ b/apps/voice/src/audio.rs
@@ -108,7 +108,7 @@ pub fn microphone(tx: Sender<Vec<f32>>) -> anyhow::Result<cpal::Stream> {
rs.push(&mono, &mut out);
let _ = tx.send(out);
};
- let bad = |e| eprintln!("raea voice: the microphone: {e}");
+ let bad = said_once::<cpal::StreamError>("raea voice: the microphone");
let stream = match cfg.sample_format() {
cpal::SampleFormat::F32 => {
dev.build_input_stream(&cfg.config(), move |d: &[f32], _: &cpal::InputCallbackInfo| take(mono(d, ch)), bad, None)
@@ -242,7 +242,7 @@ impl Speaker {
f.fill(ready.pop_front().unwrap_or(0.0));
}
};
- let stream = dev.build_output_stream(&cfg.config(), play, |e| eprintln!("raea voice: the speakers: {e}"), None).map_err(|e| anyhow!("the speakers didn't open: {e}"))?;
+ let stream = dev.build_output_stream(&cfg.config(), play, said_once::<cpal::StreamError>("raea voice: the speakers"), None).map_err(|e| anyhow!("the speakers didn't open: {e}"))?;
stream.play().map_err(|e| anyhow!("the speakers didn't start: {e}"))?;
Ok(Speaker { line, rate, to, _stream: Some(stream) })
}
@@ -286,3 +286,43 @@ mod tests {
assert!(x.iter().zip(&y).all(|(a, b)| (a - b).abs() < 1e-3));
}
}
+
+/// A device's error said once, then only how often it came back (at its 10th, 100th, ... time, and never more than once
+/// a second): a failing ALSA device calls a stream's error callback without pause, and every call printed a line: #239's
+/// app.log reached 40 GB of one line in two days.
+fn said_once<E: std::fmt::Display>(what: &'static str) -> impl FnMut(E) + Send + 'static {
+ let mut seen = Repeats::default();
+ move |e| {
+ let m = e.to_string();
+ match seen.hit(&m, std::time::Instant::now()) {
+ Some(1) => eprintln!("{what}: {m}"),
+ Some(n) => eprintln!("{what}: {m} ({n} times now)"),
+ None => {}
+ }
+ }
+}
+
+/// Which of an error's repeats get said: `hit` answers with the count to print, or nothing.
+#[derive(Default)]
+struct Repeats {
+ last: String,
+ n: u64,
+ next: u64,
+ at: Option<std::time::Instant>,
+}
+
+impl Repeats {
+ fn hit(&mut self, m: &str, now: std::time::Instant) -> Option<u64> {
+ if m != self.last || self.n == 0 {
+ (self.last, self.n, self.next) = (m.to_string(), 0, 1);
+ }
+ self.n += 1;
+ let soon = self.at.is_some_and(|t| now.duration_since(t).as_secs() < 1);
+ if self.n < self.next || (soon && self.n > 1) {
+ return None;
+ }
+ self.next = self.n.saturating_mul(10);
+ self.at = Some(now);
+ Some(self.n)
+ }
+}
diff --git a/systems/mix/src/live.rs b/systems/mix/src/live.rs
index 3e5f5794..bf389d6f 100644
--- a/systems/mix/src/live.rs
+++ b/systems/mix/src/live.rs
@@ -451,11 +451,51 @@ fn start(cx: &mut FirewheelContext, block: u32) -> Result<(cpal::Stream, u32), S
// the block size when the device's range takes it, else its own
let fits = dev.supported_output_configs().map(|mut c| c.any(|r| r.channels() == channels && matches!(r.buffer_size(), cpal::SupportedBufferSize::Range { min, max } if *min <= block && block <= *max))).unwrap_or(false);
let config = cpal::StreamConfig { channels, sample_rate: cpal::SampleRate(rate), buffer_size: if fits { cpal::BufferSize::Fixed(block) } else { cpal::BufferSize::Default } };
- let stream = dev.build_output_stream(&config, move |o: &mut [f32], i: &cpal::OutputCallbackInfo| callback(o, i), |e| eprintln!("raea mixer: {e}"), None).map_err(|e| format!("audio stream: {e}"))?;
+ let stream = dev.build_output_stream(&config, move |o: &mut [f32], i: &cpal::OutputCallbackInfo| callback(o, i), said_once::<cpal::StreamError>("raea mixer"), None).map_err(|e| format!("audio stream: {e}"))?;
stream.play().map_err(|e| format!("audio stream: {e}"))?;
Ok((stream, rate))
}
+/// A device's error said once, then only how often it came back (at its 10th, 100th, ... time, and never more than once
+/// a second): a failing ALSA device calls a stream's error callback without pause, and every call printed a line: #239's
+/// app.log reached 40 GB of one line in two days.
+fn said_once<E: std::fmt::Display>(what: &'static str) -> impl FnMut(E) + Send + 'static {
+ let mut seen = Repeats::default();
+ move |e| {
+ let m = e.to_string();
+ match seen.hit(&m, std::time::Instant::now()) {
+ Some(1) => eprintln!("{what}: {m}"),
+ Some(n) => eprintln!("{what}: {m} ({n} times now)"),
+ None => {}
+ }
+ }
+}
+
+/// Which of an error's repeats get said: `hit` answers with the count to print, or nothing.
+#[derive(Default)]
+struct Repeats {
+ last: String,
+ n: u64,
+ next: u64,
+ at: Option<std::time::Instant>,
+}
+
+impl Repeats {
+ fn hit(&mut self, m: &str, now: std::time::Instant) -> Option<u64> {
+ if m != self.last || self.n == 0 {
+ (self.last, self.n, self.next) = (m.to_string(), 0, 1);
+ }
+ self.n += 1;
+ let soon = self.at.is_some_and(|t| now.duration_since(t).as_secs() < 1);
+ if self.n < self.next || (soon && self.n > 1) {
+ return None;
+ }
+ self.next = self.n.saturating_mul(10);
+ self.at = Some(now);
+ Some(self.n)
+ }
+}
+
impl Drop for Live {
fn drop(&mut self) {
let Some((path, buf)) = self.tap.take() else { return };
@@ -470,3 +510,21 @@ impl Drop for Live {
let _ = std::fs::write(&side, format!("{{\"anchors\": [{}], \"report\": {}}}", anchors.join(", "), self.report()));
}
}
+
+#[cfg(test)]
+mod repeats {
+ use super::Repeats;
+ use std::time::{Duration, Instant};
+
+ /// #239: half a billion repeats of one ALSA error were half a billion lines. Two days of them are a handful.
+ #[test]
+ fn a_repeating_error_is_a_handful_of_lines() {
+ let (mut r, t0) = (Repeats::default(), Instant::now());
+ // 5,000 a second for a minute
+ let said = (0..300_000u64).filter(|i| r.hit("alsa::poll() returned POLLERR", t0 + Duration::from_micros(i * 200)).is_some()).count();
+ assert!(said <= 8, "{said} lines for 300,000 repeats");
+ assert_eq!(Repeats::default().hit("x", t0), Some(1), "the first is always said");
+ // another error is said at once, when a second has gone by
+ assert_eq!(r.hit("the device went away", t0 + Duration::from_secs(120)), Some(1));
+ }
+}