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>
839 lines
34 KiB
Rust
839 lines
34 KiB
Rust
//! The Discord voice core (`app/src/discord_core.spec.md`).
|
|
//!
|
|
//! One bot, one server, one voice channel at a time. Hears each speaker separately and streams their
|
|
//! PCM to the voice worker, speaks text through the worker's TTS, and reads and writes the registered
|
|
//! chat channels. It has no assistant logic: it reports what was heard and does what it is told.
|
|
|
|
use std::collections::{HashMap, HashSet};
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
use std::time::{Duration, Instant};
|
|
use std::sync::{Arc, Mutex, OnceLock};
|
|
|
|
use async_trait::async_trait;
|
|
use serenity::all::{
|
|
Cache, ChannelId, ChannelType, Client, CommandDataOptionValue, CommandInteraction, CommandOptionType, Context,
|
|
CreateAllowedMentions, CreateCommand, CreateCommandOption, CreateInteractionResponse,
|
|
CreateInteractionResponseMessage, CreateMessage, EditInteractionResponse, EventHandler, GatewayIntents, GetMessages,
|
|
GuildId, Http, InstallationContext, Interaction, InteractionContext, Message, Ready, ShardManager, UserId,
|
|
VoiceState,
|
|
};
|
|
use songbird::driver::DecodeMode;
|
|
use songbird::input::Input;
|
|
use songbird::tracks::TrackHandle;
|
|
use songbird::{Call, Config, Event, EventContext, EventHandler as VoiceEventHandler, SerenityInit, Songbird, TrackEvent};
|
|
use tokio::sync::mpsc;
|
|
|
|
use crate::chat::{has_message_content_intent, split_message, ChatAccessError, ChatChannels, ChatMessage, MESSAGE_LIMIT};
|
|
use crate::playback::{ClipSink, Playback, PlaybackEnd, PlaybackEvent};
|
|
use crate::receive::{opus_payload, OpusFrames, SpeakerStream};
|
|
use crate::settings::Settings;
|
|
use crate::speakers::SpeakerGate;
|
|
use crate::worker_client::{Final, WorkerClient, WorkerEvent};
|
|
use crate::{debug_log, error_log};
|
|
|
|
/// No packet for this long and a speaker counts as stopped (Discord.js uses the same 100 ms).
|
|
const SPEAKING_END: Duration = Duration::from_millis(100);
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Heard {
|
|
pub speaker_id: u64,
|
|
pub speaker_name: String,
|
|
pub utt: u32,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct HeardFinal {
|
|
pub heard: Heard,
|
|
pub text: String,
|
|
pub end_reason: String,
|
|
pub audio_ms: u64,
|
|
pub wait_ms: u64,
|
|
pub stt_ms: u64,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum CoreEvent {
|
|
Ready { user_id: u64, tag: String },
|
|
Joined { guild_id: u64, channel_id: u64 },
|
|
Left { guild_id: u64, channel_id: u64, reason: String },
|
|
SpeechStart(Heard),
|
|
Partial(Heard, String),
|
|
Final(HeardFinal),
|
|
SpeakStart(String),
|
|
SpeakEnd(PlaybackEnd),
|
|
Chat(ChatMessage),
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct CoreError(pub String);
|
|
|
|
impl std::fmt::Display for CoreError {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
f.write_str(&self.0)
|
|
}
|
|
}
|
|
impl std::error::Error for CoreError {}
|
|
impl From<ChatAccessError> for CoreError {
|
|
fn from(e: ChatAccessError) -> Self {
|
|
CoreError(e.0)
|
|
}
|
|
}
|
|
fn cerr<E: std::fmt::Display>(what: &str) -> impl FnOnce(E) -> CoreError + '_ {
|
|
move |e| CoreError(format!("{what}: {e}"))
|
|
}
|
|
|
|
// --- playback sink: one player task owns the songbird track of the current clip -------------------
|
|
|
|
enum PlayerCmd {
|
|
Play(Vec<u8>),
|
|
Stop,
|
|
SetCall(Option<Arc<tokio::sync::Mutex<Call>>>),
|
|
Ended(u64),
|
|
}
|
|
|
|
struct PlayerSink(mpsc::UnboundedSender<PlayerCmd>);
|
|
|
|
impl ClipSink for PlayerSink {
|
|
fn play(&mut self, pcm: Vec<u8>) {
|
|
let _ = self.0.send(PlayerCmd::Play(pcm));
|
|
}
|
|
fn stop(&mut self) {
|
|
let _ = self.0.send(PlayerCmd::Stop);
|
|
}
|
|
}
|
|
|
|
struct TrackEnded {
|
|
tx: mpsc::UnboundedSender<PlayerCmd>,
|
|
generation: u64,
|
|
}
|
|
|
|
#[async_trait]
|
|
impl VoiceEventHandler for TrackEnded {
|
|
async fn act(&self, _: &EventContext<'_>) -> Option<Event> {
|
|
let _ = self.tx.send(PlayerCmd::Ended(self.generation));
|
|
None
|
|
}
|
|
}
|
|
|
|
/// 48 kHz stereo PCM16 as a WAV, which songbird plays without resampling.
|
|
fn wav(pcm: &[u8]) -> Vec<u8> {
|
|
let mut w = Vec::with_capacity(44 + pcm.len());
|
|
let len = pcm.len() as u32;
|
|
w.extend_from_slice(b"RIFF");
|
|
w.extend_from_slice(&(36 + len).to_le_bytes());
|
|
w.extend_from_slice(b"WAVEfmt ");
|
|
w.extend_from_slice(&16u32.to_le_bytes());
|
|
w.extend_from_slice(&1u16.to_le_bytes()); // PCM
|
|
w.extend_from_slice(&2u16.to_le_bytes()); // stereo
|
|
w.extend_from_slice(&48000u32.to_le_bytes());
|
|
w.extend_from_slice(&(48000u32 * 4).to_le_bytes());
|
|
w.extend_from_slice(&4u16.to_le_bytes());
|
|
w.extend_from_slice(&16u16.to_le_bytes());
|
|
w.extend_from_slice(b"data");
|
|
w.extend_from_slice(&len.to_le_bytes());
|
|
w.extend_from_slice(pcm);
|
|
w
|
|
}
|
|
|
|
// --- core -----------------------------------------------------------------------------------------
|
|
|
|
struct Session {
|
|
guild_id: u64,
|
|
channel_id: u64,
|
|
rx: Arc<Mutex<RxState>>,
|
|
/// Cleared when the session ends; stops its speaking-end timer.
|
|
alive: Arc<AtomicBool>,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct RxState {
|
|
ssrc_user: HashMap<u32, u64>,
|
|
streams: HashMap<u32, SpeakerStream<OpusFrames>>,
|
|
/// People currently sending packets, with the time of their last packet.
|
|
talking: HashMap<u64, Instant>,
|
|
/// Everyone whose audio reached the worker this session (they get `speaker_leave`).
|
|
heard: HashSet<u64>,
|
|
}
|
|
|
|
struct Inner {
|
|
settings: Settings,
|
|
token: String,
|
|
worker: WorkerClient,
|
|
events: mpsc::UnboundedSender<CoreEvent>,
|
|
songbird: Arc<Songbird>,
|
|
http: OnceLock<Arc<Http>>,
|
|
cache: OnceLock<Arc<Cache>>,
|
|
shards: OnceLock<Arc<ShardManager>>,
|
|
bot_id: OnceLock<u64>,
|
|
chat: ChatChannels,
|
|
chat_content: AtomicBool,
|
|
gate: Mutex<SpeakerGate>,
|
|
playback: Mutex<Playback<WorkerClient, PlayerSink>>,
|
|
player: mpsc::UnboundedSender<PlayerCmd>,
|
|
session: Mutex<Option<Session>>,
|
|
/// Serialises join and leave.
|
|
voice_lock: tokio::sync::Mutex<()>,
|
|
names: Mutex<HashMap<u64, String>>,
|
|
}
|
|
|
|
/// Handle to the core; cheap to clone.
|
|
#[derive(Clone)]
|
|
pub struct DiscordCore {
|
|
inner: Arc<Inner>,
|
|
}
|
|
|
|
impl DiscordCore {
|
|
/// The core and its event stream. `worker_events` is the worker client's event stream.
|
|
pub fn new(settings: Settings, token: String, worker: WorkerClient,
|
|
worker_events: mpsc::UnboundedReceiver<WorkerEvent>) -> (Self, mpsc::UnboundedReceiver<CoreEvent>) {
|
|
let (events, rx) = mpsc::unbounded_channel();
|
|
let (player_tx, player_rx) = mpsc::unbounded_channel();
|
|
// songbird only decrypts; the core reorders and decodes itself (see receive.rs for why).
|
|
let config = Config::default().decode_mode(DecodeMode::Decrypt);
|
|
let inner = Arc::new(Inner {
|
|
gate: Mutex::new(SpeakerGate::new(settings.voice.max_speakers)),
|
|
chat: ChatChannels::new(&settings.chat_channels),
|
|
playback: Mutex::new(Playback::new(worker.clone(), PlayerSink(player_tx.clone()))),
|
|
settings,
|
|
token,
|
|
worker,
|
|
events,
|
|
songbird: Songbird::serenity_from_config(config),
|
|
http: OnceLock::new(),
|
|
cache: OnceLock::new(),
|
|
shards: OnceLock::new(),
|
|
bot_id: OnceLock::new(),
|
|
chat_content: AtomicBool::new(false),
|
|
player: player_tx,
|
|
session: Mutex::new(None),
|
|
voice_lock: tokio::sync::Mutex::new(()),
|
|
names: Mutex::new(HashMap::new()),
|
|
});
|
|
tokio::spawn(player_task(Arc::downgrade(&inner), player_rx));
|
|
tokio::spawn(worker_task(Arc::downgrade(&inner), worker_events));
|
|
(Self { inner }, rx)
|
|
}
|
|
|
|
fn http(&self) -> Result<&Arc<Http>, CoreError> {
|
|
self.inner.http.get().ok_or_else(|| CoreError("the Discord core has not been started".into()))
|
|
}
|
|
|
|
/// The application has the Message Content intent; without it chat channels cannot be read.
|
|
pub fn chat_content(&self) -> bool {
|
|
self.inner.chat_content.load(Ordering::Relaxed)
|
|
}
|
|
|
|
pub fn bot_id(&self) -> Option<u64> {
|
|
self.inner.bot_id.get().copied()
|
|
}
|
|
|
|
/// Log in, register the slash command, and join the auto-join channel if one is set.
|
|
pub async fn start(&self) -> Result<(), CoreError> {
|
|
let inner = &self.inner;
|
|
let http = Http::new(&inner.token);
|
|
let app = http.get_current_application_info().await.map_err(cerr("could not reach Discord"))?;
|
|
let flags = app.flags.map(|f| f.bits()).unwrap_or(0);
|
|
let content = has_message_content_intent(flags);
|
|
inner.chat_content.store(content, Ordering::Relaxed);
|
|
let mut intents = GatewayIntents::GUILDS | GatewayIntents::GUILD_VOICE_STATES;
|
|
if inner.chat.any_readable() {
|
|
intents |= GatewayIntents::GUILD_MESSAGES;
|
|
if content {
|
|
intents |= GatewayIntents::MESSAGE_CONTENT;
|
|
} else {
|
|
error_log!("discord", "Message Content Intent is off for this bot; chat channels cannot be read. \
|
|
Turn it on in the Discord Developer Portal (Bot > Privileged Gateway Intents).");
|
|
}
|
|
}
|
|
let (ready_tx, mut ready_rx) = mpsc::unbounded_channel();
|
|
let mut client = Client::builder(&inner.token, intents)
|
|
.event_handler(Handler { core: self.clone(), ready: ready_tx })
|
|
.register_songbird_with(inner.songbird.clone())
|
|
.await
|
|
.map_err(cerr("could not create the Discord client"))?;
|
|
let _ = inner.http.set(client.http.clone());
|
|
let _ = inner.cache.set(client.cache.clone());
|
|
let _ = inner.shards.set(client.shard_manager.clone());
|
|
let (fail_tx, mut fail_rx) = mpsc::unbounded_channel();
|
|
tokio::spawn(async move {
|
|
if let Err(e) = client.start().await {
|
|
let _ = fail_tx.send(e.to_string());
|
|
}
|
|
});
|
|
let ready: Ready = tokio::select! {
|
|
r = ready_rx.recv() => r.ok_or_else(|| CoreError("gateway closed before ready".into()))?,
|
|
e = fail_rx.recv() => return Err(CoreError(format!("could not log in: {}", e.unwrap_or_default()))),
|
|
};
|
|
let _ = inner.bot_id.set(ready.user.id.get());
|
|
debug_log!("discord", "logged in as {} chatContent={content}", ready.user.id);
|
|
let _ = inner.events.send(CoreEvent::Ready { user_id: ready.user.id.get(), tag: ready.user.tag() });
|
|
if let Err(e) = self.register_command(app.id.get()).await {
|
|
// Voice and chat still work; the command can be registered on the next start.
|
|
error_log!("discord", "could not register the slash command: {e}");
|
|
}
|
|
if let Some(ch) = inner.settings.discord.voice_channel_id {
|
|
if let Err(e) = self.join(ch).await {
|
|
error_log!("voice", "auto-join {ch} failed: {e}");
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
async fn register_command(&self, app_id: u64) -> Result<(), CoreError> {
|
|
let Some(guild) = self.inner.settings.discord.guild_id else {
|
|
error_log!("discord", "discord.guildId is not set; the slash command is not registered");
|
|
return Ok(());
|
|
};
|
|
let name = &self.inner.settings.discord.command_name;
|
|
let sub = |n: &str, d: &str| CreateCommandOption::new(CommandOptionType::SubCommand, n, d);
|
|
let cmd = CreateCommand::new(name)
|
|
.description("자비스 음성 비서")
|
|
.contexts(vec![InteractionContext::Guild])
|
|
.integration_types(vec![InstallationContext::Guild])
|
|
.add_option(sub("join", "내가 있는 음성 채널로 자비스를 부릅니다"))
|
|
.add_option(sub("leave", "자비스를 음성 채널에서 내보냅니다"))
|
|
.add_option(sub("stop", "자비스가 하던 말을 멈춥니다"));
|
|
let http = self.http()?;
|
|
http.set_application_id(app_id.into());
|
|
// Creates or updates this one command by name and leaves the app's other commands alone.
|
|
GuildId::new(guild).create_command(http.as_ref(), cmd).await.map_err(cerr("create command"))?;
|
|
debug_log!("discord", "slash command /{name} registered in {guild}");
|
|
Ok(())
|
|
}
|
|
|
|
// --- voice ------------------------------------------------------------------------------------
|
|
|
|
pub fn voice_channel_id(&self) -> Option<u64> {
|
|
self.inner.session.lock().unwrap().as_ref().map(|s| s.channel_id)
|
|
}
|
|
|
|
/// Join a voice channel of the configured server (leaving the current one) and post the notice.
|
|
pub async fn join(&self, channel_id: u64) -> Result<(), CoreError> {
|
|
let _guard = self.inner.voice_lock.lock().await;
|
|
let http = self.http()?.clone();
|
|
let channel = ChannelId::new(channel_id).to_channel(&http).await.map_err(cerr("could not fetch the channel"))?;
|
|
let Some(gc) = channel.guild().filter(|c| matches!(c.kind, ChannelType::Voice | ChannelType::Stage)) else {
|
|
return Err(CoreError(format!("channel {channel_id} is not a voice channel")));
|
|
};
|
|
if let Some(g) = self.inner.settings.discord.guild_id {
|
|
if gc.guild_id.get() != g {
|
|
return Err(CoreError(format!("channel {channel_id} is not in the configured server")));
|
|
}
|
|
}
|
|
if self.voice_channel_id() == Some(channel_id) {
|
|
return Ok(());
|
|
}
|
|
self.leave_locked("moved").await;
|
|
let call = self.inner.songbird.join(gc.guild_id, gc.id).await.map_err(|e| {
|
|
CoreError(format!("could not connect to voice channel {channel_id}: {e}"))
|
|
});
|
|
let call = match call {
|
|
Ok(c) => c,
|
|
Err(e) => {
|
|
let _ = self.inner.songbird.remove(gc.guild_id).await;
|
|
return Err(e);
|
|
}
|
|
};
|
|
let rx = Arc::new(Mutex::new(RxState::default()));
|
|
{
|
|
let mut c = call.lock().await;
|
|
let h = Receiver { core: Arc::downgrade(&self.inner), rx: rx.clone(), guild_id: gc.guild_id.get() };
|
|
c.add_global_event(CoreEvent_::SpeakingStateUpdate.into(), h.clone());
|
|
c.add_global_event(CoreEvent_::RtpPacket.into(), h.clone());
|
|
c.add_global_event(CoreEvent_::ClientDisconnect.into(), h.clone());
|
|
c.add_global_event(CoreEvent_::DriverDisconnect.into(), h);
|
|
}
|
|
let alive = Arc::new(AtomicBool::new(true));
|
|
tokio::spawn(speaking_end_timer(Arc::downgrade(&self.inner), rx.clone(), alive.clone()));
|
|
*self.inner.session.lock().unwrap() = Some(Session { guild_id: gc.guild_id.get(), channel_id, rx, alive });
|
|
let _ = self.inner.player.send(PlayerCmd::SetCall(Some(call)));
|
|
debug_log!("voice", "joined voice {channel_id}");
|
|
let _ = self.inner.events.send(CoreEvent::Joined { guild_id: gc.guild_id.get(), channel_id });
|
|
let notice = CreateMessage::new().content(&self.inner.settings.voice.join_notice)
|
|
.allowed_mentions(CreateAllowedMentions::new());
|
|
if let Err(e) = gc.id.send_message(&http, notice).await {
|
|
error_log!("voice", "could not post the transcription notice in {channel_id}: {e}");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Leave the voice channel. False if not in one.
|
|
pub async fn leave(&self, reason: &str) -> bool {
|
|
let _guard = self.inner.voice_lock.lock().await;
|
|
self.leave_locked(reason).await
|
|
}
|
|
|
|
async fn leave_locked(&self, reason: &str) -> bool {
|
|
let Some(s) = self.inner.session.lock().unwrap().take() else { return false };
|
|
end_session(&self.inner, s, reason).await;
|
|
true
|
|
}
|
|
|
|
/// Speak text in the voice channel. The request id, or None when not in a voice channel.
|
|
pub fn say(&self, text: &str, more: bool) -> Option<String> {
|
|
self.voice_channel_id()?;
|
|
let id = with_playback(&self.inner, |p| p.say(text, more));
|
|
Some(id)
|
|
}
|
|
|
|
/// More text for a request started with `say(.., true)`.
|
|
pub fn continue_text(&self, id: &str, text: &str, more: bool) {
|
|
with_playback(&self.inner, |p| p.continue_text(id, text, more));
|
|
}
|
|
|
|
/// Stop speaking at once and drop everything queued. How many requests were stopped.
|
|
pub fn stop(&self) -> usize {
|
|
with_playback(&self.inner, |p| p.stop())
|
|
}
|
|
|
|
pub fn speaking(&self) -> bool {
|
|
self.inner.playback.lock().unwrap().busy()
|
|
}
|
|
|
|
// --- chat channels ----------------------------------------------------------------------------
|
|
|
|
/// The latest `limit` (1-100) messages of a registered channel, oldest first.
|
|
pub async fn read_chat(&self, channel_id: u64, limit: u8) -> Result<Vec<ChatMessage>, CoreError> {
|
|
self.inner.chat.check_read(channel_id)?;
|
|
if !self.chat_content() {
|
|
return Err(CoreError("the bot's Message Content Intent is off".into()));
|
|
}
|
|
let http = self.http()?;
|
|
let mut msgs = ChannelId::new(channel_id)
|
|
.messages(http.as_ref(), GetMessages::new().limit(limit.clamp(1, 100)))
|
|
.await
|
|
.map_err(cerr("could not read the channel"))?;
|
|
msgs.sort_by_key(|m| m.id);
|
|
Ok(msgs.iter().map(|m| to_chat(&self.inner, m)).collect())
|
|
}
|
|
|
|
/// Send text to a registered channel, split at Discord's length limit. The message ids.
|
|
pub async fn send_chat(&self, channel_id: u64, text: &str) -> Result<Vec<u64>, CoreError> {
|
|
self.inner.chat.check_send(channel_id)?;
|
|
if text.trim().is_empty() {
|
|
return Err(CoreError("nothing to send".into()));
|
|
}
|
|
let http = self.http()?;
|
|
let mut ids = vec![];
|
|
for part in split_message(text, MESSAGE_LIMIT) {
|
|
// Never ping anyone from text the assistant wrote.
|
|
let m = CreateMessage::new().content(part).allowed_mentions(CreateAllowedMentions::new());
|
|
let sent = ChannelId::new(channel_id).send_message(http.as_ref(), m).await.map_err(cerr("could not send"))?;
|
|
ids.push(sent.id.get());
|
|
}
|
|
debug_log!("chat", "chat sent to {channel_id} parts={} chars={}", ids.len(), text.chars().count());
|
|
Ok(ids)
|
|
}
|
|
|
|
pub async fn close(&self) {
|
|
self.leave("shutdown").await;
|
|
if let Some(s) = self.inner.shards.get() {
|
|
s.shutdown_all().await;
|
|
}
|
|
}
|
|
}
|
|
|
|
use songbird::CoreEvent as CoreEvent_;
|
|
|
|
fn with_playback<T>(inner: &Inner, f: impl FnOnce(&mut Playback<WorkerClient, PlayerSink>) -> T) -> T {
|
|
let (out, events) = {
|
|
let mut p = inner.playback.lock().unwrap();
|
|
let out = f(&mut p);
|
|
(out, p.take_events())
|
|
};
|
|
for e in events {
|
|
let _ = inner.events.send(match e {
|
|
PlaybackEvent::Start(id) => CoreEvent::SpeakStart(id),
|
|
PlaybackEvent::End(e) => CoreEvent::SpeakEnd(e),
|
|
});
|
|
}
|
|
out
|
|
}
|
|
|
|
async fn end_session(inner: &Arc<Inner>, s: Session, reason: &str) {
|
|
s.alive.store(false, Ordering::Relaxed);
|
|
with_playback(inner, |p| p.stop());
|
|
let _ = inner.player.send(PlayerCmd::SetCall(None));
|
|
let (heard, lost, late, bad) = {
|
|
let mut rx = s.rx.lock().unwrap();
|
|
let (l, t, b) = rx.streams.values().fold((0, 0, 0), |a, x| (a.0 + x.lost, a.1 + x.late, a.2 + x.bad));
|
|
(std::mem::take(&mut rx.heard), l, t, b)
|
|
};
|
|
for user in heard {
|
|
inner.worker.speaker_leave(&user.to_string());
|
|
}
|
|
inner.gate.lock().unwrap().clear();
|
|
let _ = inner.songbird.remove(GuildId::new(s.guild_id)).await;
|
|
debug_log!("voice", "left voice {} reason={reason} packets lost={lost} late={late} bad={bad}", s.channel_id);
|
|
let _ = inner.events.send(CoreEvent::Left { guild_id: s.guild_id, channel_id: s.channel_id, reason: reason.into() });
|
|
}
|
|
|
|
fn should_hear(inner: &Inner, user: u64) -> bool {
|
|
if Some(user) == inner.bot_id.get().copied() {
|
|
return false;
|
|
}
|
|
if inner.settings.voice.listen_to_bots {
|
|
return true;
|
|
}
|
|
// Unknown users are people: the voice state that put a bot in the channel would have cached it.
|
|
!inner.cache.get().and_then(|c| c.user(UserId::new(user)).map(|u| u.bot)).unwrap_or(false)
|
|
}
|
|
|
|
fn name_of(inner: &Inner, user: u64) -> String {
|
|
if let Some(n) = inner.names.lock().unwrap().get(&user) {
|
|
return n.clone();
|
|
}
|
|
let guild = inner.session.lock().unwrap().as_ref().map(|s| s.guild_id).or(inner.settings.discord.guild_id);
|
|
let name = inner.cache.get().and_then(|c| {
|
|
guild
|
|
.and_then(|g| c.guild(GuildId::new(g))?.members.get(&UserId::new(user)).map(|m| m.display_name().to_owned()))
|
|
.or_else(|| c.user(UserId::new(user)).map(|u| u.display_name().to_owned()))
|
|
});
|
|
match name {
|
|
Some(n) => {
|
|
inner.names.lock().unwrap().insert(user, n.clone());
|
|
n
|
|
}
|
|
None => user.to_string(),
|
|
}
|
|
}
|
|
|
|
fn heard(inner: &Inner, speaker: &str, utt: u32) -> Option<Heard> {
|
|
let id: u64 = speaker.parse().ok()?;
|
|
Some(Heard { speaker_id: id, speaker_name: name_of(inner, id), utt })
|
|
}
|
|
|
|
fn to_chat(inner: &Inner, m: &Message) -> ChatMessage {
|
|
let name = m.member.as_ref().and_then(|p| p.nick.clone())
|
|
.unwrap_or_else(|| m.author.display_name().to_owned());
|
|
ChatMessage {
|
|
channel_id: m.channel_id.get(),
|
|
message_id: m.id.get(),
|
|
author_id: m.author.id.get(),
|
|
author_name: name,
|
|
author_is_bot: m.author.bot,
|
|
from_self: Some(m.author.id.get()) == inner.bot_id.get().copied(),
|
|
content: m.content.clone(),
|
|
created_at: m.timestamp.to_rfc3339().unwrap_or_default(),
|
|
}
|
|
}
|
|
|
|
async fn worker_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiver<WorkerEvent>) {
|
|
while let Some(ev) = rx.recv().await {
|
|
let Some(inner) = core.upgrade() else { return };
|
|
match ev {
|
|
WorkerEvent::SpeechStart(m) => {
|
|
if let Some(h) = heard(&inner, &m.speaker, m.utt) {
|
|
let _ = inner.events.send(CoreEvent::SpeechStart(h));
|
|
}
|
|
}
|
|
WorkerEvent::Partial(m) => {
|
|
if let Some(h) = heard(&inner, &m.speaker, m.utt) {
|
|
let _ = inner.events.send(CoreEvent::Partial(h, m.text));
|
|
}
|
|
}
|
|
WorkerEvent::Final(m) => on_final(&inner, m),
|
|
WorkerEvent::TtsAudio { id, seq, pcm } => with_playback(&inner, |p| p.audio(&id, seq, pcm)),
|
|
WorkerEvent::TtsDone(d) => with_playback(&inner, |p| p.done(&d)),
|
|
WorkerEvent::Ready(_) | WorkerEvent::Disconnected | WorkerEvent::Error(_) => {}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn on_final(inner: &Inner, m: Final) {
|
|
debug_log!("voice", "final speaker={} utt={} reason={} chars={} audio_ms={} wait_ms={}", m.speaker, m.utt,
|
|
m.end_reason, m.text.chars().count(), m.audio_ms, m.wait_ms);
|
|
if let Some(h) = heard(inner, &m.speaker, m.utt) {
|
|
let _ = inner.events.send(CoreEvent::Final(HeardFinal { heard: h, text: m.text, end_reason: m.end_reason,
|
|
audio_ms: m.audio_ms, wait_ms: m.wait_ms, stt_ms: m.stt_ms }));
|
|
}
|
|
}
|
|
|
|
async fn player_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiver<PlayerCmd>) {
|
|
let mut call: Option<Arc<tokio::sync::Mutex<Call>>> = None;
|
|
let mut current: Option<(TrackHandle, u64)> = None;
|
|
let mut generation = 0u64;
|
|
while let Some(cmd) = rx.recv().await {
|
|
let Some(inner) = core.upgrade() else { return };
|
|
match cmd {
|
|
PlayerCmd::SetCall(c) => {
|
|
if let Some((t, _)) = current.take() {
|
|
let _ = t.stop();
|
|
}
|
|
call = c;
|
|
}
|
|
PlayerCmd::Play(pcm) => {
|
|
generation += 1;
|
|
let Some(c) = &call else {
|
|
// Nowhere to play: count it as played so the queue moves on.
|
|
with_playback(&inner, |p| p.clip_ended());
|
|
continue;
|
|
};
|
|
let track = c.lock().await.play_only_input(Input::from(wav(&pcm)));
|
|
let ended = TrackEnded { tx: inner.player.clone(), generation };
|
|
let _ = track.add_event(Event::Track(TrackEvent::End), ended);
|
|
let ended = TrackEnded { tx: inner.player.clone(), generation };
|
|
let _ = track.add_event(Event::Track(TrackEvent::Error), ended);
|
|
current = Some((track, generation));
|
|
}
|
|
PlayerCmd::Stop => {
|
|
if let Some((t, _)) = current.take() {
|
|
let _ = t.stop();
|
|
}
|
|
}
|
|
PlayerCmd::Ended(g) => {
|
|
// Only the end of the clip we started counts; a stop() already moved on.
|
|
if current.as_ref().is_some_and(|(_, cg)| *cg == g) {
|
|
current = None;
|
|
with_playback(&inner, |p| p.clip_ended());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- receive --------------------------------------------------------------------------------------
|
|
|
|
#[derive(Clone)]
|
|
struct Receiver {
|
|
core: std::sync::Weak<Inner>,
|
|
rx: Arc<Mutex<RxState>>,
|
|
guild_id: u64,
|
|
}
|
|
|
|
impl Receiver {
|
|
fn packet(&self, inner: &Inner, rtp: &songbird::events::context_data::RtpData) {
|
|
let Some((seq, ssrc, opus)) = opus_payload(&rtp.packet, rtp.payload_offset, rtp.payload_end_pad) else { return };
|
|
let mut rx = self.rx.lock().unwrap();
|
|
let Some(&user) = rx.ssrc_user.get(&ssrc) else { return };
|
|
if !should_hear(inner, user) {
|
|
return;
|
|
}
|
|
let mut gate = inner.gate.lock().unwrap();
|
|
if rx.talking.insert(user, Instant::now()).is_none() && !gate.start(user) {
|
|
debug_log!("voice", "speaker {user} not heard: {} already speaking", gate.count());
|
|
}
|
|
// Decode even when not heard, so the decoder state stays continuous.
|
|
let frames = rx.streams.entry(ssrc).or_insert_with(|| SpeakerStream::new(OpusFrames::new())).push(seq, opus.to_vec());
|
|
if gate.is_active(user) && !frames.is_empty() {
|
|
rx.heard.insert(user);
|
|
let id = user.to_string();
|
|
for f in frames {
|
|
inner.worker.send_audio(&id, &f);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn left(&self, inner: &Inner, user: u64) {
|
|
let mut rx = self.rx.lock().unwrap();
|
|
rx.talking.remove(&user);
|
|
let ssrcs: Vec<u32> = rx.ssrc_user.iter().filter(|(_, u)| **u == user).map(|(s, _)| *s).collect();
|
|
for ssrc in ssrcs {
|
|
rx.ssrc_user.remove(&ssrc);
|
|
rx.streams.remove(&ssrc);
|
|
}
|
|
let was_heard = inner.gate.lock().unwrap().end(user);
|
|
if rx.heard.remove(&user) || was_heard {
|
|
inner.worker.speaker_leave(&user.to_string());
|
|
}
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
impl VoiceEventHandler for Receiver {
|
|
async fn act(&self, ctx: &EventContext<'_>) -> Option<Event> {
|
|
let inner = self.core.upgrade()?;
|
|
match ctx {
|
|
EventContext::SpeakingStateUpdate(s) => {
|
|
if let Some(u) = s.user_id {
|
|
self.rx.lock().unwrap().ssrc_user.insert(s.ssrc, u.0);
|
|
}
|
|
}
|
|
EventContext::RtpPacket(p) => self.packet(&inner, p),
|
|
EventContext::ClientDisconnect(d) => self.left(&inner, d.user_id.0),
|
|
EventContext::DriverDisconnect(_) => {
|
|
// The driver gave up reconnecting (kicked, channel deleted, long network loss).
|
|
let core = DiscordCore { inner: inner.clone() };
|
|
let guild = self.guild_id;
|
|
tokio::spawn(async move {
|
|
let _g = core.inner.voice_lock.lock().await;
|
|
let s = {
|
|
let mut s = core.inner.session.lock().unwrap();
|
|
if s.as_ref().is_some_and(|s| s.guild_id == guild) { s.take() } else { None }
|
|
};
|
|
if let Some(s) = s {
|
|
end_session(&core.inner, s, "disconnected").await;
|
|
}
|
|
});
|
|
}
|
|
_ => {}
|
|
}
|
|
None
|
|
}
|
|
}
|
|
|
|
/// Every 20 ms: anyone without a packet for SPEAKING_END has stopped. Play out what their reorder
|
|
/// window still holds, then tell the worker.
|
|
async fn speaking_end_timer(core: std::sync::Weak<Inner>, rx: Arc<Mutex<RxState>>, alive: Arc<AtomicBool>) {
|
|
let mut every = tokio::time::interval(Duration::from_millis(20));
|
|
while alive.load(Ordering::Relaxed) {
|
|
every.tick().await;
|
|
let Some(inner) = core.upgrade() else { return };
|
|
let mut rx = rx.lock().unwrap();
|
|
let now = Instant::now();
|
|
let ended: Vec<u64> = rx.talking.iter().filter(|(_, t)| now.duration_since(**t) >= SPEAKING_END).map(|(u, _)| *u).collect();
|
|
for user in ended {
|
|
rx.talking.remove(&user);
|
|
let ssrcs: Vec<u32> = rx.ssrc_user.iter().filter(|(_, u)| **u == user).map(|(s, _)| *s).collect();
|
|
let mut gate = inner.gate.lock().unwrap();
|
|
let active = gate.is_active(user);
|
|
let id = user.to_string();
|
|
for ssrc in ssrcs {
|
|
if let Some(st) = rx.streams.get_mut(&ssrc) {
|
|
for f in st.flush() {
|
|
if active {
|
|
inner.worker.send_audio(&id, &f);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if gate.end(user) {
|
|
inner.worker.speaking_end(&id);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- gateway events -------------------------------------------------------------------------------
|
|
|
|
struct Handler {
|
|
core: DiscordCore,
|
|
ready: mpsc::UnboundedSender<Ready>,
|
|
}
|
|
|
|
#[async_trait]
|
|
impl EventHandler for Handler {
|
|
async fn ready(&self, _: Context, ready: Ready) {
|
|
let _ = self.ready.send(ready);
|
|
}
|
|
|
|
async fn voice_state_update(&self, _: Context, old: Option<VoiceState>, new: VoiceState) {
|
|
let inner = &self.core.inner;
|
|
let user = new.user_id.get();
|
|
if let Some(m) = &new.member {
|
|
inner.names.lock().unwrap().insert(user, m.display_name().to_owned());
|
|
}
|
|
let (session_channel, rx) = {
|
|
let s = inner.session.lock().unwrap();
|
|
match s.as_ref() {
|
|
Some(s) if new.guild_id.map(|g| g.get()) == Some(s.guild_id) => (s.channel_id, s.rx.clone()),
|
|
_ => return,
|
|
}
|
|
};
|
|
let new_channel = new.channel_id.map(|c| c.get());
|
|
if Some(user) == inner.bot_id.get().copied() {
|
|
// Moved by someone else: follow the new channel id. Disconnects end via DriverDisconnect.
|
|
if let Some(c) = new_channel.filter(|c| *c != session_channel) {
|
|
if let Some(s) = inner.session.lock().unwrap().as_mut() {
|
|
s.channel_id = c;
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
let was_here = old.and_then(|o| o.channel_id).map(|c| c.get()) == Some(session_channel);
|
|
if was_here && new_channel != Some(session_channel) {
|
|
Receiver { core: Arc::downgrade(inner), rx, guild_id: 0 }.left(inner, user);
|
|
}
|
|
}
|
|
|
|
async fn message(&self, _: Context, m: Message) {
|
|
let inner = &self.core.inner;
|
|
let ch = m.channel_id.get();
|
|
if !self.core.chat_content() || !inner.chat.can_read(ch) || Some(m.author.id.get()) == self.core.bot_id() {
|
|
return;
|
|
}
|
|
debug_log!("chat", "chat message in {ch} from {} chars={}", m.author.id, m.content.chars().count());
|
|
let _ = inner.events.send(CoreEvent::Chat(to_chat(inner, &m)));
|
|
}
|
|
|
|
async fn interaction_create(&self, _: Context, interaction: Interaction) {
|
|
if let Interaction::Command(cmd) = interaction {
|
|
self.on_command(cmd).await;
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Handler {
|
|
async fn on_command(&self, cmd: CommandInteraction) {
|
|
let inner = &self.core.inner;
|
|
if cmd.data.name != inner.settings.discord.command_name {
|
|
return;
|
|
}
|
|
let Some(guild) = cmd.guild_id else { return };
|
|
if inner.settings.discord.guild_id.is_some_and(|g| g != guild.get()) {
|
|
return;
|
|
}
|
|
let Ok(http) = self.core.http().cloned() else { return };
|
|
let eph = inner.settings.discord.ephemeral_replies;
|
|
let sub = cmd.data.options.first().filter(|o| matches!(o.value, CommandDataOptionValue::SubCommand(_)))
|
|
.map(|o| o.name.clone()).unwrap_or_default();
|
|
debug_log!("discord", "command {sub} from {}", cmd.user.id);
|
|
let reply = |content: &str| CreateInteractionResponse::Message(
|
|
CreateInteractionResponseMessage::new().content(content).ephemeral(eph));
|
|
let result: Result<(), CoreError> = async {
|
|
match sub.as_str() {
|
|
"join" => {
|
|
let channel = inner.cache.get().and_then(|c| {
|
|
c.guild(guild).and_then(|g| g.voice_states.get(&cmd.user.id).and_then(|v| v.channel_id))
|
|
});
|
|
let Some(channel) = channel else {
|
|
cmd.create_response(&http, reply("먼저 음성 채널에 들어간 뒤 다시 불러 주세요.")).await
|
|
.map_err(cerr("reply"))?;
|
|
return Ok(());
|
|
};
|
|
cmd.create_response(&http, CreateInteractionResponse::Defer(
|
|
CreateInteractionResponseMessage::new().ephemeral(eph))).await.map_err(cerr("defer"))?;
|
|
self.core.join(channel.get()).await?;
|
|
cmd.edit_response(&http, EditInteractionResponse::new().content("음성 채널에 들어왔습니다.")).await
|
|
.map_err(cerr("reply"))?;
|
|
}
|
|
"leave" => {
|
|
let left = self.core.leave("command").await;
|
|
cmd.create_response(&http, reply(if left { "음성 채널에서 나갔습니다." } else { "음성 채널에 있지 않습니다." }))
|
|
.await.map_err(cerr("reply"))?;
|
|
}
|
|
"stop" => {
|
|
let stopped = self.core.stop();
|
|
cmd.create_response(&http, reply(if stopped > 0 { "멈췄습니다." } else { "지금은 말하고 있지 않습니다." }))
|
|
.await.map_err(cerr("reply"))?;
|
|
}
|
|
_ => {}
|
|
}
|
|
Ok(())
|
|
}
|
|
.await;
|
|
if let Err(e) = result {
|
|
error_log!("discord", "command {sub} failed: {e}");
|
|
let content = "처리하지 못했습니다. 잠시 뒤 다시 시도해 주세요.";
|
|
if cmd.edit_response(&http, EditInteractionResponse::new().content(content)).await.is_err() {
|
|
let _ = cmd.create_response(&http, reply(content)).await;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
#[test]
|
|
fn wav_header_describes_48k_stereo_pcm16() {
|
|
let w = super::wav(&[1, 2, 3, 4]);
|
|
assert_eq!(&w[0..4], b"RIFF");
|
|
assert_eq!(u32::from_le_bytes(w[4..8].try_into().unwrap()), 40);
|
|
assert_eq!(u16::from_le_bytes(w[22..24].try_into().unwrap()), 2);
|
|
assert_eq!(u32::from_le_bytes(w[24..28].try_into().unwrap()), 48000);
|
|
assert_eq!(u32::from_le_bytes(w[40..44].try_into().unwrap()), 4);
|
|
assert_eq!(&w[44..], &[1, 2, 3, 4]);
|
|
}
|
|
|
|
}
|