use crate::util::UnwrapPoison;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
use tracing::{debug, warn};
pub(crate) const SPEAKING_TAIL: Duration = Duration::from_millis(300);
struct Output {
_sink: rodio::MixerDeviceSink,
mixer: rodio::mixer::Mixer,
}
static OUTPUT: OnceLock<Output> = OnceLock::new();
static OPEN_LOCK: Mutex<()> = Mutex::new(());
static SPEAKING: AtomicUsize = AtomicUsize::new(0);
pub(crate) struct Speaking(());
impl Speaking {
pub(crate) fn start() -> Self {
SPEAKING.fetch_add(1, Ordering::Relaxed);
Self(())
}
}
impl Drop for Speaking {
fn drop(&mut self) {
SPEAKING.fetch_sub(1, Ordering::Release);
}
}
pub(crate) fn is_speaking() -> bool {
SPEAKING.load(Ordering::Acquire) > 0
}
pub(crate) fn audio_output_ready() -> bool {
OUTPUT.get().is_some()
}
pub(crate) fn ensure_audio_output() -> bool {
open(true)
}
pub(crate) fn ensure_audio_output_silent() -> bool {
open(false)
}
pub(crate) fn mixer() -> Option<rodio::mixer::Mixer> {
OUTPUT.get().map(|output| output.mixer.clone())
}
fn open(warn_on_failure: bool) -> bool {
if OUTPUT.get().is_some() {
return true;
}
if !crate::audio::library_available() {
if warn_on_failure {
warn!("{}", crate::audio::LIBRARY_UNAVAILABLE);
} else {
debug!("{}", crate::audio::LIBRARY_UNAVAILABLE);
}
return false;
}
let _guard = OPEN_LOCK.lock().unwrap_poison();
if OUTPUT.get().is_some() {
return true;
}
match rodio::DeviceSinkBuilder::open_default_sink() {
Ok(sink) => {
let mixer = sink.mixer().clone();
let _ = OUTPUT.set(Output { _sink: sink, mixer });
}
Err(e) => {
if warn_on_failure {
warn!("Failed to initialize audio output — playback will be disabled: {e}");
} else {
debug!("Audio output unavailable — playback stays silent: {e}");
}
}
}
OUTPUT.get().is_some()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[serial_test::serial(speech)]
fn the_speaking_flag_holds_until_the_last_phrase_ends() {
assert!(!is_speaking(), "nothing is speaking at rest");
let first = Speaking::start();
assert!(is_speaking());
let second = Speaking::start();
drop(first);
assert!(is_speaking(), "a second phrase keeps the flag raised");
drop(second);
assert!(!is_speaking(), "the flag falls with the last phrase");
}
}