Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

raea voice: Pocket's own voice by default (never a clip from the person's voice folder), a help line and a manual page, a silent microphone said as an error, and --over: its own voice taken out of the microphone's sound so the person can talk over it through speakers (echo.rs: an adaptive filter, a second one behind it that always learns; opt-in, checked in a simulated room with --room GAIN, not yet across real rooms)

shinyobjectz8b774295e182
diff --git a/apps/voice/src/audio.rs b/apps/voice/src/audio.rs
index f62ed775..969e954d 100644
--- a/apps/voice/src/audio.rs
+++ b/apps/voice/src/audio.rs
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
-use std::time::Duration;
+use std::time::{Duration, Instant};
use anyhow::{anyhow, bail, Context};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
@@ -137,12 +137,15 @@ pub fn microphone_file(path: &Path, fast: bool, tx: Sender<Vec<f32>>) -> anyhow:
Resample::new(rate, crate::turns::RATE as u32).push(&x, &mut heard);
heard.extend(std::iter::repeat_n(0.0, crate::turns::RATE * 3 / 2));
std::thread::spawn(move || {
+ // by the clock from its start, so a late wake-up is made up and it keeps a microphone's pace
+ let (began, mut sent) = (Instant::now(), 0u64);
for piece in heard.chunks(crate::turns::WIN) {
if tx.send(piece.to_vec()).is_err() {
return;
}
+ sent += piece.len() as u64;
if !fast {
- std::thread::sleep(Duration::from_micros(1_000_000 * piece.len() as u64 / crate::turns::RATE as u64));
+ std::thread::sleep((began + Duration::from_micros(1_000_000 * sent / crate::turns::RATE as u64)).saturating_duration_since(Instant::now()));
}
}
});
@@ -157,6 +160,10 @@ pub struct Line {
/// everything played, when it goes to a file
kept: Mutex<Vec<f32>>,
keep: AtomicBool,
+ /// what went to the speakers, quiet included, for the echo to be taken out of the microphone (echo.rs): kept
+ /// while `tap` is on, and taken by the session
+ pub far: Mutex<Vec<f32>>,
+ pub tap: AtomicBool,
}
impl Line {
@@ -171,14 +178,19 @@ impl Line {
}
/// The next `n` samples (fewer when the queue runs out), counted as played.
- fn take(&self, n: usize) -> Vec<f32> {
+ fn take(&self, want: usize) -> Vec<f32> {
let mut q = self.queue.lock().unwrap();
- let n = n.min(q.len());
+ let n = want.min(q.len());
let got: Vec<f32> = q.drain(..n).collect();
self.played.fetch_add(n as u64, Ordering::Relaxed);
if self.keep.load(Ordering::Relaxed) {
self.kept.lock().unwrap().extend(&got);
}
+ if self.tap.load(Ordering::Relaxed) && want < 1 << 20 {
+ let mut far = self.far.lock().unwrap();
+ far.extend(&got);
+ far.extend(std::iter::repeat_n(0.0, want - n));
+ }
got
}
}
@@ -186,8 +198,10 @@ impl Line {
/// A file in the speakers' place: what is waiting is taken at the pace it would play (all of it at once with `fast`).
fn drain(line: Arc<Line>, each: usize) {
std::thread::spawn(move || {
+ let (began, mut ticks) = (Instant::now(), 0u32);
while Arc::strong_count(&line) > 1 {
- std::thread::sleep(Duration::from_millis(20));
+ ticks += 1;
+ std::thread::sleep((began + Duration::from_millis(20) * ticks).saturating_duration_since(Instant::now()));
line.take(each);
}
});
@@ -204,7 +218,7 @@ pub struct Speaker {
impl Speaker {
/// `rate`: the voice's. With `to`, nothing sounds: what would have played is written there when the session ends.
pub fn open(rate: u32, to: Option<PathBuf>, fast: bool) -> anyhow::Result<Speaker> {
- let line = Arc::new(Line { queue: Mutex::new(VecDeque::new()), played: AtomicU64::new(0), kept: Mutex::new(Vec::new()), keep: AtomicBool::new(to.is_some()) });
+ let line = Arc::new(Line { queue: Mutex::new(VecDeque::new()), played: AtomicU64::new(0), kept: Mutex::new(Vec::new()), keep: AtomicBool::new(to.is_some()), far: Mutex::new(Vec::new()), tap: AtomicBool::new(false) });
if to.is_some() {
drain(line.clone(), if fast { usize::MAX } else { rate as usize / 50 });
return Ok(Speaker { line, rate, to, _stream: None });
diff --git a/apps/voice/src/echo.rs b/apps/voice/src/echo.rs
new file mode 100644
index 00000000..6033074b
--- /dev/null
+++ b/apps/voice/src/echo.rs
@@ -0,0 +1,379 @@
+//! raea's own voice taken out of what the microphone hears, so the person can talk over it.
+//!
+//! A computer's microphone hears its speakers. While raea speaks, what was sent to the speakers (the far side) is
+//! passed through a filter that learns the way from speaker to microphone (an NLMS adaptive filter, 128 ms long, at
+//! the hearing rate), and what the filter makes of it is taken from the microphone's sound. What is left is the
+//! person, when they speak. Where in time the echo sits (the sound card's and the room's delay) is found first, by
+//! lining up the two sides' loudness over the last second.
+//!
+//! Until the filter has learned the room (`sure`: a second of its voice, the echo down by 10 dB or more) nothing
+//! left over counts as the person, so raea is never stopped by its own voice. Once it has, sound that stands clear
+//! of the echo is the person (`near`). Two filters do it (the two-path way): the one in use never learns, the one
+//! behind it always does and replaces it when it leaves less, so the person's voice is never learned as echo.
+
+use std::collections::VecDeque;
+use std::time::{Duration, Instant};
+
+use crate::audio::Resample;
+use crate::turns::WIN;
+
+/// The filter's length: 128 ms of the way from speaker to microphone.
+const TAPS: usize = 2048;
+/// Loudness is compared in blocks of 4 ms.
+const BLOCK: usize = 64;
+/// The echo is looked for up to 480 ms late.
+const LAGS: usize = 120;
+/// A second of loudness is lined up.
+const ENV: usize = 250;
+/// How much of the far side is kept: the latest echo the filter can be asked about.
+const HIST: usize = LAGS * BLOCK + TAPS + WIN;
+/// The far side counts as sounding above this mean square (about -60 dBFS).
+const SOUNDING: f32 = 1e-6;
+/// How fast the filter learns.
+const MU: f32 = 0.3;
+
+/// What a window turned out to hold.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct Heard {
+ /// raea's own voice was sounding in it
+ pub far: bool,
+ /// something stands clear of raea's own voice (always, when raea is quiet)
+ pub near: bool,
+ /// the filter has learned the room: what's left can be trusted
+ pub sure: bool,
+}
+
+pub struct Echo {
+ far: Vec<f32>,
+ w: Vec<f32>,
+ /// the filter behind it, always learning; and for how many windows it has done better, or worse
+ behind: Vec<f32>,
+ better: usize,
+ worse: usize,
+ delay: usize,
+ mic_env: Vec<f32>,
+ far_env: Vec<f32>,
+ /// a delay seen, and how many times in a row
+ vote: (usize, usize),
+ /// how much quieter the echo leaves than it came, smoothed
+ erle: f32,
+ /// windows learned on since the delay was last set
+ learned: usize,
+ sure: bool,
+ windows: usize,
+}
+
+impl Default for Echo {
+ fn default() -> Echo {
+ Echo { far: vec![0.0; HIST], w: vec![0.0; TAPS], behind: vec![0.0; TAPS], better: 0, worse: 0, delay: 0, mic_env: Vec::new(), far_env: Vec::new(), vote: (0, 0), erle: 1.0, learned: 0, sure: false, windows: 0 }
+ }
+}
+
+fn power(x: &[f32]) -> f32 {
+ let mut p = 0.0;
+ for s in x {
+ p += s * s;
+ }
+ p
+}
+
+impl Echo {
+ /// (how late the echo is, in samples; how many times quieter it is left) for a trace.
+ pub fn state(&self) -> (usize, f32) {
+ (self.delay, self.erle)
+ }
+
+ /// The filter starts over (the echo moved in time, or the room changed).
+ fn forget(&mut self) {
+ self.w.fill(0.0);
+ self.behind.fill(0.0);
+ (self.erle, self.learned, self.sure, self.better, self.worse) = (1.0, 0, false, 0, 0);
+ }
+
+ /// Where the echo sits: the lag (in blocks) at which the microphone's loudness follows the far side's best.
+ fn lag(&self) -> Option<usize> {
+ if self.mic_env.len() < ENV || self.far_env.len() < ENV + LAGS {
+ return None;
+ }
+ let mic = &self.mic_env[self.mic_env.len() - ENV..];
+ let mean = |x: &[f32]| x.iter().sum::<f32>() / x.len() as f32;
+ let (mm, mut best) = (mean(mic), (0.6, None));
+ let mv: f32 = mic.iter().map(|a| (a - mm) * (a - mm)).sum();
+ for l in 0..=LAGS {
+ let at = self.far_env.len() - ENV - l;
+ let far = &self.far_env[at..at + ENV];
+ let fm = mean(far);
+ let (mut c, mut fv) = (0.0, 0.0);
+ for (a, b) in mic.iter().zip(far) {
+ c += (a - mm) * (b - fm);
+ fv += (b - fm) * (b - fm);
+ }
+ let r = c / (mv * fv).sqrt().max(1e-12);
+ if r > best.0 {
+ best = (r, Some(l));
+ }
+ }
+ best.1
+ }
+
+ /// One pass of a filter over a window: what's left of `mic` goes to `out`; returns (left, echo made) as power,
+ /// each sample's judged before the filter learns from it.
+ fn pass(far: &[f32], delay: usize, w: &mut [f32], mic: &[f32], learn: bool, out: &mut [f32]) -> (f32, f32) {
+ let (mut left, mut made) = (0.0, 0.0);
+ let first = far.len() - mic.len() - delay;
+ let mut norm = power(&far[first + 1 - TAPS..=first]);
+ for (n, d) in mic.iter().enumerate() {
+ let at = first + n;
+ if n > 0 {
+ norm += far[at] * far[at] - far[at - TAPS] * far[at - TAPS];
+ }
+ let x = &far[at + 1 - TAPS..=at];
+ let mut y = 0.0;
+ for (a, b) in w.iter().zip(x) {
+ y += a * b;
+ }
+ let e = d - y;
+ if learn && norm > SOUNDING {
+ let g = MU * e / (norm + 1e-3);
+ for (a, b) in w.iter_mut().zip(x) {
+ *a += g * b;
+ }
+ }
+ out[n] = e;
+ left += e * e;
+ made += y * y;
+ }
+ (left, made)
+ }
+
+ /// A window of the microphone and the window of the far side played with it. What's left of the microphone's
+ /// goes to `out`.
+ pub fn push(&mut self, mic: &[f32], far: &[f32], out: &mut Vec<f32>) -> Heard {
+ self.far.drain(..far.len());
+ self.far.extend_from_slice(far);
+ for (m, f) in mic.chunks(BLOCK).zip(far.chunks(BLOCK)) {
+ self.mic_env.push(power(m));
+ self.far_env.push(power(f));
+ }
+ let (m, f) = (self.mic_env.len().saturating_sub(ENV), self.far_env.len().saturating_sub(ENV + LAGS));
+ self.mic_env.drain(..m);
+ self.far_env.drain(..f);
+ self.windows += 1;
+ out.clear();
+ out.resize(mic.len(), 0.0);
+
+ // is raea's voice in what the filter is asked about, and has the echo moved?
+ let span = &self.far[self.far.len() - mic.len() - self.delay - TAPS..self.far.len() - self.delay];
+ let sounding = power(span) / span.len() as f32 > SOUNDING;
+ let loud = self.far_env[self.far_env.len().saturating_sub(ENV)..].iter().sum::<f32>() / (ENV * BLOCK) as f32 > SOUNDING;
+ if loud && self.windows % 4 == 0 {
+ if let Some(l) = self.lag() {
+ self.vote = if l == self.vote.0 { (l, self.vote.1 + 1) } else { (l, 1) };
+ // the filter starts 8 ms before where the echo is loudest
+ let to = l.saturating_sub(2) * BLOCK;
+ if self.vote.1 >= 3 && to.abs_diff(self.delay) > 2 * BLOCK {
+ self.delay = to;
+ self.forget();
+ }
+ }
+ }
+ if !sounding {
+ out.copy_from_slice(mic);
+ return Heard { far: false, near: true, sure: self.sure };
+ }
+
+ // The filter that is used only takes out; a second one behind it never stops learning. When the second
+ // leaves less (the first hadn't met this sound yet, or the room changed), it becomes the first. The person's
+ // voice can't be learned as echo that way: it makes the second worse, not better, and the first is untouched.
+ let (left, made) = Echo::pass(&self.far, self.delay, &mut self.w, mic, false, out);
+ let mut scratch = vec![0.0; mic.len()];
+ // (the one behind is judged as it stood before this window, then learns from it: judged while it learns, it
+ // seems to take out some of any voice, since each sample's correction carries into the next)
+ let (behind, _) = Echo::pass(&self.far, self.delay, &mut self.behind, mic, false, &mut scratch);
+ Echo::pass(&self.far, self.delay, &mut self.behind, mic, true, &mut scratch);
+ // (better only when it also takes most of the sound out: with the person talking nothing can, so a filter
+ // that chased their voice is never taken up)
+ let came = power(mic);
+ self.better = if behind < 0.7 * left && behind < 0.5 * came { self.better + 1 } else { 0 };
+ self.worse = if behind > 2.0 * left { self.worse + 1 } else { 0 };
+ // (the person's voice leaves the one behind no better off; a sound the filter hadn't met does, at once)
+ let misfit = behind < 0.85 * left;
+ if self.better >= 2 {
+ self.w.copy_from_slice(&self.behind);
+ self.better = 0;
+ } else if self.worse >= 3 {
+ self.behind.copy_from_slice(&self.w);
+ self.worse = 0;
+ }
+ // clear of the echo: well above what the filter usually leaves of it (four times, and never under a sixteenth),
+ // and not something the filter behind could have taken out
+ // (what is louder than the whole echo can't be the echo misjudged, whatever the filter behind makes of it)
+ let near = (!misfit || left > 2.0 * made) && left > made * (4.0 / self.erle).max(0.06) && left / mic.len() as f32 > SOUNDING;
+ if !(self.sure && near) {
+ self.erle = 0.9 * self.erle + 0.1 * (came / left.max(1e-12)).min(1000.0);
+ }
+ // a filter gone wrong adds sound: then the microphone's own is what's left
+ if left > came {
+ out.copy_from_slice(mic);
+ }
+ self.learned += 1;
+ // a second of its own voice learned, and the echo down by 10 dB (7 dB keeps it, once reached)
+ self.sure = self.learned >= 32 && self.erle >= if self.sure { 5.0 } else { 10.0 };
+ Heard { far: true, near, sure: self.sure }
+ }
+}
+
+/// The far side lined up with the microphone, window by window. Both come at their own pace in pieces, so a
+/// microphone window waits (a few milliseconds) until the far side that played with it, and the two windows after,
+/// have arrived: the echo then always comes after the sound that made it, never before.
+pub struct Sides {
+ rs: Resample,
+ far: Vec<f32>,
+ /// how many far samples came before `far[0]`
+ base: u64,
+ /// the far sample that plays as the microphone's first is heard
+ offset: Option<u64>,
+ mic: u64,
+ held: VecDeque<(Vec<f32>, Instant)>,
+ room: Option<f32>,
+}
+
+impl Sides {
+ /// `rate`: the far side's. `room`: a simulated room's gain (checks), in place of a real one.
+ pub fn new(rate: u32, room: Option<f32>) -> Sides {
+ Sides { rs: Resample::new(rate, crate::turns::RATE as u32), far: vec![0.0; SPAN + WIN], base: 0, offset: None, mic: 0, held: VecDeque::new(), room }
+ }
+
+ /// More of what went to the speakers.
+ pub fn far(&mut self, x: &[f32]) {
+ self.rs.push(x, &mut self.far);
+ }
+
+ /// A window from the microphone.
+ pub fn mic(&mut self, win: Vec<f32>) {
+ self.held.push_back((win, Instant::now()));
+ }
+
+ /// The next microphone window whose far side has come, and that far side.
+ pub fn next(&mut self) -> Option<(Vec<f32>, Vec<f32>)> {
+ let waited = self.held.front()?.1.elapsed();
+ let total = self.base + self.far.len() as u64;
+ let offset = *self.offset.get_or_insert(total);
+ // where the far side stands as this window ends, and the two windows more the filter is given
+ let now = offset + self.mic + WIN as u64;
+ let end = now + 2 * WIN as u64;
+ if total < end {
+ // the speakers aren't being fed (they stopped, or never started): quiet stands in
+ if waited < Duration::from_millis(300) {
+ return None;
+ }
+ self.far.resize(self.far.len() + (end - total) as usize, 0.0);
+ }
+ let (mut mic, _) = self.held.pop_front()?;
+ let at = |i: u64| (i - self.base) as usize;
+ if let Some(gain) = self.room {
+ room(&self.far[at(now) - WIN - SPAN..at(now)], gain, &mut mic);
+ }
+ let far = self.far[at(end) - WIN..at(end)].to_vec();
+ self.mic += WIN as u64;
+ // the far side behind what any later window can ask for goes
+ let old = at(now).saturating_sub(WIN + SPAN);
+ if old > 16_000 {
+ self.far.drain(..old);
+ self.base += old as u64;
+ }
+ Some((mic, far))
+ }
+}
+
+/// A room, for checks with no microphone: what the far side sounds like to a microphone 40 ms and a few surfaces
+/// away, at `gain`, added to `mic`. `far` ends where `mic` does and is `SPAN` longer.
+pub fn room(far: &[f32], gain: f32, mic: &mut [f32]) {
+ const WAYS: [(usize, f32); 6] = [(640, 1.0), (688, -0.45), (816, 0.3), (1008, -0.2), (1360, 0.12), (1840, -0.07)];
+ let first = far.len() - mic.len();
+ for (n, m) in mic.iter_mut().enumerate() {
+ let mut e = 0.0;
+ for (late, by) in WAYS {
+ e += by * far[first + n - late];
+ }
+ *m += gain * e;
+ }
+}
+/// How much more of the far side `room` needs than the window it fills.
+pub const SPAN: usize = 1840;
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Something like speech: noise that swells and falls a few times a second.
+ fn babble(n: usize, seed: u32) -> Vec<f32> {
+ let mut s = seed;
+ (0..n)
+ .map(|i| {
+ s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
+ let noise = (s >> 8) as f32 / (1u32 << 24) as f32 - 0.5;
+ noise * 0.4 * (0.55 + 0.45 * (i as f32 * 0.0021).sin()) * if (i / 4000) % 3 == 2 { 0.05 } else { 1.0 }
+ })
+ .collect()
+ }
+
+ /// Runs `secs` of raea talking in the simulated room, the person talking over it from `over` (a window) on.
+ fn run(secs: usize, over: Option<usize>) -> (Echo, Vec<Heard>, Vec<f32>) {
+ let n = secs * 16_000 / WIN;
+ let far = babble(n * WIN + SPAN, 7);
+ let person = babble(n * WIN, 99);
+ let (mut echo, mut heard, mut ratio, mut out) = (Echo::default(), Vec::new(), Vec::new(), Vec::new());
+ for k in 0..n {
+ let mut mic = vec![0.0; WIN];
+ room(&far[k * WIN..(k + 1) * WIN + SPAN], 0.8, &mut mic);
+ if over.is_some_and(|o| k >= o) {
+ for (m, p) in mic.iter_mut().zip(&person[k * WIN..]) {
+ *m += p * 0.8;
+ }
+ }
+ let came = power(&mic);
+ heard.push(echo.push(&mic, &far[SPAN + k * WIN..SPAN + (k + 1) * WIN], &mut out));
+ ratio.push(power(&out) / came.max(1e-12));
+ }
+ (echo, heard, ratio)
+ }
+
+ #[test]
+ fn its_own_voice_is_learned_and_taken_out() {
+ let (echo, heard, ratio) = run(6, None);
+ // the echo's direct sound is 640 samples late: the filter starts just before it
+ assert!(echo.delay <= 640 && echo.delay + 256 >= 640, "delay {}", echo.delay);
+ let sure = heard.iter().position(|h| h.sure).expect("never sure");
+ assert!(sure < 3 * 16_000 / WIN, "sure only after {sure} windows");
+ // once sure, nothing is taken for the person, and the echo is down to a twentieth or less in most windows
+ let after = sure + 16;
+ // (some windows stand out while the filter in use waits for the one behind; the session also wants them to
+ // sound like speech, which noise doesn't)
+ let own = heard[after..].iter().filter(|h| h.far && h.near).count();
+ assert!(own * 5 <= heard.len() - after, "its own voice taken for the person in {own} of {} windows", heard.len() - after);
+ let mut late: Vec<f32> = heard[after..].iter().zip(&ratio[after..]).filter(|(h, _)| h.far).map(|(_, r)| *r).collect();
+ late.sort_by(f32::total_cmp);
+ assert!(late[late.len() / 2] < 0.05, "half the windows keep more than a twentieth: {}", late[late.len() / 2]);
+ }
+
+ #[test]
+ fn the_person_talking_over_it_stands_clear() {
+ let at = 5 * 16_000 / WIN;
+ let (_, heard, ratio) = run(6, Some(at));
+ assert!(heard[at - 1].sure);
+ let over = &heard[at..];
+ let clear = over.iter().filter(|h| h.near).count();
+ assert!(clear * 10 >= over.len() * 6, "clear in {clear} of {} windows", over.len());
+ // (their voice has pauses) and it is left in: most of what came is still there
+ assert!(ratio[at..].iter().sum::<f32>() / over.len() as f32 > 0.3);
+ }
+
+ #[test]
+ fn quiet_passes_through() {
+ let (mut echo, mut out) = (Echo::default(), Vec::new());
+ let mic: Vec<f32> = (0..WIN).map(|i| (i as f32 * 0.1).sin() * 0.2).collect();
+ let h = echo.push(&mic, &[0.0; WIN], &mut out);
+ assert!(!h.far && h.near && out == mic);
+ }
+}
diff --git a/apps/voice/src/lib.rs b/apps/voice/src/lib.rs
index 7fa7f566..86461856 100644
--- a/apps/voice/src/lib.rs
+++ b/apps/voice/src/lib.rs
@@ -13,11 +13,13 @@ use serde_json::json;
pub mod asr;
pub mod audio;
+pub mod echo;
pub mod session;
pub mod speak;
pub mod turns;
-pub const USAGE: &str = "raea voice [--voice NAME] [--duplex] [--pause MS] [--from IN.wav] [--to OUT.wav] [--fast] | raea voice hear FILE.wav | raea voice say \"WORDS\" -o OUT.wav [--voice NAME]";
+pub const USAGE: &str = "raea voice [--voice NAME] [--duplex] [--over] [--pause MS] [--from IN.wav] [--to OUT.wav] [--room GAIN] [--fast] | raea voice hear FILE.wav | raea voice say \"WORDS\" -o OUT.wav [--voice NAME]";
+pub const ABOUT: &str = "speech in and out on this computer, as lines of JSON on stdin and stdout: what raea.app's Ideate hears and speaks with. While it speaks it doesn't listen, unless --duplex (headphones: it listens all the time) or --over (speakers: its own voice is taken out of the microphone's sound, new and not yet tried across real rooms); --room GAIN is a simulated room for checking --over with files; hear writes a recording's words, say speaks words to a file";
/// A model's download told as it goes, once every 20 MB of each file.
pub fn fetching(emit: fn(serde_json::Value)) -> impl FnMut(&str, u64) {
@@ -78,6 +80,7 @@ pub fn cli(args: &[String]) -> Result<String, String> {
match args.get(1).map(String::as_str) {
Some("hear") => hear(args.get(2).ok_or(USAGE)?).map_err(said),
Some("say") => say(args.get(2).ok_or(USAGE)?, &flag(args, "-o").ok_or(USAGE)?, flag(args, "--voice")).map_err(said),
+ Some("help" | "--help" | "-h") => Ok(format!("usage: {USAGE}\n({ABOUT})")),
Some(a) if !a.starts_with("--") => Err(USAGE.into()),
_ => {
let pause_ms = match flag(args, "--pause") {
@@ -89,6 +92,11 @@ pub fn cli(args: &[String]) -> Result<String, String> {
to: flag(args, "--to").map(PathBuf::from),
voice: flag(args, "--voice"),
duplex: args.iter().any(|a| a == "--duplex"),
+ over: args.iter().any(|a| a == "--over"),
+ room: match flag(args, "--room") {
+ Some(g) => Some(g.parse().map_err(|_| "--room takes a gain, like 0.5".to_string())?),
+ None => None,
+ },
fast: args.iter().any(|a| a == "--fast"),
pause_ms,
};
diff --git a/apps/voice/src/session.rs b/apps/voice/src/session.rs
index f02e78f0..8d1b4707 100644
--- a/apps/voice/src/session.rs
+++ b/apps/voice/src/session.rs
@@ -16,9 +16,13 @@
//! {"stopped":{"id"}} u1 was cut off (a stop, or the person spoke over it)
//! {"error":"..."}
//!
-//! While raea speaks it doesn't listen, unless `duplex` (headphones): a laptop's microphone hears its own speakers,
-//! and raea would take its own voice for the person interrupting.
+//! While raea speaks it doesn't listen: a computer's microphone hears its own speakers, and raea would take its own
+//! voice for the person interrupting. Words begun before it started are still heard. Two ways to talk over it:
+//! `duplex` listens all the time with nothing taken out (headphones), and `over` takes raea's own voice out of what
+//! the microphone hears (echo.rs) so speakers work too: what stands clear of it stops raea. `over` is new: it has
+//! been checked in a simulated room (`room`), not yet across real rooms, so it isn't the default.
+use std::collections::VecDeque;
use std::io::{BufRead, Write};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
@@ -29,6 +33,7 @@ use std::time::{Duration, Instant};
use serde_json::{json, Value};
use crate::audio::{microphone, microphone_file, Speaker};
+use crate::echo::{Echo, Heard, Sides};
use crate::speak::{Say, Words, RATE};
use crate::turns::{Turn, Turns, Vad, WIN};
@@ -37,6 +42,10 @@ pub struct Opts {
pub to: Option<PathBuf>,
pub voice: Option<String>,
pub duplex: bool,
+ /// listen while speaking, with raea's own voice taken out of the microphone's sound
+ pub over: bool,
+ /// a simulated room's gain, in place of a real one (checks)
+ pub room: Option<f32>,
pub fast: bool,
pub pause_ms: usize,
}
@@ -150,14 +159,49 @@ pub fn run(o: Opts) -> anyhow::Result<()> {
let mut turns = Turns::new(o.pause_ms);
let (mut buf, mut windows, mut mic_done) = (Vec::<f32>::new(), 0usize, false);
let mut quiet_since = Instant::now();
+ // its own voice taken out of the microphone's sound, unless that's not wanted or there's no clock to line up by
+ let mut sides = (o.over && !o.duplex && !o.fast).then(|| (Sides::new(RATE, o.room), Echo::default()));
+ speaker.line.tap.store(sides.is_some(), Ordering::Relaxed);
+ let mut ready = VecDeque::<(Vec<f32>, Option<Heard>, f64)>::new();
+ // RAEA_VOICE_TRACE=1: the echo's state every window, for finding out why it was or wasn't stopped
+ let trace = std::env::var_os("RAEA_VOICE_TRACE").is_some();
+ // windows in a row that stood clear of its own voice; windows of nothing at all from a real microphone
+ let (mut over, mut dead) = (0usize, if o.from.is_none() { Some(0usize) } else { None });
loop {
- match mic_rx.recv_timeout(Duration::from_millis(30)) {
+ match mic_rx.recv_timeout(Duration::from_millis(10)) {
Ok(piece) => buf.extend(piece),
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => mic_done = true,
}
while buf.len() >= WIN {
let win: Vec<f32> = buf.drain(..WIN).collect();
+ let loud = level(&win);
+ // a microphone raea isn't allowed to use gives nothing at all, with no error: say so, once
+ if let Some(n) = dead {
+ dead = win.iter().all(|s| *s == 0.0).then_some(n + 1);
+ if n + 1 == 3 * crate::turns::RATE / WIN {
+ emit(json!({ "error": "the microphone is giving no sound at all: allow raea to use it (System Settings > Privacy & Security > Microphone on a Mac), or pick another input" }));
+ dead = None;
+ }
+ }
+ match &mut sides {
+ Some((s, _)) => s.mic(win),
+ None => ready.push_back((win, None, loud)),
+ }
+ }
+ if let Some((s, echo)) = &mut sides {
+ s.far(&std::mem::take(&mut *speaker.line.far.lock().unwrap()));
+ while let Some((mic, far)) = s.next() {
+ let (loud, mut left) = (level(&mic), Vec::new());
+ let heard = echo.push(&mic, &far, &mut left);
+ if trace {
+ let (delay, erle) = echo.state();
+ emit(json!({ "echo": { "delay": delay, "erle": (erle * 10.0).round() / 10.0, "far": heard.far, "near": heard.near, "sure": heard.sure, "left": level(&left), "mic": loud } }));
+ }
+ ready.push_back((left, Some(heard), loud));
+ }
+ }
+ while let Some((win, cancelled, loud)) = ready.pop_front() {
windows += 1;
let speaking = talking.load(Ordering::Relaxed);
if speaking {
@@ -165,7 +209,9 @@ pub fn run(o: Opts) -> anyhow::Result<()> {
}
// its own voice dies away in the room for a moment after the last sample
let own = speaking || quiet_since.elapsed() < Duration::from_millis(250);
- if muted.load(Ordering::Relaxed) || (own && !o.duplex) {
+ let through = o.duplex || cancelled.is_some_and(|h| h.sure);
+ if muted.load(Ordering::Relaxed) || (own && !through) {
+ over = 0;
if turns.speaking() {
emit(json!({ "speech": "ended" }));
}
@@ -180,9 +226,21 @@ pub fn run(o: Opts) -> anyhow::Result<()> {
continue;
}
if windows % 4 == 0 {
- emit(json!({ "level": level(&win) }));
+ emit(json!({ "level": loud }));
+ }
+ let mut p = vad.speech(&win)?;
+ if own && !o.duplex {
+ // a trace of its own voice can be left, and their voice dips under it between words: windows that
+ // stand clear of it and sound like speech count up, the others count down, and six up is them
+ over = if cancelled.is_some_and(|h| h.near) && p >= 0.5 { over + 1 } else { over.saturating_sub(1) };
+ if trace {
+ emit(json!({ "own": { "p": (p * 100.0).round() / 100.0, "over": over, "near": cancelled.is_some_and(|h| h.near) } }));
+ }
+ if !turns.speaking() && over < 6 {
+ p = 0.0;
+ }
}
- match turns.push(&win, vad.speech(&win)?) {
+ match turns.push(&win, p) {
Some(Turn::Began) => {
emit(json!({ "speech": "began" }));
if speaking {
diff --git a/apps/voice/src/speak.rs b/apps/voice/src/speak.rs
index 19932054..a8e69458 100644
--- a/apps/voice/src/speak.rs
+++ b/apps/voice/src/speak.rs
@@ -165,7 +165,9 @@ pub fn worker(rx: Receiver<Say>, out: Arc<Line>, words: Arc<Mutex<Words>>, name:
let dir = raea_sys_ml::models::ensure(&Pocket::SPEC, &mut crate::fetching(emit))?;
let mut pocket = Pocket::load(&dir)?;
anyhow::ensure!(pocket.sample_rate() == RATE, "Pocket TTS speaks at {} Hz, not {RATE}", pocket.sample_rate());
- let name = name.unwrap_or_else(Pocket::default_voice);
+ // Pocket TTS's own first voice, never a clip of somebody found on this computer (the library's default
+ // takes one when it's there): a session speaks in a voice of someone's only when asked to by name
+ let name = name.unwrap_or_else(|| Pocket::VOICES[0].to_string());
// the voice's state loaded now, not under the first words
pocket.begin("", &name, 1, TEMPERATURE)?;
Ok((pocket, name))
diff --git a/docs/manual/reference/cli/index.md b/docs/manual/reference/cli/index.md
index 2c4c9adf..0ba37b14 100644
--- a/docs/manual/reference/cli/index.md
+++ b/docs/manual/reference/cli/index.md
@@ -103,6 +103,7 @@ Music read, foley and instruments made on this machine.
| [`raea sao`](sao.md) | Make a sound effect from a description with Stable Audio Open, on this machine. |
| [`raea tokensynth`](tokensynth.md) | Make an instrument's notes from a description of its timbre with TokenSynth, on this machine. |
| [`raea setup-audio`](setup-audio.md) | Install or check the local audio models: Stable Audio Open for foley and TokenSynth for instruments. |
+| [`raea voice`](voice.md) | Speech in and out on this computer, as lines of JSON on stdin and stdout: what raea.app's Ideate hears and speaks with. While it speaks it doesn't listen, unless --duplex (headphones: it listens all the time) or --over (speakers: its own voice is taken out of the microphone's sound, new and not yet tried across real rooms). |
## Generate and 3D tools
diff --git a/docs/manual/reference/cli/voice.md b/docs/manual/reference/cli/voice.md
new file mode 100644
index 00000000..9637f2c4
--- /dev/null
+++ b/docs/manual/reference/cli/voice.md
@@ -0,0 +1,54 @@
+---
+title: "raea voice"
+summary: "Speech in and out on this computer, as lines of JSON on stdin and stdout: what raea.app's Ideate hears and speaks with. While it speaks it doesn't listen, unless --duplex (headphones: it listens all the time) or --over (speakers: its own voice is taken out of the microphone's sound, new and not yet tried across real rooms)."
+order: 87
+sources: ["engine/cli/src/cli.rs"]
+---
+
+Speech in and out on this computer, as lines of JSON on stdin and stdout: what raea.app's Ideate hears and speaks with. While it speaks it doesn't listen, unless --duplex (headphones: it listens all the time) or --over (speakers: its own voice is taken out of the microphone's sound, new and not yet tried across real rooms).
+
+<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
+
+## Usage
+
+```sh
+raea voice [--voice NAME] [--duplex] [--over] [--pause MS] [--from IN.wav] [--to OUT.wav] [--room GAIN] [--fast] | raea voice hear FILE.wav | raea voice say "WORDS" -o OUT.wav [--voice NAME] (speech in and out on this computer, as lines of JSON on stdin and stdout: what raea.app's Ideate hears and speaks with. While it speaks it doesn't listen, unless --duplex (headphones: it listens all the time) or --over (speakers: its own voice is taken out of the microphone's sound, new and not yet tried across real rooms); --room GAIN is a simulated room for checking --over with files; hear writes a recording's words, say speaks words to a file)
+```
+
+Headless: it needs nothing running and opens no window. Takes up to 2 arguments besides its flags.
+
+## Flags
+
+| Flag | Takes | What it does |
+| --- | --- | --- |
+| `--duplex` | – | Listen all the time, with nothing taken out of the microphone's sound. For headphones: through speakers it hears itself and stops. |
+| `--fast` | – | With `--from`: read the recording as fast as it can be heard, not at the pace it was spoken. For tests. |
+| `--from` | `IN.wav` | A recording in the microphone's place. |
+| `--over` | – | Listen while it speaks, with its own voice taken out of the microphone's sound, so the person can talk over it through speakers. New: checked in a simulated room, not yet across real rooms. The first word or two said over it can be lost. |
+| `--pause` | `MS` | How long a silence ends the person's turn, in milliseconds. |
+| `--room` | `GAIN` | With `--from` and `--over`: a simulated room. What it says comes back into the recording at this gain (0.5 is a quiet room, 1.5 a loud one). |
+| `--to` | `OUT.wav` | A file in the speakers' place: everything it says is written there. |
+| `--voice` | `NAME` | The voice it speaks in, one of Pocket's own (`alba` when not given). |
+| `-o` | `OUT.wav` | `say`: the file the spoken words are written to. |
+
+<!-- generated:end -->
+
+## What it reads and writes
+
+One JSON object a line. On stdin: `{"say":{"id":"a","text":"..."}}` adds words to what it's saying (send them as they
+come), `{"end":"a"}` says that's all of them, `{"stop":true}` stops it mid-sentence, `{"mute":true}` and
+`{"mute":false}` close and open the microphone, `{"quit":true}` ends the session.
+
+On stdout: `{"ready":...}` once the models are loaded, `{"speech":"began"}` and `{"speech":"ended"}` as the person
+talks, `{"heard":{"text":"..."}}` with their words when their turn ends, `{"saying":{"id":"a"}}`,
+`{"said":{"id":"a"}}` or `{"stopped":{"id":"a"}}` for what it spoke, `{"level":-32.5}` for the microphone's loudness,
+and `{"error":"..."}`. A microphone raea isn't allowed to use gives silence with no error from the system: after three
+seconds of it, the error says to allow raea in the system's privacy settings.
+
+```sh
+raea voice hear note.wav # a recording's words
+raea voice say "Good morning." -o hello.wav # words to a file
+```
+
+The models (Silero's voice detector, Parakeet for the words, Pocket for the voice) run on this computer; nothing is
+sent anywhere.
diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rs
index 843f977a..21e46d36 100644
--- a/engine/cli/src/cli.rs
+++ b/engine/cli/src/cli.rs
@@ -142,7 +142,7 @@ pub fn run(args: &[String]) -> R<String> {
let usage = format!("{usage}\n {} ({})", tools::motion::USAGE, tools::motion::ABOUT);
// an agent's report of a bug in raea itself, to raea's server (engine/cli/src/bug.ts; Shane 11-16)
let usage = format!("{usage}\n raea bug TITLE... --text TEXT [--command CMD] [--error TEXT] [--agent NAME] [--dry-run] (a bug in raea itself, not in your own composition, sent to raea's server with raea's version and the OS, no account needed: words only, paths, emails and keys taken out before it goes; five a day from a machine, the same bug again counted on the first report; --dry-run prints what would go and sends nothing)");
- let usage = format!("{usage}\n {} ({})", raea_sys_fixes::USAGE, raea_sys_fixes::ABOUT); // a problem looked up before it's guessed at (systems/fixes)
+ let usage = format!("{usage}\n {} ({})\n {} ({})", raea_sys_fixes::USAGE, raea_sys_fixes::ABOUT, raea_app_voice::USAGE, raea_app_voice::ABOUT); // a problem looked up before it's guessed at (systems/fixes); speech to speech (apps/voice)
// a workspace's files and specs (docs/projects.feature), listed under render's usage like library
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
let (export_game, capcut, layers, xml, scene, physics, splat, wear, bake) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, raea_app_scene::USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE, raea_app_lightbake::USAGE);
diff --git a/engine/cli/src/tests.rs b/engine/cli/src/tests.rs
index 707744eb..72d59948 100644
--- a/engine/cli/src/tests.rs
+++ b/engine/cli/src/tests.rs
@@ -32,7 +32,7 @@ fn help_lists_every_verb() {
let listed = |v: &str| [format!("raea {v} "), format!("raea {v}\n"), format!("| {v} ")].iter().any(|l| help.contains(l.as_str()));
let missing: Vec<_> = verbs.iter().filter(|v| !listed(v) && !unlisted.contains(&v.as_str())).collect();
assert!(missing.is_empty(), "not in raea help: {missing:?}");
- for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_scene::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_lightbake::USAGE] {
+ for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_scene::USAGE, raea_app_voice::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_lightbake::USAGE] {
assert!(help.contains(usage), "{usage}");
}
}
diff --git a/tools/manual-ref/cli.ts b/tools/manual-ref/cli.ts
index d7134fcb..b431eff4 100644
--- a/tools/manual-ref/cli.ts
+++ b/tools/manual-ref/cli.ts
@@ -29,7 +29,7 @@ const GROUPS: [string, string, string[]][] = [
["Projects", "The workspace, its projects and what a project holds.", ["init", "workspace", "project", "spec", "component", "part", "add", "brand", "library", "index"]],
["Check", "What's wrong before anyone watches it.", ["check", "judge", "make", "fingerprint", "findings", "scene", "light", "bench", "world", "solid", "next", "doctor", "hook", "traces"]],
["Footage", "Takes, cuts and the camera, from your own media.", ["media", "cut", "frame", "track", "splat", "mezz", "neural"]],
- ["Sound", "Music read, foley and instruments made on this machine.", ["song", "sounds", "sao", "tokensynth", "setup-audio"]],
+ ["Sound", "Music read, foley and instruments made on this machine.", ["song", "sounds", "sao", "tokensynth", "setup-audio", "voice"]],
["Generate and 3D tools", "Generated media, physics, light and weathering bakes, clothes and motion for SOMA's body, Blender and Godot.", ["gen", "physics", "bake", "wear", "clothes", "motion", "blender", "godot"]],
["Agents and setup", "What an agent reads and shows the person, and the tools raea installs.", ["guide", "fix", "context", "notes", "show", "skill", "skills", "setup", "bug", "ask"]],
]