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 Some(used) = spelled() else {
return;
};
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())),
"8457f90893d987230642c68409c7d152d085a35f5d39e4020e9734d28a285e8a",
"the frozen surface changed: rebuild it with vendor/alsa-sys-dlopen/regenerate.sh, \
then move this pin with it"
);
}
#[test]
fn the_surface_carries_no_function_the_audio_crate_cannot_reach() {
let Some((generated, _)) = shim() else {
return;
};
let Some(spelled) = spelled() else {
return;
};
let declared: Vec<&str> = generated
.lines()
.filter_map(|line| line.strip_prefix("pub unsafe fn "))
.filter_map(|rest| rest.split('(').next())
.collect();
assert!(
!declared.is_empty(),
"the surface declares no function: the walk read it wrong"
);
let unreachable: Vec<&str> = declared
.iter()
.copied()
.filter(|name| !spelled.contains(*name))
.collect();
assert!(
unreachable.is_empty(),
"the surface binds {} function(s) `alsa` never spells: {unreachable:?}",
unreachable.len()
);
}
#[test]
fn the_recipe_reproduces_the_frozen_surface() {
let Some((generated, _)) = shim() else {
return;
};
let (Some(bindings), Some(layer)) = (published_bindings(), audio_crate_source_dir()) else {
return;
};
let work = crate::util::test::test_root().join("alsa-recipe");
let _ = std::fs::remove_dir_all(&work);
std::fs::create_dir_all(&work).expect("create the recipe's scratch directory");
let transform = work.join("transform");
let recipe = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("vendor/alsa-sys-dlopen/regenerate.rs");
let compiled = std::process::Command::new("rustc")
.args(["--edition", "2021", "-O", "-o"])
.arg(&transform)
.arg(&recipe)
.output();
let Ok(compiled) = compiled else {
return;
};
assert!(
compiled.status.success(),
"the recipe does not compile: {}",
String::from_utf8_lossy(&compiled.stderr)
);
let produced = std::process::Command::new(&transform)
.arg(&bindings)
.arg(&layer)
.output()
.expect("run the recipe");
assert!(
produced.status.success(),
"the recipe failed: {}",
String::from_utf8_lossy(&produced.stderr)
);
assert_eq!(
crate::util::hex_string(&sha2::Sha256::digest(&produced.stdout)),
crate::util::hex_string(&sha2::Sha256::digest(generated.as_bytes())),
"the recipe no longer writes the committed surface: \
run vendor/alsa-sys-dlopen/regenerate.sh"
);
}
fn audio_crate_sources() -> Vec<String> {
let Some(directory) = audio_crate_source_dir() else {
return Vec::new();
};
let Ok(files) = std::fs::read_dir(directory) else {
return Vec::new();
};
files
.flatten()
.map(|file| file.path())
.filter(|path| path.extension().is_some_and(|extension| extension == "rs"))
.filter_map(|path| std::fs::read_to_string(path).ok())
.collect()
}
fn audio_crate_source_dir() -> Option<std::path::PathBuf> {
let directory = registry_crate("alsa")?.join("src");
directory.is_dir().then_some(directory)
}
fn published_bindings() -> Option<std::path::PathBuf> {
let bindings = registry_crate("alsa-sys")?.join("src/generated.rs");
bindings.is_file().then_some(bindings)
}
fn registry_crate(package: &str) -> Option<std::path::PathBuf> {
let name = format!("{package}-{}", locked_version(package)?);
let cargo_home = match std::env::var_os("CARGO_HOME") {
Some(cargo_home) => std::path::PathBuf::from(cargo_home),
None => std::path::PathBuf::from(std::env::var_os("HOME")?).join(".cargo"),
};
let registries = std::fs::read_dir(cargo_home.join("registry/src")).ok()?;
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() == name {
return Some(entry.path());
}
}
}
None
}
fn spelled() -> Option<BTreeSet<String>> {
let sources = audio_crate_sources();
if sources.is_empty() {
return None;
}
let mut names = BTreeSet::new();
for source in &sources {
names.extend(names_in(source));
}
Some(names)
}
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
}
}