refactor(app): rewrite the M2 Discord voice core in Rust
The user asked for a faster, real app instead of Electron. The app is now a Rust crate (serenity + songbird); the GUI in M5 will be a Tauri 2 shell on the system WebView2. - Same behaviour as the Electron core: one voice channel, per-speaker PCM to the voice worker, speaking_end and speaker_leave, sentence playback with stop and cancel, transcription notice on join, slash command join/leave/stop (create-or-update), registered chat channels with live events, history and sends that never ping, worker process with a fresh token and restart backoff. - songbird 0.6.1 garbles about a third of received frames under DAVE (its decoder keeps the bytes DAVE decryption leaves at the end of the payload; a 20 ms stepped test tone showed repeats, skips and reordering, while sending was exact). songbird now only decrypts; the core reorders packets in a small window (Opus FEC for the last lost frame) and decodes them with libopus itself. - Live test on real Discord with two bots: five sentences heard (CER 0/0/0/5/12.5%), 0.71-0.90 s from end of speech to final, speech read back at 3.4%, sound gone 0.08 s after stop. The release binary uses about 16 MB of memory; a Windows build (MinGW) logs in under Wine. - Spec moved to app/src/discord_core.spec.md; architecture, decisions, roadmap and pc-features updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
40
app/tests/fixtures/fake_engine_worker.py
vendored
Normal file
40
app/tests/fixtures/fake_engine_worker.py
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
"""The real voice worker server with fake engines, for the app's protocol tests (no GPU, no models).
|
||||
|
||||
The fake VAD reads speech probability off the amplitude; the fake transcriber names a clip by its
|
||||
pitch ("level 0.9" for a 900 Hz tone); the fake TTS makes 10 samples per character.
|
||||
Run with the repo's src/ on PYTHONPATH: python fake_engine_worker.py <port>
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
from voice_worker.server import VoiceWorker
|
||||
|
||||
|
||||
class AmplitudeVad:
|
||||
def prob(self, window):
|
||||
return float(np.max(np.abs(window)))
|
||||
|
||||
|
||||
class LevelTranscriber:
|
||||
def transcribe(self, clips, opts):
|
||||
return [f"level {np.argmax(np.abs(np.fft.rfft(c))) * 16000 / len(c) / 1000:.1f}" for c in clips]
|
||||
|
||||
|
||||
class FakeTts:
|
||||
def synthesize(self, text, rate):
|
||||
return np.full(len(text) * 10, 1000, dtype=np.int16)
|
||||
|
||||
|
||||
async def main(port: int) -> None:
|
||||
worker = VoiceWorker(os.environ["JARVIS_VOICE_TOKEN"], LevelTranscriber(), AmplitudeVad, FakeTts())
|
||||
server = await worker.serve("127.0.0.1", port)
|
||||
print(f"READY 127.0.0.1:{port}", flush=True)
|
||||
await server.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main(int(sys.argv[1])))
|
||||
359
app/tests/live_discord.rs
Normal file
359
app/tests/live_discord.rs
Normal file
@@ -0,0 +1,359 @@
|
||||
//! The Discord voice core end to end on real Discord, with the real voice worker on the GPU.
|
||||
//!
|
||||
//! Two bots in one voice channel: the "Jarvis" bot runs the core; the "speaker" bot plays recorded
|
||||
//! Korean speech into the channel, records what Jarvis says, and writes in the channel's chat.
|
||||
//! Opt-in; it refuses to run if a person is in the channel or either bot is already in voice.
|
||||
//!
|
||||
//! JARVIS_LIVE_DISCORD=1 JARVIS_LIVE_BOT_TOKEN=... JARVIS_LIVE_SPEAKER_TOKEN=... \
|
||||
//! JARVIS_LIVE_GUILD=<server id> JARVIS_LIVE_VOICE_CHANNEL=<voice channel id> \
|
||||
//! JARVIS_VOICE_PYTHON=<worker venv python> JARVIS_MELO_PYTHON=<MeloTTS venv python> \
|
||||
//! cargo test --release --test live_discord -- --nocapture
|
||||
//!
|
||||
//! On Linux, put the pip CUDA libraries on LD_LIBRARY_PATH (nvidia/cublas/lib, nvidia/cudnn/lib).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use jarvis_app::discord::{CoreEvent, DiscordCore};
|
||||
use jarvis_app::receive::{opus_payload, OpusFrames, SpeakerStream};
|
||||
use jarvis_app::settings::parse_settings;
|
||||
use jarvis_app::worker_client::{WorkerClient, WorkerClientOptions, WorkerEvent};
|
||||
use jarvis_app::worker_process::{ProcessEvent, WorkerProcess, WorkerProcessOptions};
|
||||
use serde_json::{json, Value};
|
||||
use serenity::all::{ChannelId, Client, Context, CreateMessage, EventHandler, GatewayIntents, GuildId, Http, Ready, UserId};
|
||||
use songbird::driver::DecodeMode;
|
||||
use songbird::input::Input;
|
||||
use songbird::{Config, CoreEvent as VoiceEv, Event, EventContext, EventHandler as VoiceHandler, SerenityInit, Songbird, TrackEvent};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
const COMMAND: &str = "jarvis-live-test";
|
||||
|
||||
fn env(k: &str) -> String {
|
||||
std::env::var(k).unwrap_or_else(|_| panic!("{k} is not set"))
|
||||
}
|
||||
|
||||
fn cer(reference: &str, hyp: &str) -> f64 {
|
||||
let norm = |s: &str| s.chars().filter(|c| c.is_alphanumeric()).collect::<Vec<_>>();
|
||||
let (a, b) = (norm(reference), norm(hyp));
|
||||
let mut prev: Vec<usize> = (0..=b.len()).collect();
|
||||
for i in 1..=a.len() {
|
||||
let mut cur = vec![i];
|
||||
for j in 1..=b.len() {
|
||||
cur.push((prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + usize::from(a[i - 1] != b[j - 1])));
|
||||
}
|
||||
prev = cur;
|
||||
}
|
||||
prev[b.len()] as f64 / a.len().max(1) as f64
|
||||
}
|
||||
|
||||
/// Seconds into a 16 kHz mono PCM16 WAV where the last sound above -34 dBFS ends.
|
||||
fn speech_end_seconds(wav: &[u8]) -> f64 {
|
||||
let data = &wav[44..];
|
||||
let n = data.len() / 2;
|
||||
(0..n).rev().find(|&k| i16::from_le_bytes([data[2 * k], data[2 * k + 1]]).unsigned_abs() > 655)
|
||||
.map_or(0.0, |k| (k + 1) as f64 / 16000.0)
|
||||
}
|
||||
|
||||
struct ReadyOnce(mpsc::UnboundedSender<Ready>);
|
||||
#[async_trait]
|
||||
impl EventHandler for ReadyOnce {
|
||||
async fn ready(&self, _: Context, r: Ready) {
|
||||
let _ = self.0.send(r);
|
||||
}
|
||||
}
|
||||
|
||||
/// Jarvis's voice as the speaker bot hears it, decoded the same way the core decodes (songbird's
|
||||
/// own decoder garbles DAVE audio, see src/receive.rs).
|
||||
#[derive(Clone, Default)]
|
||||
struct Ears {
|
||||
jarvis: u64,
|
||||
ssrc: Arc<Mutex<HashMap<u32, u64>>>,
|
||||
stream: Arc<Mutex<Option<SpeakerStream<OpusFrames>>>>,
|
||||
pcm: Arc<Mutex<Vec<i16>>>,
|
||||
/// When the last audible frame arrived.
|
||||
last_packet: Arc<Mutex<Option<Instant>>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl VoiceHandler for Ears {
|
||||
async fn act(&self, ctx: &EventContext<'_>) -> Option<Event> {
|
||||
match ctx {
|
||||
EventContext::SpeakingStateUpdate(s) => {
|
||||
if let Some(u) = s.user_id {
|
||||
self.ssrc.lock().unwrap().insert(s.ssrc, u.0);
|
||||
}
|
||||
}
|
||||
EventContext::RtpPacket(p) => {
|
||||
let (seq, ssrc, opus) = opus_payload(&p.packet, p.payload_offset, p.payload_end_pad)?;
|
||||
if self.ssrc.lock().unwrap().get(&ssrc) != Some(&self.jarvis) {
|
||||
return None;
|
||||
}
|
||||
let mut st = self.stream.lock().unwrap();
|
||||
let frames = st.get_or_insert_with(|| SpeakerStream::new(OpusFrames::new())).push(seq, opus.to_vec());
|
||||
let mut pcm = self.pcm.lock().unwrap();
|
||||
for f in frames {
|
||||
// Audible: louder than -36 dBFS. The sender's closing silence frames do not count.
|
||||
let rms = (f.iter().map(|&x| f64::from(x).powi(2)).sum::<f64>() / f.len().max(1) as f64).sqrt();
|
||||
if rms > 500.0 {
|
||||
*self.last_packet.lock().unwrap() = Some(Instant::now());
|
||||
}
|
||||
pcm.extend_from_slice(&f);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
struct Ended(mpsc::UnboundedSender<()>);
|
||||
#[async_trait]
|
||||
impl VoiceHandler for Ended {
|
||||
async fn act(&self, _: &EventContext<'_>) -> Option<Event> {
|
||||
let _ = self.0.send(());
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
async fn until(what: &str, ms: u64, mut pred: impl FnMut() -> bool) {
|
||||
let deadline = Instant::now() + Duration::from_millis(ms);
|
||||
while !pred() {
|
||||
assert!(Instant::now() < deadline, "timed out waiting for {what}");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn discord_voice_core_on_real_discord() {
|
||||
if std::env::var("JARVIS_LIVE_DISCORD").as_deref() != Ok("1") {
|
||||
eprintln!("skipped: set JARVIS_LIVE_DISCORD=1");
|
||||
return;
|
||||
}
|
||||
let guild: u64 = env("JARVIS_LIVE_GUILD").parse().unwrap();
|
||||
let voice: u64 = env("JARVIS_LIVE_VOICE_CHANNEL").parse().unwrap();
|
||||
let bot_token = env("JARVIS_LIVE_BOT_TOKEN");
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
let samples = root.join("../scripts/m0/assets/ko_samples");
|
||||
|
||||
// The speaker bot first: it checks the channel is free before anything joins.
|
||||
let speaker_songbird = Songbird::serenity_from_config(Config::default().decode_mode(DecodeMode::Decrypt));
|
||||
let (rtx, mut rrx) = mpsc::unbounded_channel();
|
||||
let mut speaker = Client::builder(env("JARVIS_LIVE_SPEAKER_TOKEN"),
|
||||
GatewayIntents::GUILDS | GatewayIntents::GUILD_VOICE_STATES | GatewayIntents::GUILD_MESSAGES | GatewayIntents::MESSAGE_CONTENT)
|
||||
.event_handler(ReadyOnce(rtx)).register_songbird_with(speaker_songbird.clone()).await.unwrap();
|
||||
let (s_http, s_cache, s_shards) = (speaker.http.clone(), speaker.cache.clone(), speaker.shard_manager.clone());
|
||||
tokio::spawn(async move { speaker.start().await.unwrap() });
|
||||
let speaker_id = rrx.recv().await.unwrap().user.id.get();
|
||||
let jarvis_app_id = Http::new(&bot_token).get_current_application_info().await.unwrap().id.get();
|
||||
until("guild in cache", 10_000, || s_cache.guild(GuildId::new(guild)).is_some()).await;
|
||||
{
|
||||
let g = s_cache.guild(GuildId::new(guild)).unwrap();
|
||||
let people = g.voice_states.values().filter(|v| v.channel_id.map(|c| c.get()) == Some(voice)
|
||||
&& !s_cache.user(v.user_id).map(|u| u.bot).unwrap_or(false)).count();
|
||||
assert_eq!(people, 0, "refusing to test: people are in the voice channel");
|
||||
for id in [speaker_id, jarvis_app_id] {
|
||||
assert!(g.voice_states.get(&UserId::new(id)).and_then(|v| v.channel_id).is_none(),
|
||||
"refusing to test: bot {id} is in a voice channel");
|
||||
}
|
||||
}
|
||||
|
||||
// The real voice worker.
|
||||
let mut args = vec![];
|
||||
if let Ok(m) = std::env::var("JARVIS_MELO_PYTHON") {
|
||||
args = vec!["--melo-python".to_string(), m];
|
||||
}
|
||||
let wp = WorkerProcess::new(WorkerProcessOptions::new(env("JARVIS_VOICE_PYTHON"), root.join("../src"), args)).unwrap();
|
||||
let mut pev = wp.subscribe();
|
||||
wp.start();
|
||||
tokio::time::timeout(Duration::from_secs(240), async {
|
||||
while pev.recv().await.unwrap() != ProcessEvent::Ready {}
|
||||
}).await.expect("worker ready");
|
||||
let mut wo = WorkerClientOptions::new(wp.url(), wp.token.clone());
|
||||
wo.stt = json!({"hotwords": ["자비스"]}).as_object().unwrap().clone();
|
||||
let (worker, worker_events) = WorkerClient::new(wo);
|
||||
worker.start();
|
||||
worker.wait_ready(Duration::from_secs(10)).await.expect("worker hello");
|
||||
|
||||
let settings = parse_settings(&json!({
|
||||
"discord": {"guildId": guild.to_string(), "voiceChannelId": voice.to_string(), "commandName": COMMAND},
|
||||
// The "person" here is a bot, so bots must be heard.
|
||||
"voice": {"listenToBots": true},
|
||||
// The voice channel's own chat stands in for a registered chat channel.
|
||||
"chatChannels": [{"id": voice.to_string(), "name": "테스트", "description": "라이브 테스트"}],
|
||||
})).unwrap();
|
||||
let (core, mut core_rx) = DiscordCore::new(settings, bot_token.clone(), worker.clone(), worker_events);
|
||||
let events: Arc<Mutex<Vec<CoreEvent>>> = Arc::default();
|
||||
let ev2 = events.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Some(e) = core_rx.recv().await {
|
||||
ev2.lock().unwrap().push(e);
|
||||
}
|
||||
});
|
||||
core.start().await.expect("core start"); // logs in, registers the command, auto-joins, posts the notice
|
||||
assert_eq!(core.voice_channel_id(), Some(voice));
|
||||
let jarvis = core.bot_id().unwrap();
|
||||
|
||||
let call = speaker_songbird.join(GuildId::new(guild), ChannelId::new(voice)).await.expect("speaker joins");
|
||||
let ears = Ears { jarvis, ..Default::default() };
|
||||
{
|
||||
let mut c = call.lock().await;
|
||||
c.add_global_event(VoiceEv::SpeakingStateUpdate.into(), ears.clone());
|
||||
c.add_global_event(VoiceEv::RtpPacket.into(), ears.clone());
|
||||
}
|
||||
let mut report = serde_json::Map::new();
|
||||
let steps = futures_util::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
|
||||
|
||||
// 1. The slash command is registered.
|
||||
let jarvis_http = Http::new(&bot_token);
|
||||
jarvis_http.set_application_id(jarvis_app_id.into());
|
||||
let cmds = jarvis_http.get_guild_commands(GuildId::new(guild)).await.unwrap();
|
||||
let cmd = cmds.iter().find(|c| c.name == COMMAND).expect("command registered");
|
||||
let mut subs: Vec<_> = cmd.options.iter().map(|o| o.name.clone()).collect();
|
||||
subs.sort();
|
||||
assert_eq!(subs, ["join", "leave", "stop"]);
|
||||
|
||||
// 2. Recorded sentences played into the channel come back as the speaker's finals.
|
||||
let refs: Value = serde_json::from_str(&std::fs::read_to_string(samples.join("refs.json")).unwrap()).unwrap();
|
||||
let mut stt = vec![];
|
||||
let mut total = 0.0;
|
||||
for r in refs["samples"].as_array().unwrap().iter().take(5) {
|
||||
let wav = std::fs::read(samples.join(r["file"].as_str().unwrap())).unwrap();
|
||||
let reference = r["text"].as_str().unwrap();
|
||||
let before = events.lock().unwrap().len();
|
||||
let (etx, mut erx) = mpsc::unbounded_channel();
|
||||
let track = call.lock().await.play_only_input(Input::from(wav.clone()));
|
||||
track.add_event(Event::Track(TrackEvent::End), Ended(etx)).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let started = loop {
|
||||
if track.get_info().await.is_ok_and(|i| i.position > Duration::ZERO) {
|
||||
break Instant::now();
|
||||
}
|
||||
assert!(Instant::now() < deadline, "timed out waiting for the track to play");
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
};
|
||||
let speech_end = started + Duration::from_secs_f64(speech_end_seconds(&wav));
|
||||
let mut final_at = None;
|
||||
until("final", 20_000, || {
|
||||
let got = events.lock().unwrap()[before..].iter().any(|e| matches!(e, CoreEvent::Final(f) if f.heard.speaker_id == speaker_id));
|
||||
if got && final_at.is_none() {
|
||||
final_at = Some(Instant::now());
|
||||
}
|
||||
got
|
||||
}).await;
|
||||
tokio::time::timeout(Duration::from_secs(20), erx.recv()).await.expect("track end");
|
||||
tokio::time::sleep(Duration::from_millis(800)).await;
|
||||
let mine: Vec<_> = events.lock().unwrap()[before..].iter().filter_map(|e| match e {
|
||||
CoreEvent::Final(f) if f.heard.speaker_id == speaker_id => Some(f.clone()),
|
||||
_ => None,
|
||||
}).collect();
|
||||
let hyp = mine.iter().map(|f| f.text.as_str()).collect::<Vec<_>>().join(" ");
|
||||
assert!(!mine[0].heard.speaker_name.is_empty());
|
||||
let c = cer(reference, &hyp);
|
||||
total += c;
|
||||
let latency = final_at.unwrap().saturating_duration_since(speech_end).as_millis();
|
||||
stt.push(json!({"ref": reference, "hyp": hyp, "cer": c, "speech_end_to_final_ms": latency,
|
||||
"end_reason": mine.iter().map(|f| f.end_reason.clone()).collect::<Vec<_>>()}));
|
||||
assert!(!hyp.is_empty(), "nothing heard for {reference}");
|
||||
}
|
||||
report.insert("stt".into(), Value::from(stt.clone()));
|
||||
let mean = total / (stt.len() as f64);
|
||||
assert!(mean < 0.15, "mean CER {mean}");
|
||||
|
||||
// 3. Jarvis speaks; the speaker bot hears it and the STT reads it back.
|
||||
let text = "안녕하세요, 저는 자비스입니다. 디스코드 음성 연결을 확인하고 있어요.";
|
||||
ears.pcm.lock().unwrap().clear();
|
||||
let id = core.say(text, false).expect("in voice");
|
||||
until("speech to end", 30_000, || events.lock().unwrap().iter().any(|e| matches!(e, CoreEvent::SpeakEnd(x) if x.id == id))).await;
|
||||
let end = events.lock().unwrap().iter().find_map(|e| match e { CoreEvent::SpeakEnd(x) if x.id == id => Some(x.clone()), _ => None }).unwrap();
|
||||
assert!(!end.cancelled && !end.failed && end.played == 2, "{end:?}");
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
let heard = ears.pcm.lock().unwrap().clone();
|
||||
let seconds = heard.len() as f64 / 96000.0;
|
||||
assert!(seconds > 2.0, "heard only {seconds} s");
|
||||
let mut eo = WorkerClientOptions::new(wp.url(), wp.token.clone());
|
||||
eo.stt = json!({"partials": false}).as_object().unwrap().clone();
|
||||
let (echo, mut echo_rx) = WorkerClient::new(eo);
|
||||
echo.start();
|
||||
echo.wait_ready(Duration::from_secs(5)).await.unwrap();
|
||||
for chunk in heard.chunks(1920) {
|
||||
echo.send_audio("echo", chunk);
|
||||
}
|
||||
for _ in 0..25 {
|
||||
echo.send_audio("echo", &[0; 1920]);
|
||||
}
|
||||
echo.speaking_end("echo");
|
||||
let mut back = vec![];
|
||||
let _ = tokio::time::timeout(Duration::from_secs(3), async {
|
||||
while let Some(e) = echo_rx.recv().await {
|
||||
if let WorkerEvent::Final(f) = e {
|
||||
back.push(f.text);
|
||||
}
|
||||
}
|
||||
}).await;
|
||||
echo.close();
|
||||
let hyp = back.join(" ");
|
||||
report.insert("tts_read_back".into(), json!({"seconds": seconds, "hyp": hyp, "cer": cer(text, &hyp)}));
|
||||
assert!(cer(text, &hyp) < 0.2, "read back: {hyp}");
|
||||
|
||||
// 4. Stop silences it within a few frames and cancels the rest.
|
||||
let long = "이 문장은 정지 명령을 시험하려고 길게 말하는 첫 번째 문장입니다. 두 번째 문장도 꽤 길게 이어집니다. \
|
||||
세 번째 문장까지 들리면 정지가 안 된 것입니다. 네 번째 문장은 절대 들리면 안 됩니다.";
|
||||
let id = core.say(long, false).unwrap();
|
||||
until("speech to start", 30_000, || events.lock().unwrap().iter().any(|e| *e == CoreEvent::SpeakStart(id.clone()))).await;
|
||||
tokio::time::sleep(Duration::from_millis(1500)).await;
|
||||
let stop_at = Instant::now();
|
||||
assert_eq!(core.stop(), 1);
|
||||
tokio::time::sleep(Duration::from_millis(1500)).await;
|
||||
let ends: Vec<_> = events.lock().unwrap().iter().filter_map(|e| match e { CoreEvent::SpeakEnd(x) if x.id == id => Some(x.clone()), _ => None }).collect();
|
||||
assert!(ends.len() == 1 && ends[0].cancelled, "{ends:?}");
|
||||
let tail = ears.last_packet.lock().unwrap().map(|t| t.saturating_duration_since(stop_at).as_millis() as i64).unwrap_or(-1);
|
||||
report.insert("last_sound_after_stop_ms".into(), json!(tail));
|
||||
assert!(tail < 400, "audio went on {tail} ms after stop");
|
||||
assert!(!core.speaking());
|
||||
|
||||
// 5. Chat: live event, history with the join notice, and a send that pings nobody.
|
||||
let marker = format!("라이브 테스트 메시지 {}", stop_at.elapsed().as_nanos());
|
||||
ChannelId::new(voice).send_message(&s_http, CreateMessage::new().content(&marker)).await.unwrap();
|
||||
until("chat event", 10_000, || events.lock().unwrap().iter().any(|e| matches!(e, CoreEvent::Chat(c) if c.content == marker))).await;
|
||||
let ev = events.lock().unwrap().iter().find_map(|e| match e { CoreEvent::Chat(c) if c.content == marker => Some(c.clone()), _ => None }).unwrap();
|
||||
assert!(ev.channel_id == voice && ev.author_id == speaker_id && ev.author_is_bot && !ev.from_self);
|
||||
let history = core.read_chat(voice, 20).await.unwrap();
|
||||
assert!(history.iter().any(|m| m.content == marker && !m.from_self));
|
||||
assert!(history.iter().any(|m| m.from_self && m.content.contains("받아 적습니다")), "join notice missing");
|
||||
let reply = format!("자비스 답장 @everyone {}", stop_at.elapsed().as_nanos());
|
||||
let ids = core.send_chat(voice, &reply).await.unwrap();
|
||||
let sent = ChannelId::new(voice).message(&s_http, serenity::all::MessageId::new(ids[0])).await.unwrap();
|
||||
assert_eq!(sent.content, reply);
|
||||
assert!(!sent.mention_everyone);
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
assert!(!events.lock().unwrap().iter().any(|e| matches!(e, CoreEvent::Chat(c) if c.content == reply)));
|
||||
|
||||
// 6. Leaving.
|
||||
assert!(core.leave("command").await);
|
||||
until("Jarvis to leave", 10_000, || {
|
||||
s_cache.guild(GuildId::new(guild)).and_then(|g| g.voice_states.get(&UserId::new(jarvis)).and_then(|v| v.channel_id)).is_none()
|
||||
}).await;
|
||||
assert_eq!(core.voice_channel_id(), None);
|
||||
assert!(core.say("아무도 못 듣는 말", false).is_none());
|
||||
|
||||
println!("live report {}", serde_json::to_string_pretty(&Value::Object(report.clone())).unwrap());
|
||||
})).await;
|
||||
|
||||
// Clean up even when a step failed: the test command, the speaker, the core, the worker.
|
||||
let http = Http::new(&bot_token);
|
||||
http.set_application_id(jarvis_app_id.into());
|
||||
for c in http.get_guild_commands(GuildId::new(guild)).await.unwrap().iter().filter(|c| c.name == COMMAND) {
|
||||
let _ = http.delete_guild_command(GuildId::new(guild), c.id).await;
|
||||
}
|
||||
let _ = speaker_songbird.remove(GuildId::new(guild)).await;
|
||||
s_shards.shutdown_all().await;
|
||||
core.close().await;
|
||||
worker.close();
|
||||
wp.stop().await;
|
||||
if let Err(panic) = steps {
|
||||
std::panic::resume_unwind(panic);
|
||||
}
|
||||
}
|
||||
230
app/tests/worker_client.rs
Normal file
230
app/tests/worker_client.rs
Normal file
@@ -0,0 +1,230 @@
|
||||
//! The worker client against a stand-in worker server (hello, events, reconnect, failed TTS).
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use jarvis_app::frames::{encode_audio_frame, KIND_TTS};
|
||||
use jarvis_app::playback::TtsBackend;
|
||||
use jarvis_app::worker_client::{TtsDone, WorkerClient, WorkerClientOptions, WorkerEvent};
|
||||
use serde_json::{json, Value};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
const TOKEN: &str = "t0ken";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
enum Got {
|
||||
Json(Value),
|
||||
Bin(Vec<u8>),
|
||||
}
|
||||
|
||||
/// A fake worker: checks the hello, records what arrives, and lets the test push frames.
|
||||
struct FakeWorker {
|
||||
port: u16,
|
||||
received: Arc<Mutex<Vec<Got>>>,
|
||||
push: Arc<Mutex<Option<mpsc::UnboundedSender<Message>>>>,
|
||||
task: tokio::task::JoinHandle<()>,
|
||||
conns: Arc<Mutex<Vec<tokio::task::JoinHandle<()>>>>,
|
||||
}
|
||||
|
||||
impl FakeWorker {
|
||||
async fn start(port: u16) -> Self {
|
||||
let listener = TcpListener::bind(("127.0.0.1", port)).await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let received = Arc::new(Mutex::new(vec![]));
|
||||
let push = Arc::new(Mutex::new(None));
|
||||
let conns = Arc::new(Mutex::new(vec![]));
|
||||
let (r, p, cs) = (received.clone(), push.clone(), conns.clone());
|
||||
let task = tokio::spawn(async move {
|
||||
while let Ok((tcp, _)) = listener.accept().await {
|
||||
let ws = tokio_tungstenite::accept_async(tcp).await.unwrap();
|
||||
let (mut tx, mut rx) = ws.split();
|
||||
let (ptx, mut prx) = mpsc::unbounded_channel::<Message>();
|
||||
*p.lock().unwrap() = Some(ptx.clone());
|
||||
let r = r.clone();
|
||||
cs.lock().unwrap().push(tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::select! {
|
||||
m = prx.recv() => match m { Some(m) => { if tx.send(m).await.is_err() { break } } None => break },
|
||||
m = rx.next() => match m {
|
||||
Some(Ok(Message::Text(t))) => {
|
||||
let v: Value = serde_json::from_str(t.as_str()).unwrap();
|
||||
if v["type"] == "hello" {
|
||||
if v["token"] != TOKEN { let _ = tx.close().await; break; }
|
||||
let ok = json!({"type": "hello_ok", "stt_ready": true, "tts_ready": true, "stt": v["stt"]});
|
||||
let _ = ptx.send(Message::text(ok.to_string()));
|
||||
}
|
||||
r.lock().unwrap().push(Got::Json(v));
|
||||
}
|
||||
Some(Ok(Message::Binary(b))) => r.lock().unwrap().push(Got::Bin(b.to_vec())),
|
||||
Some(Ok(_)) => {}
|
||||
_ => break,
|
||||
},
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
});
|
||||
Self { port, received, push, task, conns }
|
||||
}
|
||||
|
||||
fn url(&self) -> String {
|
||||
format!("ws://127.0.0.1:{}", self.port)
|
||||
}
|
||||
|
||||
fn got(&self) -> Vec<Got> {
|
||||
self.received.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
fn send(&self, m: Message) {
|
||||
self.push.lock().unwrap().as_ref().unwrap().send(m).unwrap();
|
||||
}
|
||||
|
||||
/// The worker dies: stop listening and drop the connection.
|
||||
fn kill(self) -> u16 {
|
||||
self.task.abort();
|
||||
for c in self.conns.lock().unwrap().drain(..) {
|
||||
c.abort();
|
||||
}
|
||||
*self.push.lock().unwrap() = None;
|
||||
self.port
|
||||
}
|
||||
}
|
||||
|
||||
fn client(url: &str, stt: Value) -> (WorkerClient, mpsc::UnboundedReceiver<WorkerEvent>) {
|
||||
let mut o = WorkerClientOptions::new(url, TOKEN);
|
||||
o.stt = stt.as_object().cloned().unwrap_or_default();
|
||||
o.backoff = Duration::from_millis(20);
|
||||
o.max_backoff = Duration::from_millis(50);
|
||||
WorkerClient::new(o)
|
||||
}
|
||||
|
||||
async fn until(mut pred: impl FnMut() -> bool) {
|
||||
tokio::time::timeout(Duration::from_secs(3), async {
|
||||
while !pred() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("timed out");
|
||||
}
|
||||
|
||||
async fn next_matching(rx: &mut mpsc::UnboundedReceiver<WorkerEvent>, f: impl Fn(&WorkerEvent) -> bool) -> WorkerEvent {
|
||||
tokio::time::timeout(Duration::from_secs(3), async {
|
||||
loop {
|
||||
let e = rx.recv().await.expect("events closed");
|
||||
if f(&e) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("timed out")
|
||||
}
|
||||
|
||||
fn tts_frame(id: &str, seq: u32) -> Message {
|
||||
let mut f = vec![KIND_TTS, id.len() as u8];
|
||||
f.extend_from_slice(id.as_bytes());
|
||||
f.extend_from_slice(&seq.to_le_bytes());
|
||||
f.extend_from_slice(&[0; 8]);
|
||||
Message::binary(f)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hello_carries_token_formats_and_stt_then_audio_flows() {
|
||||
let w = FakeWorker::start(0).await;
|
||||
let (c, _rx) = client(&w.url(), json!({"hotwords": ["자비스"]}));
|
||||
c.start();
|
||||
let ok = c.wait_ready(Duration::from_secs(2)).await.expect("ready");
|
||||
assert_eq!(Value::Object(ok.stt), json!({"hotwords": ["자비스"]}));
|
||||
let pcm = vec![1i16; 1920];
|
||||
c.send_audio("123", &pcm);
|
||||
c.speaking_end("123");
|
||||
c.speaker_leave("123");
|
||||
until(|| w.got().len() >= 4).await;
|
||||
let got = w.got();
|
||||
assert_eq!(got[0], Got::Json(json!({"type": "hello", "token": TOKEN, "audio": {"rate": 48000, "channels": 2},
|
||||
"tts": {"rate": 48000, "channels": 2}, "stt": {"hotwords": ["자비스"]}})));
|
||||
assert_eq!(got[1], Got::Bin(encode_audio_frame("123", &pcm).unwrap()));
|
||||
assert_eq!(got[2..], [Got::Json(json!({"type": "speaking_end", "speaker": "123"})),
|
||||
Got::Json(json!({"type": "speaker_leave", "speaker": "123"}))]);
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn events_pass_on_and_only_tts_audio_of_open_requests() {
|
||||
let w = FakeWorker::start(0).await;
|
||||
let (c, mut rx) = client(&w.url(), json!({}));
|
||||
c.start();
|
||||
c.wait_ready(Duration::from_secs(2)).await.unwrap();
|
||||
assert!(c.tts("r1", "안녕하세요.", false));
|
||||
until(|| w.got().iter().any(|g| matches!(g, Got::Json(v) if v["type"] == "tts"))).await;
|
||||
w.send(tts_frame("zz", 0)); // not ours
|
||||
w.send(tts_frame("r1", 0));
|
||||
w.send(Message::text(json!({"type": "final", "speaker": "1", "utt": 1, "text": "네", "end_reason": "silence",
|
||||
"audio_ms": 900, "wait_ms": 100, "stt_ms": 80}).to_string()));
|
||||
w.send(Message::text(json!({"type": "tts_done", "id": "r1", "chunks": 1, "cancelled": false, "failed": false}).to_string()));
|
||||
let mut seen = vec![];
|
||||
while seen.len() < 4 {
|
||||
let e = next_matching(&mut rx, |_| true).await;
|
||||
if !matches!(e, WorkerEvent::Ready(_)) {
|
||||
seen.push(e);
|
||||
}
|
||||
if matches!(seen.last(), Some(WorkerEvent::TtsDone(_))) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(matches!(&seen[0], WorkerEvent::TtsAudio { id, seq: 0, .. } if id == "r1"));
|
||||
assert!(matches!(&seen[1], WorkerEvent::Final(f) if f.text == "네" && f.end_reason == "silence"));
|
||||
assert_eq!(seen[2], WorkerEvent::TtsDone(TtsDone { id: "r1".into(), chunks: 1, cancelled: false, failed: false }));
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_refused_tts_request_ends_as_failed() {
|
||||
let w = FakeWorker::start(0).await;
|
||||
let (c, mut rx) = client(&w.url(), json!({}));
|
||||
c.start();
|
||||
c.wait_ready(Duration::from_secs(2)).await.unwrap();
|
||||
c.tts("r9", "x", false);
|
||||
until(|| w.got().len() >= 2).await;
|
||||
w.send(Message::text(json!({"type": "error", "code": "tts_unavailable", "message": "no", "id": "r9"}).to_string()));
|
||||
let e = next_matching(&mut rx, |e| matches!(e, WorkerEvent::TtsDone(_))).await;
|
||||
assert_eq!(e, WorkerEvent::TtsDone(TtsDone { id: "r9".into(), chunks: 0, cancelled: false, failed: true }));
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconnects_after_a_restart_and_fails_the_tts_in_flight() {
|
||||
let w = FakeWorker::start(0).await;
|
||||
let (c, mut rx) = client(&w.url(), json!({"language": "ko"}));
|
||||
c.start();
|
||||
c.wait_ready(Duration::from_secs(2)).await.unwrap();
|
||||
c.tts("r1", "길게 말하는 중", false);
|
||||
c.configure(json!({"partials": false}).as_object().unwrap().clone());
|
||||
until(|| w.got().len() >= 3).await;
|
||||
assert_eq!(w.got()[2], Got::Json(json!({"type": "config", "partials": false})));
|
||||
let port = w.kill();
|
||||
let e = next_matching(&mut rx, |e| matches!(e, WorkerEvent::TtsDone(_))).await;
|
||||
assert_eq!(e, WorkerEvent::TtsDone(TtsDone { id: "r1".into(), chunks: 0, cancelled: false, failed: true }));
|
||||
next_matching(&mut rx, |e| *e == WorkerEvent::Disconnected).await;
|
||||
assert!(!c.is_ready());
|
||||
c.send_audio("1", &[0, 0]); // dropped, not queued
|
||||
let w = FakeWorker::start(port).await;
|
||||
next_matching(&mut rx, |e| matches!(e, WorkerEvent::Ready(_))).await;
|
||||
let got = w.got();
|
||||
// The new hello carries the settings changed since, and no stale audio was queued.
|
||||
assert!(matches!(&got[0], Got::Json(v) if v["stt"] == json!({"language": "ko", "partials": false})));
|
||||
assert!(!got.iter().any(|g| matches!(g, Got::Bin(_))));
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tts_while_disconnected_fails_at_once() {
|
||||
let (c, mut rx) = client("ws://127.0.0.1:1", json!({}));
|
||||
assert!(!c.tts("r1", "x", false));
|
||||
let e = next_matching(&mut rx, |_| true).await;
|
||||
assert_eq!(e, WorkerEvent::TtsDone(TtsDone { id: "r1".into(), chunks: 0, cancelled: false, failed: true }));
|
||||
}
|
||||
120
app/tests/worker_process.rs
Normal file
120
app/tests/worker_process.rs
Normal file
@@ -0,0 +1,120 @@
|
||||
//! The worker process with a stand-in `voice_worker` package run by a real Python, so the spawn line
|
||||
//! is the one the app uses. JARVIS_TEST_PYTHON overrides the Python (default python3 / python).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use jarvis_app::worker_process::{ProcessEvent, WorkerProcess, WorkerProcessOptions};
|
||||
use serde_json::Value;
|
||||
|
||||
const FAKE_MAIN: &str = r#"
|
||||
import json, os, sys, time
|
||||
out = os.environ["FAKE_OUT"]
|
||||
runs = len(os.listdir(out))
|
||||
with open(os.path.join(out, f"run{runs}.json"), "w") as f:
|
||||
json.dump({"argv": sys.argv[1:], "token": os.environ.get("JARVIS_VOICE_TOKEN")}, f)
|
||||
if os.environ.get("FAKE_CRASH_FIRST") == "1" and runs == 0:
|
||||
sys.exit(3)
|
||||
print("loading models...", flush=True)
|
||||
print("READY 127.0.0.1:" + sys.argv[sys.argv.index("--port") + 1], flush=True)
|
||||
time.sleep(60)
|
||||
"#;
|
||||
|
||||
fn python() -> String {
|
||||
std::env::var("JARVIS_TEST_PYTHON").unwrap_or_else(|_| if cfg!(windows) { "python".into() } else { "python3".into() })
|
||||
}
|
||||
|
||||
struct Fake {
|
||||
root: PathBuf,
|
||||
out: PathBuf,
|
||||
}
|
||||
|
||||
impl Fake {
|
||||
fn new(tag: &str) -> Self {
|
||||
let root = std::env::temp_dir().join(format!("jarvis-fake-worker-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("voice_worker")).unwrap();
|
||||
std::fs::write(root.join("voice_worker/__init__.py"), "").unwrap();
|
||||
std::fs::write(root.join("voice_worker/__main__.py"), FAKE_MAIN).unwrap();
|
||||
let out = root.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
Self { root, out }
|
||||
}
|
||||
fn run(&self, n: usize) -> Value {
|
||||
serde_json::from_str(&std::fs::read_to_string(self.out.join(format!("run{n}.json"))).unwrap()).unwrap()
|
||||
}
|
||||
fn opts(&self, crash_first: bool) -> WorkerProcessOptions {
|
||||
let mut o = WorkerProcessOptions::new(python(), &self.root, vec!["--melo-python".into(), "/x/python".into()]);
|
||||
o.env.insert("FAKE_OUT".into(), self.out.display().to_string());
|
||||
if crash_first {
|
||||
o.env.insert("FAKE_CRASH_FIRST".into(), "1".into());
|
||||
}
|
||||
o.restart_delay = Duration::from_millis(50);
|
||||
o
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fake {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.root);
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for(rx: &mut tokio::sync::broadcast::Receiver<ProcessEvent>, f: impl Fn(&ProcessEvent) -> bool) -> ProcessEvent {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let e = rx.recv().await.unwrap();
|
||||
if f(&e) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("timed out")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn runs_the_worker_on_loopback_with_the_token_only_in_the_environment() {
|
||||
let fake = Fake::new("env");
|
||||
let p = WorkerProcess::new(fake.opts(false)).unwrap();
|
||||
let mut rx = p.subscribe();
|
||||
p.start();
|
||||
wait_for(&mut rx, |e| *e == ProcessEvent::Ready).await;
|
||||
let run = fake.run(0);
|
||||
let port = p.port().to_string();
|
||||
let argv: Vec<String> = serde_json::from_value(run["argv"].clone()).unwrap();
|
||||
assert_eq!(argv, ["--host", "127.0.0.1", "--port", &port, "--melo-python", "/x/python"]);
|
||||
assert_eq!(run["token"], p.token.as_str());
|
||||
assert!(p.token.len() >= 40);
|
||||
assert!(!argv.join(" ").contains(&p.token));
|
||||
assert!(p.url().starts_with("ws://127.0.0.1:"));
|
||||
p.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_dead_worker_restarts_on_the_same_port_with_the_same_token() {
|
||||
let fake = Fake::new("restart");
|
||||
let p = WorkerProcess::new(fake.opts(true)).unwrap();
|
||||
let mut rx = p.subscribe();
|
||||
p.start();
|
||||
assert_eq!(wait_for(&mut rx, |e| matches!(e, ProcessEvent::Exited { .. })).await, ProcessEvent::Exited { code: Some(3) });
|
||||
wait_for(&mut rx, |e| *e == ProcessEvent::Ready).await;
|
||||
assert_eq!(p.restarts(), 1);
|
||||
assert_eq!(fake.run(1)["argv"], fake.run(0)["argv"]);
|
||||
assert_eq!(fake.run(1)["token"], fake.run(0)["token"]);
|
||||
p.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_ends_the_worker_for_good() {
|
||||
let fake = Fake::new("stop");
|
||||
let p = WorkerProcess::new(fake.opts(false)).unwrap();
|
||||
let mut rx = p.subscribe();
|
||||
p.start();
|
||||
wait_for(&mut rx, |e| *e == ProcessEvent::Ready).await;
|
||||
p.stop().await;
|
||||
assert!(matches!(rx.recv().await.unwrap(), ProcessEvent::Exited { .. }));
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert!(rx.try_recv().is_err(), "no restart after stop");
|
||||
assert_eq!(p.restarts(), 0);
|
||||
}
|
||||
110
app/tests/worker_protocol.rs
Normal file
110
app/tests/worker_protocol.rs
Normal file
@@ -0,0 +1,110 @@
|
||||
//! The worker client and playback against the real Python voice worker server with fake engines, so
|
||||
//! both sides of the protocol are checked together. Needs a Python with the worker's requirements:
|
||||
//! JARVIS_VOICE_PYTHON=<venv python> cargo test --test worker_protocol
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use jarvis_app::playback::{ClipSink, Playback, PlaybackEvent};
|
||||
use jarvis_app::worker_client::{WorkerClient, WorkerClientOptions, WorkerEvent};
|
||||
use jarvis_app::worker_process::free_port;
|
||||
use serde_json::json;
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
|
||||
const TOKEN: &str = "protocol-test-token";
|
||||
|
||||
/// 20 ms of a 48 kHz stereo tone whose amplitude and pitch (x1000 Hz) are `level`.
|
||||
fn frame(level: f64) -> Vec<i16> {
|
||||
(0..960)
|
||||
.flat_map(|i| {
|
||||
let v = (level * (2.0 * std::f64::consts::PI * level * 1000.0 * i as f64 / 48000.0).sin() * 32767.0) as i16;
|
||||
[v, v]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Sink(Vec<usize>);
|
||||
impl ClipSink for Sink {
|
||||
fn play(&mut self, pcm: Vec<u8>) {
|
||||
self.0.push(pcm.len());
|
||||
}
|
||||
fn stop(&mut self) {}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn audio_and_tts_round_trip_through_the_python_server() {
|
||||
let Ok(python) = std::env::var("JARVIS_VOICE_PYTHON") else {
|
||||
eprintln!("skipped: set JARVIS_VOICE_PYTHON");
|
||||
return;
|
||||
};
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
let port = free_port().unwrap();
|
||||
let mut child = tokio::process::Command::new(python)
|
||||
.arg(root.join("tests/fixtures/fake_engine_worker.py"))
|
||||
.arg(port.to_string())
|
||||
.env("PYTHONPATH", root.join("../src"))
|
||||
.env("JARVIS_VOICE_TOKEN", TOKEN)
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut lines = BufReader::new(child.stdout.take().unwrap()).lines();
|
||||
while let Some(l) = lines.next_line().await.unwrap() {
|
||||
if l.starts_with("READY") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let mut o = WorkerClientOptions::new(format!("ws://127.0.0.1:{port}"), TOKEN);
|
||||
o.stt = json!({"partials": false, "hotwords": ["자비스"]}).as_object().unwrap().clone();
|
||||
let (c, mut rx) = WorkerClient::new(o);
|
||||
c.start();
|
||||
let ok = c.wait_ready(Duration::from_secs(5)).await.expect("ready");
|
||||
assert!(ok.stt_ready && ok.tts_ready);
|
||||
assert_eq!(ok.stt["hotwords"], json!(["자비스"]));
|
||||
|
||||
// Two Discord-format speakers; the second leaves mid-utterance and still gets its final.
|
||||
let (a, b) = ("111111111111111111", "222222222222222222");
|
||||
for _ in 0..30 {
|
||||
c.send_audio(a, &frame(0.9));
|
||||
c.send_audio(b, &frame(0.6));
|
||||
}
|
||||
c.speaking_end(a);
|
||||
c.speaker_leave(b);
|
||||
let mut finals = std::collections::HashMap::new();
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while finals.len() < 2 {
|
||||
if let Some(WorkerEvent::Final(f)) = rx.recv().await {
|
||||
finals.insert(f.speaker.clone(), f);
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("finals");
|
||||
assert_eq!((finals[a].text.as_str(), finals[a].end_reason.as_str(), finals[a].utt), ("level 0.9", "speaking_end", 1));
|
||||
assert_eq!((finals[b].text.as_str(), finals[b].end_reason.as_str()), ("level 0.6", "speaking_end"));
|
||||
|
||||
// TTS sentences play in order through Playback; 10 samples per character, stereo, 2 bytes each.
|
||||
let mut p = Playback::new(c.clone(), Sink::default());
|
||||
p.say("첫 번째 문장입니다. 두 번째 문장은 조금 더 깁니다.", false);
|
||||
let end = tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
match rx.recv().await.unwrap() {
|
||||
WorkerEvent::TtsAudio { id, seq, pcm } => {
|
||||
p.audio(&id, seq, pcm);
|
||||
p.clip_ended();
|
||||
}
|
||||
WorkerEvent::TtsDone(d) => p.done(&d),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(PlaybackEvent::End(e)) = p.take_events().into_iter().find(|e| matches!(e, PlaybackEvent::End(_))) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("speech end");
|
||||
assert_eq!((end.played, end.cancelled, end.failed), (2, false, false));
|
||||
c.close();
|
||||
let _ = child.kill().await;
|
||||
}
|
||||
Reference in New Issue
Block a user