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:
javis-bot
2026-11-11 11:57:53 +09:00
parent 8479112ddd
commit f25c26cf53
54 changed files with 8454 additions and 5135 deletions

224
app/src/worker_process.rs Normal file
View File

@@ -0,0 +1,224 @@
//! Starts the Python voice worker as a child process and restarts it if it dies.
//!
//! Each app launch makes a new random token and hands it over in the environment
//! (`JARVIS_VOICE_TOKEN`), never on the command line. The worker listens on 127.0.0.1 only.
use std::collections::HashMap;
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use base64::Engine;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::{Child, Command};
use tokio::sync::{broadcast, Notify};
use crate::{debug_log, error_log};
#[derive(Debug, Clone)]
pub struct WorkerProcessOptions {
pub python: String,
pub cwd: PathBuf,
pub args: Vec<String>,
/// Fixed port; 0 picks a free one once at start (kept across restarts).
pub port: u16,
/// Extra environment for the worker (over the app's own).
pub env: HashMap<String, String>,
pub restart_delay: Duration,
pub max_restart_delay: Duration,
}
impl WorkerProcessOptions {
pub fn new(python: impl Into<String>, cwd: impl Into<PathBuf>, args: Vec<String>) -> Self {
Self {
python: python.into(),
cwd: cwd.into(),
args,
port: 0,
env: HashMap::new(),
restart_delay: Duration::from_secs(1),
max_restart_delay: Duration::from_secs(30),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProcessEvent {
/// The worker printed READY: models are loaded and it accepts connections.
Ready,
Exited { code: Option<i32> },
}
pub fn free_port() -> std::io::Result<u16> {
Ok(std::net::TcpListener::bind("127.0.0.1:0")?.local_addr()?.port())
}
struct Shared {
stopping: bool,
child_pid: Option<u32>,
restarts: u32,
}
pub struct WorkerProcess {
opts: WorkerProcessOptions,
pub token: String,
port: u16,
shared: Arc<Mutex<Shared>>,
stop: Arc<Notify>,
events: broadcast::Sender<ProcessEvent>,
task: Mutex<Option<tokio::task::JoinHandle<()>>>,
}
impl WorkerProcess {
pub fn new(opts: WorkerProcessOptions) -> std::io::Result<Self> {
let port = if opts.port == 0 { free_port()? } else { opts.port };
let mut raw = [0u8; 32];
rand::fill(&mut raw);
let token = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(raw);
Ok(Self {
opts,
token,
port,
shared: Arc::new(Mutex::new(Shared { stopping: false, child_pid: None, restarts: 0 })),
stop: Arc::new(Notify::new()),
events: broadcast::channel(64).0,
task: Mutex::new(None),
})
}
pub fn url(&self) -> String {
format!("ws://127.0.0.1:{}", self.port)
}
pub fn port(&self) -> u16 {
self.port
}
pub fn restarts(&self) -> u32 {
self.shared.lock().unwrap().restarts
}
pub fn subscribe(&self) -> broadcast::Receiver<ProcessEvent> {
self.events.subscribe()
}
/// Spawn the worker and keep it running until `stop()`.
pub fn start(&self) {
let (opts, token, port) = (self.opts.clone(), self.token.clone(), self.port);
let (shared, stop, events) = (self.shared.clone(), self.stop.clone(), self.events.clone());
let task = tokio::spawn(async move {
let mut delay = opts.restart_delay;
loop {
let started = Instant::now();
let mut child = match spawn(&opts, &token, port) {
Ok(c) => c,
Err(e) => {
error_log!("worker", "voice worker could not start: {e}");
let _ = events.send(ProcessEvent::Exited { code: None });
if wait_or_stop(&stop, &shared, delay).await {
return;
}
delay = (delay * 2).min(opts.max_restart_delay);
continue;
}
};
shared.lock().unwrap().child_pid = child.id();
debug_log!("worker", "voice worker started pid={:?} port={port}", child.id());
let mut ready_rx = events.subscribe();
// The worker's own logs hold timings and counts only (voice_worker.spec.md).
if let Some(out) = child.stdout.take() {
let events = events.clone();
tokio::spawn(async move {
let mut lines = BufReader::new(out).lines();
while let Ok(Some(line)) = lines.next_line().await {
if line.starts_with("READY ") {
debug_log!("worker", "voice worker READY after {} ms", started.elapsed().as_millis());
let _ = events.send(ProcessEvent::Ready);
} else {
debug_log!("worker", "{line}");
}
}
});
}
if let Some(err) = child.stderr.take() {
tokio::spawn(async move {
let mut lines = BufReader::new(err).lines();
while let Ok(Some(line)) = lines.next_line().await {
debug_log!("worker", "{line}");
}
});
}
let status = tokio::select! {
s = child.wait() => s.ok(),
_ = stop.notified() => {
let _ = child.kill().await;
let code = child.wait().await.ok().and_then(|s| s.code());
let _ = events.send(ProcessEvent::Exited { code });
return;
}
};
// A worker that got as far as READY resets the backoff.
while let Ok(ev) = ready_rx.try_recv() {
if ev == ProcessEvent::Ready {
delay = opts.restart_delay;
}
}
let code = status.and_then(|s| s.code());
shared.lock().unwrap().child_pid = None;
let _ = events.send(ProcessEvent::Exited { code });
if shared.lock().unwrap().stopping {
return;
}
error_log!("worker", "voice worker exited (code {code:?}); restarting in {} ms", delay.as_millis());
if wait_or_stop(&stop, &shared, delay).await {
return;
}
shared.lock().unwrap().restarts += 1;
delay = (delay * 2).min(opts.max_restart_delay);
}
});
*self.task.lock().unwrap() = Some(task);
}
/// Stop the worker and do not restart it. Returns once it has exited.
pub async fn stop(&self) {
self.shared.lock().unwrap().stopping = true;
self.stop.notify_one();
let task = self.task.lock().unwrap().take();
if let Some(t) = task {
let _ = t.await;
}
}
}
/// Sleep `delay` unless stopped meanwhile (true = stopped).
async fn wait_or_stop(stop: &Notify, shared: &Mutex<Shared>, delay: Duration) -> bool {
if shared.lock().unwrap().stopping {
return true;
}
tokio::select! {
_ = tokio::time::sleep(delay) => shared.lock().unwrap().stopping,
_ = stop.notified() => true,
}
}
fn spawn(opts: &WorkerProcessOptions, token: &str, port: u16) -> std::io::Result<Child> {
let mut cmd = Command::new(&opts.python);
cmd.args(["-m", "voice_worker", "--host", "127.0.0.1", "--port", &port.to_string()])
.args(&opts.args)
.current_dir(&opts.cwd)
.envs(&opts.env)
.env("JARVIS_VOICE_TOKEN", token)
.env("PYTHONUNBUFFERED", "1")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
#[cfg(windows)]
{
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
cmd.creation_flags(CREATE_NO_WINDOW);
}
cmd.spawn()
}