mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* audio: count microphone overloads on the realtime thread, log them coalesced CoreAudio reports kAudioDeviceProcessorOverload as ErrorKind::Xrun from its real-time thread. Hex's handler ran tracing::warn! there (formatting plus a blocking write to stderr and process.log behind a mutex) and locked STREAM_GLITCHED_AT, once per overload, hundreds of times a day, on a thread that had already missed its cycle. The error callback now only moves atomics (a total, a refused real-time promotion count, and the last overload time against a clock taken before the stream runs). AudioInput::recv_timeout, the poll that drains the stream for dictation and meetings, reports them: one line per burst with count and realtime_denied, at most every 10 s, and the count a throttled poll holds back is taken by the next one rather than lost. since_last_stream_glitch keeps its signature and semantics from the same counters. On macOS the first chunk of each open also logs the callback's frames and period, since cpal exposes no readback for BufferSize::Default and overloads arrive sooner on a smaller hardware period. No FFI or unsafe was added. Moved the counters into audio/overloads.rs to keep audio.rs under the 1,500-line shape limit. * audio: write a closing stream's leftover overloads, and stop calling them CoreAudio's Review follow-ups to the coalesced overload log: - impl Drop for AudioInput drops the stream first, so no callback races, then overloads::flush writes any count the 10 s window still held. Without it, a burst left over at close surfaced on the next open, hours later, next to "microphone stream opened" and read as a cold-start burst. Flush is swap-based and skips the rate limit; nothing pending costs one atomic load, and the fixture and test inputs (no stream) drop as before. - cpal 0.18 emits RealtimeDenied only from the aaudio and jack hosts, so the separate REALTIME_DENIED counter and the realtime_denied log field are gone: record() takes no argument and both kinds just count. Comments and docs no longer call these CoreAudio's overloads, since the poll reports any host's. - now_nanos reads the clock cell before Instant::now, so a first-ever record cannot land on the 0 that means never. - report_period skips HEX_AUDIO_FIXTURE, whose chunks are the file's rather than a device's, and says so. docs/features/recovery.md gains the close-time flush and uses the "Changed after dev" heading; the unsupported "hundreds a day" claim is gone. * audio: clamp the overload clock reading to at least one get_or_init(Instant::now) and the next Instant::now() can return the same tick on Apple Silicon and Windows, so a first-ever reading could still be 0, the sentinel for "never". now_nanos returns at least 1, and the GLITCHED_AT doc says the reading is clamped rather than merely later than the clock.
177 lines
6.8 KiB
Rust
177 lines
6.8 KiB
Rust
//! `HEX_AUDIO_FIXTURE`: a WAV file that stands in for every microphone, so
|
|
//! benchmarks and tests drive the real capture, stream, and output pipeline
|
|
//! without recording anyone. The file plays at real-time pace in 10 ms
|
|
//! chunks, from its start at each open, and loops. Each chunk is stamped
|
|
//! with when its last sample was due on the clock the shortcuts use
|
|
//! ([`CaptureInstant::now`]), as a device stamps its samples' own time: a
|
|
//! late wake on a busy machine delivers the chunk late but never moves it.
|
|
//! Device enumeration is skipped: the fixture is the only input.
|
|
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::atomic::AtomicBool;
|
|
use std::sync::mpsc;
|
|
use std::sync::{Arc, Mutex, OnceLock};
|
|
use std::thread;
|
|
use std::time::{Duration, Instant};
|
|
|
|
use color_eyre::eyre::{Result, WrapErr, eyre};
|
|
|
|
use super::{AudioInput, CaptureInstant, STREAM_STALL_TIMEOUT, Selection};
|
|
|
|
/// What the fixture input is called in the log and Settings.
|
|
pub(super) const NAME: &str = "Audio fixture";
|
|
|
|
/// Chunks per second, as a device's 10 ms period delivers them.
|
|
const CHUNKS_PER_SECOND: u32 = 100;
|
|
|
|
/// The fixture's path, read once: `HEX_AUDIO_FIXTURE`.
|
|
pub(super) fn path() -> Option<&'static Path> {
|
|
static PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
|
|
PATH.get_or_init(|| {
|
|
std::env::var_os("HEX_AUDIO_FIXTURE")
|
|
.filter(|value| !value.is_empty())
|
|
.map(PathBuf::from)
|
|
})
|
|
.as_deref()
|
|
}
|
|
|
|
/// The fixture's mono samples and sample rate, decoded once.
|
|
fn clip(path: &Path) -> Result<(Arc<Vec<f32>>, u32)> {
|
|
type Decoded = (PathBuf, Arc<Vec<f32>>, u32);
|
|
static CLIP: Mutex<Option<Decoded>> = Mutex::new(None);
|
|
let mut cached = CLIP.lock().unwrap_or_else(|error| error.into_inner());
|
|
if let Some((_, samples, rate)) = cached.as_ref().filter(|(at, ..)| at == path) {
|
|
return Ok((samples.clone(), *rate));
|
|
}
|
|
let (samples, rate) = read(path)?;
|
|
let samples = Arc::new(samples);
|
|
*cached = Some((path.to_path_buf(), samples.clone(), rate));
|
|
Ok((samples, rate))
|
|
}
|
|
|
|
fn read(path: &Path) -> Result<(Vec<f32>, u32)> {
|
|
let mut reader = hound::WavReader::open(path)
|
|
.wrap_err_with(|| format!("could not open the audio fixture {}", path.display()))?;
|
|
let spec = reader.spec();
|
|
let samples = match spec.sample_format {
|
|
hound::SampleFormat::Float => reader
|
|
.samples::<f32>()
|
|
.collect::<std::result::Result<Vec<_>, _>>()?,
|
|
hound::SampleFormat::Int => {
|
|
let scale = (1_i64 << (spec.bits_per_sample.clamp(1, 32) - 1)) as f32;
|
|
reader
|
|
.samples::<i32>()
|
|
.map(|sample| sample.map(|sample| sample as f32 / scale))
|
|
.collect::<std::result::Result<Vec<_>, _>>()?
|
|
}
|
|
};
|
|
let channels = usize::from(spec.channels.max(1));
|
|
let mono = super::mono(&samples, channels, |sample| *sample);
|
|
if mono.len() < (spec.sample_rate / CHUNKS_PER_SECOND) as usize {
|
|
return Err(eyre!("the audio fixture {} holds no audio", path.display()));
|
|
}
|
|
Ok((mono, spec.sample_rate))
|
|
}
|
|
|
|
/// Opens the fixture as a microphone. Dropping the input stops its thread.
|
|
pub(super) fn open(path: &Path) -> Result<AudioInput> {
|
|
let (samples, sample_rate) = clip(path)?;
|
|
let (sender, chunks) = mpsc::channel();
|
|
let (_, stream_errors) = mpsc::sync_channel(1);
|
|
let frames = (sample_rate / CHUNKS_PER_SECOND) as usize;
|
|
let period = Duration::from_secs(1) / CHUNKS_PER_SECOND;
|
|
thread::Builder::new()
|
|
.name("audio-fixture".into())
|
|
.spawn(move || {
|
|
let started = Instant::now();
|
|
let opened = CaptureInstant::now();
|
|
let mut at = 0;
|
|
for chunk in 1_u32.. {
|
|
// Paced against the start, so a late wake never drifts.
|
|
let due = started + period * chunk;
|
|
if let Some(wait) = due.checked_duration_since(Instant::now()) {
|
|
thread::sleep(wait);
|
|
}
|
|
let mut out = Vec::with_capacity(frames);
|
|
while out.len() < frames {
|
|
let take = (frames - out.len()).min(samples.len() - at);
|
|
out.extend_from_slice(&samples[at..at + take]);
|
|
at = (at + take) % samples.len();
|
|
}
|
|
if sender.send((out, opened + period * chunk)).is_err() {
|
|
return;
|
|
}
|
|
}
|
|
})
|
|
.wrap_err("could not start the audio fixture")?;
|
|
tracing::warn!(
|
|
path = %path.display(),
|
|
sample_rate,
|
|
"HEX_AUDIO_FIXTURE replaces the microphone"
|
|
);
|
|
Ok(AudioInput {
|
|
_stream: None,
|
|
chunks,
|
|
sample_rate,
|
|
device_name: NAME.into(),
|
|
uid: None,
|
|
selection: Selection::InUse,
|
|
stream_errors,
|
|
watch_service_restarts: false,
|
|
restart_generation: super::audio_service_restart_generation(),
|
|
hex_microphone: crate::audio::hex_microphone::capture_feed(sample_rate).1,
|
|
stall_after: Some(STREAM_STALL_TIMEOUT),
|
|
last_delivery: Mutex::new(Instant::now()),
|
|
reported_period: AtomicBool::new(false),
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn a_fixture_plays_its_file_from_the_start_in_ten_ms_chunks() {
|
|
let directory = std::env::temp_dir().join(format!("hex-fixture-{}", std::process::id()));
|
|
std::fs::create_dir_all(&directory).unwrap();
|
|
let path = directory.join("fixture.wav");
|
|
let spec = hound::WavSpec {
|
|
channels: 2,
|
|
sample_rate: 8_000,
|
|
bits_per_sample: 16,
|
|
sample_format: hound::SampleFormat::Int,
|
|
};
|
|
let mut writer = hound::WavWriter::create(&path, spec).unwrap();
|
|
for frame in 0..120_i16 {
|
|
writer.write_sample(frame * 100).unwrap();
|
|
writer.write_sample(frame * 100).unwrap();
|
|
}
|
|
writer.finalize().unwrap();
|
|
|
|
let (samples, rate) = read(&path).unwrap();
|
|
assert_eq!(rate, 8_000);
|
|
assert_eq!(samples.len(), 120);
|
|
|
|
let input = open(&path).unwrap();
|
|
let mut heard = Vec::new();
|
|
let mut last = CaptureInstant::ZERO;
|
|
while heard.len() < 160 {
|
|
let super::super::AudioInputEvent::Chunk {
|
|
samples,
|
|
captured_through,
|
|
} = input.recv_timeout(Duration::from_secs(1))
|
|
else {
|
|
panic!("the fixture stopped delivering");
|
|
};
|
|
assert_eq!(samples.len(), 80);
|
|
assert!(captured_through > last);
|
|
last = captured_through;
|
|
heard.extend(samples);
|
|
}
|
|
// It loops: the 121st sample is the first again.
|
|
assert_eq!(heard[0], heard[120]);
|
|
assert!((heard[1] - 100.0 / 32_768.0).abs() < 1e-6);
|
|
drop(input);
|
|
let _ = std::fs::remove_dir_all(&directory);
|
|
}
|
|
}
|