capri-voice: add call module
This commit is contained in:
1 file changed
+100
@@ -0,0 +1,100 @@
|
||||
//! Call audio on PipeWire/Pulse (replaces Capri's VB-CABLE installer): a non-persistent virtual cable created only
|
||||
//! on an explicit owner action, without root. Call apps select the "Capri call microphone" input.
|
||||
use std::io::Write;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
|
||||
use anyhow::{Context, Result, ensure};
|
||||
|
||||
pub const SINK: &str = "capri_call";
|
||||
pub const SOURCE: &str = "capri_call_mic";
|
||||
|
||||
/// `pactl` argument lists: null sink, the remapped source call apps record, and optionally the owner's microphone.
|
||||
pub fn cable_commands(microphone: Option<&str>) -> Vec<Vec<String>> {
|
||||
let mut out = vec![
|
||||
vec!["load-module", "module-null-sink", "sink_name=capri_call", "rate=48000", "channels=1", "channel_map=mono", "sink_properties=device.description=Capri-call-output"],
|
||||
vec!["load-module", "module-remap-source", "master=capri_call.monitor", "source_name=capri_call_mic", "channels=1", "channel_map=mono", "source_properties=device.description=Capri-call-microphone"],
|
||||
]
|
||||
.into_iter()
|
||||
.map(|v| v.into_iter().map(String::from).collect::<Vec<_>>())
|
||||
.collect::<Vec<_>>();
|
||||
if let Some(mic) = microphone {
|
||||
out.push(vec!["load-module".into(), "module-loopback".into(), format!("source={mic}"), format!("sink={SINK}"), "latency_msec=30".into(), "source_dont_move=true".into()]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Loaded module indexes; [`remove`] unloads them. Nothing persists after a sound-server restart.
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct Cable {
|
||||
pub modules: Vec<u32>,
|
||||
}
|
||||
|
||||
/// Creates the cable. `microphone`: a Pulse source name to mix the owner's voice into the call.
|
||||
pub fn create(microphone: Option<&str>) -> Result<Cable> {
|
||||
let mut cable = Cable::default();
|
||||
for args in cable_commands(microphone) {
|
||||
let out = Command::new("pactl").args(&args).output().context("pactl is required for call audio (pacman -S libpulse)")?;
|
||||
let index = String::from_utf8_lossy(&out.stdout).trim().parse::<u32>().ok().filter(|_| out.status.success());
|
||||
let Some(index) = index else {
|
||||
remove(&cable);
|
||||
anyhow::bail!("Call audio output is unavailable: {}", String::from_utf8_lossy(&out.stderr).trim());
|
||||
};
|
||||
cable.modules.push(index);
|
||||
}
|
||||
Ok(cable)
|
||||
}
|
||||
|
||||
pub fn remove(cable: &Cable) {
|
||||
for index in cable.modules.iter().rev() {
|
||||
let _ = Command::new("pactl").args(["unload-module", &index.to_string()]).status();
|
||||
}
|
||||
}
|
||||
|
||||
/// Capri's speech written into the cable sink with `pacat` (24 kHz mono f32).
|
||||
pub struct CallOutput {
|
||||
child: Child,
|
||||
}
|
||||
|
||||
impl CallOutput {
|
||||
pub fn open() -> Result<Self> {
|
||||
let child = Command::new("pacat")
|
||||
.args(["--playback", &format!("--device={SINK}"), "--format=float32le", "--rate=24000", "--channels=1", "--raw", "--client-name=Capri", "--stream-name=Capri call voice"])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.context("pacat is required for call audio (pacman -S libpulse)")?;
|
||||
Ok(Self { child })
|
||||
}
|
||||
|
||||
/// Writes one chunk at `volume` (0..100, Capri's call voice volume).
|
||||
pub fn write(&mut self, pcm: &[f32], volume: u32) -> Result<()> {
|
||||
ensure!(self.child.try_wait()?.is_none(), "Call audio output is unavailable.");
|
||||
let gain = volume.min(100) as f32 / 100.0;
|
||||
let bytes: Vec<u8> = pcm.iter().flat_map(|x| (x * gain).to_le_bytes()).collect();
|
||||
self.child.stdin.as_mut().context("Call audio output is unavailable.")?.write_all(&bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CallOutput {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cable_is_a_null_sink_and_remapped_source() {
|
||||
let cmds = cable_commands(Some("alsa_input.usb-Mic"));
|
||||
assert_eq!(cmds.len(), 3);
|
||||
assert_eq!(cmds[0][1], "module-null-sink");
|
||||
assert!(cmds[1].contains(&"master=capri_call.monitor".to_string()));
|
||||
assert!(cmds[2].contains(&"source=alsa_input.usb-Mic".to_string()) && cmds[2].contains(&"sink=capri_call".to_string()));
|
||||
assert_eq!(cable_commands(None).len(), 2);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user