Files
javis_bot/app/tests/live_discord.rs
javis-bot f25c26cf53 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>
2026-11-11 11:57:53 +09:00

360 lines
18 KiB
Rust

//! 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);
}
}