capri-voice: add service module
This commit is contained in:
1 file changed
+810
@@ -0,0 +1,810 @@
|
||||
//! `VoiceHandle`: the app-facing service. Microphone, spoken replies and music capture start only on explicit calls;
|
||||
//! nothing is opened at startup. Events arrive on the channel returned by [`VoiceHandle::start`].
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use capri_core::SettingsStore;
|
||||
use parking_lot::Mutex;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::capture::InputDevice;
|
||||
use crate::echo::EchoGuard;
|
||||
use crate::effects::EffectsChain;
|
||||
use crate::install::{InstallStatus, Phase, Selection};
|
||||
use crate::mic::{Mic, MicCommand};
|
||||
use crate::music::{Analyzer, MusicDecision, Yamnet};
|
||||
use crate::player::{Chunk, Mouth, MouthSampler, Playback, PlaybackEvent, Speaker};
|
||||
use crate::settings::{CallSettings, MusicSettings, SpeechSettings, VoiceEffects, VoiceSettings};
|
||||
use crate::text::{MAX_SPEECH_SENTENCE, SentenceBuffer, speech_language_mismatch, wants_follow_up};
|
||||
use crate::tts::Chatterbox;
|
||||
use crate::{MusicState, VoiceEvent, VoiceStatus, call, tts};
|
||||
|
||||
/// Capri `VOICE_PREVIEWS`.
|
||||
pub fn preview_text(language: &str) -> &'static str {
|
||||
match language {
|
||||
"ru" => "Привет, чумба. Я рядом. Как тебе мой голос?",
|
||||
"de" => "Hey, ich bin hier. Wie klingt meine Stimme?",
|
||||
"fr" => "Salut, je suis là. Tu aimes ma voix ?",
|
||||
"es" => "Hola, estoy aquí. ¿Qué te parece mi voz?",
|
||||
"pt" => "Olá, estou aqui. O que acha da minha voz?",
|
||||
"it" => "Ciao, sono qui. Come ti sembra la mia voce?",
|
||||
"nl" => "Hoi, ik ben hier. Hoe klinkt mijn stem?",
|
||||
"ja" => "こんにちは。ここにいるよ。私の声はどう?",
|
||||
"zh" => "嗨,我就在这里。你觉得我的声音怎么样?",
|
||||
"ko" => "안녕, 나 여기 있어. 내 목소리 어때?",
|
||||
"ar" => "مرحباً، أنا هنا. كيف يبدو صوتي؟",
|
||||
"he" => "שלום, אני כאן. איך הקול שלי נשמע?",
|
||||
"hi" => "नमस्ते, मैं यहीं हूँ। मेरी आवाज़ कैसी लग रही है?",
|
||||
"da" => "Hej, jeg er her. Hvordan lyder min stemme?",
|
||||
"fi" => "Hei, olen täällä. Miltä ääneni kuulostaa?",
|
||||
"no" => "Hei, jeg er her. Hvordan høres stemmen min ut?",
|
||||
"sv" => "Hej, jag är här. Hur låter min röst?",
|
||||
"pl" => "Hej, jestem tutaj. Jak brzmi mój głos?",
|
||||
"tr" => "Selam, buradayım. Sesim nasıl geliyor?",
|
||||
"el" => "Γεια σου, είμαι εδώ. Πώς σου φαίνεται η φωνή μου;",
|
||||
"ms" => "Hai, saya di sini. Bagaimana suara saya?",
|
||||
"sw" => "Habari, niko hapa. Sauti yangu inasikika vipi?",
|
||||
_ => "Hey choom, I am right here. How does this sound?",
|
||||
}
|
||||
}
|
||||
|
||||
struct Turn {
|
||||
id: String,
|
||||
from_microphone: bool,
|
||||
buffer: SentenceBuffer,
|
||||
text: String,
|
||||
sentences: usize,
|
||||
tx: Option<mpsc::UnboundedSender<String>>,
|
||||
task: Option<tokio::task::JoinHandle<()>>,
|
||||
cancel: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Voice {
|
||||
enabled: bool,
|
||||
loading: bool,
|
||||
language: Option<String>,
|
||||
model: Option<Arc<Mutex<Chatterbox>>>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Call {
|
||||
cable: Option<call::Cable>,
|
||||
output: Option<call::CallOutput>,
|
||||
share_replies: bool,
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
store: Arc<SettingsStore>,
|
||||
events: mpsc::UnboundedSender<VoiceEvent>,
|
||||
rt: tokio::runtime::Handle,
|
||||
playback: Playback,
|
||||
speaker: Mutex<Option<Speaker>>,
|
||||
mic: Mutex<Option<(u64, Mic)>>,
|
||||
mic_generation: AtomicU32,
|
||||
mic_level: Arc<AtomicU32>,
|
||||
echo: Arc<Mutex<EchoGuard>>,
|
||||
voice: Mutex<Voice>,
|
||||
turn: Mutex<Option<Turn>>,
|
||||
effects: Mutex<EffectsChain>,
|
||||
mouth: Mutex<Mouth>,
|
||||
follow_up: Mutex<Option<(String, bool)>>,
|
||||
music: Mutex<Option<Arc<AtomicBool>>>,
|
||||
music_state: Mutex<MusicState>,
|
||||
install: watch::Sender<InstallStatus>,
|
||||
install_cancel: Mutex<Option<CancellationToken>>,
|
||||
call: Mutex<Call>,
|
||||
devices: Mutex<Vec<InputDevice>>,
|
||||
}
|
||||
|
||||
/// Cheap to clone; every method is non-blocking unless noted.
|
||||
#[derive(Clone)]
|
||||
pub struct VoiceHandle(Arc<Inner>);
|
||||
|
||||
pub type VoiceService = VoiceHandle;
|
||||
|
||||
impl VoiceHandle {
|
||||
/// Must be called inside a tokio runtime. Opens no device.
|
||||
pub fn start(store: Arc<SettingsStore>) -> (Self, mpsc::UnboundedReceiver<VoiceEvent>) {
|
||||
let (events, rx) = mpsc::unbounded_channel();
|
||||
let pause = store.section::<SpeechSettings>().normalized().trailing_silence_seconds;
|
||||
let inner = Arc::new(Inner {
|
||||
store,
|
||||
events,
|
||||
rt: tokio::runtime::Handle::current(),
|
||||
playback: Playback::default(),
|
||||
speaker: Mutex::new(None),
|
||||
mic: Mutex::new(None),
|
||||
mic_generation: AtomicU32::new(0),
|
||||
mic_level: Arc::new(AtomicU32::new(0)),
|
||||
echo: Arc::new(Mutex::new(EchoGuard::new(pause))),
|
||||
voice: Mutex::new(Voice::default()),
|
||||
turn: Mutex::new(None),
|
||||
effects: Mutex::new(EffectsChain::default()),
|
||||
mouth: Mutex::new(Mouth::Closed),
|
||||
follow_up: Mutex::new(None),
|
||||
music: Mutex::new(None),
|
||||
music_state: Mutex::new(MusicState::default()),
|
||||
install: watch::Sender::new(InstallStatus::default()),
|
||||
install_cancel: Mutex::new(None),
|
||||
call: Mutex::new(Call::default()),
|
||||
devices: Mutex::new(Vec::new()),
|
||||
});
|
||||
tokio::spawn(ticker(Arc::downgrade(&inner)));
|
||||
let mut status = inner.install.subscribe();
|
||||
let events = inner.events.clone();
|
||||
tokio::spawn(async move {
|
||||
while status.changed().await.is_ok() {
|
||||
let s = status.borrow_and_update().clone();
|
||||
if events.send(VoiceEvent::Install(s)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
(Self(inner), rx)
|
||||
}
|
||||
|
||||
fn emit(&self, event: VoiceEvent) {
|
||||
let _ = self.0.events.send(event);
|
||||
}
|
||||
|
||||
fn speech_dir(&self) -> PathBuf {
|
||||
self.0.store.paths().data.join("speech")
|
||||
}
|
||||
|
||||
pub fn settings_store(&self) -> &Arc<SettingsStore> {
|
||||
&self.0.store
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ microphone
|
||||
|
||||
/// Turns the microphone on or off. Off at every launch; never persisted.
|
||||
pub fn set_microphone(&self, on: bool) -> Result<()> {
|
||||
if !on {
|
||||
self.0.mic.lock().take();
|
||||
self.0.mic_level.store(0, Ordering::Relaxed);
|
||||
return Ok(());
|
||||
}
|
||||
if self.0.mic.lock().is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
ensure!(self.0.install.borrow().phase != Phase::Installing, "Wait for speech installation to finish, or cancel it.");
|
||||
let settings = self.0.store.get();
|
||||
let speech = settings.section::<SpeechSettings>().normalized();
|
||||
let language = speech.language(&settings);
|
||||
let dir = self.speech_dir();
|
||||
ensure!(crate::asr::installed(&dir, &speech.asr_model), "The selected speech recognition model is unavailable. Install it in Settings → Speech.");
|
||||
*self.0.echo.lock() = EchoGuard::new(speech.trailing_silence_seconds);
|
||||
let generation = self.0.mic_generation.fetch_add(1, Ordering::Relaxed) as u64 + 1;
|
||||
let model = crate::asr::model_path(&dir, &speech.asr_model);
|
||||
let (lang, threads, gpu) = (language.clone(), speech.cpu_threads, speech.asr_gpu);
|
||||
let recognizer: crate::mic::RecognizerFactory = Box::new(move || Ok(Box::new(crate::asr::Whisper::load(&model, &lang, threads, gpu)?) as Box<dyn crate::asr::Recognizer>));
|
||||
let weak = Arc::downgrade(&self.0);
|
||||
let sink: crate::mic::Sink = Arc::new(move |event| {
|
||||
if let Some(inner) = weak.upgrade() {
|
||||
VoiceHandle(inner).on_microphone_event(generation, event);
|
||||
}
|
||||
});
|
||||
let mic = crate::mic::start(&speech, &language, &dir, self.0.echo.clone(), self.0.mic_level.clone(), recognizer, sink)?;
|
||||
*self.0.mic.lock() = Some((generation, mic));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn on_microphone_event(&self, generation: u64, event: VoiceEvent) {
|
||||
match &event {
|
||||
VoiceEvent::Interrupt => self.stop_speaking(),
|
||||
VoiceEvent::StopRequest => {
|
||||
let me = self.clone();
|
||||
self.0.rt.spawn(async move { let _ = me.set_microphone(false); });
|
||||
}
|
||||
VoiceEvent::Microphone(status) if !status.on => {
|
||||
let mut mic = self.0.mic.lock();
|
||||
if mic.as_ref().is_some_and(|(g, _)| *g == generation) {
|
||||
mic.take();
|
||||
}
|
||||
}
|
||||
VoiceEvent::Wake { follow_up: false, manual: false, .. } => {
|
||||
let speech = self.0.store.section::<SpeechSettings>();
|
||||
if speech.wake_sound == "tone" && self.ensure_speaker() {
|
||||
self.0.playback.push(Chunk { turn_id: "wake".into(), sequence: 0, text: String::new(), pcm: crate::player::wake_tone(speech.wake_volume) });
|
||||
}
|
||||
}
|
||||
VoiceEvent::Submit { .. } => *self.0.follow_up.lock() = None,
|
||||
_ => {}
|
||||
}
|
||||
self.emit(event);
|
||||
}
|
||||
|
||||
pub fn microphone_on(&self) -> bool {
|
||||
self.0.mic.lock().is_some()
|
||||
}
|
||||
|
||||
/// Input level 0..1 of the last 100 ms (`min(1, rms × 10)`).
|
||||
pub fn microphone_level(&self) -> f32 {
|
||||
if self.microphone_on() { f32::from_bits(self.0.mic_level.load(Ordering::Relaxed)) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Composer microphone button: opens or closes the command window.
|
||||
pub fn listen_now(&self) {
|
||||
if let Some((_, mic)) = self.0.mic.lock().as_ref() {
|
||||
mic.send(MicCommand::ListenNow);
|
||||
}
|
||||
}
|
||||
|
||||
/// The owner typed a message: closes the command window and cancels a pending follow-up.
|
||||
pub fn typed_input(&self) {
|
||||
*self.0.follow_up.lock() = None;
|
||||
if let Some((_, mic)) = self.0.mic.lock().as_ref() {
|
||||
mic.send(MicCommand::TypedInput);
|
||||
}
|
||||
}
|
||||
|
||||
/// Input devices (cached; see [`Self::refresh_devices`]).
|
||||
pub fn input_devices(&self) -> Vec<InputDevice> {
|
||||
self.0.devices.lock().clone()
|
||||
}
|
||||
|
||||
/// Re-enumerates inputs in the background (metadata only, no stream opened).
|
||||
pub fn refresh_devices(&self) {
|
||||
let me = self.clone();
|
||||
self.0.rt.spawn_blocking(move || *me.0.devices.lock() = crate::capture::input_devices());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ spoken replies
|
||||
|
||||
fn ensure_speaker(&self) -> bool {
|
||||
let mut speaker = self.0.speaker.lock();
|
||||
if speaker.is_none() {
|
||||
match Speaker::open(&self.0.playback) {
|
||||
Ok(s) => *speaker = Some(s),
|
||||
Err(e) => {
|
||||
self.emit(VoiceEvent::Error { area: "playback", message: format!("Audio playback failed. Try unmuting Capri again. ({e})") });
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn voice_status(&self) {
|
||||
let v = self.0.voice.lock();
|
||||
let status = VoiceStatus { enabled: v.enabled, ready: v.model.is_some(), loading: v.loading, language: v.language.clone(), error: v.error.clone() };
|
||||
drop(v);
|
||||
self.emit(VoiceEvent::Voice(status));
|
||||
}
|
||||
|
||||
pub fn voice_installed(&self) -> bool {
|
||||
let settings = self.0.store.get();
|
||||
let voice = settings.section::<VoiceSettings>();
|
||||
voice.language(&settings).is_some_and(|l| tts::installed(&self.speech_dir(), &l, &voice.quality))
|
||||
}
|
||||
|
||||
/// Speaker button. Enabling loads the voice model in the background; disabling stops speech and frees its memory.
|
||||
pub fn set_voice_enabled(&self, on: bool) -> Result<()> {
|
||||
if !on {
|
||||
self.stop_speaking();
|
||||
*self.0.voice.lock() = Voice::default();
|
||||
self.voice_status();
|
||||
return Ok(());
|
||||
}
|
||||
let settings = self.0.store.get();
|
||||
let voice = settings.section::<VoiceSettings>();
|
||||
let language = voice.language(&settings).context("Choose a voice matching the conversation language.")?;
|
||||
ensure!(self.voice_installed(), "Capri’s voice is not installed for this language. Install it in Settings → Voice model.");
|
||||
{
|
||||
let mut v = self.0.voice.lock();
|
||||
if v.enabled && v.language.as_deref() == Some(&language) {
|
||||
return Ok(());
|
||||
}
|
||||
*v = Voice { enabled: true, loading: true, language: Some(language.clone()), ..Default::default() };
|
||||
}
|
||||
self.voice_status();
|
||||
let me = self.clone();
|
||||
let dir = self.speech_dir();
|
||||
self.0.rt.spawn(async move {
|
||||
let lang = language.clone();
|
||||
let loaded = tokio::task::spawn_blocking(move || {
|
||||
let reference = tts::load_wav(&tts::reference_path(&dir))?;
|
||||
let threads = (voice.cpu_threads as usize).clamp(1, std::thread::available_parallelism().map_or(4, |n| n.get()));
|
||||
Chatterbox::load(&dir, &lang, &voice.quality, &reference, threads)
|
||||
})
|
||||
.await
|
||||
.map_err(anyhow::Error::from)
|
||||
.and_then(|r| r);
|
||||
{
|
||||
let mut v = me.0.voice.lock();
|
||||
if !v.enabled || v.language.as_deref() != Some(&language) {
|
||||
return; // muted or switched while loading
|
||||
}
|
||||
v.loading = false;
|
||||
match loaded {
|
||||
Ok(model) => v.model = Some(Arc::new(Mutex::new(model))),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %format!("{e:#}"), "voice model failed to load");
|
||||
v.error = Some("Capri’s voice could not start. Text replies are still available.".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
me.voice_status();
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn voice_enabled(&self) -> bool {
|
||||
self.0.voice.lock().enabled
|
||||
}
|
||||
|
||||
/// `TurnEvent::Started`. `from_microphone`: the turn answers a [`VoiceEvent::Submit`] (enables follow-up listening).
|
||||
pub fn begin_turn(&self, turn_id: &str, from_microphone: bool) {
|
||||
self.stop_speaking();
|
||||
let voice = self.0.voice.lock();
|
||||
let speaking = voice.enabled && voice.language.is_some();
|
||||
let language = voice.language.clone().unwrap_or_default();
|
||||
drop(voice);
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let (tx, task) = if speaking {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let task = tokio::spawn(pump(self.clone(), turn_id.to_string(), language, rx, cancel.clone()));
|
||||
(Some(tx), Some(task))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
*self.0.turn.lock() = Some(Turn { id: turn_id.into(), from_microphone, buffer: SentenceBuffer::default(), text: String::new(), sentences: 0, tx, task, cancel });
|
||||
}
|
||||
|
||||
fn queue(&self, turn_id: &str, delta: &str, last: bool) {
|
||||
let mut guard = self.0.turn.lock();
|
||||
if guard.as_ref().is_none_or(|t| t.id != turn_id) {
|
||||
drop(guard);
|
||||
self.begin_turn(turn_id, false);
|
||||
guard = self.0.turn.lock();
|
||||
}
|
||||
let turn = guard.as_mut().unwrap();
|
||||
turn.text.push_str(delta);
|
||||
let Some(tx) = &turn.tx else { return };
|
||||
let mut error = None;
|
||||
for sentence in turn.buffer.push(delta, last) {
|
||||
turn.sentences += 1;
|
||||
if sentence.chars().count() > MAX_SPEECH_SENTENCE {
|
||||
error = Some("This sentence is too long to read aloud. The full text is still available.");
|
||||
} else if turn.sentences > 100 {
|
||||
error = Some("This reply is too long to read aloud.");
|
||||
} else {
|
||||
let _ = tx.send(sentence);
|
||||
}
|
||||
if error.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if last {
|
||||
turn.tx = None; // the pump ends after the last sentence
|
||||
}
|
||||
drop(guard);
|
||||
if let Some(message) = error {
|
||||
self.stop_speaking();
|
||||
self.emit(VoiceEvent::Error { area: "voice", message: message.into() });
|
||||
}
|
||||
}
|
||||
|
||||
/// `TurnEvent::Delta`: reply text as it streams. Text never waits for speech.
|
||||
pub fn speak_delta(&self, turn_id: &str, text: &str) {
|
||||
self.queue(turn_id, text, false);
|
||||
}
|
||||
|
||||
/// `TurnEvent::Completed`: flushes the last sentence; arms follow-up listening after a spoken question.
|
||||
pub fn finish_turn(&self, turn_id: &str) {
|
||||
self.queue(turn_id, "", true);
|
||||
let turn = self.0.turn.lock();
|
||||
let Some(turn) = turn.as_ref().filter(|t| t.id == turn_id) else { return };
|
||||
let speech = self.0.store.section::<SpeechSettings>();
|
||||
let wants = speech.follow_up && turn.from_microphone && self.microphone_on() && wants_follow_up(&turn.text);
|
||||
let generated = turn.task.is_none();
|
||||
*self.0.follow_up.lock() = wants.then(|| (turn_id.to_string(), generated));
|
||||
if generated {
|
||||
self.emit(VoiceEvent::Generated { turn_id: turn_id.into() });
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops speech immediately (barge-in, mute, new turn, cancel).
|
||||
pub fn stop_speaking(&self) {
|
||||
if let Some(turn) = self.0.turn.lock().take() {
|
||||
turn.cancel.store(true, Ordering::Relaxed);
|
||||
if let Some(task) = turn.task {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
*self.0.follow_up.lock() = None;
|
||||
self.0.playback.stop();
|
||||
self.0.effects.lock().reset();
|
||||
}
|
||||
|
||||
/// Speaks Capri's preview sentence, with `effects` applied for this preview only when given.
|
||||
pub fn preview_voice(&self, effects: Option<VoiceEffects>) -> Result<()> {
|
||||
let language = self.0.voice.lock().language.clone().context("No spoken voice is selected for this language.")?;
|
||||
ensure!(self.0.voice.lock().enabled, "Enable Capri’s voice first.");
|
||||
ensure!(!self.0.playback.busy(), "Wait for the current reply or preview to finish.");
|
||||
let saved = self.0.store.section::<VoiceEffects>();
|
||||
self.0.effects.lock().configure(&effects.unwrap_or(saved));
|
||||
let id = format!("preview:{}", uuid::Uuid::new_v4());
|
||||
self.begin_turn(&id, false);
|
||||
self.queue(&id, preview_text(&language), true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// RMS of what is playing (0 when silent).
|
||||
pub fn audio_level(&self) -> f32 {
|
||||
self.0.playback.level()
|
||||
}
|
||||
|
||||
/// Current mouth layer for the avatar.
|
||||
pub fn mouth(&self) -> Mouth {
|
||||
*self.0.mouth.lock()
|
||||
}
|
||||
|
||||
pub fn speaking(&self) -> bool {
|
||||
self.0.playback.busy()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ music
|
||||
|
||||
/// Starts or stops music listening (explicit owner action; never restarted from saved settings).
|
||||
pub fn set_music(&self, on: bool) {
|
||||
let mut music = self.0.music.lock();
|
||||
if let Some(stop) = music.take() {
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
}
|
||||
if !on {
|
||||
*self.0.music_state.lock() = MusicState::default();
|
||||
self.emit(VoiceEvent::MusicState(MusicState::default()));
|
||||
return;
|
||||
}
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
*music = Some(stop.clone());
|
||||
drop(music);
|
||||
let me = self.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("capri-music".into())
|
||||
.spawn(move || {
|
||||
let result = me.music_loop(&stop);
|
||||
let mut music = me.0.music.lock();
|
||||
if music.as_ref().is_some_and(|s| Arc::ptr_eq(s, &stop)) {
|
||||
music.take();
|
||||
}
|
||||
drop(music);
|
||||
*me.0.music_state.lock() = MusicState::default();
|
||||
me.emit(VoiceEvent::MusicState(MusicState::default()));
|
||||
if let Err(e) = result {
|
||||
tracing::warn!(error = %format!("{e:#}"), "music listening stopped");
|
||||
me.emit(VoiceEvent::Error { area: "music", message: "Music listening stopped. Enable it again to retry.".into() });
|
||||
}
|
||||
})
|
||||
.expect("music thread");
|
||||
}
|
||||
|
||||
fn publish_music(&self, state: MusicState) {
|
||||
*self.0.music_state.lock() = state;
|
||||
self.emit(VoiceEvent::MusicState(state));
|
||||
}
|
||||
|
||||
fn music_loop(&self, stop: &AtomicBool) -> Result<()> {
|
||||
self.publish_music(MusicState { listening: true, preparing: true, ..Default::default() });
|
||||
let data = self.0.store.paths().data.clone();
|
||||
let dir = self.0.rt.block_on(crate::music::provision_detector(&crate::download::http_client(), &data, &|_, _| {}))?;
|
||||
let mut model = Yamnet::load(&dir)?;
|
||||
let mut analyzer = Analyzer::new(|w: &[f32]| model.classify(w));
|
||||
let mut decision = MusicDecision::default();
|
||||
self.publish_music(MusicState { listening: true, ..Default::default() });
|
||||
let playback = self.0.playback.clone();
|
||||
crate::music::read_packets(crate::music::monitor_command(), stop, |packet| {
|
||||
// Capri's own voice is not music: packets during speech (and 400 ms after) are dropped.
|
||||
if playback.last_audible.lock().is_some_and(|t| t.elapsed() < Duration::from_millis(400)) {
|
||||
analyzer.reset();
|
||||
return Ok(());
|
||||
}
|
||||
let Some(result) = analyzer.accept(&packet)? else { return Ok(()) };
|
||||
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs_f64() * 1000.0;
|
||||
decision.update(&result, now);
|
||||
let animations = self.0.store.section::<MusicSettings>().enabled;
|
||||
let ready = animations && decision.animation_ready();
|
||||
self.publish_music(MusicState {
|
||||
listening: true,
|
||||
preparing: false,
|
||||
playing: animations && decision.hearing_music,
|
||||
bpm: if ready { decision.tempo } else { 0.0 },
|
||||
confidence: if ready { decision.tempo_confidence } else { 0.0 },
|
||||
beat_at_ms: if ready { decision.beat_at } else { 0.0 },
|
||||
energy: decision.energy,
|
||||
speech: decision.speech,
|
||||
});
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn music_state(&self) -> MusicState {
|
||||
*self.0.music_state.lock()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ installation
|
||||
|
||||
pub fn install_status(&self) -> InstallStatus {
|
||||
self.0.install.borrow().clone()
|
||||
}
|
||||
|
||||
/// Downloads recognition and/or voice files for the current settings. Stops the microphone and voice first.
|
||||
pub fn install_speech(&self, recognition: bool, voice: bool) -> Result<()> {
|
||||
ensure!(self.0.install.borrow().phase != Phase::Installing, "Another installation is running.");
|
||||
let settings = self.0.store.get();
|
||||
let speech = settings.section::<SpeechSettings>();
|
||||
let v = settings.section::<VoiceSettings>();
|
||||
let selection = Selection {
|
||||
recognition: recognition.then(|| speech.asr_model.clone()),
|
||||
speech: if voice { Some((v.language(&settings).context("No spoken voice is available for the conversation language.")?, v.quality.clone())) } else { None },
|
||||
};
|
||||
self.set_microphone(false)?;
|
||||
self.set_voice_enabled(false)?;
|
||||
let cancel = CancellationToken::new();
|
||||
*self.0.install_cancel.lock() = Some(cancel.clone());
|
||||
let (me, dir, logs) = (self.clone(), self.speech_dir(), self.0.store.paths().logs());
|
||||
self.0.rt.spawn(async move {
|
||||
let _ = crate::install::install(&dir, &logs, &selection, &me.0.install, &cancel).await;
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn cancel_install(&self) {
|
||||
if let Some(c) = self.0.install_cancel.lock().take() {
|
||||
c.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn recognition_installed(&self) -> bool {
|
||||
crate::asr::installed(&self.speech_dir(), &self.0.store.section::<SpeechSettings>().asr_model)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ call audio
|
||||
|
||||
/// Owner-approved: creates the PipeWire call cable and routes Capri's replies into it.
|
||||
pub fn create_call_cable(&self) -> Result<()> {
|
||||
let mut c = self.0.call.lock();
|
||||
if c.cable.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let settings = self.0.store.get();
|
||||
let mic = settings.section::<SpeechSettings>().microphone_device;
|
||||
let source = mic.strip_prefix("pulse:").map(String::from).unwrap_or_else(|| "@DEFAULT_SOURCE@".into());
|
||||
let mix = settings.section::<CallSettings>().mix_microphone;
|
||||
let cable = call::create(mix.then_some(source.as_str()))?;
|
||||
match call::CallOutput::open() {
|
||||
Ok(output) => {
|
||||
(c.cable, c.output, c.share_replies) = (Some(cable), Some(output), true);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
call::remove(&cable);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove_call_cable(&self) {
|
||||
let mut c = self.0.call.lock();
|
||||
c.output = None;
|
||||
if let Some(cable) = c.cable.take() {
|
||||
call::remove(&cable);
|
||||
}
|
||||
c.share_replies = false;
|
||||
}
|
||||
|
||||
pub fn call_active(&self) -> bool {
|
||||
self.0.call.lock().cable.is_some()
|
||||
}
|
||||
|
||||
pub fn share_replies(&self) -> bool {
|
||||
self.0.call.lock().share_replies
|
||||
}
|
||||
|
||||
pub fn set_share_replies(&self, on: bool) {
|
||||
let mut c = self.0.call.lock();
|
||||
c.share_replies = on && c.cable.is_some();
|
||||
}
|
||||
|
||||
/// Releases every device, process and virtual cable (app exit).
|
||||
pub fn shutdown(&self) {
|
||||
let _ = self.set_microphone(false);
|
||||
self.set_music(false);
|
||||
let _ = self.set_voice_enabled(false);
|
||||
self.remove_call_cable();
|
||||
self.cancel_install();
|
||||
self.0.speaker.lock().take();
|
||||
}
|
||||
}
|
||||
|
||||
async fn pump(handle: VoiceHandle, turn_id: String, language: String, mut rx: mpsc::UnboundedReceiver<String>, cancel: Arc<AtomicBool>) {
|
||||
let inner = &handle.0;
|
||||
let mut sequence = 0u32;
|
||||
let fail = |message: &str| {
|
||||
if !cancel.load(Ordering::Relaxed) {
|
||||
handle.stop_speaking();
|
||||
handle.emit(VoiceEvent::Error { area: "voice", message: message.into() });
|
||||
}
|
||||
};
|
||||
while let Some(sentence) = rx.recv().await {
|
||||
if language == "en" && speech_language_mismatch(&sentence, "en") {
|
||||
return fail("Capri’s English voice cannot read this reply. The text is still shown.");
|
||||
}
|
||||
let model = loop {
|
||||
let (model, loading) = {
|
||||
let v = inner.voice.lock();
|
||||
(v.model.clone(), v.loading)
|
||||
};
|
||||
match model {
|
||||
Some(m) => break m,
|
||||
None if loading => tokio::time::sleep(Duration::from_millis(100)).await,
|
||||
None => return,
|
||||
}
|
||||
};
|
||||
let (lang, flag) = (language.clone(), cancel.clone());
|
||||
let text = sentence.clone();
|
||||
let result = tokio::task::spawn_blocking(move || model.lock().synthesize(&text, &lang, &flag)).await;
|
||||
let pcm = match result {
|
||||
Ok(Ok(pcm)) => pcm,
|
||||
_ if cancel.load(Ordering::Relaxed) => return,
|
||||
Ok(Err(e)) if e.to_string() == "CAPRI_VOICE_SPEECH_LIMIT" => return fail("This sentence could not be spoken. Voice is still ready."),
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!(error = %format!("{e:#}"), "speech synthesis failed");
|
||||
return fail("Capri’s voice is unavailable. Text replies are still available.");
|
||||
}
|
||||
Err(_) => return,
|
||||
};
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let pcm = inner.effects.lock().process(&pcm, sequence == 0);
|
||||
if !handle.ensure_speaker() {
|
||||
return;
|
||||
}
|
||||
share_with_call(&handle, &pcm);
|
||||
inner.playback.push(Chunk { turn_id: turn_id.clone(), sequence, text: sentence, pcm });
|
||||
sequence += 1;
|
||||
}
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let tail = inner.effects.lock().tail();
|
||||
if !tail.is_empty() {
|
||||
share_with_call(&handle, &tail);
|
||||
inner.playback.push(Chunk { turn_id: turn_id.clone(), sequence, text: String::new(), pcm: tail });
|
||||
}
|
||||
if let Some(pending) = inner.follow_up.lock().as_mut().filter(|p| p.0 == turn_id) {
|
||||
pending.1 = true;
|
||||
}
|
||||
handle.emit(VoiceEvent::Generated { turn_id });
|
||||
}
|
||||
|
||||
fn share_with_call(handle: &VoiceHandle, pcm: &[f32]) {
|
||||
let mut call = handle.0.call.lock();
|
||||
if !call.share_replies {
|
||||
return;
|
||||
}
|
||||
let volume = handle.0.store.section::<CallSettings>().call_voice_volume;
|
||||
if let Some(output) = call.output.as_mut()
|
||||
&& output.write(pcm, volume).is_err()
|
||||
{
|
||||
call.output = None;
|
||||
call.share_replies = false;
|
||||
drop(call);
|
||||
handle.emit(VoiceEvent::Error { area: "call", message: "Call audio output is unavailable.".into() });
|
||||
}
|
||||
}
|
||||
|
||||
/// Playback events → subtitles, echo guard, mouth and follow-up (every 50 ms).
|
||||
async fn ticker(weak: Weak<Inner>) {
|
||||
let mut sampler = MouthSampler::default();
|
||||
let mut was_busy = false;
|
||||
let mut interval = tokio::time::interval(Duration::from_millis(50));
|
||||
loop {
|
||||
interval.tick().await;
|
||||
let Some(inner) = weak.upgrade() else { return };
|
||||
let handle = VoiceHandle(inner);
|
||||
let inner = &handle.0;
|
||||
let now = Instant::now();
|
||||
for event in inner.playback.take_events() {
|
||||
match event {
|
||||
PlaybackEvent::Started { turn_id, sequence, text, duration_ms } => {
|
||||
inner.echo.lock().playback(true, &text, now);
|
||||
handle.emit(VoiceEvent::Subtitle { turn_id, sequence, text, duration_ms });
|
||||
}
|
||||
PlaybackEvent::Ended { turn_id, sequence } => handle.emit(VoiceEvent::SubtitleEnded { turn_id, sequence }),
|
||||
PlaybackEvent::Stopped => {
|
||||
inner.echo.lock().playback(false, "", now);
|
||||
handle.emit(VoiceEvent::PlaybackStopped);
|
||||
}
|
||||
PlaybackEvent::Idle => inner.echo.lock().playback(false, "", now),
|
||||
}
|
||||
}
|
||||
let busy = inner.playback.busy();
|
||||
let level = inner.playback.level();
|
||||
let mouth = sampler.sample(now, busy, level);
|
||||
*inner.mouth.lock() = mouth;
|
||||
if busy || was_busy {
|
||||
let turn_id = inner.turn.lock().as_ref().map(|t| t.id.clone());
|
||||
handle.emit(VoiceEvent::Speaking { turn_id, level: if busy { level } else { 0.0 }, mouth });
|
||||
}
|
||||
was_busy = busy;
|
||||
if !busy {
|
||||
let ready = inner.follow_up.lock().as_ref().is_some_and(|p| p.1);
|
||||
if ready {
|
||||
inner.follow_up.lock().take();
|
||||
let seconds = inner.store.section::<SpeechSettings>().normalized().follow_up_seconds;
|
||||
if let Some((_, mic)) = inner.mic.lock().as_ref() {
|
||||
mic.send(MicCommand::Continue { ms: seconds as u64 * 1000 });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use capri_core::{Paths, Settings};
|
||||
|
||||
fn handle() -> (VoiceHandle, mpsc::UnboundedReceiver<VoiceEvent>, tempfile::TempDir) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let paths = Paths::under(dir.path().to_path_buf());
|
||||
paths.ensure().unwrap();
|
||||
let (h, rx) = VoiceHandle::start(SettingsStore::new(paths, Settings::default()));
|
||||
(h, rx, dir)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn nothing_opens_without_models_and_text_turns_still_finish() {
|
||||
let (h, mut rx, _dir) = handle();
|
||||
assert!(!h.microphone_on() && !h.voice_enabled());
|
||||
assert!(h.set_microphone(true).unwrap_err().to_string().contains("Install it"));
|
||||
assert!(h.set_voice_enabled(true).unwrap_err().to_string().contains("not installed"));
|
||||
h.begin_turn("t1", true);
|
||||
h.speak_delta("t1", "Hello. How are you?");
|
||||
h.finish_turn("t1");
|
||||
assert_eq!(rx.recv().await, Some(VoiceEvent::Generated { turn_id: "t1".into() }), "voice off: generated at once");
|
||||
assert_eq!(h.audio_level(), 0.0);
|
||||
assert_eq!(h.mouth(), Mouth::Closed);
|
||||
assert!(h.preview_voice(None).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn install_requires_a_selection_and_reports_status() {
|
||||
let (h, mut rx, _dir) = handle();
|
||||
assert!(h.install_speech(false, false).is_ok());
|
||||
let failed = tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
if let Some(VoiceEvent::Install(s)) = rx.recv().await
|
||||
&& s.phase == Phase::Error
|
||||
{
|
||||
return s;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(failed.error.unwrap().contains("Choose a supported"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn previews_cover_every_speech_language() {
|
||||
for language in crate::settings::SPEECH_LANGUAGES {
|
||||
assert!(!preview_text(language).is_empty());
|
||||
}
|
||||
assert_ne!(preview_text("fr"), preview_text("en"));
|
||||
}
|
||||
|
||||
const _: fn() = || {
|
||||
fn check<T: Send + Sync>() {}
|
||||
check::<VoiceHandle>();
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user