pub(crate) mod cue;
pub(crate) mod output;
pub(crate) mod util;
pub mod voice;
pub(crate) mod wake_word;
#[cfg(target_os = "linux")]
const ALSA_SONAME: &[u8] = b"libasound.so.2\0";
#[must_use]
pub fn library_available() -> bool {
#[cfg(target_os = "linux")]
{
use std::sync::OnceLock;
static AVAILABLE: OnceLock<bool> = OnceLock::new();
*AVAILABLE.get_or_init(|| {
let handle = unsafe {
libc::dlopen(
ALSA_SONAME.as_ptr().cast(),
libc::RTLD_LAZY | libc::RTLD_LOCAL,
)
};
!handle.is_null()
})
}
#[cfg(not(target_os = "linux"))]
{
true
}
}
pub(crate) const LIBRARY_UNAVAILABLE: &str = concat!(
"Voice is unavailable: the audio library (libasound2 on Linux) is not installed on this ",
"machine."
);
pub fn open_speech_output_if_enabled() {
if !library_available() {
tracing::info!("{LIBRARY_UNAVAILABLE}");
return;
}
if crate::speech::synth::is_config_enabled() {
let _ = output::ensure_audio_output();
}
}
pub(crate) fn remove_retired_models() {
let Some(root) = crate::config::CONFIG.try_storage_root() else {
return;
};
let dir = root.join("models");
if !dir.exists() {
return;
}
match std::fs::remove_dir_all(&dir) {
Ok(()) => tracing::info!(dir = %dir.display(), "Removed the retired speech model tree"),
Err(e) => {
tracing::warn!(dir = %dir.display(), error = %e, "Could not remove the retired speech model tree");
}
}
}
#[cfg(test)]
mod tests {
use sha2::Digest as _;
use std::collections::BTreeSet;
fn shim() -> Option<(String, String)> {
let root =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("vendor/alsa-sys-dlopen/src");
Some((
std::fs::read_to_string(root.join("generated.rs")).ok()?,
std::fs::read_to_string(root.join("lib.rs")).ok()?,
))
}
#[cfg(target_os = "linux")]
#[test]
fn the_probe_and_the_shim_name_one_library() {
let Some((generated, _)) = shim() else {
return;
};
let soname = std::str::from_utf8(&super::ALSA_SONAME[..super::ALSA_SONAME.len() - 1])
.expect("the soname is text");
assert!(
generated.contains(soname),
"the shim resolves a different soname than the probe ({soname})"
);
}
#[test]
fn the_frozen_surface_carries_every_name_the_audio_crate_uses() {
let Some((generated, lib)) = shim() else {
return;
};
let sources = audio_crate_sources();
if sources.is_empty() {
return;
}
let mut used = BTreeSet::new();
for source in &sources {
used.extend(names_in(source));
}
assert!(
!used.is_empty(),
"the `alsa` sources on this machine name no surface symbol: the walk read them wrong"
);
for anchor in [
"snd_pcm_open",
"snd_ctl_open",
"snd_seq_event_data",
"SND_PCM_NONBLOCK",
"__va_list_tag",
] {
assert!(used.contains(anchor), "the walk did not reach `{anchor}`");
}
let surface = format!("{generated}\n{lib}");
let missing: Vec<&str> = used
.iter()
.map(String::as_str)
.filter(|name| !defines(&surface, name))
.collect();
assert!(
missing.is_empty(),
"the frozen surface is missing {} name(s) `alsa` uses: {missing:?}",
missing.len()
);
}
#[test]
fn the_frozen_surface_is_the_one_the_recipe_writes() {
let Some((generated, _)) = shim() else {
return;
};
assert_eq!(
crate::util::hex_string(&sha2::Sha256::digest(generated.as_bytes())),
"45d0525c39224698c96dfabaddf0a45ee253a6a05fc98a34cbf6b83789f37aa5",
"the frozen surface changed: rebuild it with vendor/alsa-sys-dlopen/regenerate.sh"
);
}
fn audio_crate_sources() -> Vec<String> {
let Some(version) = locked_version("alsa") else {
return Vec::new();
};
let root = match std::env::var_os("CARGO_HOME") {
Some(cargo_home) => std::path::PathBuf::from(cargo_home),
None => match std::env::var_os("HOME") {
Some(home) => std::path::PathBuf::from(home).join(".cargo"),
None => return Vec::new(),
},
};
let mut sources = Vec::new();
let Ok(registries) = std::fs::read_dir(root.join("registry/src")) else {
return sources;
};
for registry in registries.flatten() {
let Ok(crates) = std::fs::read_dir(registry.path()) else {
continue;
};
for entry in crates.flatten() {
if entry.file_name().to_string_lossy() != format!("alsa-{version}") {
continue;
}
let Ok(files) = std::fs::read_dir(entry.path().join("src")) else {
continue;
};
for file in files.flatten() {
let path = file.path();
if path.extension().is_some_and(|extension| extension == "rs")
&& let Ok(source) = std::fs::read_to_string(&path)
{
sources.push(source);
}
}
}
}
sources
}
fn locked_version(package: &str) -> Option<String> {
let lock = std::fs::read_to_string(
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.lock"),
)
.ok()?;
let mut lines = lock.lines();
while let Some(line) = lines.next() {
if line == format!("name = \"{package}\"") {
let version = lines.next()?.strip_prefix("version = \"")?;
return Some(version.strip_suffix('"')?.to_owned());
}
}
None
}
fn defines(surface: &str, name: &str) -> bool {
[
format!("fn {name}("),
format!("type {name} ="),
format!("struct {name} {{"),
format!("union {name} {{"),
format!("const {name}:"),
]
.iter()
.any(|shape| surface.contains(shape.as_str()))
}
fn names_in(source: &str) -> BTreeSet<String> {
let code = without_comments(source);
let mut names = BTreeSet::new();
let mut current = String::new();
for ch in code.chars() {
if ch.is_ascii_alphanumeric() || ch == '_' {
current.push(ch);
continue;
}
if current.starts_with("snd_") || current.starts_with("SND_") {
names.insert(std::mem::take(&mut current));
} else {
current.clear();
}
}
if current.starts_with("snd_") || current.starts_with("SND_") {
names.insert(current);
}
for (index, _) in code.match_indices("alsa::") {
let rest = &code[index + "alsa::".len()..];
let end = rest
.find(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_'))
.unwrap_or(rest.len());
if end > 0 {
names.insert(rest[..end].to_owned());
}
}
names
}
fn without_comments(source: &str) -> String {
let chars: Vec<char> = source.chars().collect();
let mut code = String::with_capacity(source.len());
let mut index = 0;
while index < chars.len() {
match chars[index] {
'/' if chars.get(index + 1) == Some(&'/') => {
while index < chars.len() && chars[index] != '\n' {
index += 1;
}
}
'/' if chars.get(index + 1) == Some(&'*') => {
index += 2;
while index < chars.len()
&& !(chars[index] == '*' && chars.get(index + 1) == Some(&'/'))
{
index += 1;
}
index += 2;
}
'"' => {
index += 1;
while index < chars.len() {
if chars[index] == '\\' {
index += 2;
continue;
}
let done = chars[index] == '"';
index += 1;
if done {
break;
}
}
}
ch => {
code.push(ch);
index += 1;
}
}
}
code
}
}