AnyBot/src/voice.rs

370 lines
16 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 語音 on this device: only recording from the microphone and playing sound. What was said is
// turned into text, and answers into sound, by the brain's voice service (speech.rs), the same
// for every screen and the phone. macOS records with its own AVAudioRecorder (through osascript,
// no extra install); elsewhere cpal does (mic.rs).
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
/// Longest recording (estimated; the recorder script also stops itself at 10 minutes).
pub const MAX_SECS: u64 = 600;
/// 會議記錄 can run longer: two hours stays under the transcription service's 25 MB limit at this
/// recorder's bitrate (estimated).
pub const MEETING_MAX_SECS: u64 = 7_200;
/// A recording limit in words (「10 分鐘」, 「2 小時」).
pub fn length_words(secs: u64) -> String {
if secs >= 3600 && secs.is_multiple_of(3600) {
format!("{} 小時", secs / 3600)
} else {
format!("{} 分鐘", secs / 60)
}
}
const RECORDER: &str = r#"ObjC.import('AVFoundation');
ObjC.import('Foundation');
function run(argv) {
const url = $.NSURL.fileURLWithPath(argv[0]);
const settings = $.NSDictionary.dictionaryWithObjectsForKeys(
[$.NSNumber.numberWithInt(1633772320), $.NSNumber.numberWithDouble(16000.0), $.NSNumber.numberWithInt(1)],
[$('AVFormatIDKey'), $('AVSampleRateKey'), $('AVNumberOfChannelsKey')]);
const rec = $.AVAudioRecorder.alloc.initWithURLSettingsError(url, settings, null);
if (rec.isNil()) return 'fail';
if (!rec.record) return 'denied';
const fm = $.NSFileManager.defaultManager;
for (let i = 0; i < 72000; i++) { if (fm.fileExistsAtPath(argv[1])) break; delay(0.1); }
rec.stop;
return 'ok';
}"#;
/// 通話模式: listens until the person stops talking (AVAudioRecorder metering).
/// Speech is louder than SPEECH_DB; SILENCE_TICKS × 0.1 s of quiet after speech ends a turn;
/// nothing heard for WAIT_TICKS × 0.1 s gives up (all estimated).
const SPEECH_DB: f64 = -38.0;
const SILENCE_TICKS: u32 = 12;
const WAIT_TICKS: u32 = 300;
const LISTENER: &str = r#"ObjC.import('AVFoundation');
ObjC.import('Foundation');
function run(argv) {
const url = $.NSURL.fileURLWithPath(argv[0]);
const settings = $.NSDictionary.dictionaryWithObjectsForKeys(
[$.NSNumber.numberWithInt(1633772320), $.NSNumber.numberWithDouble(16000.0), $.NSNumber.numberWithInt(1)],
[$('AVFormatIDKey'), $('AVSampleRateKey'), $('AVNumberOfChannelsKey')]);
const rec = $.AVAudioRecorder.alloc.initWithURLSettingsError(url, settings, null);
if (rec.isNil()) return 'fail';
rec.meteringEnabled = true;
if (!rec.record) return 'denied';
const fm = $.NSFileManager.defaultManager;
const speech = Number(argv[2]), quietMax = Number(argv[3]), waitMax = Number(argv[4]);
let heard = false, quiet = 0;
for (let i = 0; i < 6000; i++) {
if (fm.fileExistsAtPath(argv[1])) break;
delay(0.1);
rec.updateMeters;
const p = rec.averagePowerForChannel(0);
if (p > speech) { heard = true; quiet = 0; } else if (heard) { quiet++; }
if (heard && quiet >= quietMax) break;
if (!heard && i >= waitMax) { rec.stop; return 'nothing'; }
}
rec.stop;
return heard ? 'ok' : 'nothing';
}"#;
/// The recorder: macOS's AVAudioRecorder script, or cpal (mic.rs) elsewhere.
enum Rec {
Script(Child),
Mic(crate::mic::Recorder),
}
pub struct Recording {
rec: Rec,
pub file: PathBuf,
stop: PathBuf,
pub started: Instant,
}
pub fn start() -> Result<Recording, String> {
let nonce = crate::httpd::random_hex(6);
if !cfg!(target_os = "macos") {
let file = std::env::temp_dir().join(format!("anybot-voice-{}-{}-{nonce}.wav", std::process::id(), chrono::Utc::now().timestamp_millis()));
let rec = crate::mic::start(file.clone(), None, MEETING_MAX_SECS);
return Ok(Recording { rec: Rec::Mic(rec), stop: file.with_extension("stop"), file, started: Instant::now() });
}
let base = std::env::temp_dir().join(format!("anybot-voice-{}-{}-{nonce}", std::process::id(), chrono::Utc::now().timestamp_millis()));
let file = base.with_extension("m4a");
let stop = base.with_extension("stop");
let child = Command::new("osascript")
.args(["-l", "JavaScript", "-e", RECORDER, "--"])
.arg(&file)
.arg(&stop)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|e| format!("無法開始錄音:{e}"))?;
Ok(Recording { rec: Rec::Script(child), file, stop, started: Instant::now() })
}
/// Listen for one spoken turn: stops by itself when the person goes quiet.
pub fn listen() -> Result<Recording, String> {
let nonce = crate::httpd::random_hex(6);
if !cfg!(target_os = "macos") {
let file = std::env::temp_dir().join(format!("anybot-call-{}-{}-{nonce}.wav", std::process::id(), chrono::Utc::now().timestamp_millis()));
let rec = crate::mic::start(file.clone(), Some(crate::mic::Listen { speech_db: SPEECH_DB, quiet_ticks: SILENCE_TICKS, wait_ticks: WAIT_TICKS }), MAX_SECS);
return Ok(Recording { rec: Rec::Mic(rec), stop: file.with_extension("stop"), file, started: Instant::now() });
}
let base = std::env::temp_dir().join(format!("anybot-call-{}-{}-{nonce}", std::process::id(), chrono::Utc::now().timestamp_millis()));
let (file, stop) = (base.with_extension("m4a"), base.with_extension("stop"));
let child = Command::new("osascript")
.args(["-l", "JavaScript", "-e", LISTENER, "--"])
.arg(&file)
.arg(&stop)
.args([SPEECH_DB.to_string(), SILENCE_TICKS.to_string(), WAIT_TICKS.to_string()])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|e| format!("無法開始聽:{e}"))?;
Ok(Recording { rec: Rec::Script(child), file, stop, started: Instant::now() })
}
impl Recording {
/// The listener stopped by itself (the person finished, or nobody spoke).
pub fn done(&mut self) -> bool {
match &mut self.rec {
Rec::Script(c) => matches!(c.try_wait(), Ok(Some(_))),
Rec::Mic(m) => m.done(),
}
}
/// Stop and give back the audio file.
pub fn finish(mut self) -> Result<PathBuf, String> {
let child = match &mut self.rec {
Rec::Script(c) => c,
Rec::Mic(m) => {
let res = match m.finish() {
Some("fail") => Err("找不到可以用的麥克風。".into()),
Some("nothing") => Err("沒有聽到說話。".into()),
None => Err("錄音沒有正常結束。".into()),
Some(_) if std::fs::metadata(&self.file).map(|m| m.len() > 4000).unwrap_or(false) => Ok(self.file.clone()),
Some(_) => Err("沒有錄到聲音。".into()),
};
if res.is_err() {
let _ = std::fs::remove_file(&self.file);
}
return res;
}
};
let _ = std::fs::write(&self.stop, b"");
let t = Instant::now();
let status = loop {
if let Ok(Some(_)) = child.try_wait() {
break true;
}
if t.elapsed() > Duration::from_secs(4) {
let _ = child.kill();
let _ = child.wait();
break false;
}
std::thread::sleep(Duration::from_millis(50));
};
let _ = std::fs::remove_file(&self.stop);
let mut said = String::new();
if let Some(mut o) = child.stdout.take() {
use std::io::Read;
let _ = o.read_to_string(&mut said);
}
let res = match said.trim() {
"denied" => {
let _ = crate::computer::spawn_reaped(Command::new("open").arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone"));
Err("macOS 還沒讓 AnyBot 使用麥克風。我已經打開「系統設定 → 隱私權與安全性 → 麥克風」:把 AnyBot(或「終端機」)打開,再試一次。".into())
}
"fail" => Err("找不到可以用的麥克風。".into()),
"nothing" => Err("沒有聽到說話。".into()),
_ if !status => Err("錄音沒有正常結束。".into()),
_ => {
let ok = std::fs::metadata(&self.file).map(|m| m.len() > 1000).unwrap_or(false);
if ok {
Ok(self.file.clone())
} else {
Err("沒有錄到聲音。".into())
}
}
};
if res.is_err() {
let _ = std::fs::remove_file(&self.file);
}
res
}
pub fn cancel(mut self) {
let _ = std::fs::write(&self.stop, b"");
match &mut self.rec {
Rec::Script(c) => {
std::thread::sleep(Duration::from_millis(300));
let _ = c.kill();
let _ = c.wait();
}
Rec::Mic(m) => {
let _ = m.finish();
}
}
let _ = std::fs::remove_file(&self.stop);
let _ = std::fs::remove_file(&self.file);
}
}
/// The spoken languages offered for voice chat (the original: 語言 Auto-detect…): (code, name).
pub const SPOKEN: [(&str, &str); 6] = [("", "自動偵測"), ("zh", "中文"), ("en", "English"), ("ja", "日本語"), ("ko", "한국어"), ("es", "Español")];
/// The speeds offered (the original: 速度 1x…).
pub const SPEEDS: [f32; 5] = [0.75, 1.0, 1.25, 1.5, 2.0];
// ---------- 播放 ----------
/// Each `say` gets a number; a newer one (or `stop_speaking`) makes the older one stop.
static PLAY_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static PLAYING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Get the sound (`fetch`: from the brain) and play it, instead of whatever was playing. What
/// goes wrong lands in `note`. `speaking()` is true from now until it has finished.
pub fn say(fetch: impl FnOnce() -> Result<Vec<u8>, String> + Send + 'static, note: std::sync::Arc<std::sync::Mutex<Option<String>>>) {
use std::sync::atomic::Ordering::SeqCst;
let gen = PLAY_GEN.fetch_add(1, SeqCst) + 1;
PLAYING.store(true, SeqCst);
std::thread::spawn(move || {
let r = fetch().and_then(|mp3| if PLAY_GEN.load(SeqCst) == gen { play(mp3, gen) } else { Ok(()) });
if PLAY_GEN.load(SeqCst) == gen {
if let Err(e) = r {
*note.lock().unwrap() = Some(e);
}
PLAYING.store(false, SeqCst);
}
});
}
/// MP3 out of the speakers, until it ends or a newer `say` / `stop_speaking` comes.
fn play(mp3: Vec<u8>, gen: u64) -> Result<(), String> {
use std::sync::atomic::Ordering::SeqCst;
let mut sink = rodio::DeviceSinkBuilder::open_default_sink().map_err(|_| "找不到可以播放聲音的裝置".to_string())?;
sink.log_on_drop(false);
let dec = rodio::Decoder::new(std::io::Cursor::new(mp3)).map_err(|_| "語音服務傳回的聲音放不出來".to_string())?;
let player = rodio::Player::connect_new(sink.mixer());
player.append(dec);
while !player.empty() {
if PLAY_GEN.load(SeqCst) != gen {
player.stop();
break;
}
std::thread::sleep(Duration::from_millis(50));
}
Ok(())
}
// ---------- 提示音 ----------
/// 提示音: two soft bell notes going up (E6, then A6 0.16 s later), about 0.8 s, quiet. Made
/// here instead of shipped as a file, so it sounds the same on macOS, Windows and Linux.
pub fn chime_samples(rate: u32) -> Vec<f32> {
let r = rate as f32;
let len = (r * 0.8) as usize;
let mut out = vec![0.0f32; len];
let tau = std::f32::consts::TAU;
for (freq, start) in [(1318.51f32, 0.0f32), (1760.0, 0.16)] {
let s0 = (start * r) as usize;
for (i, o) in out.iter_mut().enumerate().skip(s0) {
let t = (i - s0) as f32 / r;
// 4 ms to full, then a bell's fall; a softer octave above gives it its ring.
let env = (t / 0.004).min(1.0) * (-t * 7.0).exp();
*o += 0.16 * env * ((tau * freq * t).sin() + 0.3 * (-t * 5.0).exp() * (tau * 2.0 * freq * t).sin());
}
}
// The last 20 ms down to nothing (no click when the sound stops).
let tail = (r * 0.02) as usize;
for k in 0..tail {
out[len - 1 - k] *= k as f32 / tail as f32;
}
out
}
/// Ring the 提示音 once, without waiting. Several requests at once ring once (2 s apart at most).
pub fn chime() {
static LAST: std::sync::Mutex<Option<Instant>> = std::sync::Mutex::new(None);
{
let mut last = LAST.lock().unwrap();
if last.is_some_and(|t| t.elapsed() < Duration::from_secs(2)) {
return;
}
*last = Some(Instant::now());
}
std::thread::spawn(|| {
let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else { return };
sink.log_on_drop(false);
const RATE: u32 = 44_100;
let player = rodio::Player::connect_new(sink.mixer());
player.append(rodio::buffer::SamplesBuffer::new(std::num::NonZero::new(1).unwrap(), std::num::NonZero::new(RATE).unwrap(), chime_samples(RATE)));
player.sleep_until_end();
});
}
pub fn stop_speaking() {
use std::sync::atomic::Ordering::SeqCst;
PLAY_GEN.fetch_add(1, SeqCst);
PLAYING.store(false, SeqCst);
}
pub fn speaking() -> bool {
PLAYING.load(std::sync::atomic::Ordering::SeqCst)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_newer_say_or_stop_ends_the_playing() {
let note = std::sync::Arc::new(std::sync::Mutex::new(None));
// The service failing: said in the note, and nothing is playing after.
say(|| Err("xAI 不接受這把金鑰".into()), note.clone());
let t = Instant::now();
while speaking() && t.elapsed() < Duration::from_secs(2) {
std::thread::sleep(Duration::from_millis(10));
}
assert!(!speaking());
assert_eq!(note.lock().unwrap().as_deref(), Some("xAI 不接受這把金鑰"));
// Stopped while the sound was still on its way: it never plays, and says nothing.
let quiet = std::sync::Arc::new(std::sync::Mutex::new(None));
say(|| {
std::thread::sleep(Duration::from_millis(150));
Err("late".into())
}, quiet.clone());
assert!(speaking());
stop_speaking();
assert!(!speaking());
std::thread::sleep(Duration::from_millis(250));
assert!(!speaking() && quiet.lock().unwrap().is_none());
assert_eq!(length_words(7_200), "2 小時");
}
/// The 提示音 as a file to listen to: ANYBOT_TEST_OUT=chime.wav cargo test --bin anybot chime_to_file -- --ignored
#[test]
#[ignore]
fn chime_to_file() {
std::fs::write(std::env::var("ANYBOT_TEST_OUT").unwrap(), crate::mic::wav(&chime_samples(44_100), 44_100)).unwrap();
}
#[test]
fn the_chime_is_short_quiet_and_ends_in_silence() {
let rate = 44_100;
let s = chime_samples(rate);
let secs = s.len() as f32 / rate as f32;
assert!((0.6..=1.0).contains(&secs), "{secs} s");
let peak = s.iter().fold(0.0f32, |m, x| m.max(x.abs()));
assert!(peak > 0.1 && peak < 0.5, "peak {peak}");
// No click at the end: the last 10 ms are next to nothing.
assert!(s[s.len() - rate as usize / 100..].iter().all(|x| x.abs() < 0.005));
// Two notes: the second starts later and higher, so the start is the first note alone.
assert!(s[..rate as usize / 10].iter().any(|x| x.abs() > 0.05));
}
}