diff --git a/Cargo.lock b/Cargo.lock index 09de061..8af9482 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5154,6 +5154,26 @@ dependencies = [ "tsproto-packets", ] +[[package]] +name = "tsc-core" +version = "0.1.0" +dependencies = [ + "anyhow", + "futures", + "serde_json", + "thiserror 2.0.21", + "tokio", + "tokio-tungstenite 0.30.0", + "tracing", + "tsc-audio", + "tsc-gateway-proto", + "tsc-model", + "tsc-observer", + "tsc-query", + "tsclientlib", + "tsproto-packets", +] + [[package]] name = "tsc-gateway" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 810a2a5..23a9618 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ members = [ "crates/proto/ts-bookkeeping", "crates/proto/tsclientlib", "crates/tsc-audio", + "crates/tsc-core", "crates/tsc-gateway", "crates/tsc-gateway-proto", "crates/tsc-model", @@ -25,6 +26,7 @@ default-members = [ "crates/proto/ts-bookkeeping", "crates/proto/tsclientlib", "crates/tsc-audio", + "crates/tsc-core", "crates/tsc-gateway", "crates/tsc-gateway-proto", "crates/tsc-model", diff --git a/crates/tsc-audio/src/resample.rs b/crates/tsc-audio/src/resample.rs index 9b46ff9..33aa699 100644 --- a/crates/tsc-audio/src/resample.rs +++ b/crates/tsc-audio/src/resample.rs @@ -24,8 +24,64 @@ pub fn resample_all(samples: &[f32], channels: usize, from: u32, to: u32) -> Res Ok(output.take_data()) } +/// Streaming mono resampler with linear interpolation, for device audio whose +/// rate differs from 48 kHz. Cheap and latency-free; good enough for voice. +#[derive(Clone, Debug)] +pub struct Linear { + /// Input samples per output sample. + step: f64, + /// Position of the next output sample, relative to `prev`. + pos: f64, + prev: f32, +} + +impl Linear { + pub fn new(from: u32, to: u32) -> Self { + Self { step: from as f64 / to as f64, pos: 0.0, prev: 0.0 } + } + + pub fn is_passthrough(&self) -> bool { + self.step == 1.0 + } + + /// Resample a chunk, appending to `out`. State carries over between calls. + pub fn process(&mut self, input: &[f32], out: &mut Vec) { + if self.is_passthrough() { + out.extend_from_slice(input); + return; + } + for &next in input { + while self.pos < 1.0 { + out.push(self.prev + (next - self.prev) * self.pos as f32); + self.pos += self.step; + } + self.pos -= 1.0; + self.prev = next; + } + } +} + #[cfg(test)] mod tests { + #[test] + fn linear_streaming_rate_and_tone() { + let tone: Vec = (0..44_100) + .map(|i| 0.5 * (std::f32::consts::TAU * 1000.0 * i as f32 / 44_100.0).sin()) + .collect(); + let mut r = Linear::new(44_100, 48_000); + let mut out = Vec::new(); + // Arbitrary chunk sizes must give the same stream. + for chunk in tone.chunks(333) { + r.process(chunk, &mut out); + } + assert!((out.len() as i64 - 48_000).abs() <= 2, "len {}", out.len()); + assert!(crate::pcm::tone_ratio(&out[100..], 1000.0, 48_000) > 0.95); + let mut same = Linear::new(48_000, 48_000); + let mut o = Vec::new(); + same.process(&[1.0, 2.0], &mut o); + assert_eq!(o, vec![1.0, 2.0]); + } + use super::*; use crate::pcm; diff --git a/crates/tsc-core/Cargo.toml b/crates/tsc-core/Cargo.toml new file mode 100644 index 0000000..c6a4644 --- /dev/null +++ b/crates/tsc-core/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "tsc-core" +version = "0.1.0" +description = "Client engine: server sessions merging voice, gateway and query sources; the API the UI drives." +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[features] +default = ["audio-device"] +# Capture and play audio through the system's devices. +audio-device = ["tsc-audio/device"] + +[dependencies] +anyhow = "1" +futures = "0.3" +serde_json = "1" +thiserror = "2" +tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"] } +tokio-tungstenite = "0.30" +tracing = "0.1" +tsc-audio = { path = "../tsc-audio", default-features = false } +tsc-gateway-proto = { path = "../tsc-gateway-proto" } +tsc-model = { path = "../tsc-model" } +tsc-observer = { path = "../tsc-observer" } +tsc-query = { path = "../tsc-query" } +tsclientlib = { path = "../proto/tsclientlib" } +tsproto-packets = { path = "../proto/tsproto-packets" } + +[dev-dependencies] +tokio = { version = "1", features = ["macros", "rt-multi-thread", "test-util"] } + +[lints] +workspace = true diff --git a/crates/tsc-core/src/audio.rs b/crates/tsc-core/src/audio.rs new file mode 100644 index 0000000..0fac225 --- /dev/null +++ b/crates/tsc-core/src/audio.rs @@ -0,0 +1,199 @@ +//! Audio thread: capture → encode → voice connection, and incoming voice → +//! jitter buffer/mixer → playback. +//! +//! Devices live on their own OS thread (cpal streams are not `Send` on every +//! platform); the connection task talks to it through channels. + +use std::sync::mpsc as std_mpsc; +use std::thread; +use std::time::Duration; + +use tokio::sync::mpsc; +use tracing::{debug, warn}; +use tsc_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE}; +use tsc_audio::resample::Linear; +use tsc_audio::{Framer, Mixer, VoiceCodec, VoiceEncoder}; +use tsclientlib::ClientId; +use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket}; + +pub(crate) enum AudioIn { + Packet(InAudioBuf), + Transmit(bool), + InputMuted(bool), + OutputMuted(bool), +} + +pub(crate) struct AudioHandle { + tx: std_mpsc::Sender, +} + +impl AudioHandle { + pub fn send(&self, msg: AudioIn) { + let _ = self.tx.send(msg); + } +} + +/// Voice activity: transmit while the level is above the threshold, with a +/// short hang time so word endings are not cut. +struct Vad { + threshold: f32, + hang_frames: u32, + remaining: u32, +} + +impl Vad { + fn active(&mut self, frame: &[f32]) -> bool { + if pcm::energy(frame) > self.threshold { + self.remaining = self.hang_frames; + } else if self.remaining > 0 { + self.remaining -= 1; + } + self.remaining > 0 + } +} + +/// Start the audio thread. Encoded packets go to `outgoing`; problems (e.g. +/// no device) are reported through `errors`. +pub(crate) fn spawn( + outgoing: mpsc::UnboundedSender, + errors: mpsc::UnboundedSender, + voice_activation: bool, +) -> AudioHandle { + let (tx, rx) = std_mpsc::channel(); + thread::Builder::new() + .name("tsc-audio".into()) + .spawn(move || run(rx, outgoing, errors, voice_activation)) + .expect("spawn audio thread"); + AudioHandle { tx } +} + +fn run( + rx: std_mpsc::Receiver, + outgoing: mpsc::UnboundedSender, + errors: mpsc::UnboundedSender, + voice_activation: bool, +) { + #[cfg(feature = "audio-device")] + let mut capture = match tsc_audio::device::Capture::open_default(500) { + Ok(c) => Some(c), + Err(e) => { + let _ = errors.send(format!("no microphone: {e}")); + None + } + }; + #[cfg(feature = "audio-device")] + let mut playback = match tsc_audio::device::Playback::open_default(200) { + Ok(p) => Some(p), + Err(e) => { + let _ = errors.send(format!("no speakers: {e}")); + None + } + }; + #[cfg(not(feature = "audio-device"))] + let _ = errors.send("built without audio device support".to_string()); + + let mut encoder = match VoiceEncoder::new(VoiceCodec::Voice) { + Ok(e) => e, + Err(e) => { + let _ = errors.send(e.to_string()); + return; + } + }; + let mut mixer = Mixer::new(); + let mut framer = Framer::new(FRAME_SAMPLES); + let mut vad = Vad { threshold: 1e-4, hang_frames: 15, remaining: 0 }; + let (mut ptt, mut input_muted, mut output_muted) = (false, false, false); + let mut was_sending = false; + + #[cfg(feature = "audio-device")] + let mut capture_resampler = capture.as_ref().map(|c| Linear::new(c.rate, SAMPLE_RATE)); + #[cfg(feature = "audio-device")] + let mut playback_resampler = playback.as_ref().map(|p| Linear::new(SAMPLE_RATE, p.rate)); + let mut captured = Vec::new(); + let mut resampled = Vec::new(); + + loop { + // Control messages and incoming voice. + loop { + match rx.try_recv() { + Ok(AudioIn::Packet(packet)) => { + let from = match packet.data().data() { + AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from, + _ => continue, + }; + if let Err(error) = mixer.handle_packet(ClientId(from), packet) { + debug!(%error, "dropped voice packet"); + } + } + Ok(AudioIn::Transmit(on)) => ptt = on, + Ok(AudioIn::InputMuted(m)) => input_muted = m, + Ok(AudioIn::OutputMuted(m)) => output_muted = m, + Err(std_mpsc::TryRecvError::Empty) => break, + Err(std_mpsc::TryRecvError::Disconnected) => return, + } + } + + // Capture → 48 kHz mono → 20 ms frames → Opus. + captured.clear(); + resampled.clear(); + #[cfg(feature = "audio-device")] + if let (Some(c), Some(r)) = (&mut capture, &mut capture_resampler) { + c.read_available(&mut captured); + let mono = pcm::to_mono(&captured, c.channels); + r.process(&mono, &mut resampled); + } + let mut frames = Vec::new(); + framer.push(&resampled, |f| frames.push(f.to_vec())); + for frame in frames { + let send = !input_muted && if voice_activation { vad.active(&frame) } else { ptt }; + if send { + match encoder.encode(&frame) { + Ok(packet) => { + let _ = outgoing.send(packet); + } + Err(e) => warn!(%e, "encoding failed"), + } + } else if was_sending { + let _ = outgoing.send(encoder.end_of_stream()); + } + was_sending = send; + } + + // Mixer → device rate/channels → playback. + #[cfg(feature = "audio-device")] + if let (Some(p), Some(r)) = (&mut playback, &mut playback_resampler) { + let needed_48k = (p.free() / p.channels) as u64 * SAMPLE_RATE as u64 / p.rate as u64; + if needed_48k as usize >= FRAME_SAMPLES { + let mut stereo = vec![0.0; FRAME_SAMPLES * 2]; + mixer.fill_buffer(&mut stereo); + if output_muted { + stereo.fill(0.0); + } + let mono = pcm::to_mono(&stereo, 2); + let mut out = Vec::with_capacity(mono.len()); + r.process(&mono, &mut out); + p.write(&pcm::from_mono(&out, p.channels)); + } + } + #[cfg(not(feature = "audio-device"))] + let _ = (output_muted, &mut mixer); + + thread::sleep(Duration::from_millis(5)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn vad_hangs_after_speech() { + let mut vad = Vad { threshold: 1e-3, hang_frames: 2, remaining: 0 }; + let loud = vec![0.5; 960]; + let quiet = vec![0.0; 960]; + assert!(!vad.active(&quiet)); + assert!(vad.active(&loud)); + assert!(vad.active(&quiet)); + assert!(!vad.active(&quiet)); + } +} diff --git a/crates/tsc-core/src/gateway.rs b/crates/tsc-core/src/gateway.rs new file mode 100644 index 0000000..af822be --- /dev/null +++ b/crates/tsc-core/src/gateway.rs @@ -0,0 +1,120 @@ +//! The gateway source: presence and relayed chat through `tsgw`. + +use futures::{SinkExt, StreamExt}; +use tokio::sync::mpsc; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tracing::info; +use tsc_gateway_proto::{ClientMsg, Envelope, ServerMsg, sign_challenge}; +use tsc_model::{ChatMessage, ChatTarget, Presence}; + +pub(crate) enum GatewayCmd { + OpenChat(ChatTarget), + CloseChat(ChatTarget), + SendChat(ChatTarget, String), + Stop, +} + +pub(crate) enum GatewayEvent { + Connected, + Presence(Presence), + Chat(ChatMessage), + Error(String), + Disconnected(Option), +} + +pub(crate) async fn run( + url: String, + identity: tsclientlib::Identity, + mut commands: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, +) { + let reason = + run_inner(&url, &identity, &mut commands, &events).await.err().map(|e| e.to_string()); + let _ = events.send(GatewayEvent::Disconnected(reason)); +} + +async fn run_inner( + url: &str, + identity: &tsclientlib::Identity, + commands: &mut mpsc::UnboundedReceiver, + events: &mpsc::UnboundedSender, +) -> anyhow::Result<()> { + let mut request = url.into_client_request()?; + request.headers_mut().insert("Sec-WebSocket-Protocol", tsc_gateway_proto::SUBPROTOCOL.parse()?); + let (mut ws, _) = tokio_tungstenite::connect_async(request).await?; + let mut next_id = 1u64; + let mut presence = Presence::default(); + + macro_rules! send { + ($msg:expr) => {{ + next_id += 1; + let env = Envelope::with_id(next_id, $msg); + ws.send(Message::Text(serde_json::to_string(&env)?.into())).await?; + }}; + } + + loop { + tokio::select! { + msg = ws.next() => { + let text = match msg { + Some(Ok(Message::Text(t))) => t, + Some(Ok(Message::Close(_))) | None => return Ok(()), + Some(Ok(_)) => continue, + Some(Err(e)) => return Err(e.into()), + }; + let env: Envelope = serde_json::from_str(text.as_str())?; + match env.msg { + ServerMsg::Hello { gateway_id, server_uid, nonce, server_name, .. } => { + let ts = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH)? + .as_secs() as i64; + let key = identity.key(); + send!(ClientMsg::Auth { + omega: key.to_pub().to_ts(), + key_offset: identity.counter(), + ts, + signature: sign_challenge(key, &gateway_id, &server_uid, &nonce, ts), + nickname: String::new(), + }); + info!(%server_name, "gateway hello"); + } + ServerMsg::AuthOk { .. } => { + let _ = events.send(GatewayEvent::Connected); + send!(ClientMsg::SubscribePresence); + } + ServerMsg::PresenceSnapshot { snapshot, .. } => { + presence = Presence::from_snapshot(snapshot); + let _ = events.send(GatewayEvent::Presence(presence.clone())); + } + ServerMsg::PresenceDelta { delta, .. } => { + presence.apply(&delta); + let _ = events.send(GatewayEvent::Presence(presence.clone())); + } + ServerMsg::ChatEvent { message, .. } => { + let _ = events.send(GatewayEvent::Chat(message)); + } + ServerMsg::Error { code, message } => { + let _ = events.send(GatewayEvent::Error(format!("{code:?}: {message}"))); + if matches!( + code, + tsc_gateway_proto::ErrorCode::AuthFailed + | tsc_gateway_proto::ErrorCode::UnknownIdentity + | tsc_gateway_proto::ErrorCode::LevelTooLow + | tsc_gateway_proto::ErrorCode::Banned + ) { + anyhow::bail!("gateway refused login: {message}"); + } + } + _ => {} + } + } + cmd = commands.recv() => match cmd { + None | Some(GatewayCmd::Stop) => return Ok(()), + Some(GatewayCmd::OpenChat(target)) => send!(ClientMsg::OpenChat { target }), + Some(GatewayCmd::CloseChat(target)) => send!(ClientMsg::CloseChat { target }), + Some(GatewayCmd::SendChat(target, text)) => send!(ClientMsg::SendChat { target, text }), + }, + } + } +} diff --git a/crates/tsc-core/src/lib.rs b/crates/tsc-core/src/lib.rs new file mode 100644 index 0000000..c9a155f --- /dev/null +++ b/crates/tsc-core/src/lib.rs @@ -0,0 +1,222 @@ +//! The client engine. +//! +//! The UI talks to an [`Engine`] with [`Command`]s and receives [`Event`]s. +//! Each server the user works with is a session with up to three sources: +//! +//! - **voice**: a normal client connection (visible, can talk) +//! - **gateway**: a `tsgw` gateway (invisible presence, relayed chat) +//! - **query**: the user's own ServerQuery credentials (same, without a gateway) +//! +//! Presence comes from the most authoritative connected source +//! (voice > gateway > query). Channel chat goes through the voice connection +//! when the user is in that channel, otherwise through a relay. + +mod audio; +mod gateway; +mod query; +mod route; +mod session; +mod voice; + +use std::collections::HashMap; +use std::sync::Arc; + +use tokio::sync::{broadcast, mpsc}; +use tsc_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor}; + +pub use route::{ChatRoute, Dedup, route_chat}; +pub use voice::VoiceOptions; + +pub type SessionId = u64; + +/// What the UI asks for. +#[derive(Clone, Debug)] +pub enum Command { + ConnectVoice { + session: SessionId, + options: Box, + }, + DisconnectVoice { + session: SessionId, + }, + /// Invisible presence and relay chat through a `tsgw` gateway. + ObserveGateway { + session: SessionId, + url: String, + identity: Box, + }, + /// Invisible presence and relay chat with own ServerQuery credentials. + ObserveQuery { + session: SessionId, + connect: Box, + }, + StopObserving { + session: SessionId, + }, + OpenChat { + session: SessionId, + target: ChatTarget, + }, + CloseChat { + session: SessionId, + target: ChatTarget, + }, + SendChat { + session: SessionId, + target: ChatTarget, + text: String, + }, + MoveToChannel { + session: SessionId, + channel: ChannelId, + password: Option, + }, + SetInputMuted { + session: SessionId, + muted: bool, + }, + SetOutputMuted { + session: SessionId, + muted: bool, + }, + /// Push-to-talk state (or "always transmit" when voice activation is off). + SetTransmitting { + session: SessionId, + on: bool, + }, + /// Close everything of a session. + CloseSession { + session: SessionId, + }, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum VoiceState { + #[default] + Disconnected, + Connecting, + Connected, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ObserveState { + #[default] + Off, + Connecting, + /// Invisible presence is live. + Observing, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Source { + Voice, + Gateway, + Query, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SessionState { + pub voice: VoiceState, + pub observe: ObserveState, + /// Where presence currently comes from. + pub presence_source: Option, + /// Our own channel while voice-connected. + pub own_channel: Option, + pub input_muted: bool, + pub output_muted: bool, + pub transmitting: bool, +} + +/// What the engine reports. +#[derive(Clone, Debug)] +pub enum Event { + State { + session: SessionId, + state: SessionState, + }, + ServerInfo { + session: SessionId, + name: String, + flavor: ServerFlavor, + capabilities: Capabilities, + }, + /// Full presence of the session (the UI rebuilds its view from it). + Presence { + session: SessionId, + presence: Arc, + }, + Chat { + session: SessionId, + message: ChatMessage, + }, + /// A client in the session started or stopped talking (voice only). + Talking { + session: SessionId, + client: u16, + talking: bool, + }, + Error { + session: SessionId, + message: String, + }, +} + +/// Handle to the engine. Cheap to clone; all methods are non-blocking. +#[derive(Clone)] +pub struct Engine { + commands: mpsc::UnboundedSender, + events: broadcast::Sender, +} + +impl Engine { + /// Start the engine on the current tokio runtime. + pub fn start() -> Self { + let (commands, rx) = mpsc::unbounded_channel(); + let (events, _) = broadcast::channel(4096); + tokio::spawn(run(rx, events.clone())); + Self { commands, events } + } + + pub fn send(&self, command: Command) { + let _ = self.commands.send(command); + } + + pub fn subscribe(&self) -> broadcast::Receiver { + self.events.subscribe() + } +} + +async fn run(mut commands: mpsc::UnboundedReceiver, events: broadcast::Sender) { + let mut sessions: HashMap = HashMap::new(); + while let Some(command) = commands.recv().await { + let id = command_session(&command); + if matches!(command, Command::CloseSession { .. }) { + if let Some(s) = sessions.remove(&id) { + s.send(command); + } + continue; + } + sessions + .entry(id) + .or_insert_with(|| session::SessionHandle::spawn(id, events.clone())) + .send(command); + } +} + +fn command_session(command: &Command) -> SessionId { + match command { + Command::ConnectVoice { session, .. } + | Command::DisconnectVoice { session } + | Command::ObserveGateway { session, .. } + | Command::ObserveQuery { session, .. } + | Command::StopObserving { session } + | Command::OpenChat { session, .. } + | Command::CloseChat { session, .. } + | Command::SendChat { session, .. } + | Command::MoveToChannel { session, .. } + | Command::SetInputMuted { session, .. } + | Command::SetOutputMuted { session, .. } + | Command::SetTransmitting { session, .. } + | Command::CloseSession { session } => *session, + } +} diff --git a/crates/tsc-core/src/query.rs b/crates/tsc-core/src/query.rs new file mode 100644 index 0000000..bee41e0 --- /dev/null +++ b/crates/tsc-core/src/query.rs @@ -0,0 +1,88 @@ +//! The query source: own ServerQuery credentials, in-process observer and relays. + +use tokio::sync::{broadcast, mpsc}; +use tsc_model::{ChatMessage, ChatTarget, Presence}; +use tsc_observer::{Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool}; + +pub(crate) enum QueryCmd { + OpenChat(ChatTarget), + CloseChat(ChatTarget), + SendChat { target: ChatTarget, nick: String, text: String }, + Stop, +} + +pub(crate) enum QueryEvent { + Presence(Presence), + Chat(ChatMessage), + Error(String), + Disconnected, +} + +pub(crate) async fn run( + connect: tsc_query::Connect, + mut commands: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, +) { + let observer = Observer::spawn(ObserverConfig::new(connect.clone())); + let relays = RelayPool::new(RelayConfig::new(connect)); + let mut observed = observer.subscribe(); + let mut relayed = relays.subscribe(); + let mut open = std::collections::HashSet::new(); + loop { + tokio::select! { + e = observed.recv() => match e { + Ok(ObserverEvent::Snapshot(_)) | Ok(ObserverEvent::Delta(_)) | Err(broadcast::error::RecvError::Lagged(_)) => { + let presence = observer.presence().read().unwrap().clone(); + let _ = events.send(QueryEvent::Presence(presence)); + } + Ok(ObserverEvent::Chat(msg)) => { + if open.contains(&msg.target) { + let _ = events.send(QueryEvent::Chat(msg)); + } + } + Ok(ObserverEvent::Disconnected(reason)) => { + let _ = events.send(QueryEvent::Error(format!("query connection lost: {reason}"))); + } + Err(broadcast::error::RecvError::Closed) => break, + }, + e = relayed.recv() => match e { + Ok(RelayEvent::Message(msg)) => { + let _ = events.send(QueryEvent::Chat(msg)); + } + Ok(RelayEvent::Closed { channel, reason }) => { + let _ = events.send(QueryEvent::Error(format!("relay for channel {channel} closed: {reason}"))); + } + Err(_) => {} + }, + cmd = commands.recv() => match cmd { + None | Some(QueryCmd::Stop) => break, + Some(QueryCmd::OpenChat(target)) => { + if let ChatTarget::Channel(cid) = target + && let Err(e) = relays.open(cid).await + { + let _ = events.send(QueryEvent::Error(e.to_string())); + continue; + } + open.insert(target); + } + Some(QueryCmd::CloseChat(target)) => { + if let ChatTarget::Channel(cid) = target { + relays.close(cid).await; + } + open.remove(&target); + } + Some(QueryCmd::SendChat { target, nick, text }) => { + let result = match &target { + ChatTarget::Channel(cid) => relays.send(*cid, &nick, &text).await, + _ => Err(tsc_query::Error::Unsupported("only channel chat is relayed with own credentials")), + }; + if let Err(e) = result { + let _ = events.send(QueryEvent::Error(e.to_string())); + } + } + }, + } + } + relays.close_all().await; + let _ = events.send(QueryEvent::Disconnected); +} diff --git a/crates/tsc-core/src/route.rs b/crates/tsc-core/src/route.rs new file mode 100644 index 0000000..9531204 --- /dev/null +++ b/crates/tsc-core/src/route.rs @@ -0,0 +1,121 @@ +//! Chat routing and duplicate suppression. + +use std::collections::VecDeque; + +use tsc_model::{ChannelId, ChatMessage, ChatTarget}; + +/// Which source carries a chat. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ChatRoute { + Voice, + Gateway, + Query, + Unavailable(&'static str), +} + +/// Pick the source for reading/writing `target`. +/// +/// The voice connection can only use the channel chat of its own channel; +/// other channels need a relay (gateway first, then own query credentials). +pub fn route_chat( + target: &ChatTarget, + voice_channel: Option, + gateway: bool, + query: bool, +) -> ChatRoute { + match target { + ChatTarget::Server | ChatTarget::Private(_) if voice_channel.is_some() => ChatRoute::Voice, + ChatTarget::Channel(cid) if voice_channel == Some(*cid) => ChatRoute::Voice, + ChatTarget::Private(_) => ChatRoute::Unavailable("private chat needs a voice connection"), + _ if gateway => ChatRoute::Gateway, + _ if query => ChatRoute::Query, + ChatTarget::Channel(_) => ChatRoute::Unavailable( + "join the channel, or use a gateway or query credentials to chat without joining", + ), + ChatTarget::Server => ChatRoute::Unavailable("not connected"), + } +} + +/// Drops the second copy of a message that arrives through two sources +/// (e.g. voice and a gateway relay during a switch-over). +#[derive(Default)] +pub struct Dedup { + recent: VecDeque<(ChatTarget, String, String, i64)>, +} + +impl Dedup { + const WINDOW_MS: i64 = 2000; + + /// `true` if an equal message was seen within two seconds. + pub fn is_duplicate(&mut self, msg: &ChatMessage) -> bool { + while self.recent.front().is_some_and(|m| msg.ts_ms - m.3 > Self::WINDOW_MS * 2) { + self.recent.pop_front(); + } + // Relays post as "[nick] text"; compare the plain text. + let text = strip_relay_prefix(&msg.text).to_string(); + let dup = self.recent.iter().any(|(t, a, x, ts)| { + *t == msg.target + && *a == msg.author_name + && *x == text + && (msg.ts_ms - ts).abs() <= Self::WINDOW_MS + }); + if !dup { + self.recent.push_back((msg.target.clone(), msg.author_name.clone(), text, msg.ts_ms)); + if self.recent.len() > 256 { + self.recent.pop_front(); + } + } + dup + } +} + +fn strip_relay_prefix(text: &str) -> &str { + if let Some(rest) = text.strip_prefix('[') + && let Some((_, after)) = rest.split_once("] ") + { + return after; + } + text +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn routes() { + let ch = ChatTarget::Channel; + assert_eq!(route_chat(&ch(1), Some(1), true, true), ChatRoute::Voice); + assert_eq!(route_chat(&ch(2), Some(1), true, true), ChatRoute::Gateway); + assert_eq!(route_chat(&ch(2), Some(1), false, true), ChatRoute::Query); + assert!(matches!(route_chat(&ch(2), Some(1), false, false), ChatRoute::Unavailable(_))); + assert_eq!(route_chat(&ChatTarget::Server, Some(1), true, false), ChatRoute::Voice); + assert_eq!(route_chat(&ChatTarget::Server, None, true, false), ChatRoute::Gateway); + assert!(matches!( + route_chat(&ChatTarget::Private("u".into()), None, true, true), + ChatRoute::Unavailable(_) + )); + } + + fn msg(author: &str, text: &str, ts_ms: i64) -> ChatMessage { + ChatMessage { + target: ChatTarget::Channel(1), + author_name: author.into(), + author_uid: None, + author_id: None, + text: text.into(), + ts_ms, + via_relay: false, + } + } + + #[test] + fn dedup_window() { + let mut d = Dedup::default(); + assert!(!d.is_duplicate(&msg("a", "hi", 1000))); + assert!(d.is_duplicate(&msg("a", "hi", 1500))); + assert!(d.is_duplicate(&msg("a", "[a] hi", 1600))); + assert!(!d.is_duplicate(&msg("b", "hi", 1600))); + assert!(!d.is_duplicate(&msg("a", "hi", 9000))); + } +} diff --git a/crates/tsc-core/src/session.rs b/crates/tsc-core/src/session.rs new file mode 100644 index 0000000..bcb638c --- /dev/null +++ b/crates/tsc-core/src/session.rs @@ -0,0 +1,452 @@ +//! One server session: merges its sources and routes commands. + +use std::collections::HashSet; +use std::sync::Arc; + +use tokio::sync::{broadcast, mpsc}; +use tracing::debug; +use tsc_model::{ChatMessage, ChatTarget, Presence}; + +use crate::audio::{self, AudioHandle, AudioIn}; +use crate::gateway::{self, GatewayCmd, GatewayEvent}; +use crate::query::{self, QueryCmd, QueryEvent}; +use crate::route::{ChatRoute, Dedup, route_chat}; +use crate::voice::{self, VoiceCmd, VoiceEvent}; +use crate::{Command, Event, ObserveState, SessionId, SessionState, Source, VoiceState}; + +pub(crate) struct SessionHandle { + tx: mpsc::UnboundedSender, +} + +impl SessionHandle { + pub fn spawn(id: SessionId, events: broadcast::Sender) -> Self { + let (tx, rx) = mpsc::unbounded_channel(); + tokio::spawn(Session::new(id, events).run(rx)); + Self { tx } + } + + pub fn send(&self, command: Command) { + let _ = self.tx.send(command); + } +} + +/// Events from sources, tagged with the generation of the source so events +/// of a replaced source are ignored. +enum SourceEvent { + Voice(u64, VoiceEvent), + Gateway(u64, GatewayEvent), + Query(u64, QueryEvent), + AudioOut(u64, tsproto_packets::packets::OutPacket), + AudioError(String), +} + +struct Session { + id: SessionId, + events: broadcast::Sender, + state: SessionState, + generation: u64, + voice: Option<(u64, mpsc::UnboundedSender)>, + voice_presence: Option, + nickname: String, + gateway: Option<(u64, mpsc::UnboundedSender)>, + gateway_presence: Option, + query: Option<(u64, mpsc::UnboundedSender)>, + query_presence: Option, + audio: Option, + open_chats: HashSet, + dedup: Dedup, + sources_tx: mpsc::UnboundedSender, + sources_rx: Option>, +} + +impl Session { + fn new(id: SessionId, events: broadcast::Sender) -> Self { + let (sources_tx, sources_rx) = mpsc::unbounded_channel(); + Self { + id, + events, + state: SessionState::default(), + generation: 0, + voice: None, + voice_presence: None, + nickname: String::new(), + gateway: None, + gateway_presence: None, + query: None, + query_presence: None, + audio: None, + open_chats: HashSet::new(), + dedup: Dedup::default(), + sources_tx, + sources_rx: Some(sources_rx), + } + } + + fn emit(&self, event: Event) { + let _ = self.events.send(event); + } + + fn error(&self, message: impl Into) { + self.emit(Event::Error { session: self.id, message: message.into() }); + } + + fn emit_state(&self) { + self.emit(Event::State { session: self.id, state: self.state.clone() }); + } + + async fn run(mut self, mut commands: mpsc::UnboundedReceiver) { + let mut sources = self.sources_rx.take().expect("receiver"); + loop { + tokio::select! { + cmd = commands.recv() => match cmd { + None | Some(Command::CloseSession { .. }) => break, + Some(cmd) => self.command(cmd), + }, + Some(event) = sources.recv() => self.source_event(event), + } + } + self.stop_all(); + } + + fn next_generation(&mut self) -> u64 { + self.generation += 1; + self.generation + } + + /// Spawn a task that forwards a source's events, tagged. + fn forward( + &self, + mut rx: mpsc::UnboundedReceiver, + wrap: impl Fn(E) -> SourceEvent + Send + 'static, + ) { + let tx = self.sources_tx.clone(); + tokio::spawn(async move { + while let Some(e) = rx.recv().await { + if tx.send(wrap(e)).is_err() { + break; + } + } + }); + } + + fn command(&mut self, cmd: Command) { + match cmd { + Command::ConnectVoice { options, .. } => { + if let Some((_, tx)) = self.voice.take() { + let _ = tx.send(VoiceCmd::Disconnect); + } + let generation = self.next_generation(); + self.nickname = options.nickname.clone(); + let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); + let (ev_tx, ev_rx) = mpsc::unbounded_channel(); + if options.audio { + let (out_tx, out_rx) = mpsc::unbounded_channel(); + let (err_tx, err_rx) = mpsc::unbounded_channel(); + self.audio = Some(audio::spawn(out_tx, err_tx, false)); + self.forward(out_rx, move |p| SourceEvent::AudioOut(generation, p)); + self.forward(err_rx, SourceEvent::AudioError); + } + tokio::spawn(voice::run(*options, cmd_rx, ev_tx)); + self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e)); + self.voice = Some((generation, cmd_tx)); + self.state.voice = VoiceState::Connecting; + self.emit_state(); + } + Command::DisconnectVoice { .. } => { + if let Some((_, tx)) = &self.voice { + let _ = tx.send(VoiceCmd::Disconnect); + } + } + Command::ObserveGateway { url, identity, .. } => { + self.stop_observing(); + let generation = self.next_generation(); + let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); + let (ev_tx, ev_rx) = mpsc::unbounded_channel(); + tokio::spawn(gateway::run(url, *identity, cmd_rx, ev_tx)); + self.forward(ev_rx, move |e| SourceEvent::Gateway(generation, e)); + self.gateway = Some((generation, cmd_tx)); + self.state.observe = ObserveState::Connecting; + self.emit_state(); + self.reopen_relayed_chats(); + } + Command::ObserveQuery { connect, .. } => { + self.stop_observing(); + let generation = self.next_generation(); + let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); + let (ev_tx, ev_rx) = mpsc::unbounded_channel(); + tokio::spawn(query::run(*connect, cmd_rx, ev_tx)); + self.forward(ev_rx, move |e| SourceEvent::Query(generation, e)); + self.query = Some((generation, cmd_tx)); + self.state.observe = ObserveState::Connecting; + self.emit_state(); + self.reopen_relayed_chats(); + } + Command::StopObserving { .. } => { + self.stop_observing(); + self.publish_presence(); + } + Command::OpenChat { target, .. } => { + self.open_chats.insert(target.clone()); + self.open_relay(&target); + } + Command::CloseChat { target, .. } => { + self.open_chats.remove(&target); + if let Some((_, tx)) = &self.gateway { + let _ = tx.send(GatewayCmd::CloseChat(target.clone())); + } + if let Some((_, tx)) = &self.query { + let _ = tx.send(QueryCmd::CloseChat(target)); + } + } + Command::SendChat { target, text, .. } => match self.route(&target) { + ChatRoute::Voice => self.voice_cmd(VoiceCmd::SendChat(target, text)), + ChatRoute::Gateway => { + if let Some((_, tx)) = &self.gateway { + let _ = tx.send(GatewayCmd::SendChat(target, text)); + } + } + ChatRoute::Query => { + if let Some((_, tx)) = &self.query { + let nick = if self.nickname.is_empty() { + "user".into() + } else { + self.nickname.clone() + }; + let _ = tx.send(QueryCmd::SendChat { target, nick, text }); + } + } + ChatRoute::Unavailable(reason) => self.error(reason), + }, + Command::MoveToChannel { channel, password, .. } => { + self.voice_cmd(VoiceCmd::Move(channel, password)); + } + Command::SetInputMuted { muted, .. } => { + self.state.input_muted = muted; + self.voice_cmd(VoiceCmd::SetInputMuted(muted)); + if let Some(a) = &self.audio { + a.send(AudioIn::InputMuted(muted)); + } + self.emit_state(); + } + Command::SetOutputMuted { muted, .. } => { + self.state.output_muted = muted; + self.voice_cmd(VoiceCmd::SetOutputMuted(muted)); + if let Some(a) = &self.audio { + a.send(AudioIn::OutputMuted(muted)); + } + self.emit_state(); + } + Command::SetTransmitting { on, .. } => { + self.state.transmitting = on; + if let Some(a) = &self.audio { + a.send(AudioIn::Transmit(on)); + } + self.emit_state(); + } + Command::CloseSession { .. } => {} + } + } + + fn voice_cmd(&self, cmd: VoiceCmd) { + match &self.voice { + Some((_, tx)) => { + let _ = tx.send(cmd); + } + None => self.error("not connected with voice"), + } + } + + fn route(&self, target: &ChatTarget) -> ChatRoute { + let voice_channel = + if self.state.voice == VoiceState::Connected { self.state.own_channel } else { None }; + route_chat(target, voice_channel, self.gateway.is_some(), self.query.is_some()) + } + + /// Chats that are not covered by the voice connection need a relay. + fn open_relay(&self, target: &ChatTarget) { + match self.route(target) { + ChatRoute::Gateway => { + if let Some((_, tx)) = &self.gateway { + let _ = tx.send(GatewayCmd::OpenChat(target.clone())); + } + } + ChatRoute::Query => { + if let Some((_, tx)) = &self.query { + let _ = tx.send(QueryCmd::OpenChat(target.clone())); + } + } + _ => {} + } + } + + fn reopen_relayed_chats(&self) { + for target in &self.open_chats { + self.open_relay(target); + } + } + + fn stop_observing(&mut self) { + if let Some((_, tx)) = self.gateway.take() { + let _ = tx.send(GatewayCmd::Stop); + } + if let Some((_, tx)) = self.query.take() { + let _ = tx.send(QueryCmd::Stop); + } + self.gateway_presence = None; + self.query_presence = None; + self.state.observe = ObserveState::Off; + self.emit_state(); + } + + fn stop_all(&mut self) { + if let Some((_, tx)) = self.voice.take() { + let _ = tx.send(VoiceCmd::Disconnect); + } + self.audio = None; + self.stop_observing(); + } + + fn is_current(&self, source: Source, generation: u64) -> bool { + let current = match source { + Source::Voice => self.voice.as_ref().map(|(g, _)| *g), + Source::Gateway => self.gateway.as_ref().map(|(g, _)| *g), + Source::Query => self.query.as_ref().map(|(g, _)| *g), + }; + current == Some(generation) + } + + fn source_event(&mut self, event: SourceEvent) { + match event { + SourceEvent::Voice(g, e) if self.is_current(Source::Voice, g) => self.voice_event(e), + SourceEvent::Gateway(g, e) if self.is_current(Source::Gateway, g) => { + self.gateway_event(e) + } + SourceEvent::Query(g, e) if self.is_current(Source::Query, g) => self.query_event(e), + SourceEvent::AudioOut(g, packet) if self.is_current(Source::Voice, g) => { + if let Some((_, tx)) = &self.voice { + let _ = tx.send(VoiceCmd::Audio(packet)); + } + } + SourceEvent::AudioError(message) => self.error(message), + _ => debug!("event from a replaced source ignored"), + } + } + + fn voice_event(&mut self, e: VoiceEvent) { + match e { + VoiceEvent::Connected { name, flavor } => { + self.state.voice = VoiceState::Connected; + self.emit_state(); + let capabilities = flavor.capabilities(); + self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities }); + self.reopen_relayed_chats(); + } + VoiceEvent::Presence(p) => { + self.voice_presence = Some(p); + self.publish_presence(); + } + VoiceEvent::OwnChannel(cid) => { + if self.state.own_channel != Some(cid) { + self.state.own_channel = Some(cid); + self.emit_state(); + } + } + VoiceEvent::Chat(msg) => self.chat(msg), + VoiceEvent::Audio(packet) => { + if let Some(a) = &self.audio { + a.send(AudioIn::Packet(packet)); + } + } + VoiceEvent::Talking { client, talking } => { + self.emit(Event::Talking { session: self.id, client, talking }); + } + VoiceEvent::Disconnected(reason) => { + self.voice = None; + self.voice_presence = None; + self.audio = None; + self.state.voice = VoiceState::Disconnected; + self.state.own_channel = None; + self.emit_state(); + if let Some(reason) = reason { + self.error(format!("voice: {reason}")); + } + self.publish_presence(); + } + } + } + + fn gateway_event(&mut self, e: GatewayEvent) { + match e { + GatewayEvent::Connected => { + self.state.observe = ObserveState::Observing; + self.emit_state(); + } + GatewayEvent::Presence(p) => { + self.gateway_presence = Some(p); + self.publish_presence(); + } + GatewayEvent::Chat(msg) => self.chat(msg), + GatewayEvent::Error(message) => self.error(format!("gateway: {message}")), + GatewayEvent::Disconnected(reason) => { + self.gateway = None; + self.gateway_presence = None; + self.state.observe = ObserveState::Off; + self.emit_state(); + if let Some(reason) = reason { + self.error(format!("gateway: {reason}")); + } + self.publish_presence(); + } + } + } + + fn query_event(&mut self, e: QueryEvent) { + match e { + QueryEvent::Presence(p) => { + if self.state.observe != ObserveState::Observing { + self.state.observe = ObserveState::Observing; + self.emit_state(); + } + self.query_presence = Some(p); + self.publish_presence(); + } + QueryEvent::Chat(msg) => self.chat(msg), + QueryEvent::Error(message) => self.error(format!("query: {message}")), + QueryEvent::Disconnected => { + self.query = None; + self.query_presence = None; + self.state.observe = ObserveState::Off; + self.emit_state(); + self.publish_presence(); + } + } + } + + fn chat(&mut self, msg: ChatMessage) { + let wanted = match &msg.target { + ChatTarget::Server | ChatTarget::Private(_) => true, + target => self.open_chats.contains(target) || !msg.via_relay, + }; + if wanted && !self.dedup.is_duplicate(&msg) { + self.emit(Event::Chat { session: self.id, message: msg }); + } + } + + /// Publish the presence of the most authoritative source. + fn publish_presence(&mut self) { + let (source, presence) = if let Some(p) = &self.voice_presence { + (Some(Source::Voice), p.clone()) + } else if let Some(p) = &self.gateway_presence { + (Some(Source::Gateway), p.clone()) + } else if let Some(p) = &self.query_presence { + (Some(Source::Query), p.clone()) + } else { + (None, Presence::default()) + }; + if self.state.presence_source != source { + self.state.presence_source = source; + self.emit_state(); + } + self.emit(Event::Presence { session: self.id, presence: Arc::new(presence) }); + } +} diff --git a/crates/tsc-core/src/voice.rs b/crates/tsc-core/src/voice.rs new file mode 100644 index 0000000..7b848c2 --- /dev/null +++ b/crates/tsc-core/src/voice.rs @@ -0,0 +1,342 @@ +//! The voice source: a normal client connection. + +use std::time::Duration; + +use futures::prelude::*; +use tokio::sync::mpsc; +use tokio::time::{Instant, timeout}; +use tracing::{info, warn}; +use tsc_model::{ + ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerFlavor, +}; +use tsclientlib::data; +use tsclientlib::events::Event as BookEvent; +use tsclientlib::prelude::*; +use tsclientlib::{ + ClientType, Connection, DisconnectOptions, Identity, MaxClients, MessageTarget, StreamItem, + Version, +}; +use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket}; + +#[derive(Clone, Debug)] +pub struct VoiceOptions { + pub address: String, + pub nickname: String, + pub identity: Option, + /// Signed client version; `None` for the library default. + pub client_version: Option, + pub server_password: Option, + /// Channel path to join, e.g. `Lobby/Sub`. + pub channel: Option, + /// Open the audio devices (capture and playback). + pub audio: bool, +} + +impl VoiceOptions { + pub fn new(address: impl Into, nickname: impl Into) -> Self { + Self { + address: address.into(), + nickname: nickname.into(), + identity: None, + client_version: None, + server_password: None, + channel: None, + audio: false, + } + } +} + +pub(crate) enum VoiceCmd { + SendChat(ChatTarget, String), + Move(ChannelId, Option), + SetInputMuted(bool), + SetOutputMuted(bool), + /// An encoded voice packet from the audio thread. + Audio(OutPacket), + Disconnect, +} + +pub(crate) enum VoiceEvent { + Connected { + name: String, + flavor: ServerFlavor, + }, + Presence(Presence), + OwnChannel(ChannelId), + Chat(ChatMessage), + /// Incoming voice for the audio thread, and who is talking. + Audio(InAudioBuf), + Talking { + client: u16, + talking: bool, + }, + Disconnected(Option), +} + +/// The presence visible through a voice connection. +pub(crate) fn presence_from_book(book: &data::Connection) -> Presence { + let limit = |m: &Option| match m { + Some(MaxClients::Limited(n)) => Some(*n as i32), + _ => None, + }; + Presence { + server_name: book.server.name.clone(), + channels: book + .channels + .values() + .map(|c| { + ( + c.id.0, + ChannelInfo { + id: c.id.0, + parent: c.parent.0, + order: c.order.0, + name: c.name.clone(), + topic: c.topic.clone().filter(|t| !t.is_empty()), + has_password: c.has_password.unwrap_or(false), + max_clients: limit(&c.max_clients), + needed_subscribe_power: 0, + needed_talk_power: c.needed_talk_power.unwrap_or(0), + is_default: c.is_default.unwrap_or(false), + }, + ) + }) + .collect(), + clients: book + .clients + .values() + .map(|c| { + ( + c.id.0, + ClientInfo { + id: c.id.0, + uid: c.uid.as_ref().map(|u| u.as_ref().to_string()), + nickname: c.name.clone(), + channel: c.channel.0, + is_query: matches!(c.client_type, ClientType::Query { .. }), + away: c.away_message.clone(), + input_muted: c.input_muted, + output_muted: c.output_muted, + talking: None, + streaming: c.is_streaming, + server_groups: c.server_groups.iter().map(|g| g.0).collect(), + country: Some(c.country_code.clone()).filter(|c| !c.is_empty()), + }, + ) + }) + .collect(), + } +} + +fn now_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or_default() +} + +enum Input { + Item(Option>), + Cmd(Option), + Tick, +} + +/// Run a voice connection until it ends or is told to disconnect. +pub(crate) async fn run( + options: VoiceOptions, + mut commands: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, +) { + let reason = match run_inner(&options, &mut commands, &events).await { + Ok(()) => None, + Err(e) => Some(e.to_string()), + }; + let _ = events.send(VoiceEvent::Disconnected(reason)); +} + +async fn run_inner( + options: &VoiceOptions, + commands: &mut mpsc::UnboundedReceiver, + events: &mpsc::UnboundedSender, +) -> anyhow::Result<()> { + let mut builder = Connection::build(options.address.clone()).name(options.nickname.clone()); + if let Some(identity) = &options.identity { + builder = builder.identity(identity.clone()); + } + if let Some(version) = &options.client_version { + builder = builder.version(version.clone()); + } + if let Some(pw) = &options.server_password { + builder = builder.password(pw.clone()); + } + if let Some(channel) = &options.channel { + builder = builder.channel(channel.clone()); + } + let mut con = builder.connect()?; + + // Wait for the initial state. + let connected = timeout(Duration::from_secs(30), async { + con.events() + .try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_)))) + .next() + .await + }) + .await + .map_err(|_| anyhow::anyhow!("timed out while connecting"))?; + match connected { + Some(Ok(_)) => {} + Some(Err(e)) => return Err(e.into()), + None => anyhow::bail!("connection closed"), + } + { + let state = con.get_state()?; + let flavor = ServerFlavor::from_version_string(&state.server.version); + info!(server = %state.server.name, ?flavor, "voice connected"); + let _ = events.send(VoiceEvent::Connected { name: state.server.name.clone(), flavor }); + } + // Subscribe to all channels to see everyone. + let cmd = con.get_state()?.server.set_subscribed(true); + cmd.send(&mut con)?; + publish_state(&con, events)?; + + // Who is talking: last voice packet per client. + let mut talking: std::collections::HashMap = Default::default(); + let mut tick = tokio::time::interval(Duration::from_millis(250)); + + loop { + let input = { + let mut stream = con.events(); + tokio::select! { + item = stream.next() => Input::Item(item), + cmd = commands.recv() => Input::Cmd(cmd), + _ = tick.tick() => Input::Tick, + } + }; + match input { + Input::Item(None) => anyhow::bail!("connection closed"), + Input::Item(Some(Err(e))) => return Err(e.into()), + Input::Item(Some(Ok(item))) => match item { + StreamItem::BookEvents(book_events) => { + for e in &book_events { + if let BookEvent::Message { target, invoker, message } = e { + let own_channel = own_channel(&con); + let target = match target { + MessageTarget::Server => ChatTarget::Server, + MessageTarget::Channel => { + ChatTarget::Channel(own_channel.unwrap_or(0)) + } + MessageTarget::Client(_) | MessageTarget::Poke(_) => { + ChatTarget::Private( + invoker + .uid + .as_ref() + .map(|u| u.as_ref().to_string()) + .unwrap_or_default(), + ) + } + }; + let _ = events.send(VoiceEvent::Chat(ChatMessage { + target, + author_name: invoker.name.clone(), + author_uid: invoker.uid.as_ref().map(|u| u.as_ref().to_string()), + author_id: Some(invoker.id.0), + text: message.clone(), + ts_ms: now_ms(), + via_relay: false, + })); + } + } + publish_state(&con, events)?; + } + StreamItem::Audio(packet) => { + let from = match packet.data().data() { + AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from, + _ => continue, + }; + if talking.insert(from, Instant::now()).is_none() { + let _ = events.send(VoiceEvent::Talking { client: from, talking: true }); + } + let _ = events.send(VoiceEvent::Audio(packet)); + } + StreamItem::DisconnectedTemporarily(reason) => { + warn!(?reason, "voice connection interrupted, reconnecting"); + } + _ => {} + }, + Input::Cmd(None) | Input::Cmd(Some(VoiceCmd::Disconnect)) => break, + Input::Cmd(Some(cmd)) => handle_command(&mut con, cmd)?, + Input::Tick => { + talking.retain(|client, last| { + let active = last.elapsed() < Duration::from_millis(400); + if !active { + let _ = + events.send(VoiceEvent::Talking { client: *client, talking: false }); + } + active + }); + } + } + } + + con.disconnect(DisconnectOptions::new())?; + let _ = timeout(Duration::from_secs(3), con.events().for_each(|_| future::ready(()))).await; + Ok(()) +} + +fn own_channel(con: &Connection) -> Option { + let state = con.get_state().ok()?; + state.clients.get(&state.own_client).map(|c| c.channel.0) +} + +fn publish_state( + con: &Connection, + events: &mpsc::UnboundedSender, +) -> anyhow::Result<()> { + let state = con.get_state()?; + let _ = events.send(VoiceEvent::Presence(presence_from_book(state))); + if let Some(own) = state.clients.get(&state.own_client) { + let _ = events.send(VoiceEvent::OwnChannel(own.channel.0)); + } + Ok(()) +} + +fn handle_command(con: &mut Connection, cmd: VoiceCmd) -> anyhow::Result<()> { + match cmd { + VoiceCmd::SendChat(target, text) => { + let state = con.get_state()?; + let out = match target { + ChatTarget::Server => state.server.send_textmessage(&text), + ChatTarget::Channel(_) => state.send_message(MessageTarget::Channel, &text), + ChatTarget::Private(uid) => { + let client = state + .clients + .values() + .find(|c| c.uid.as_ref().is_some_and(|u| u.as_ref().to_string() == uid)) + .ok_or_else(|| anyhow::anyhow!("client is not on the server"))?; + state.send_message(MessageTarget::Client(client.id), &text) + } + }; + out.send(con)?; + } + VoiceCmd::Move(channel, password) => { + let state = con.get_state()?; + let own = &state.clients[&state.own_client]; + let mut part = own.client_move(tsclientlib::ChannelId(channel)); + if let Some(pw) = &password { + part = part.set_password(pw); + } + part.send(con)?; + } + VoiceCmd::SetInputMuted(muted) => { + con.get_state()?.client_update().set_input_muted(muted).send(con)?; + } + VoiceCmd::SetOutputMuted(muted) => { + con.get_state()?.client_update().set_output_muted(muted).send(con)?; + } + VoiceCmd::Audio(packet) => { + con.send_audio(packet)?; + } + VoiceCmd::Disconnect => {} + } + Ok(()) +} diff --git a/crates/tsc-core/tests/live.rs b/crates/tsc-core/tests/live.rs new file mode 100644 index 0000000..73f715a --- /dev/null +++ b/crates/tsc-core/tests/live.rs @@ -0,0 +1,122 @@ +//! Engine against the development servers (dev/docker-compose.yml). +//! Runs only with `TSC_LIVE=1`; `scripts/it-smoke.sh` sets it. + +use std::time::Duration; + +use tokio::sync::broadcast::Receiver; +use tokio::time::{Instant, timeout_at}; +use tsc_core::{Command, Engine, Event, ObserveState, Source, VoiceOptions, VoiceState}; +use tsc_model::ChatTarget; + +fn live() -> bool { + std::env::var("TSC_LIVE").is_ok_and(|v| v == "1") +} + +/// Wait for an event matching `f`, failing after 20 s. +async fn wait_for( + rx: &mut Receiver, + what: &str, + mut f: impl FnMut(&Event) -> bool, +) -> Event { + let deadline = Instant::now() + Duration::from_secs(20); + loop { + match timeout_at(deadline, rx.recv()).await { + Ok(Ok(e)) if f(&e) => return e, + Ok(Ok(Event::Error { message, .. })) => eprintln!("engine error: {message}"), + Ok(_) => {} + Err(_) => panic!("timed out waiting for {what}"), + } + } +} + +async fn engine_roundtrip(voice_addr: &str, query: tsc_query::Connect) { + let engine = Engine::start(); + let mut events = engine.subscribe(); + let nick = format!("engine-{}", std::process::id() % 10_000); + + // Session 1: voice. + engine.send(Command::ConnectVoice { + session: 1, + options: Box::new(VoiceOptions::new(voice_addr, &nick)), + }); + wait_for(&mut events, "voice connected", |e| { + matches!(e, Event::State { session: 1, state } if state.voice == VoiceState::Connected && state.own_channel.is_some()) + }) + .await; + + // Session 2: invisible, through own query credentials. + engine.send(Command::ObserveQuery { session: 2, connect: Box::new(query) }); + let (mut observing, mut sees_voice_client) = (false, false); + wait_for(&mut events, "query presence with the voice client", |e| { + match e { + Event::State { session: 2, state } => { + observing = state.observe == ObserveState::Observing + && state.presence_source == Some(Source::Query); + } + Event::Presence { session: 2, presence } => { + sees_voice_client = presence.clients.values().any(|c| c.nickname == nick); + } + _ => {} + } + observing && sees_voice_client + }) + .await; + + // Channel chat: voice -> relay. + engine.send(Command::OpenChat { session: 2, target: ChatTarget::Channel(1) }); + tokio::time::sleep(Duration::from_secs(2)).await; + engine.send(Command::SendChat { + session: 1, + target: ChatTarget::Channel(1), + text: "engine-hello".into(), + }); + wait_for(&mut events, "relayed channel message", |e| { + matches!(e, Event::Chat { session: 2, message } if message.text == "engine-hello" && message.target == ChatTarget::Channel(1)) + }) + .await; + + // And back: relay -> voice. + engine.send(Command::SendChat { + session: 2, + target: ChatTarget::Channel(1), + text: "from-query".into(), + }); + wait_for( + &mut events, + "message posted by the relay", + |e| matches!(e, Event::Chat { session: 1, message } if message.text.ends_with("from-query")), + ) + .await; + + engine.send(Command::CloseSession { session: 1 }); + engine.send(Command::CloseSession { session: 2 }); + tokio::time::sleep(Duration::from_millis(500)).await; +} + +fn query(transport: tsc_query::Transport, addr: &str) -> tsc_query::Connect { + tsc_query::Connect { + transport, + addr: addr.into(), + user: "serveradmin".into(), + secret: Some("tsc-dev-admin".into()), + server_port: Some(9987), + server_id: None, + line: tsc_query::LineOptions { rate_limit: None, ..Default::default() }, + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_engine() { + if !live() { + return; + } + engine_roundtrip("127.0.0.1:9988", query(tsc_query::Transport::Ssh, "127.0.0.1:10022")).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_engine() { + if !live() { + return; + } + engine_roundtrip("127.0.0.1:9987", query(tsc_query::Transport::Raw, "127.0.0.1:10011")).await; +} diff --git a/scripts/it-smoke.sh b/scripts/it-smoke.sh index 1b0eb62..b7275f4 100755 --- a/scripts/it-smoke.sh +++ b/scripts/it-smoke.sh @@ -215,4 +215,7 @@ for svc in "${SERVERS[@]}"; do gateway_check "$svc" "$addr" done +log "engine (tsc-core) against both servers" +TSC_LIVE=1 cargo test --quiet -p tsc-core --test live 2>&1 | grep -E "test result|panicked|timed out" || fail "engine tests failed" + log "all smoke tests passed"