diff --git a/crates/voelin-core/src/files.rs b/crates/voelin-core/src/files.rs index 2587e4f..493ff74 100644 --- a/crates/voelin-core/src/files.rs +++ b/crates/voelin-core/src/files.rs @@ -106,11 +106,11 @@ impl TransferState { } /// Reports a transfer's states. -pub(crate) type Report = Arc; +pub type Report = Arc; /// Where a running download writes. #[derive(Clone, Debug)] -pub(crate) enum Sink { +pub enum Sink { /// Write `part` (appending with `append`), then rename it to `dest`. File { part: PathBuf, diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index 446333b..8cda54b 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -3,7 +3,8 @@ //! 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) +//! - **voice**: a normal client connection (visible, can talk), made by a +//! [`link::ServerLink`] ([`TsLink`] for TeamSpeak servers; see [`link`]) //! - **gateway**: a `tsgw` gateway (invisible presence, relayed chat) //! - **query**: the user's own ServerQuery credentials (same, without a gateway) //! @@ -53,6 +54,7 @@ pub mod files; pub mod gateway; pub mod history; pub mod identity; +pub mod link; #[cfg(feature = "media")] pub mod media; pub mod offline; @@ -64,6 +66,7 @@ pub mod stream; mod stream_types; #[cfg(feature = "media")] pub mod studio; +mod ts_link; pub mod versions; mod voice; mod web; @@ -88,12 +91,15 @@ pub use files::{Bytes, DownloadTo, FileEntry, RequestId, TransferId, TransferSta pub use gateway::{GatewayRequest, GatewayUpdate}; use history::SharedHistory; pub use history::{History, HistoryMessage, HistorySource}; +pub use link::ConnectOptions; +pub use link::ConnectOptions as VoiceOptions; +pub use link::ServerLink; pub use offline::{OfflineMessage, OfflineMessageInfo}; pub use route::{ChatRoute, Dedup, route_chat}; use settings::{SettingChange, Settings, SharedSettings}; use stream::{EncodedFrame, LayerId, LayerSpec, StreamInfo, StreamSetup, ViewerInfo}; pub use stream::{StreamFrame, StreamSink, StreamState, WatchState}; -pub use voice::VoiceOptions; +pub use ts_link::TsLink; /// Banners are downloaded and shown by the same rule. pub use web::is_svg; /// Pictures from the web go through the desktop's proxy (set at startup). @@ -786,8 +792,19 @@ impl Engine { } /// Start the engine on the current tokio runtime with `settings` and - /// chat `history`. + /// chat `history`, connecting voice with [`TsLink`]. pub fn start_with(settings: Settings, history: History) -> Self { + Self::start_with_link(settings, history, Arc::new(TsLink)) + } + + /// Start the engine on the current tokio runtime with `settings` and + /// chat `history`, connecting voice with `link` (every session's voice + /// source is one of its connections, see [`link`]). + pub fn start_with_link( + settings: Settings, + history: History, + link: Arc, + ) -> Self { let (commands, rx) = mpsc::unbounded_channel(); let (events, _) = broadcast::channel(4096); // About a minute of one watched stream. @@ -799,7 +816,7 @@ impl Engine { history, cache: SharedCache::new(Cache::new(Cache::default_dir())), }; - tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone())); + tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone(), link)); Self { commands, events, frames, runtime: tokio::runtime::Handle::current(), shared } } @@ -883,6 +900,7 @@ async fn run( events: broadcast::Sender, frames: broadcast::Sender, engine: Shared, + link: Arc, ) { let Shared { settings: shared, history, cache, contacts } = engine.clone(); // Before any command: a contact set meanwhile would be lost. @@ -1032,6 +1050,7 @@ async fn run( frames.clone(), settings.clone(), engine.clone(), + link.clone(), myts_identity.subscribe(), myts_data.subscribe(), ); diff --git a/crates/voelin-core/src/link.rs b/crates/voelin-core/src/link.rs new file mode 100644 index 0000000..81a06fc --- /dev/null +++ b/crates/voelin-core/src/link.rs @@ -0,0 +1,295 @@ +//! The seam between a session and the server it talks to as a client. +//! +//! A session merges up to three sources (voice, gateway, query). The *voice* +//! source is the connection that is visible on the server, can talk and +//! carries chat, files, pokes, offline messages and streams. Everything the +//! session needs from it goes through [`ServerLink`]: the session hands the +//! link the connection's options and a [`LinkCtx`], and talks to it with two +//! channels, [`LinkCmd`]s in and [`LinkEvent`]s out. Nothing else of the +//! backend shows: the session merges, deduplicates, stores and routes what a +//! link reports, whichever server software is behind it. +//! +//! # Contract for a link +//! +//! - [`ServerLink::spawn`] returns at once; the connection runs on its own +//! task and reports through `events`. Connecting is not an event: the +//! session shows `Connecting` from the moment it spawned the link, until +//! [`LinkEvent::Connected`] (or [`LinkEvent::Disconnected`] if it failed). +//! - The first thing a connected link reports is [`LinkEvent::Connected`] +//! (name, backend, what it can do, our client id, the server's unique id), +//! then [`LinkEvent::Presence`] whenever anything in the server's tree or +//! client list changed (a full snapshot each time) and +//! [`LinkEvent::OwnChannel`] when we moved. +//! - The last event is [`LinkEvent::Disconnected`], with the reason if it was +//! not asked for, whichever way the connection ended. A link that gets +//! [`LinkCmd::Disconnect`] (or whose command channel closes) leaves. +//! - Streams (screen sharing) are the link's business from the capabilities +//! on: when [`Capabilities::streams`] is set in `Connected`, it runs the +//! stream task, takes [`LinkCmd::Stream`] and reports through the event +//! bus ([`LinkCtx::emit`]) like the other answers that need not pass the +//! session first (file lists, transfers, offline messages, stream state). +//! What the session must place itself comes as events: our own stream's +//! life ([`LinkEvent::OwnStream`], for the gateway directory) and the audio +//! of watched streams ([`LinkEvent::StreamAudio`], for the audio thread). +//! - What the session must see first (chat, pokes, who is talking, audio) +//! comes as [`LinkEvent`]s; the answers to requests the UI made (a file +//! list, a request's `Done`) go straight to the event bus with +//! [`LinkCtx::emit`]. +//! - Events of a link the session replaced are ignored (each link has a +//! generation), so a link need not stop emitting at once. +//! +//! # Implementations +//! +//! [`TsLink`](crate::TsLink) (`ts_link.rs`, with `voice.rs`) is the +//! TeamSpeak 3 and 6 connection of `tsclientlib`; it is the only one for now, +//! and [`Engine::start_with_link`](crate::Engine::start_with_link) takes +//! another (the tests drive the session with an in-memory one, +//! `tests/link_fake.rs`). The decoupling plan moves `TsLink` out of this +//! crate into the TeamSpeak gateway (VoelinGateWay, `voelin-gateway-ts`), and +//! the Voelin protocol's QUIC transport becomes the other implementation, +//! both behind the backend-neutral `voelin_proto::link::Session` of +//! VoelinProtocol; `ServerLink` is this crate's side of that seam until then. +//! Two fields of the types here still carry TeamSpeak types: the identity and +//! version in [`ConnectOptions`] and the account proof in [`LinkCtx`]; they +//! leave with `TsLink`. + +use std::path::PathBuf; +use std::sync::Arc; + +use tokio::sync::{broadcast, mpsc, watch}; +use voelin_audio::{EncodedVoice, VoicePacket}; +use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence}; +use voelin_stream::PeerConfig; + +use crate::files::{Report, RequestId, Sink, TransferId}; +use crate::settings::SharedSettings; +use crate::stream::{OwnStreamEvent, StreamCmd, StreamFrame}; +use crate::{BackendInfo, Event, SessionId}; + +/// Starts the voice connection of a session. +/// +/// One link serves every session of an engine; [`spawn`](Self::spawn) starts +/// one connection. +pub trait ServerLink: Send + Sync + 'static { + /// Connect to the server `options` names and run the connection on its + /// own task: take commands from `cmds`, report through `events`, and end + /// with [`LinkEvent::Disconnected`]. Does not block. + fn spawn( + &self, + options: ConnectOptions, + ctx: LinkCtx, + cmds: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, + ); +} + +/// What a connection needs to know: the server, who to be, where to join. +/// ([`VoiceOptions`](crate::VoiceOptions) is the name the app uses for it.) +#[derive(Clone, Debug)] +pub struct ConnectOptions { + pub address: String, + pub nickname: String, + /// The identity to connect with (TeamSpeak's, for now). + pub identity: Option, + /// Signed compatibility version; `None` selects the native platform's tuple. + pub client_version: Option, + pub server_password: Option, + /// Channel path to join, e.g. `Lobby/Sub`, or `/`. + pub channel: Option, + /// The password of `channel`. + pub channel_password: Option, + /// A privilege key to use when connecting. + pub token: Option, + /// Open the audio devices (capture and playback). + pub audio: bool, + /// Network settings for stream peer connections (TeamSpeak 6). + pub stream_peer: PeerConfig, +} + +impl ConnectOptions { + 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, + channel_password: None, + token: None, + audio: false, + stream_peer: PeerConfig::default(), + } + } +} + +/// What the engine gives a link besides the options: where the connection +/// answers the requests the session need not see, and what it shares with +/// the session's other parts. +#[derive(Clone)] +pub struct LinkCtx { + pub(crate) session: SessionId, + pub(crate) events: broadcast::Sender, + /// The frames of watched streams (kept off the event bus). + pub(crate) frames: broadcast::Sender, + pub(crate) settings: SharedSettings, + /// The main account's proof, for every connection ([`crate::Command::SetMytsIdentity`]). + pub(crate) myts_identity: watch::Receiver>>, + /// What the server is shown of the account ([`crate::Command::SetMytsData`]). + pub(crate) myts_data: watch::Receiver>>, +} + +impl LinkCtx { + /// The session this connection belongs to. + pub fn session(&self) -> SessionId { + self.session + } + + /// Tell the engine's event bus something (a request's answer, a + /// transfer's progress). + pub fn emit(&self, event: Event) { + let _ = self.events.send(event); + } + + pub(crate) fn done(&self, request: RequestId, result: Result<(), String>) { + self.emit(Event::RequestDone { session: self.session, request, result }); + } +} + +/// A file on the server: channel, its password, path. +#[derive(Clone, Debug)] +pub struct Remote { + pub channel: ChannelId, + pub password: Option, + pub path: String, +} + +/// What the session asks of a connection. +pub enum LinkCmd { + SendChat(ChatTarget, String), + Move(ChannelId, Option), + SetInputMuted(bool), + SetOutputMuted(bool), + /// An encoded voice frame from the audio thread. + Audio(EncodedVoice), + /// A stream command; the link answers on the event bus. Only sent while + /// the connection's capabilities include streams. + Stream(StreamCmd), + Poke { + client: u16, + message: String, + }, + ListFiles { + request: RequestId, + dir: Remote, + }, + /// Download `file`; `transfer` if the user can cancel it. + Download { + transfer: Option, + file: Remote, + sink: Sink, + report: Report, + }, + Upload { + transfer: Option, + file: Remote, + from: PathBuf, + overwrite: bool, + resume: bool, + report: Report, + }, + CancelTransfer(TransferId), + DeleteFiles { + /// `None`: best effort, nobody waits for the answer. + request: Option, + channel: ChannelId, + password: Option, + paths: Vec, + }, + RenameFile { + request: RequestId, + from: Remote, + to: Remote, + }, + CreateDirectory { + request: RequestId, + dir: Remote, + }, + /// Announce our avatar's hash (empty: no avatar). + SetAvatarHash { + request: Option, + hash: String, + }, + OfflineList { + request: RequestId, + }, + OfflineGet { + request: RequestId, + id: u32, + }, + OfflineAdd { + request: RequestId, + to_uid: String, + subject: String, + text: String, + }, + OfflineDelete { + request: RequestId, + id: u32, + }, + OfflineFlag { + request: RequestId, + id: u32, + read: bool, + }, + Disconnect, +} + +/// What a connection tells the session. +pub enum LinkEvent { + Connected { + name: String, + /// The server software, and what it can do (the connection knows + /// both from the server's version). + backend: BackendInfo, + capabilities: Capabilities, + own_client: u16, + /// The server's unique id. + server_uid: String, + /// Our unique id as the server knows it. + own_uid: Option, + }, + /// The server's channels and clients as they are now. + Presence(Box), + OwnChannel(ChannelId), + Chat(ChatMessage), + Poke { + from: u16, + from_uid: Option, + from_name: String, + message: String, + }, + /// Incoming voice for the audio thread. + Audio(VoicePacket), + /// Who is talking (on, and off again when it stopped). + Talking { + client: u16, + talking: bool, + }, + /// Our own stream's life, for the gateway directory. + OwnStream(OwnStreamEvent), + /// An Opus frame (48 kHz) of a watched stream, for the audio thread + /// ([`ConnectOptions::audio`]); `time` is its RTP time on the 48 kHz + /// clock. + StreamAudio { + stream: String, + time: u64, + data: Arc<[u8]>, + }, + /// A watched stream ended: its audio leaves the mixer. + StreamAudioEnded(String), + /// A command failed (the connection stays). + Error(String), + /// The connection ended; the reason if it was not asked for. The last event. + Disconnected(Option), +} diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index c6f782d..5658df9 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -19,7 +19,6 @@ use tracing::{debug, info, warn}; use voelin_audio::{AudioSettings, EncodedVoice, TalkerId}; use voelin_gateway_proto::{ErrorCode, HistoryEntry, StreamEntry, StreamSpec, feature}; use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails, badges}; -use voelin_stream::ClientState; use crate::audio::{self, AudioEvent, AudioHandle, AudioIn}; use crate::cache::{self, Fetch, FetchError, RetryHint, SharedCache, Waiter}; @@ -30,6 +29,7 @@ use crate::gateway::{ Push, ReactionPush, }; use crate::history::{self, ChatCtx, HistoryMessage, MessageSource, SharedHistory}; +use crate::link::{LinkCmd, LinkCtx, LinkEvent, Remote, ServerLink}; use crate::query::{self, QueryCmd, QueryEvent}; use crate::route::{ChatRoute, Dedup, route_chat}; use crate::settings::{ @@ -37,10 +37,9 @@ use crate::settings::{ PRIVACY_PRIVATE_MESSAGES, SharedSettings, }; use crate::stream::{ - LayerSpec, OwnStreamEvent, PeerConfig, StreamFrame, StreamHandle, StreamInfo, StreamInput, - StreamKind, kind_name, parse_kind, parse_srtp_profiles, + LayerSpec, OwnStreamEvent, StreamCmd, StreamFrame, StreamInfo, StreamKind, kind_name, + parse_kind, parse_srtp_profiles, }; -use crate::voice::{self, Remote, VoiceCmd, VoiceEvent, VoiceLink}; use crate::web; use crate::{Command, Event, ObserveState, SessionId, SessionState, Shared, Source, VoiceState}; @@ -79,19 +78,30 @@ pub(crate) struct SessionHandle { } impl SessionHandle { + #[allow(clippy::too_many_arguments)] // what the engine hands each session pub fn spawn( id: SessionId, events: broadcast::Sender, frames: broadcast::Sender, audio_settings: AudioSettings, shared: Shared, + link: Arc, myts_identity: watch::Receiver>>, myts_data: watch::Receiver>>, ) -> Self { let (tx, rx) = mpsc::unbounded_channel(); tokio::spawn( - Session::new(id, events, frames, audio_settings, shared, myts_identity, myts_data) - .run(rx), + Session::new( + id, + events, + frames, + audio_settings, + shared, + link, + myts_identity, + myts_data, + ) + .run(rx), ); Self { tx } } @@ -104,13 +114,11 @@ impl SessionHandle { /// Events from sources, tagged with the generation of the source so events /// of a replaced source are ignored. enum SourceEvent { - Voice(u64, VoiceEvent), + Voice(u64, LinkEvent), Gateway(u64, GatewayEvent), Query(u64, QueryEvent), AudioOut(u64, EncodedVoice), Audio(u64, AudioEvent), - /// Our own stream (from the stream task of that voice connection). - OwnStream(u64, OwnStreamEvent), /// The gateway's stream directory after subscribing. Directory(u64, Result, ClientError>), /// The server's unique id the database remembers for an address. @@ -289,13 +297,15 @@ struct OwnStream { } struct Session { + /// Starts the voice connections. + link: Arc, myts_identity: watch::Receiver>>, myts_data: watch::Receiver>>, id: SessionId, events: broadcast::Sender, state: SessionState, generation: u64, - voice: Option<(u64, mpsc::UnboundedSender)>, + voice: Option<(u64, mpsc::UnboundedSender)>, voice_address: String, voice_presence: Option, nickname: String, @@ -317,18 +327,15 @@ struct Session { /// Other names of this server (`voice:
`, `gateway:`), /// remembered with its unique id once a source tells it. aliases: Vec, - /// Streams of the voice connection (TeamSpeak 6 only). - streams: Option, - stream_peer: PeerConfig, + /// The voice connection carries streams (its capabilities say so; the + /// connection runs their task, `LinkCmd::Stream` reaches it). + streams: bool, /// Simulcast layers of our stream, for the stream task. stream_layers: Vec, /// The SRTP profile setting (`Command::SetSrtpProfiles`), over the voice /// options' `stream_peer`. srtp_profiles: Option>, frames: broadcast::Sender, - /// Channel and `client_is_streaming` of the voice presence, as last told - /// to the streams. - streaming_clients: BTreeMap, /// The gateway's stream directory, by id. directory: BTreeMap, own_stream: Option, @@ -379,12 +386,14 @@ struct Session { } impl Session { + #[allow(clippy::too_many_arguments)] // what the engine hands each session fn new( id: SessionId, events: broadcast::Sender, frames: broadcast::Sender, audio_settings: AudioSettings, shared: Shared, + link: Arc, myts_identity: watch::Receiver>>, myts_data: watch::Receiver>>, ) -> Self { @@ -392,6 +401,7 @@ impl Session { let Shared { settings, history, cache, contacts } = shared; let contacts_rx = Some(contacts.watch()); Self { + link, myts_identity, myts_data, cache, @@ -433,12 +443,10 @@ impl Session { history, own_uid: None, aliases: Vec::new(), - streams: None, - stream_peer: PeerConfig::default(), + streams: false, stream_layers: Vec::new(), srtp_profiles: None, frames, - streaming_clients: BTreeMap::new(), directory: BTreeMap::new(), own_stream: None, open_chats: HashSet::new(), @@ -508,17 +516,19 @@ impl Session { fn command(&mut self, cmd: Command) { match cmd { Command::ConnectVoice { options, .. } => { - if let Some((_, tx)) = self.voice.take() { - let _ = tx.send(VoiceCmd::Disconnect); - } + // The streams end first: their shutdown goes through the + // connection that is replaced. self.stop_streams("voice reconnecting"); + if let Some((_, tx)) = self.voice.take() { + let _ = tx.send(LinkCmd::Disconnect); + } + let mut options = *options; let generation = self.next_generation(); self.voice_address = options.address.clone(); self.details = None; self.nickname = options.nickname.clone(); - self.stream_peer = options.stream_peer.clone(); if let Some(profiles) = &self.srtp_profiles { - self.stream_peer.srtp_profiles = parse_srtp_profiles(profiles); + options.stream_peer.srtp_profiles = parse_srtp_profiles(profiles); } self.known_server(format!("voice:{}", options.address)); let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); @@ -531,14 +541,15 @@ impl Session { self.forward(out_rx, move |p| SourceEvent::AudioOut(generation, p)); self.forward(audio_rx, move |e| SourceEvent::Audio(generation, e)); } - let link = VoiceLink { - myts_identity: self.myts_identity.clone(), - myts_data: self.myts_data.clone(), + let ctx = LinkCtx { session: self.id, events: self.events.clone(), + frames: self.frames.clone(), settings: self.settings.clone(), + myts_identity: self.myts_identity.clone(), + myts_data: self.myts_data.clone(), }; - tokio::spawn(voice::run(*options, link, cmd_rx, ev_tx)); + self.link.spawn(options, ctx, cmd_rx, ev_tx); self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e)); self.forget_images(); self.voice = Some((generation, cmd_tx)); @@ -547,7 +558,7 @@ impl Session { } Command::DisconnectVoice { .. } => { if let Some((_, tx)) = &self.voice { - let _ = tx.send(VoiceCmd::Disconnect); + let _ = tx.send(LinkCmd::Disconnect); } } Command::ObserveGateway { urls, identity, .. } => { @@ -625,7 +636,7 @@ impl Session { self.store_own(&target, &text, &route); } match route { - ChatRoute::Voice => self.voice_cmd(VoiceCmd::SendChat(target, text)), + ChatRoute::Voice => self.voice_cmd(LinkCmd::SendChat(target, text)), ChatRoute::Gateway => { if let Some((_, tx)) = &self.gateway { let _ = tx.send(GatewayCmd::SendChat(target, text)); @@ -656,11 +667,11 @@ impl Session { }, Command::Gateway { request, .. } => self.gateway_request(request), Command::MoveToChannel { channel, password, .. } => { - self.voice_cmd(VoiceCmd::Move(channel, password)); + self.voice_cmd(LinkCmd::Move(channel, password)); } Command::SetInputMuted { muted, .. } => { self.state.input_muted = muted; - self.voice_cmd(VoiceCmd::SetInputMuted(muted)); + self.voice_cmd(LinkCmd::SetInputMuted(muted)); if let Some(a) = &self.audio { a.send(AudioIn::InputMuted(muted)); } @@ -668,7 +679,7 @@ impl Session { } Command::SetOutputMuted { muted, .. } => { self.state.output_muted = muted; - self.voice_cmd(VoiceCmd::SetOutputMuted(muted)); + self.voice_cmd(LinkCmd::SetOutputMuted(muted)); if let Some(a) = &self.audio { a.send(AudioIn::OutputMuted(muted)); } @@ -705,50 +716,43 @@ impl Session { } } Command::StartStream { setup, auto_accept, .. } => { - self.stream_input(StreamInput::Start { setup, auto_accept }); + self.stream_input(StreamCmd::Start { setup, auto_accept }); } - Command::StopStream { .. } => self.stream_input(StreamInput::Stop), + Command::StopStream { .. } => self.stream_input(StreamCmd::Stop), Command::AcceptViewer { viewer, accept, .. } => { - self.stream_input(StreamInput::Respond { viewer, accept }); + self.stream_input(StreamCmd::Respond { viewer, accept }); } - Command::KickViewer { viewer, .. } => self.stream_input(StreamInput::Kick { viewer }), + Command::KickViewer { viewer, .. } => self.stream_input(StreamCmd::Kick { viewer }), Command::SendStreamFrame { frame, .. } => { // Frames without a stream are dropped silently. - if let Some(s) = &self.streams { - s.send(StreamInput::Frame(frame)); - } + self.stream_cmd(StreamCmd::Frame(frame)); } Command::WatchStream { stream_id, .. } => { - self.stream_input(StreamInput::Watch { stream_id }); + self.stream_input(StreamCmd::Watch { stream_id }); } Command::LeaveStream { stream_id, .. } => { - self.stream_input(StreamInput::Leave { stream_id }); + self.stream_input(StreamCmd::Leave { stream_id }); } Command::RequestStreamKeyframe { stream_id, .. } => { - self.stream_input(StreamInput::RequestKeyframe { stream_id }); + self.stream_input(StreamCmd::RequestKeyframe { stream_id }); } Command::StreamUndecodable { stream_id, .. } => { - self.stream_input(StreamInput::Undecodable { stream_id }); + self.stream_input(StreamCmd::Undecodable { stream_id }); } Command::SetWatchLayer { stream_id, layer, .. } => { - self.stream_input(StreamInput::WatchLayer { stream_id, layer }); + self.stream_input(StreamCmd::WatchLayer { stream_id, layer }); } // Kept for streams started later, also without a connection. Command::SetStreamLayers { layers, .. } => { self.stream_layers = layers.clone(); - if let Some(s) = &self.streams { - s.send(StreamInput::Layers(layers)); - } + self.stream_cmd(StreamCmd::Layers(layers)); } Command::SetSrtpProfiles(profiles) => { - self.stream_peer.srtp_profiles = parse_srtp_profiles(&profiles); self.srtp_profiles = Some(profiles.clone()); - if let Some(s) = &self.streams { - s.send(StreamInput::SrtpProfiles(profiles)); - } + self.stream_cmd(StreamCmd::SrtpProfiles(profiles)); } Command::Poke { client, message, .. } => { - self.voice_cmd(VoiceCmd::Poke { client, message }); + self.voice_cmd(LinkCmd::Poke { client, message }); } Command::ListFiles { request, channel, password, path, .. } => { if self.voice.is_none() { @@ -758,7 +762,7 @@ impl Session { return; } let dir = Remote { channel, password, path }; - self.voice_cmd(VoiceCmd::ListFiles { request, dir }); + self.voice_cmd(LinkCmd::ListFiles { request, dir }); } Command::DownloadFile { transfer, channel, password, path, to, .. } => { self.download(transfer, Remote { channel, password, path }, &to); @@ -796,34 +800,27 @@ impl Session { let report = self.transfer_report(transfer); let file = Remote { channel, password, path }; let transfer = Some(transfer); - self.voice_cmd(VoiceCmd::Upload { - transfer, - file, - from, - overwrite, - resume, - report, - }); + self.voice_cmd(LinkCmd::Upload { transfer, file, from, overwrite, resume, report }); } Command::CancelTransfer { transfer, .. } => { - self.voice_cmd(VoiceCmd::CancelTransfer(transfer)); + self.voice_cmd(LinkCmd::CancelTransfer(transfer)); } Command::DeleteFiles { request, channel, password, paths, .. } => { let request = Some(request); self.voice_request( request, - VoiceCmd::DeleteFiles { request, channel, password, paths }, + LinkCmd::DeleteFiles { request, channel, password, paths }, ); } Command::RenameFile { request, channel, password, from, to, to_channel, .. } => { let (to_channel, to_password) = to_channel.unwrap_or((channel, password.clone())); let from = Remote { channel, password, path: from }; let to = Remote { channel: to_channel, password: to_password, path: to }; - self.voice_request(Some(request), VoiceCmd::RenameFile { request, from, to }); + self.voice_request(Some(request), LinkCmd::RenameFile { request, from, to }); } Command::CreateDirectory { request, channel, password, path, .. } => { let dir = Remote { channel, password, path }; - self.voice_request(Some(request), VoiceCmd::CreateDirectory { request, dir }); + self.voice_request(Some(request), LinkCmd::CreateDirectory { request, dir }); } Command::SetAvatar { request, image, .. } => self.set_avatar(request, image), Command::FetchAvatar { client_uid, .. } => { @@ -855,7 +852,7 @@ impl Session { self.emit(Event::OfflineMessages { session: self.id, request, result }); return; } - self.voice_cmd(VoiceCmd::OfflineList { request }); + self.voice_cmd(LinkCmd::OfflineList { request }); } Command::GetOfflineMessage { request, id, .. } => { if self.voice.is_none() { @@ -863,17 +860,17 @@ impl Session { self.emit(Event::OfflineMessage { session: self.id, request, result }); return; } - self.voice_cmd(VoiceCmd::OfflineGet { request, id }); + self.voice_cmd(LinkCmd::OfflineGet { request, id }); } Command::SendOfflineMessage { request, to_uid, subject, text, .. } => { - let cmd = VoiceCmd::OfflineAdd { request, to_uid, subject, text }; + let cmd = LinkCmd::OfflineAdd { request, to_uid, subject, text }; self.voice_request(Some(request), cmd); } Command::DeleteOfflineMessage { request, id, .. } => { - self.voice_request(Some(request), VoiceCmd::OfflineDelete { request, id }); + self.voice_request(Some(request), LinkCmd::OfflineDelete { request, id }); } Command::SetOfflineMessageRead { request, id, read, .. } => { - self.voice_request(Some(request), VoiceCmd::OfflineFlag { request, id, read }); + self.voice_request(Some(request), LinkCmd::OfflineFlag { request, id, read }); } // Engine-wide. Command::SetMytsIdentity(_) @@ -893,7 +890,7 @@ impl Session { // Files, avatars, icons /// A request to the voice connection; without one it fails at once. - fn voice_request(&self, request: Option, cmd: VoiceCmd) { + fn voice_request(&self, request: Option, cmd: LinkCmd) { match (&self.voice, request) { (Some(_), _) => self.voice_cmd(cmd), (None, Some(request)) => self.emit(Event::RequestDone { @@ -924,7 +921,7 @@ impl Session { } let report = self.transfer_report(transfer); let sink = Sink::from_target(to); - self.voice_cmd(VoiceCmd::Download { transfer: Some(transfer), file, sink, report }); + self.voice_cmd(LinkCmd::Download { transfer: Some(transfer), file, sink, report }); } /// Upload our avatar and announce its hash, or remove it. @@ -937,7 +934,7 @@ impl Session { let Some(image) = image else { // The file too (best effort), then no hash. if let Some(path) = self.own_uid.as_deref().and_then(files::avatar_path) { - let cmd = VoiceCmd::DeleteFiles { + let cmd = LinkCmd::DeleteFiles { request: None, channel: 0, password: None, @@ -946,7 +943,7 @@ impl Session { self.voice_cmd(cmd); } let hash = String::new(); - self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash }); + self.voice_cmd(LinkCmd::SetAvatarHash { request: Some(request), hash }); return; }; let (sources, cache, settings) = @@ -982,7 +979,7 @@ impl Session { let _ = sources.send(SourceEvent::AvatarUploaded(generation, request, result)); }); let file = Remote { channel: 0, password: None, path: "/avatar".into() }; - let upload = VoiceCmd::Upload { + let upload = LinkCmd::Upload { transfer: None, file, from: image, @@ -1402,7 +1399,7 @@ impl Session { let sink = Sink::File { part: temp.clone(), dest: temp, append: false }; let file = Remote { channel, password: None, path }; let failed = report.clone(); - if voice.send(VoiceCmd::Download { transfer: None, file, sink, report }).is_err() { + if voice.send(LinkCmd::Download { transfer: None, file, sink, report }).is_err() { failed(TransferState::Failed(NO_VOICE.into())); } } @@ -1450,9 +1447,7 @@ impl Session { } if friends != self.stream_friends { self.stream_friends = friends.clone(); - if let Some(s) = &self.streams { - s.send(StreamInput::Friends(friends)); - } + self.stream_cmd(StreamCmd::Friends(friends)); } } @@ -1501,26 +1496,36 @@ impl Session { allows(self.settings.current().get(key), uid.map(|u| self.contacts.relation(u))) } - fn stream_input(&self, input: StreamInput) { - match &self.streams { - Some(s) => s.send(input), - None if self.state.voice == VoiceState::Connected => { - self.error("streams need a TeamSpeak 6 server"); - } - None => self.error("not connected with voice"), + /// A stream command of the user: an error where the connection has no + /// streams. + fn stream_input(&self, cmd: StreamCmd) { + if self.streams { + self.stream_cmd(cmd); + } else if self.state.voice == VoiceState::Connected { + self.error("streams need a TeamSpeak 6 server"); + } else { + self.error("not connected with voice"); + } + } + + /// A command for the streams of the voice connection; dropped where it + /// has none. + fn stream_cmd(&self, cmd: StreamCmd) { + if let (true, Some((_, tx))) = (self.streams, &self.voice) { + let _ = tx.send(LinkCmd::Stream(cmd)); } } fn stop_streams(&mut self, reason: &str) { - if let Some(s) = self.streams.take() { - s.send(StreamInput::Shutdown(reason.into())); + if self.streams { + self.stream_cmd(StreamCmd::Shutdown(reason.into())); + self.streams = false; } - self.streaming_clients.clear(); // The stream task's report comes from a replaced source. self.own_stream_ended(); } - fn voice_cmd(&self, cmd: VoiceCmd) { + fn voice_cmd(&self, cmd: LinkCmd) { match &self.voice { Some((_, tx)) => { let _ = tx.send(cmd); @@ -1709,7 +1714,9 @@ impl Session { /// The registered streams of the directory, for the stream task. fn feed_directory(&self) { - let Some(streams) = &self.streams else { return }; + if !self.streams { + return; + } let entries = self .directory .values() @@ -1728,7 +1735,7 @@ impl Session { }) }) .collect(); - streams.send(StreamInput::Directory(entries)); + self.stream_cmd(StreamCmd::Directory(entries)); } fn register_own_stream(&mut self) { @@ -1833,7 +1840,7 @@ impl Session { } self.stop_streams("session closed"); if let Some((_, tx)) = self.voice.take() { - let _ = tx.send(VoiceCmd::Disconnect); + let _ = tx.send(LinkCmd::Disconnect); } self.audio = None; self.stop_observing(); @@ -1857,7 +1864,7 @@ impl Session { 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)); + let _ = tx.send(LinkCmd::Audio(packet)); } } SourceEvent::Audio(g, event) if self.is_current(Source::Voice, g) => match event { @@ -1866,9 +1873,6 @@ impl Session { self.emit(Event::InputLevel { session: Some(self.id), level_db: db, sending }) } }, - SourceEvent::OwnStream(g, e) if self.is_current(Source::Voice, g) => { - self.own_stream_event(e) - } SourceEvent::Directory(g, result) if self.is_current(Source::Gateway, g) => { match result { Ok(streams) => { @@ -1894,7 +1898,7 @@ impl Session { } SourceEvent::AvatarUploaded(g, request, result) => match result { Ok(hash) if self.is_current(Source::Voice, g) => { - self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash }); + self.voice_cmd(LinkCmd::SetAvatarHash { request: Some(request), hash }); } Ok(_) => self.emit(Event::RequestDone { session: self.id, @@ -1922,9 +1926,9 @@ impl Session { } } - fn voice_event(&mut self, e: VoiceEvent) { + fn voice_event(&mut self, e: LinkEvent) { match e { - VoiceEvent::Connected { + LinkEvent::Connected { name, backend, capabilities, @@ -1946,51 +1950,28 @@ impl Session { { let _ = tx.send(GatewayCmd::RetryNow); } - if capabilities.streams - && let Some((generation, voice)) = &self.voice - { - let generation = *generation; - let (own_tx, own_rx) = mpsc::unbounded_channel(); - self.forward(own_rx, move |e| SourceEvent::OwnStream(generation, e)); - let streams = StreamHandle::spawn( - self.id, - own_client, - self.stream_peer.clone(), - voice.clone(), - self.events.clone(), - self.frames.clone(), - self.audio.clone(), - self.settings.clone(), - own_tx, - ); + if capabilities.streams { + self.streams = true; if !self.stream_layers.is_empty() { - streams.send(StreamInput::Layers(self.stream_layers.clone())); + self.stream_cmd(StreamCmd::Layers(self.stream_layers.clone())); + } + // The setting may have changed since the connection was asked for. + if let Some(profiles) = self.srtp_profiles.clone() { + self.stream_cmd(StreamCmd::SrtpProfiles(profiles)); } - self.streams = Some(streams); self.feed_directory(); } self.emit(Event::ServerInfo { session: self.id, name, backend, capabilities }); self.reopen_relayed_chats(); self.open_histories(); } - VoiceEvent::Presence(p) => { + LinkEvent::Presence(p) => { // Client ids are reused: forget the volumes of those who left. if let (Some(a), Some(old)) = (&self.audio, &self.voice_presence) { for id in old.clients.keys().filter(|id| !p.clients.contains_key(id)) { a.send(AudioIn::ClientLeft(TalkerId(*id))); } } - if let Some(s) = &self.streams { - let clients: BTreeMap<_, _> = p - .clients - .values() - .map(|c| (c.id, ClientState { channel: c.channel, streaming: c.streaming })) - .collect(); - if clients != self.streaming_clients { - self.streaming_clients = clients.clone(); - s.send(StreamInput::Clients(clients)); - } - } self.report_details(&p); self.fetch_images(&p); self.apply_contacts(&p); @@ -1998,7 +1979,7 @@ impl Session { self.voice_presence = Some(*p); self.publish_presence(); } - VoiceEvent::Poke { from, from_uid, from_name, message } => { + LinkEvent::Poke { from, from_uid, from_name, message } => { let blocked = self.contacts.is_blocked(from_uid.as_deref()); if blocked && self.block_mode() == BlockMode::Hide { debug!(?from_uid, "poke of a blocked contact hidden"); @@ -2011,35 +1992,37 @@ impl Session { let session = self.id; self.emit(Event::Poke { session, from, from_uid, from_name, message, blocked }); } - VoiceEvent::Error(message) => self.error(message), - VoiceEvent::Stream(n) => { - if let Some(s) = &self.streams { - s.send(StreamInput::Notification(n)); + LinkEvent::Error(message) => self.error(message), + LinkEvent::OwnStream(e) => self.own_stream_event(e), + LinkEvent::StreamAudio { stream, time, data } => { + if let Some(a) = &self.audio { + a.send(AudioIn::StreamAudio { stream, time, data }); } } - VoiceEvent::StreamRequestFailed(request, error) => { - if let Some(s) = &self.streams { - s.send(StreamInput::RequestFailed(request, error)); + LinkEvent::StreamAudioEnded(stream) => { + if let Some(a) = &self.audio { + a.send(AudioIn::StreamEnded(stream)); } } - VoiceEvent::OwnChannel(cid) => { + LinkEvent::OwnChannel(cid) => { if self.state.own_channel != Some(cid) { self.state.own_channel = Some(cid); self.emit_state(); } } - VoiceEvent::Chat(msg) => self.chat(msg, MessageSource::Voice, None), - VoiceEvent::Audio(packet) => { + LinkEvent::Chat(msg) => self.chat(msg, MessageSource::Voice, None), + LinkEvent::Audio(packet) => { if let Some(a) = &self.audio { a.send(AudioIn::Packet(packet)); } } - VoiceEvent::Talking { client, talking } => { + LinkEvent::Talking { client, talking } => { self.emit(Event::Talking { session: self.id, client, talking }); } - VoiceEvent::Disconnected(reason) => { - self.stop_streams("voice disconnected"); + LinkEvent::Disconnected(reason) => { + // The connection ended its streams itself. self.voice = None; + self.stop_streams("voice disconnected"); self.voice_presence = None; self.audio = None; self.forget_images(); @@ -2303,6 +2286,7 @@ mod banner_tests { frames, AudioSettings::default(), shared, + Arc::new(crate::TsLink), myts_identity, myts_data, ); @@ -2391,7 +2375,7 @@ mod banner_tests { Err("temporarily unavailable".into()), ); session.retry_images(session.image_retries[&request].due.unwrap()); - let VoiceCmd::Download { file, sink: Sink::File { part, .. }, report, .. } = + let LinkCmd::Download { file, sink: Sink::File { part, .. }, report, .. } = commands.try_recv().unwrap() else { panic!("expected an image download"); @@ -2438,7 +2422,7 @@ mod banner_tests { session.state.server_uid = Some("server-a".into()); session.fetch_pictures(&presence); assert!(session.pictures.contains(url)); - let VoiceCmd::Download { file, sink: Sink::File { part, .. }, report, .. } = + let LinkCmd::Download { file, sink: Sink::File { part, .. }, report, .. } = commands.try_recv().unwrap() else { panic!("expected a file download"); @@ -2980,7 +2964,7 @@ mod banner_tests { let (mut session, _events) = session("gateway-wake"); let (tx, mut rx) = mpsc::unbounded_channel(); session.gateway = Some((session.next_generation(), tx)); - let connected = || VoiceEvent::Connected { + let connected = || LinkEvent::Connected { name: "test".into(), backend: crate::BackendInfo::default(), capabilities: voelin_model::Capabilities::default(), diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index efbe37e..a864b52 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -39,12 +39,11 @@ pub use voelin_stream::{ VideoCodec, VideoFormat, }; -use crate::audio::{AudioHandle, AudioIn}; +use crate::link::LinkEvent; use crate::settings::{STREAM_PERMISSIONS, SharedSettings, StreamPermissions}; pub use crate::stream_types::{ EndReason, LeaveReason, StreamInfo, StreamKind, StreamSetup, ViewerInfo, ViewerState, }; -use crate::voice::VoiceCmd; use crate::{Event, SessionId}; /// How often the viewer count of one stream in our channel is asked for @@ -111,14 +110,14 @@ pub struct StreamSink { impl StreamSink { /// Send one frame; `false` once the stream has ended. pub fn send(&self, frame: EncodedFrame) -> bool { - self.live.load(Ordering::Relaxed) && self.tx.send(StreamInput::Frame(frame)).is_ok() + self.live.load(Ordering::Relaxed) && self.tx.send(StreamCmd::Frame(frame).into()).is_ok() } /// Send one video frame encoded in `format`: only viewers whose answer /// chose that codec (and H.264 profile) get it. pub fn send_video(&self, frame: EncodedFrame, format: VideoFormat) -> bool { self.live.load(Ordering::Relaxed) - && self.tx.send(StreamInput::VideoFrame(frame, format)).is_ok() + && self.tx.send(StreamCmd::VideoFrame(frame, format).into()).is_ok() } /// Whether a viewer's answer chose `format`. @@ -152,7 +151,7 @@ impl StreamSink { /// (`PeerConfig::set_h264_format`), so the offer declares what the /// encoder writes into its SPS, also for 4K, 8K and high frame rates. pub fn layer_format(&self, layer: LayerId, format: LayerFormat) { - let _ = self.tx.send(StreamInput::LayerFormat { layer, format }); + let _ = self.tx.send(StreamCmd::LayerFormat { layer, format }.into()); } pub fn is_live(&self) -> bool { @@ -172,7 +171,9 @@ impl PartialEq for StreamSink { } } -pub(crate) enum StreamInput { +/// What the session asks of the streams of a connection ([`crate::link::LinkCmd::Stream`]). +#[derive(Debug)] +pub enum StreamCmd { Start { setup: StreamSetup, auto_accept: bool, @@ -210,26 +211,39 @@ pub(crate) enum StreamInput { format: LayerFormat, }, /// SRTP profile order of new connections, by name - /// ([`parse_srtp_profiles`]). + /// (unknown names are left out). SrtpProfiles(Vec), Frame(EncodedFrame), /// A video frame for the viewers that chose its codec and H.264 profile. VideoFrame(EncodedFrame, VideoFormat), - Notification(StreamNotification), - RequestFailed(Request, String), - /// Clients on the server: channel and `client_is_streaming`. - Clients(BTreeMap), /// Clients that are friends (contacts), for `stream.permissions`. Friends(BTreeSet), /// The registered streams of the gateway's directory (full list). Directory(Vec), - /// The voice connection is gone. + /// The voice connection is going: streams end, with this reason. Shutdown(String), } +/// What the stream task takes: the session's [`StreamCmd`]s, and what only the +/// connection that runs it knows (the server's notifications and the state +/// of its clients). +pub(crate) enum StreamInput { + Cmd(StreamCmd), + Notification(StreamNotification), + RequestFailed(Request, String), + /// Clients on the server: channel and `client_is_streaming`. + Clients(BTreeMap), +} + +impl From for StreamInput { + fn from(cmd: StreamCmd) -> Self { + Self::Cmd(cmd) + } +} + /// Our own stream, for the session (the gateway directory). #[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) enum OwnStreamEvent { +pub enum OwnStreamEvent { Live { id: String, title: String, @@ -294,6 +308,8 @@ impl StreamLookup for GatewayLookup { } } +/// The stream task of a connection. The connection (a link) owns it: it +/// feeds it what the server says and sends the requests it makes. pub(crate) struct StreamHandle { tx: mpsc::UnboundedSender, } @@ -304,12 +320,12 @@ impl StreamHandle { session: SessionId, own_client: u16, config: PeerConfig, - voice: mpsc::UnboundedSender, + requests: mpsc::UnboundedSender, events: broadcast::Sender, frames: broadcast::Sender, - audio: Option, + audio: bool, settings: SharedSettings, - own: mpsc::UnboundedSender, + link: mpsc::UnboundedSender, ) -> Self { let (tx, rx) = mpsc::unbounded_channel(); let mut streams = Streams::new(ClientId(own_client), config); @@ -318,7 +334,7 @@ impl StreamHandle { let task = StreamTask { session, streams, - voice, + requests, events, frames, audio, @@ -326,7 +342,7 @@ impl StreamHandle { sink: None, layers: Vec::new(), settings, - own, + link, setup: None, formats: BTreeMap::new(), live: None, @@ -339,8 +355,8 @@ impl StreamHandle { Self { tx } } - pub fn send(&self, input: StreamInput) { - let _ = self.tx.send(input); + pub fn send(&self, input: impl Into) { + let _ = self.tx.send(input.into()); } } @@ -366,11 +382,14 @@ fn offer_format( struct StreamTask { session: SessionId, streams: Streams, - voice: mpsc::UnboundedSender, + /// Where the requests go that the stream sessions make (the connection + /// sends them to the server). + requests: mpsc::UnboundedSender, events: broadcast::Sender, frames: broadcast::Sender, - /// Where the audio of watched streams plays, if the session has audio. - audio: Option, + /// The session has audio: the audio of watched streams goes to it + /// ([`LinkEvent::StreamAudio`]). + audio: bool, /// For the sinks handed out. tx: mpsc::UnboundedSender, /// The sink of our live stream. @@ -379,8 +398,9 @@ struct StreamTask { layers: Vec, /// `stream.permissions` decides join requests. settings: SharedSettings, - /// Our stream's life, for the session. - own: mpsc::UnboundedSender, + /// The link's events, for the session: our stream's life + /// ([`LinkEvent::OwnStream`]) and the audio of watched streams. + link: mpsc::UnboundedSender, /// The setup of our stream since `Start`. setup: Option, /// What each layer of our stream is encoded at, since `Start`. @@ -404,7 +424,7 @@ impl StreamTask { tokio::select! { input = rx.recv() => match input { None => break, - Some(StreamInput::Shutdown(reason)) => { + Some(StreamInput::Cmd(StreamCmd::Shutdown(reason))) => { self.shutdown(reason); break; } @@ -453,58 +473,8 @@ impl StreamTask { } async fn input(&mut self, input: StreamInput) { - let session = self.session; let result = match input { - StreamInput::Start { setup, auto_accept } => { - self.setup = Some(setup.clone()); - self.formats.clear(); - let layers = self.layers.clone(); - let setup = setup.into(); - let options = StreamerOptions { setup, auto_accept, layers, ..Default::default() }; - self.streams.start(options).map(|()| { - self.emit(Event::StreamState { session, state: StreamState::Starting }); - }) - } - StreamInput::Stop => self.streams.stop(), - StreamInput::Respond { viewer, accept } => { - self.streams.respond(ClientId(viewer), accept).await - } - StreamInput::Kick { viewer } => self.streams.kick(ClientId(viewer)), - StreamInput::Watch { stream_id } => self.streams.watch(&stream_id, "").map(|()| { - self.emit(Event::WatchState { session, stream_id, state: WatchState::Requested }); - }), - StreamInput::Leave { stream_id } => self.streams.leave(&stream_id), - StreamInput::RequestKeyframe { stream_id } => { - self.streams.request_keyframe(&stream_id); - Ok(()) - } - StreamInput::Undecodable { stream_id } => self.streams.video_undecodable(&stream_id), - StreamInput::WatchLayer { stream_id, layer } => self - .streams - .set_watch_layer(&stream_id, layer) - .map(|()| self.watch_layers(&stream_id)), - StreamInput::Layers(layers) => { - self.layers = layers.clone(); - // Without a stream they are used for the next one. - if self.streams.streamer().is_some() { - self.streams.set_layers(layers) - } else { - Ok(()) - } - } - StreamInput::LayerFormat { layer, format } => self.layer_format(layer, format), - StreamInput::SrtpProfiles(names) => { - self.streams.set_srtp_profiles(parse_srtp_profiles(&names)); - Ok(()) - } - StreamInput::Frame(frame) => { - self.streams.write_frame(&frame); - Ok(()) - } - StreamInput::VideoFrame(frame, format) => { - self.streams.write_frame_in(&frame, Some(format)); - Ok(()) - } + StreamInput::Cmd(cmd) => self.command(cmd).await, StreamInput::Notification(n) => { self.streams.handle_notification(n).await; Ok(()) @@ -513,10 +483,6 @@ impl StreamTask { self.streams.request_failed(&request, &error); Ok(()) } - StreamInput::Friends(friends) => { - self.friends = friends; - Ok(()) - } StreamInput::Clients(clients) => { // Streams of clients that left, stopped streaming or are not // in our channel are gone; unannounced ones are looked up. @@ -525,15 +491,76 @@ impl StreamTask { self.add_directory_streams(); Ok(()) } - StreamInput::Directory(entries) => { + }; + if let Err(e) = result { + let session = self.session; + self.emit(Event::Error { session, message: format!("stream: {e}") }); + } + } + + async fn command(&mut self, cmd: StreamCmd) -> Result<(), voelin_stream::SessionError> { + let session = self.session; + match cmd { + StreamCmd::Start { setup, auto_accept } => { + self.setup = Some(setup.clone()); + self.formats.clear(); + let layers = self.layers.clone(); + let setup = setup.into(); + let options = StreamerOptions { setup, auto_accept, layers, ..Default::default() }; + self.streams.start(options).map(|()| { + self.emit(Event::StreamState { session, state: StreamState::Starting }); + }) + } + StreamCmd::Stop => self.streams.stop(), + StreamCmd::Respond { viewer, accept } => { + self.streams.respond(ClientId(viewer), accept).await + } + StreamCmd::Kick { viewer } => self.streams.kick(ClientId(viewer)), + StreamCmd::Watch { stream_id } => self.streams.watch(&stream_id, "").map(|()| { + self.emit(Event::WatchState { session, stream_id, state: WatchState::Requested }); + }), + StreamCmd::Leave { stream_id } => self.streams.leave(&stream_id), + StreamCmd::RequestKeyframe { stream_id } => { + self.streams.request_keyframe(&stream_id); + Ok(()) + } + StreamCmd::Undecodable { stream_id } => self.streams.video_undecodable(&stream_id), + StreamCmd::WatchLayer { stream_id, layer } => self + .streams + .set_watch_layer(&stream_id, layer) + .map(|()| self.watch_layers(&stream_id)), + StreamCmd::Layers(layers) => { + self.layers = layers.clone(); + // Without a stream they are used for the next one. + if self.streams.streamer().is_some() { + self.streams.set_layers(layers) + } else { + Ok(()) + } + } + StreamCmd::LayerFormat { layer, format } => self.layer_format(layer, format), + StreamCmd::SrtpProfiles(names) => { + self.streams.set_srtp_profiles(parse_srtp_profiles(&names)); + Ok(()) + } + StreamCmd::Frame(frame) => { + self.streams.write_frame(&frame); + Ok(()) + } + StreamCmd::VideoFrame(frame, format) => { + self.streams.write_frame_in(&frame, Some(format)); + Ok(()) + } + StreamCmd::Friends(friends) => { + self.friends = friends; + Ok(()) + } + StreamCmd::Directory(entries) => { self.gateway.lock().unwrap_or_else(PoisonError::into_inner).entries = entries; self.add_directory_streams(); Ok(()) } - StreamInput::Shutdown(_) => Ok(()), - }; - if let Err(e) = result { - self.emit(Event::Error { session, message: format!("stream: {e}") }); + StreamCmd::Shutdown(_) => Ok(()), } } @@ -558,7 +585,7 @@ impl StreamTask { } fn own_stream(&self, event: OwnStreamEvent) { - let _ = self.own.send(event); + let _ = self.link.send(LinkEvent::OwnStream(event)); } /// Send the requests on the connection and report the events. @@ -566,7 +593,7 @@ impl StreamTask { while let Some(output) = self.streams.poll_output() { match output { Output::Request(request) => { - let _ = self.voice.send(VoiceCmd::Stream(request)); + let _ = self.requests.send(request); } Output::Event(event) => self.event(event), } @@ -609,7 +636,8 @@ impl StreamTask { viewer = viewer.0, accept, "join request answered by stream.permissions" ); - let _ = self.tx.send(StreamInput::Respond { viewer: viewer.0, accept }); + let _ = + self.tx.send(StreamCmd::Respond { viewer: viewer.0, accept }.into()); } None => { self.emit(Event::StreamViewerRequest { @@ -654,15 +682,15 @@ impl StreamTask { WatchEvent::Accepted => WatchState::Connecting, WatchEvent::Connected => WatchState::Connected, WatchEvent::Ended(reason) => { - if let Some(audio) = &self.audio { - audio.send(AudioIn::StreamEnded(id.clone())); + if self.audio { + let _ = self.link.send(LinkEvent::StreamAudioEnded(id.clone())); } WatchState::Ended(reason.into()) } WatchEvent::Layers(_) => return self.watch_layers(&id), WatchEvent::Frame(frame) => { - if let (MediaKind::Audio, Some(audio)) = (frame.kind, &self.audio) { - audio.send(AudioIn::StreamAudio { + if let (MediaKind::Audio, true) = (frame.kind, self.audio) { + let _ = self.link.send(LinkEvent::StreamAudio { stream: id.clone(), time: frame.time.rebase(Frequency::FORTY_EIGHT_KHZ).numer(), data: frame.data.clone(), @@ -719,8 +747,8 @@ impl StreamTask { } for watched in self.streams.watching() { let stream_id = watched.id().to_owned(); - if let Some(audio) = &self.audio { - audio.send(AudioIn::StreamEnded(stream_id.clone())); + if self.audio { + let _ = self.link.send(LinkEvent::StreamAudioEnded(stream_id.clone())); } self.emit(Event::WatchState { session, stream_id, state: WatchState::Ended(ended()) }); } @@ -858,6 +886,7 @@ mod tests { use voelin_stream::{FrameSource, SyntheticSource}; use super::*; + use crate::audio::{AudioHandle, AudioIn}; use crate::settings::Settings; const CLIENTS: [u16; 2] = [5, 6]; @@ -982,44 +1011,67 @@ mod tests { broadcast::Receiver, mpsc::UnboundedReceiver, ) { - let (own_tx, own_rx) = mpsc::unbounded_channel(); + // The streamer's own-stream events, out of the link's events. + let (own_tx, mut link_rx) = mpsc::unbounded_channel::(); + let (own_out, own_rx) = mpsc::unbounded_channel(); + tokio::spawn(async move { + while let Some(event) = link_rx.recv().await { + if let LinkEvent::OwnStream(event) = event { + let _ = own_out.send(event); + } + } + }); + // The viewer's link events: what the session does with the audio of + // watched streams, it does with its audio thread. + let (viewer_tx, mut viewer_rx) = mpsc::unbounded_channel::(); + let has_audio = audio.is_some(); + tokio::spawn(async move { + while let Some(event) = viewer_rx.recv().await { + match (event, &audio) { + (LinkEvent::StreamAudio { stream, time, data }, Some(audio)) => { + audio.send(AudioIn::StreamAudio { stream, time, data }); + } + (LinkEvent::StreamAudioEnded(stream), Some(audio)) => { + audio.send(AudioIn::StreamEnded(stream)); + } + _ => {} + } + } + }); let (events, rx) = broadcast::channel(4096); let (frames, frames_rx) = broadcast::channel(4096); - let mut voices = Vec::new(); + let mut requests = Vec::new(); let mut handles = Vec::new(); - let mut audio = audio; for (i, clid) in CLIENTS.into_iter().enumerate() { - let (voice, voice_rx) = mpsc::unbounded_channel(); + let (request_tx, request_rx) = mpsc::unbounded_channel(); let config = config.clone(); let session = i as u64 + 1; handles.push(StreamHandle::spawn( session, clid, config, - voice, + request_tx, events.clone(), frames.clone(), - if session == 2 { audio.take() } else { None }, + session == 2 && has_audio, SharedSettings::new(settings.clone()), - if session == 1 { own_tx.clone() } else { mpsc::unbounded_channel().0 }, + if session == 1 { own_tx.clone() } else { viewer_tx.clone() }, )); - voices.push(voice_rx); + requests.push(request_rx); } let handles = Arc::new(handles); // The server: relays requests from one task as notifications to the others. - for (i, mut voice_rx) in voices.into_iter().enumerate() { + for (i, mut request_rx) in requests.into_iter().enumerate() { let handles = handles.clone(); tokio::spawn(async move { - while let Some(cmd) = voice_rx.recv().await { - if let VoiceCmd::Stream(request) = cmd { - for (to, n) in relay(CLIENTS[i], request) { - let announcement = matches!(n, StreamNotification::Started { .. }); - if late && to == CLIENTS[1] && announcement { - continue; - } - let index = CLIENTS.iter().position(|c| *c == to).unwrap(); - handles[index].send(StreamInput::Notification(n)); + while let Some(request) = request_rx.recv().await { + for (to, n) in relay(CLIENTS[i], request) { + let announcement = matches!(n, StreamNotification::Started { .. }); + if late && to == CLIENTS[1] && announcement { + continue; } + let index = CLIENTS.iter().position(|c| *c == to).unwrap(); + handles[index].send(StreamInput::Notification(n)); } } }); @@ -1034,7 +1086,7 @@ mod tests { rx: &mut broadcast::Receiver, ) -> StreamSink { let setup = StreamSetup { name: "t".into(), ..Default::default() }; - handles[0].send(StreamInput::Start { setup, auto_accept: true }); + handles[0].send(StreamCmd::Start { setup, auto_accept: true }); // Live for the streamer and listed for the viewer, in either order. let (mut sink, mut listed) = (None, false); wait(rx, |e| { @@ -1048,7 +1100,7 @@ mod tests { (sink.is_some() && listed).then_some(()) }) .await; - handles[1].send(StreamInput::Watch { stream_id: "s-1".into() }); + handles[1].send(StreamCmd::Watch { stream_id: "s-1".into() }); wait(rx, |e| match e { Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()), _ => None, @@ -1095,7 +1147,7 @@ mod tests { assert!(sink.take_keyframe_request()); // Stopping ends the sink and tells the viewer. - handles[0].send(StreamInput::Stop); + handles[0].send(StreamCmd::Stop); wait(&mut rx, |e| match e { Event::WatchState { session: 2, state: WatchState::Ended(EndReason::Stopped), .. @@ -1107,8 +1159,17 @@ mod tests { feeder.await.unwrap(); // Stream audio went to the viewer's audio thread, in 20 ms steps, - // and the ended stream was forgotten there. - let received: Vec = audio_rx.try_iter().collect(); + // and the ended stream was forgotten there (the link events pass + // through a task on their way). + let mut received: Vec = Vec::new(); + timeout(Duration::from_secs(5), async { + while !matches!(received.last(), Some(AudioIn::StreamEnded(_))) { + received.extend(audio_rx.try_iter()); + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the stream's audio ended"); let times: Vec = received .iter() .filter_map(|m| match m { @@ -1121,13 +1182,13 @@ mod tests { assert!(matches!(received.last(), Some(AudioIn::StreamEnded(id)) if id == "s-1")); // Errors surface as events. - handles[1].send(StreamInput::Leave { stream_id: "s-1".into() }); + handles[1].send(StreamCmd::Leave { stream_id: "s-1".into() }); wait(&mut rx, |e| match e { Event::Error { session: 2, message } if message.contains("not watching") => Some(()), _ => None, }) .await; - handles[1].send(StreamInput::Shutdown("bye".into())); + handles[1].send(StreamCmd::Shutdown("bye".into())); } /// Simulcast layers and the SRTP setting through the stream tasks: the @@ -1141,9 +1202,9 @@ mod tests { LayerSpec { id: 1, scale: 0.5, ..LayerSpec::single(500_000) }, ]; // Set before the stream starts: kept for it. - handles[0].send(StreamInput::Layers(layers.clone())); + handles[0].send(StreamCmd::Layers(layers.clone())); // The viewer is the DTLS server: its order decides. - handles[1].send(StreamInput::SrtpProfiles(vec!["AEAD_AES_128_GCM".into()])); + handles[1].send(StreamCmd::SrtpProfiles(vec!["AEAD_AES_128_GCM".into()])); let sink = live_and_watching(&handles, &mut rx).await; let mut keyframes = LayerSet::new(); sink.take_layer_keyframes(&mut keyframes); @@ -1194,7 +1255,7 @@ mod tests { assert!(sink.layer_bitrate(0).is_some_and(|b| b > 0)); assert_eq!(sink.layer_bitrate(1), None, "no viewer on layer 1"); - handles[0].send(StreamInput::Stop); + handles[0].send(StreamCmd::Stop); wait(&mut rx, |e| match e { Event::WatchState { session: 2, state: WatchState::Ended(_), .. } => Some(()), _ => None, @@ -1214,7 +1275,7 @@ mod tests { let config = PeerConfig { video_codecs: vec![VideoCodec::H264], ..PeerConfig::loopback() }; let (handles, mut rx, _frames, _) = pair_full(None, &Settings::in_memory(), false, config); let setup = StreamSetup { name: "4K120".into(), ..Default::default() }; - handles[0].send(StreamInput::Start { setup, auto_accept: true }); + handles[0].send(StreamCmd::Start { setup, auto_accept: true }); // Live for the streamer and listed for the viewer, in either order. let (mut sink, mut listed) = (None, false); wait(&mut rx, |e| { @@ -1233,7 +1294,7 @@ mod tests { |bitrate| LayerFormat { width: 3840, height: 2160, fps: 60, bitrate, automatic: true }; // Before the viewer asks: its offer is made after this. sink.layer_format(0, format(60_000_000)); - handles[1].send(StreamInput::Watch { stream_id: "s-1".into() }); + handles[1].send(StreamCmd::Watch { stream_id: "s-1".into() }); wait(&mut rx, |e| match e { Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()), _ => None, @@ -1263,7 +1324,7 @@ mod tests { sink.layer_format(0, format(9_000_000)); tokio::time::sleep(Duration::from_millis(200)).await; assert!(!keyframes(), "nothing changed"); - handles[0].send(StreamInput::Stop); + handles[0].send(StreamCmd::Stop); } #[test] @@ -1303,7 +1364,7 @@ mod tests { kind: StreamKind::Window, ..Default::default() }; - handles[0].send(StreamInput::Start { setup, auto_accept: true }); + handles[0].send(StreamCmd::Start { setup, auto_accept: true }); wait(&mut rx, |e| match e { Event::StreamState { session: 1, state: StreamState::Live { .. } } => Some(()), _ => None, @@ -1337,7 +1398,7 @@ mod tests { audio: true, viewers: None, }; - handles[1].send(StreamInput::Directory(vec![entry])); + handles[1].send(StreamCmd::Directory(vec![entry])); wait(&mut rx, |e| match e { Event::StreamsChanged { session: 2, streams } if streams.iter().any(|s| s.id == "s-1") => @@ -1347,7 +1408,7 @@ mod tests { _ => None, }) .await; - handles[1].send(StreamInput::Watch { stream_id: "s-1".into() }); + handles[1].send(StreamCmd::Watch { stream_id: "s-1".into() }); wait(&mut rx, |e| match e { Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()), _ => None, @@ -1356,7 +1417,7 @@ mod tests { // One connected viewer, then the end. let viewers = timeout(Duration::from_secs(5), own.recv()).await.unwrap().unwrap(); assert_eq!(viewers, OwnStreamEvent::Viewers(1)); - handles[0].send(StreamInput::Stop); + handles[0].send(StreamCmd::Stop); loop { match timeout(Duration::from_secs(5), own.recv()).await.unwrap().unwrap() { OwnStreamEvent::Ended { id } => break assert_eq!(id, "s-1"), @@ -1365,7 +1426,7 @@ mod tests { } } for h in handles.iter() { - h.send(StreamInput::Shutdown("done".into())); + h.send(StreamCmd::Shutdown("done".into())); } } @@ -1510,10 +1571,10 @@ mod tests { h.send(in_channels(1, viewer_channel)); } if friend { - handles[0].send(StreamInput::Friends(BTreeSet::from([CLIENTS[1]]))); + handles[0].send(StreamCmd::Friends(BTreeSet::from([CLIENTS[1]]))); } let setup = StreamSetup { name: "p".into(), ..Default::default() }; - handles[0].send(StreamInput::Start { setup, auto_accept: false }); + handles[0].send(StreamCmd::Start { setup, auto_accept: false }); let (mut live, mut listed) = (false, false); wait(&mut rx, |e| { match e { @@ -1526,7 +1587,7 @@ mod tests { (live && listed).then_some(()) }) .await; - handles[1].send(StreamInput::Watch { stream_id: "s-1".into() }); + handles[1].send(StreamCmd::Watch { stream_id: "s-1".into() }); let answer = wait(&mut rx, |e| match e { Event::WatchState { session: 2, state: WatchState::Connected, .. } => { Some(Some(true)) @@ -1542,7 +1603,7 @@ mod tests { .await; assert_eq!(answer, expected, "{permissions:?}, viewer in channel {viewer_channel}"); for h in handles.iter() { - h.send(StreamInput::Shutdown("done".into())); + h.send(StreamCmd::Shutdown("done".into())); } } } @@ -1580,7 +1641,7 @@ mod tests { }, { let handles = handles.clone(); - move || handles[1].send(StreamInput::RequestKeyframe { stream_id: "s-1".into() }) + move || handles[1].send(StreamCmd::RequestKeyframe { stream_id: "s-1".into() }) }, ); let input = pipeline.input(); @@ -1610,7 +1671,7 @@ mod tests { let sent = streamer.stats(); assert!(sent.video_frames >= 15 && sent.audio_frames > 0, "{sent:?}"); - handles[0].send(StreamInput::Stop); + handles[0].send(StreamCmd::Stop); wait(&mut rx, |e| match e { Event::WatchState { session: 2, state: WatchState::Ended(_), .. } => Some(()), _ => None, diff --git a/crates/voelin-core/src/ts_link.rs b/crates/voelin-core/src/ts_link.rs new file mode 100644 index 0000000..d122cd2 --- /dev/null +++ b/crates/voelin-core/src/ts_link.rs @@ -0,0 +1,34 @@ +//! [`TsLink`]: the TeamSpeak implementation of [`ServerLink`]. +//! +//! It connects as a normal TeamSpeak 3 or 6 client with `tsclientlib` and +//! runs the connection ([`crate::voice`]) with everything that rides on it: +//! chat, voice, files, pokes, offline messages and, on TeamSpeak 6, the +//! stream task. Which product the server is (and what it can do) is decided +//! there, from the version it sends, and reported in +//! [`LinkEvent::Connected`](crate::link::LinkEvent::Connected). +//! +//! Everything it uses (`voice.rs`, `book.rs`, `stream.rs`, `versions.rs`, +//! `identity.rs`) is TeamSpeak's and leaves this crate together with it: +//! the plan moves `TsLink` into the TeamSpeak gateway, `voelin-gateway-ts` +//! of VoelinGateWay. + +use tokio::sync::mpsc; + +use crate::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink}; +use crate::voice; + +/// Connects to TeamSpeak 3 and 6 servers. The engine's default link. +#[derive(Clone, Copy, Debug, Default)] +pub struct TsLink; + +impl ServerLink for TsLink { + fn spawn( + &self, + options: ConnectOptions, + ctx: LinkCtx, + cmds: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, + ) { + tokio::spawn(voice::run(options, ctx, cmds, events)); + } +} diff --git a/crates/voelin-core/src/voice.rs b/crates/voelin-core/src/voice.rs index f930c6d..da0c9c5 100644 --- a/crates/voelin-core/src/voice.rs +++ b/crates/voelin-core/src/voice.rs @@ -1,19 +1,26 @@ -//! The voice source: a normal client connection. +//! The TeamSpeak link: a normal client connection ([`crate::TsLink`] runs +//! [`run`]). //! //! Besides presence, chat, voice and stream signalling it carries what only //! a client connection can do: pokes, file transfer (channel files, //! avatars, icons) and offline messages. Their answers go straight to the -//! engine's event bus ([`VoiceLink`]); what the session must see first -//! (chat, pokes: blocking) comes as [`VoiceEvent`]s. +//! engine's event bus ([`LinkCtx`]); what the session must see first +//! (chat, pokes: blocking) comes as [`LinkEvent`]s. +//! +//! On TeamSpeak 6 servers the connection also runs the stream task +//! ([`crate::stream`]): it hands the task the server's stream notifications +//! and the clients' channels, and sends the requests the task makes. The +//! session only sees the commands it gave ([`LinkCmd::Stream`]) and, for the +//! gateway directory, our own stream's life ([`LinkEvent::OwnStream`]). -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use base64::Engine as _; use futures::prelude::*; -use tokio::sync::{broadcast, mpsc, watch}; +use tokio::sync::{mpsc, watch}; use tokio::task::AbortHandle; use tokio::time::{Instant, timeout}; use tracing::{debug, info, warn}; @@ -21,86 +28,22 @@ use tsclientlib::events::Event as BookEvent; use tsclientlib::messages::c2s; use tsclientlib::prelude::*; use tsclientlib::{ - Connection, DisconnectOptions, FiletransferHandle, Identity, InMessage, MessageHandle, - MessageTarget, StreamItem, TsError, Version, + Connection, DisconnectOptions, FiletransferHandle, InMessage, MessageHandle, MessageTarget, + StreamItem, TsError, }; use tsproto_packets::packets::{AudioData, CodecType, InAudioBuf, OutAudio, OutCommand, OutPacket}; use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket}; -use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor}; -use voelin_stream::{PeerConfig, Request, StreamNotification}; +use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, ServerFlavor}; +use voelin_stream::{ClientState, Request, StreamNotification}; use crate::book::presence_from_book; use crate::cache; use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState}; +use crate::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, Remote}; use crate::offline::{OfflineMessage, OfflineMessageInfo}; -use crate::settings::{FILES_PROGRESS_MS, SharedSettings}; -use crate::{BackendInfo, Event, JoinFailure, POKE_MESSAGE_MAX, SessionId}; - -#[derive(Clone, Debug)] -pub struct VoiceOptions { - pub address: String, - pub nickname: String, - pub identity: Option, - /// Signed compatibility version; `None` selects the native platform's tuple. - pub client_version: Option, - pub server_password: Option, - /// Channel path to join, e.g. `Lobby/Sub`, or `/`. - pub channel: Option, - /// The password of `channel`. - pub channel_password: Option, - /// A privilege key to use when connecting. - pub token: Option, - /// Open the audio devices (capture and playback). - pub audio: bool, - /// Network settings for stream peer connections (TeamSpeak 6). - pub stream_peer: PeerConfig, -} - -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, - channel_password: None, - token: None, - audio: false, - stream_peer: PeerConfig::default(), - } - } -} - -/// Where a voice connection reports answers the session does not need to see. -#[derive(Clone)] -pub(crate) struct VoiceLink { - pub myts_identity: watch::Receiver>>, - /// What the server is shown of the account ([`crate::Command::SetMytsData`]). - pub myts_data: watch::Receiver>>, - pub session: SessionId, - pub events: broadcast::Sender, - pub settings: SharedSettings, -} - -impl VoiceLink { - fn emit(&self, event: Event) { - let _ = self.events.send(event); - } - - fn done(&self, request: RequestId, result: Result<(), String>) { - self.emit(Event::RequestDone { session: self.session, request, result }); - } -} - -/// A file on the server: channel, its password, path. -#[derive(Clone, Debug)] -pub(crate) struct Remote { - pub channel: ChannelId, - pub password: Option, - pub path: String, -} +use crate::settings::FILES_PROGRESS_MS; +use crate::stream::{StreamCmd, StreamHandle, StreamInput}; +use crate::{BackendInfo, Event, JoinFailure, POKE_MESSAGE_MAX}; impl Remote { fn cpw(&self) -> String { @@ -115,121 +58,6 @@ fn encode_password(password: Option<&str>) -> String { .unwrap_or_default() } -pub(crate) enum VoiceCmd { - SendChat(ChatTarget, String), - Move(ChannelId, Option), - SetInputMuted(bool), - SetOutputMuted(bool), - /// An encoded voice frame from the audio thread. - Audio(EncodedVoice), - /// A stream command; failures come back as [`VoiceEvent::StreamRequestFailed`]. - Stream(Request), - Poke { - client: u16, - message: String, - }, - ListFiles { - request: RequestId, - dir: Remote, - }, - /// Download `file`; `transfer` if the user can cancel it. - Download { - transfer: Option, - file: Remote, - sink: Sink, - report: Report, - }, - Upload { - transfer: Option, - file: Remote, - from: PathBuf, - overwrite: bool, - resume: bool, - report: Report, - }, - CancelTransfer(TransferId), - DeleteFiles { - /// `None`: best effort, nobody waits for the answer. - request: Option, - channel: ChannelId, - password: Option, - paths: Vec, - }, - RenameFile { - request: RequestId, - from: Remote, - to: Remote, - }, - CreateDirectory { - request: RequestId, - dir: Remote, - }, - /// `clientupdate client_flag_avatar` (empty: no avatar). - SetAvatarHash { - request: Option, - hash: String, - }, - OfflineList { - request: RequestId, - }, - OfflineGet { - request: RequestId, - id: u32, - }, - OfflineAdd { - request: RequestId, - to_uid: String, - subject: String, - text: String, - }, - OfflineDelete { - request: RequestId, - id: u32, - }, - OfflineFlag { - request: RequestId, - id: u32, - read: bool, - }, - Disconnect, -} - -pub(crate) enum VoiceEvent { - Connected { - name: String, - /// The server software, and what it can do (the connection knows - /// both from the server's version). - backend: BackendInfo, - capabilities: Capabilities, - own_client: u16, - /// The server's unique id (from its public key, as the server - /// generation computes it). - server_uid: String, - /// Our unique id as the server knows it. - own_uid: Option, - }, - Presence(Box), - OwnChannel(ChannelId), - Chat(ChatMessage), - Poke { - from: u16, - from_uid: Option, - from_name: String, - message: String, - }, - /// Incoming voice for the audio thread, and who is talking. - Audio(VoicePacket), - Talking { - client: u16, - talking: bool, - }, - Stream(StreamNotification), - StreamRequestFailed(Request, String), - /// A command failed (the connection stays). - Error(String), - Disconnected(Option), -} - /// What the engine is told of the server this connection reached: the /// product and version to show, and what the product can do. The flavor /// (TeamSpeak 3 or 6) is decided here, from the version the server sent, and @@ -283,7 +111,9 @@ enum Input { MytsDataChanged, AccountSourceClosed, Item(Option>), - Cmd(Option), + Cmd(Option), + /// A request of the stream task, for the server. + Request(Request), Tick, } @@ -321,7 +151,7 @@ enum Pending { Move { channel: ChannelId, }, - /// Failures are reported as [`VoiceEvent::Error`] with this label. + /// Failures are reported as [`LinkEvent::Error`] with this label. Report(&'static str), /// Best effort: the answer does not matter. Quiet, @@ -389,23 +219,42 @@ enum Slot { /// Run a voice connection until it ends or is told to disconnect. pub(crate) async fn run( - options: VoiceOptions, - link: VoiceLink, - mut commands: mpsc::UnboundedReceiver, - events: mpsc::UnboundedSender, + options: ConnectOptions, + ctx: LinkCtx, + mut commands: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, ) { - let reason = match run_inner(&options, link, &mut commands, &events).await { + let reason = match run_inner(&options, ctx, &mut commands, &events).await { Ok(()) => None, Err(e) => Some(e.to_string()), }; - let _ = events.send(VoiceEvent::Disconnected(reason)); + let _ = events.send(LinkEvent::Disconnected(reason)); +} + +/// The stream task of a connection. When the connection ends, in whatever +/// way, its streams end with it. +struct ConnectionStreams(StreamHandle); + +impl ConnectionStreams { + fn send(&self, input: impl Into) { + self.0.send(input); + } +} + +impl Drop for ConnectionStreams { + fn drop(&mut self) { + // After a `StreamCmd::Shutdown` of the session this reaches a task + // that has ended, which is fine; the task keeps a sender of its own, + // so it never ends by itself. + self.0.send(StreamCmd::Shutdown("voice disconnected".into())); + } } /// The state of a connected voice source. struct Voice { con: Connection, - link: VoiceLink, - events: mpsc::UnboundedSender, + link: LinkCtx, + events: mpsc::UnboundedSender, server_uid: String, /// Who is talking: last voice packet per client. talking: HashMap, @@ -418,13 +267,17 @@ struct Voice { /// What this connection has shown the server of the account (avatar, /// badges, User Tag): what changes, and what a sign-out clears. myts_shown: tsclientlib::MytsData, + /// The streams of the connection (TeamSpeak 6 servers). + streams: Option, + /// The clients as last told to the streams: channel and `client_is_streaming`. + streaming_clients: BTreeMap, } async fn run_inner( - options: &VoiceOptions, - link: VoiceLink, - commands: &mut mpsc::UnboundedReceiver, - events: &mpsc::UnboundedSender, + options: &ConnectOptions, + link: LinkCtx, + commands: &mut mpsc::UnboundedReceiver, + events: &mpsc::UnboundedSender, ) -> anyhow::Result<()> { let version = match &options.client_version { Some(version) => version.clone(), @@ -486,7 +339,10 @@ async fn run_inner( }) .await .map_err(|_| anyhow::anyhow!("timed out while connecting"))??; - let server_uid = { + // The requests the stream task makes; `requests_tx` stays here, so the + // channel is open (and empty) also where there is no stream task. + let (requests_tx, mut requests) = mpsc::unbounded_channel(); + let (server_uid, streams) = { let state = con.get_state()?; let flavor = ServerFlavor::from_version_string(&state.server.version); let ids = voelin_gateway_proto::UniqueIds::from_omega(&state.server.public_key.to_ts()); @@ -498,7 +354,22 @@ async fn run_inner( .and_then(|c| c.uid.as_ref()) .map(|u| u.as_ref().to_string()); let (backend, capabilities) = backend_of(&flavor); - let _ = events.send(VoiceEvent::Connected { + // Before the session hears of the connection, so that the commands it + // then gives find the task. + let streams = capabilities.streams.then(|| { + ConnectionStreams(StreamHandle::spawn( + link.session, + state.own_client.0, + options.stream_peer.clone(), + requests_tx.clone(), + link.events.clone(), + link.frames.clone(), + options.audio, + link.settings.clone(), + events.clone(), + )) + }); + let _ = events.send(LinkEvent::Connected { name: state.server.name.clone(), backend, capabilities, @@ -506,7 +377,7 @@ async fn run_inner( server_uid: server_uid.clone(), own_uid, }); - server_uid + (server_uid, streams) }; // Subscribe to all channels to see everyone. let cmd = con.get_state()?.server.set_subscribed(true); @@ -522,6 +393,8 @@ async fn run_inner( transfers: HashMap::new(), myts_data_due: false, myts_shown: tsclientlib::MytsData::default(), + streams, + streaming_clients: BTreeMap::new(), }; voice.publish_state()?; // The account's avatar, badges and User Tag, for everyone on the @@ -538,9 +411,15 @@ async fn run_inner( }) { break Err(anyhow::anyhow!("myTeamSpeak account update timed out")); } - let input = - next_input(&mut voice.con.events(), commands, &mut tick, &mut identity, &mut data) - .await; + let input = next_input( + &mut voice.con.events(), + commands, + &mut requests, + &mut tick, + &mut identity, + &mut data, + ) + .await; match input { Input::AccountSourceClosed => break Err(anyhow::anyhow!("account source closed")), Input::MytsIdentityChanged => { @@ -568,10 +447,15 @@ async fn run_inner( break Err(e); } } - Input::Cmd(None) | Input::Cmd(Some(VoiceCmd::Disconnect)) => break Ok(()), + Input::Cmd(None) | Input::Cmd(Some(LinkCmd::Disconnect)) => break Ok(()), Input::Cmd(Some(cmd)) => { if let Err(e) = voice.command(cmd) { - let _ = voice.events.send(VoiceEvent::Error(e.to_string())); + let _ = voice.events.send(LinkEvent::Error(e.to_string())); + } + } + Input::Request(request) => { + if let Err(e) = voice.stream_request(request) { + let _ = voice.events.send(LinkEvent::Error(e.to_string())); } } Input::Tick => voice.tick(), @@ -589,7 +473,8 @@ async fn run_inner( async fn next_input( stream: &mut (impl Stream> + Unpin), - commands: &mut mpsc::UnboundedReceiver, + commands: &mut mpsc::UnboundedReceiver, + requests: &mut mpsc::UnboundedReceiver, tick: &mut tokio::time::Interval, identity: &mut watch::Receiver>>, data: &mut watch::Receiver>>, @@ -611,6 +496,7 @@ async fn next_input( // the audio command queue remains ready. tokio::select! { cmd = commands.recv() => Input::Cmd(cmd), + Some(request) = requests.recv() => Input::Request(request), _ = tick.tick() => Input::Tick, item = stream.next() => Input::Item(item), } @@ -637,13 +523,25 @@ async fn shutdown_connection(mut con: Connection) -> Result<(), tsclientlib::Err } impl Voice { - fn publish_state(&self) -> anyhow::Result<()> { + fn publish_state(&mut self) -> anyhow::Result<()> { let state = self.con.get_state()?; let talking = |id| self.talking.contains_key(&id); let presence = presence_from_book(state, Some(&self.server_uid), talking); - let _ = self.events.send(VoiceEvent::Presence(Box::new(presence))); + // The streams follow the clients' channels and streaming flags. + if let Some(streams) = &self.streams { + let clients: BTreeMap<_, _> = presence + .clients + .values() + .map(|c| (c.id, ClientState { channel: c.channel, streaming: c.streaming })) + .collect(); + if clients != self.streaming_clients { + self.streaming_clients = clients.clone(); + streams.send(StreamInput::Clients(clients)); + } + } + let _ = self.events.send(LinkEvent::Presence(Box::new(presence))); if let Some(own) = state.clients.get(&state.own_client) { - let _ = self.events.send(VoiceEvent::OwnChannel(own.channel.0)); + let _ = self.events.send(LinkEvent::OwnChannel(own.channel.0)); } Ok(()) } @@ -654,7 +552,7 @@ impl Voice { self.talking.retain(|client, last| { let active = last.elapsed() < Duration::from_millis(400); if !active { - let _ = events.send(VoiceEvent::Talking { client: *client, talking: false }); + let _ = events.send(LinkEvent::Talking { client: *client, talking: false }); } active }); @@ -684,10 +582,10 @@ impl Voice { _ => return Ok(()), }; if self.talking.insert(from, Instant::now()).is_none() { - let _ = self.events.send(VoiceEvent::Talking { client: from, talking: true }); + let _ = self.events.send(LinkEvent::Talking { client: from, talking: true }); } if let Some(packet) = voice_packet(&packet) { - let _ = self.events.send(VoiceEvent::Audio(packet)); + let _ = self.events.send(LinkEvent::Audio(packet)); } } StreamItem::MessageEvent(msg) => self.message_event(&msg), @@ -790,7 +688,7 @@ impl Voice { let uid = invoker.uid.as_ref().map(|u| u.as_ref().to_string()); let target = match target { MessageTarget::Poke(_) => { - let _ = self.events.send(VoiceEvent::Poke { + let _ = self.events.send(LinkEvent::Poke { from: invoker.id.0, from_uid: uid, from_name: invoker.name.to_string(), @@ -807,7 +705,7 @@ impl Voice { } MessageTarget::Client(_) => ChatTarget::Private(uid.clone().unwrap_or_default()), }; - let _ = self.events.send(VoiceEvent::Chat(ChatMessage { + let _ = self.events.send(LinkEvent::Chat(ChatMessage { target, author_name: invoker.name.to_string(), author_uid: uid, @@ -875,8 +773,10 @@ impl Voice { } } _ => { - for n in StreamNotification::from_message(msg) { - let _ = self.events.send(VoiceEvent::Stream(n)); + if let Some(streams) = &self.streams { + for n in StreamNotification::from_message(msg) { + streams.send(StreamInput::Notification(n)); + } } } } @@ -898,9 +798,8 @@ impl Voice { }; match pending { Pending::Stream(request) => { - if let Err(e) = result { - let _ = - self.events.send(VoiceEvent::StreamRequestFailed(request, e.to_string())); + if let (Err(e), Some(streams)) = (result, &self.streams) { + streams.send(StreamInput::RequestFailed(request, e.to_string())); } } Pending::FileList { request, channel, path, entries } => { @@ -954,7 +853,7 @@ impl Voice { }, Pending::Report(what) => { if let Err(e) = result { - let _ = self.events.send(VoiceEvent::Error(format!("{what}: {e}"))); + let _ = self.events.send(LinkEvent::Error(format!("{what}: {e}"))); } } } @@ -1089,9 +988,15 @@ impl Voice { Ok(()) } - fn command(&mut self, cmd: VoiceCmd) -> anyhow::Result<()> { + /// Send a request of the stream task to the server. + fn stream_request(&mut self, request: Request) -> anyhow::Result<()> { + let cmd = request.to_command(); + self.send(cmd, Pending::Stream(request)) + } + + fn command(&mut self, cmd: LinkCmd) -> anyhow::Result<()> { match cmd { - VoiceCmd::SendChat(target, text) => { + LinkCmd::SendChat(target, text) => { let state = self.con.get_state()?; let out = match target { ChatTarget::Server => state.server.send_textmessage(&text), @@ -1112,7 +1017,7 @@ impl Voice { }; self.send(out, Pending::Report("message"))?; } - VoiceCmd::Move(channel, password) => { + LinkCmd::Move(channel, password) => { let own = self.con.get_state()?.own_client; let cpw = encode_password(password.as_deref()); let cmd = @@ -1123,19 +1028,20 @@ impl Voice { })); self.send(cmd, Pending::Move { channel })?; } - VoiceCmd::SetInputMuted(muted) => { + LinkCmd::SetInputMuted(muted) => { self.con.get_state()?.client_update().set_input_muted(muted).send(&mut self.con)?; } - VoiceCmd::SetOutputMuted(muted) => { + LinkCmd::SetOutputMuted(muted) => { let update = self.con.get_state()?.client_update().set_output_muted(muted); update.send(&mut self.con)?; } - VoiceCmd::Audio(voice) => self.con.send_audio(out_audio(&voice))?, - VoiceCmd::Stream(request) => { - let cmd = request.to_command(); - self.send(cmd, Pending::Stream(request))?; + LinkCmd::Audio(voice) => self.con.send_audio(out_audio(&voice))?, + LinkCmd::Stream(cmd) => { + if let Some(streams) = &self.streams { + streams.send(cmd); + } } - VoiceCmd::Poke { client, message } => { + LinkCmd::Poke { client, message } => { let cmd = c2s::OutClientPokeRequestMessage::new(&mut std::iter::once( c2s::OutClientPokeRequestPart { client_id: tsclientlib::ClientId(client), @@ -1144,7 +1050,7 @@ impl Voice { )); self.send(cmd, Pending::Report("poke"))?; } - VoiceCmd::ListFiles { request, dir } => { + LinkCmd::ListFiles { request, dir } => { let path = files::normalize_dir(&dir.path); let cpw = dir.cpw(); let cmd = c2s::OutFileListRequestMessage::new(&mut std::iter::once( @@ -1158,7 +1064,7 @@ impl Voice { Pending::FileList { request, channel: dir.channel, path, entries: Vec::new() }; self.send(cmd, pending)?; } - VoiceCmd::Download { transfer, file, sink, report } => { + LinkCmd::Download { transfer, file, sink, report } => { let offset = sink.offset(); let seek = (offset > 0).then_some(offset); let password = file.password.as_deref().filter(|p| !p.is_empty()); @@ -1179,7 +1085,7 @@ impl Voice { self.transfers.insert(id, Slot::Waiting(handle)); } } - VoiceCmd::Upload { transfer, file, from, overwrite, resume, report } => { + LinkCmd::Upload { transfer, file, from, overwrite, resume, report } => { let size = match std::fs::metadata(&from) { Ok(m) if m.is_file() => m.len(), Ok(_) => { @@ -1209,7 +1115,7 @@ impl Voice { self.transfers.insert(id, Slot::Waiting(handle)); } } - VoiceCmd::CancelTransfer(id) => match self.transfers.remove(&id) { + LinkCmd::CancelTransfer(id) => match self.transfers.remove(&id) { Some(Slot::Waiting(handle)) => { if let Some(job) = self.jobs.remove(&handle) { job.report()(TransferState::Cancelled); @@ -1224,7 +1130,7 @@ impl Voice { } _ => debug!(id, "cancel: no such transfer (finished?)"), }, - VoiceCmd::DeleteFiles { request, channel, password, paths } => { + LinkCmd::DeleteFiles { request, channel, password, paths } => { let cpw = encode_password(password.as_deref()); let mut parts = paths.iter().map(|p| c2s::OutDeleteFilePart { channel_id: tsclientlib::ChannelId(channel), @@ -1234,7 +1140,7 @@ impl Voice { let cmd = c2s::OutDeleteFileMessage::new(&mut parts); self.send(cmd, request.map_or(Pending::Quiet, Pending::Done))?; } - VoiceCmd::RenameFile { request, from, to } => { + LinkCmd::RenameFile { request, from, to } => { let (cpw, tcpw) = (from.cpw(), to.cpw()); let other = to.channel != from.channel; let cmd = @@ -1248,7 +1154,7 @@ impl Voice { })); self.send(cmd, Pending::Done(request))?; } - VoiceCmd::CreateDirectory { request, dir } => { + LinkCmd::CreateDirectory { request, dir } => { let cpw = dir.cpw(); let cmd = c2s::OutCreateDirectoryMessage::new(&mut std::iter::once( c2s::OutCreateDirectoryPart { @@ -1259,23 +1165,23 @@ impl Voice { )); self.send(cmd, Pending::Done(request))?; } - VoiceCmd::SetAvatarHash { request, hash } => { + LinkCmd::SetAvatarHash { request, hash } => { let update = self.con.get_state()?.client_update().set_avatar_hash(&hash); let cmd = c2s::OutClientUpdateMessage::new(&mut std::iter::once(update)); let pending = request.map_or(Pending::Report("avatar"), Pending::Done); self.send(cmd, pending)?; } - VoiceCmd::OfflineList { request } => { + LinkCmd::OfflineList { request } => { let cmd = c2s::OutOfflineMessageListRequestMessage::new(); self.send(cmd, Pending::OfflineList { request, messages: Vec::new() })?; } - VoiceCmd::OfflineGet { request, id } => { + LinkCmd::OfflineGet { request, id } => { let cmd = c2s::OutOfflineMessageGetMessage::new(&mut std::iter::once( c2s::OutOfflineMessageGetPart { message_id: id }, )); self.send(cmd, Pending::OfflineGet { request, id, message: None })?; } - VoiceCmd::OfflineAdd { request, to_uid, subject, text } => { + LinkCmd::OfflineAdd { request, to_uid, subject, text } => { // The command carries the unique id's bytes (base64 on the wire). let bytes = base64::engine::general_purpose::STANDARD .decode(to_uid.trim()) @@ -1296,19 +1202,19 @@ impl Voice { )); self.send(cmd, Pending::Done(request))?; } - VoiceCmd::OfflineDelete { request, id } => { + LinkCmd::OfflineDelete { request, id } => { let cmd = c2s::OutOfflineMessageDelMessage::new(&mut std::iter::once( c2s::OutOfflineMessageDelPart { message_id: id }, )); self.send(cmd, Pending::Done(request))?; } - VoiceCmd::OfflineFlag { request, id, read } => { + LinkCmd::OfflineFlag { request, id, read } => { let cmd = c2s::OutOfflineMessageUpdateFlagMessage::new(&mut std::iter::once( c2s::OutOfflineMessageUpdateFlagPart { message_id: id, is_read: read }, )); self.send(cmd, Pending::Done(request))?; } - VoiceCmd::Disconnect => {} + LinkCmd::Disconnect => {} } Ok(()) } @@ -1637,14 +1543,16 @@ mod image_download_tests { #[cfg(test)] mod account_tests { use super::*; + use tokio::sync::broadcast; #[tokio::test(start_paused = true)] async fn account_priority_preserves_ready_network_and_timer_progress() { let (account, mut identity) = watch::channel(None); let (account_data, mut data) = watch::channel(None); let (commands, mut receiver) = mpsc::unbounded_channel(); + let (_requests, mut requests) = mpsc::unbounded_channel(); for _ in 0..512 { - commands.send(VoiceCmd::SetInputMuted(false)).unwrap(); + commands.send(LinkCmd::SetInputMuted(false)).unwrap(); } let mut stream = futures::stream::poll_fn(|_| { std::task::Poll::Ready(Some(Err(tsclientlib::Error::NotConnected))) @@ -1652,21 +1560,45 @@ mod account_tests { let mut tick = tokio::time::interval(Duration::from_millis(1)); account.send_replace(None); assert!(matches!( - next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await, + next_input( + &mut stream, + &mut receiver, + &mut requests, + &mut tick, + &mut identity, + &mut data + ) + .await, Input::MytsIdentityChanged )); identity.borrow_and_update(); // What is shown of the account changes too, ahead of the rest. account_data.send_replace(Some(Arc::new(tsclientlib::MytsData::default()))); assert!(matches!( - next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await, + next_input( + &mut stream, + &mut receiver, + &mut requests, + &mut tick, + &mut identity, + &mut data + ) + .await, Input::MytsDataChanged )); data.borrow_and_update(); let (mut network, mut timers, mut audio) = (0, 0, 0); for _ in 0..512 { tokio::time::advance(Duration::from_millis(1)).await; - match next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await + match next_input( + &mut stream, + &mut receiver, + &mut requests, + &mut tick, + &mut identity, + &mut data, + ) + .await { Input::Item(_) => network += 1, Input::Tick => timers += 1, @@ -1736,10 +1668,11 @@ mod account_tests { let identity = tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap(); let (events, _) = broadcast::channel(8); - let link = VoiceLink { + let link = LinkCtx { session: 1, events, - settings: SharedSettings::new(crate::settings::Settings::default()), + frames: broadcast::channel(1).0, + settings: crate::settings::SharedSettings::new(crate::settings::Settings::default()), myts_identity: watch::channel(Some(Arc::new(identity))).1, myts_data: watch::channel(Some(Arc::new(data))).1, }; @@ -1754,6 +1687,8 @@ mod account_tests { transfers: HashMap::new(), myts_data_due: false, myts_shown: tsclientlib::MytsData::default(), + streams: None, + streaming_clients: BTreeMap::new(), } } @@ -1821,17 +1756,18 @@ mod account_tests { let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); let (account, identity) = watch::channel(None); let (events, _) = broadcast::channel(8); - let link = VoiceLink { + let link = LinkCtx { session: 1, events, - settings: SharedSettings::new(crate::settings::Settings::default()), + frames: broadcast::channel(1).0, + settings: crate::settings::SharedSettings::new(crate::settings::Settings::default()), myts_identity: identity, myts_data: watch::channel(None).1, }; let (_commands, commands) = mpsc::unbounded_channel(); let (events, mut received) = mpsc::unbounded_channel(); let task = tokio::spawn(run( - VoiceOptions::new(server.local_addr().unwrap().to_string(), "account-test"), + ConnectOptions::new(server.local_addr().unwrap().to_string(), "account-test"), link, commands, events, @@ -1856,7 +1792,7 @@ mod account_tests { drop(account); timeout(Duration::from_secs(2), task).await.unwrap().unwrap(); assert!( - matches!(received.recv().await, Some(VoiceEvent::Disconnected(Some(reason))) if reason == "account source closed") + matches!(received.recv().await, Some(LinkEvent::Disconnected(Some(reason))) if reason == "account source closed") ); assert!(received.try_recv().is_err()); } diff --git a/crates/voelin-core/tests/link_fake.rs b/crates/voelin-core/tests/link_fake.rs new file mode 100644 index 0000000..59f08ff --- /dev/null +++ b/crates/voelin-core/tests/link_fake.rs @@ -0,0 +1,541 @@ +//! The session through an in-memory [`ServerLink`]: a `FakeLink` hands each +//! connection the test asks for to the test, which plays the server by +//! sending scripted [`LinkEvent`]s and reads the [`LinkCmd`]s the session +//! gives. Presence, chat, the dedup of a message that comes twice, history +//! and the end of a connection are the session's own behaviour; nothing here +//! needs a TeamSpeak server or a TeamSpeak type. + +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use tokio::sync::{broadcast, mpsc}; +use voelin_core::history::MessageSource; +use voelin_core::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink}; +use voelin_core::settings::Settings; +use voelin_core::stream::{StreamCmd, StreamSetup}; +use voelin_core::{ + BackendInfo, Command, Engine, Event, History, HistoryMessage, HistorySource, SessionId, + SessionState, Source, VoiceOptions, VoiceState, +}; +use voelin_model::{ + Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, +}; + +/// A connection the session asked the link for. +struct Conn { + options: ConnectOptions, + session: SessionId, + cmds: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, +} + +impl Conn { + /// Play `script`, the server's side, in order. + fn play(&self, script: impl IntoIterator) { + for event in script { + self.events.send(event).expect("the session listens"); + } + } + + /// The next command the session gave. + async fn cmd(&mut self) -> LinkCmd { + tokio::time::timeout(Duration::from_secs(10), self.cmds.recv()) + .await + .expect("a command in time") + .expect("the session keeps the connection") + } +} + +/// Hands every connection to the test. +struct FakeLink { + conns: mpsc::UnboundedSender, +} + +impl FakeLink { + fn new() -> (Self, mpsc::UnboundedReceiver) { + let (conns, rx) = mpsc::unbounded_channel(); + (Self { conns }, rx) + } +} + +impl ServerLink for FakeLink { + fn spawn( + &self, + options: ConnectOptions, + ctx: LinkCtx, + cmds: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, + ) { + let conn = Conn { options, session: ctx.session(), cmds, events }; + let _ = self.conns.send(conn); + } +} + +const SESSION: SessionId = 1; +const SERVER_UID: &str = "fake-server="; +const ME: u16 = 7; +const ME_UID: &str = "me="; +const LOBBY: ChannelId = 1; +const GAMES: ChannelId = 2; + +struct Harness { + engine: Engine, + events: broadcast::Receiver, + conns: mpsc::UnboundedReceiver, +} + +impl Harness { + fn start() -> Self { + let (link, conns) = FakeLink::new(); + let engine = + Engine::start_with_link(Settings::in_memory(), History::in_memory(), Arc::new(link)); + let events = engine.subscribe(); + Self { engine, events, conns } + } + + /// Ask for a voice connection and take it from the link. + async fn connect(&mut self) -> Conn { + let options = VoiceOptions::new("fake.test:9987", "tester"); + self.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) }); + tokio::time::timeout(Duration::from_secs(10), self.conns.recv()) + .await + .expect("the session spawns the link") + .expect("the link lives") + } + + /// The next event `f` picks, skipping the others. + async fn next(&mut self, mut f: impl FnMut(Event) -> Option) -> T { + tokio::time::timeout(Duration::from_secs(10), async { + loop { + if let Some(t) = f(self.events.recv().await.expect("engine events")) { + return t; + } + } + }) + .await + .expect("event in time") + } + + /// The next state of the session that `ok` accepts. + async fn state(&mut self, mut ok: impl FnMut(&SessionState) -> bool) -> SessionState { + self.next(|e| match e { + Event::State { state, .. } if ok(&state) => Some(state), + _ => None, + }) + .await + } + + /// The next live chat message. + async fn chat(&mut self) -> ChatMessage { + self.next(|e| match e { + Event::Chat { message, .. } => Some(message), + _ => None, + }) + .await + } + + /// The messages stored for `target`, oldest first. + async fn stored(&self, target: ChatTarget) -> Vec { + self.engine + .history() + .page(SERVER_UID, &target, Default::default(), false) + .await + .expect("the history") + } +} + +fn now_ms() -> i64 { + SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64 +} + +fn capabilities(streams: bool) -> Capabilities { + Capabilities { streams, file_transfer: true, ..Default::default() } +} + +fn backend() -> BackendInfo { + BackendInfo { product: "Fake".into(), version: "1.2".into() } +} + +fn connected(streams: bool) -> LinkEvent { + LinkEvent::Connected { + name: "Fake Server".into(), + backend: backend(), + capabilities: capabilities(streams), + own_client: ME, + server_uid: SERVER_UID.into(), + own_uid: Some(ME_UID.into()), + } +} + +fn client(id: u16, nickname: &str, channel: ChannelId) -> ClientInfo { + ClientInfo { + id, + uid: Some(format!("{nickname}=")), + nickname: nickname.into(), + channel, + ..Default::default() + } +} + +/// Two channels, three clients; we are in the second channel. +fn presence() -> Presence { + let channel = |id, name: &str| ChannelInfo { id, name: name.into(), ..Default::default() }; + let mut presence = Presence { server_name: "Fake Server".into(), ..Default::default() }; + presence.channels.insert(LOBBY, channel(LOBBY, "Lobby")); + presence.channels.insert(GAMES, channel(GAMES, "Games")); + for c in [client(ME, "tester", GAMES), client(8, "alice", GAMES), client(9, "bob", LOBBY)] { + presence.clients.insert(c.id, c); + } + presence +} + +fn message(author: &str, text: &str, ts_ms: i64) -> ChatMessage { + ChatMessage { + target: ChatTarget::Channel(GAMES), + author_name: author.into(), + author_uid: Some(format!("{author}=")), + author_id: None, + text: text.into(), + ts_ms, + via_relay: false, + blocked: false, + } +} + +/// Connecting, the server's presence, moving, talking, a failing command +/// and the end of the connection, as the session reports them. +#[tokio::test(flavor = "multi_thread")] +async fn presence_follows_the_link_until_it_disconnects() { + let mut h = Harness::start(); + let conn = h.connect().await; + // What the link was given. + assert_eq!( + (conn.options.address.as_str(), conn.options.nickname.as_str()), + ("fake.test:9987", "tester") + ); + assert_eq!(conn.session, SESSION); + h.state(|s| s.voice == VoiceState::Connecting).await; + + conn.play([ + connected(false), + LinkEvent::Presence(Box::new(presence())), + LinkEvent::OwnChannel(GAMES), + ]); + // In the order the session tells them: the server, its presence, our channel. + let (name, info, caps) = h + .next(|e| match e { + Event::ServerInfo { name, backend, capabilities, .. } => { + Some((name, backend, capabilities)) + } + _ => None, + }) + .await; + assert_eq!((name.as_str(), info.label().as_str()), ("Fake Server", "Fake 1.2")); + assert_eq!(caps, capabilities(false)); + let shown = h + .next(|e| match e { + Event::Presence { presence, .. } if !presence.clients.is_empty() => Some(presence), + _ => None, + }) + .await; + assert_eq!(*shown, presence()); + let state = h.state(|s| s.own_channel == Some(GAMES)).await; + assert_eq!(state.voice, VoiceState::Connected); + assert_eq!(state.own_client, Some(ME)); + assert_eq!(state.server_uid.as_deref(), Some(SERVER_UID)); + assert_eq!(state.presence_source, Some(Source::Voice)); + + conn.play([ + LinkEvent::Talking { client: 8, talking: true }, + LinkEvent::Poke { + from: 8, + from_uid: Some("alice=".into()), + from_name: "alice".into(), + message: "wake up".into(), + }, + LinkEvent::Error("move refused".into()), + ]); + h.next(|e| matches!(e, Event::Talking { client: 8, talking: true, .. }).then_some(())).await; + let poke = h + .next(|e| match e { + Event::Poke { from_name, message, blocked, .. } => Some((from_name, message, blocked)), + _ => None, + }) + .await; + assert_eq!(poke, ("alice".into(), "wake up".into(), false)); + let error = h + .next(|e| match e { + Event::Error { message, .. } => Some(message), + _ => None, + }) + .await; + assert_eq!(error, "move refused"); + + // The link ends the connection: the session forgets what it showed. + conn.play([LinkEvent::Disconnected(Some("server shut down".into()))]); + let state = h.state(|s| s.voice == VoiceState::Disconnected).await; + assert_eq!((state.own_channel, state.own_client), (None, None)); + let error = h + .next(|e| match e { + Event::Error { message, .. } => Some(message), + _ => None, + }) + .await; + assert_eq!(error, "voice: server shut down"); + let state = h.state(|s| s.presence_source.is_none()).await; + assert_eq!(state.voice, VoiceState::Disconnected); + let shown = h + .next(|e| match e { + Event::Presence { presence, .. } => Some(presence), + _ => None, + }) + .await; + assert!(shown.clients.is_empty() && shown.channels.is_empty()); +} + +/// What the user asks for reaches the link; streams only where the link's +/// capabilities say it has them. +#[tokio::test(flavor = "multi_thread")] +async fn commands_reach_the_link() { + let mut h = Harness::start(); + let mut conn = h.connect().await; + conn.play([ + connected(false), + LinkEvent::Presence(Box::new(presence())), + LinkEvent::OwnChannel(GAMES), + ]); + h.state(|s| s.own_channel == Some(GAMES)).await; + + let engine = h.engine.clone(); + engine.send(Command::SendChat { + session: SESSION, + target: ChatTarget::Channel(GAMES), + text: "hello".into(), + }); + let LinkCmd::SendChat(target, text) = conn.cmd().await else { panic!("a chat message") }; + assert_eq!((target, text.as_str()), (ChatTarget::Channel(GAMES), "hello")); + engine.send(Command::MoveToChannel { + session: SESSION, + channel: LOBBY, + password: Some("pw".into()), + }); + let LinkCmd::Move(channel, password) = conn.cmd().await else { panic!("a move") }; + assert_eq!((channel, password.as_deref()), (LOBBY, Some("pw"))); + engine.send(Command::SetInputMuted { session: SESSION, muted: true }); + assert!(matches!(conn.cmd().await, LinkCmd::SetInputMuted(true))); + assert!(h.state(|s| s.input_muted).await.input_muted); + engine.send(Command::Poke { session: SESSION, client: 8, message: "hi".into() }); + assert!(matches!(conn.cmd().await, LinkCmd::Poke { client: 8, .. })); + engine.send(Command::ListFiles { + session: SESSION, + request: 5, + channel: GAMES, + password: None, + path: "/docs/".into(), + }); + let LinkCmd::ListFiles { request, dir } = conn.cmd().await else { panic!("a file list") }; + assert_eq!((request, dir.channel, dir.path.as_str()), (5, GAMES, "/docs/")); + + // No streams in the capabilities: the session refuses them itself. + let setup = || StreamSetup { name: "screen".into(), ..Default::default() }; + engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true }); + let error = h + .next(|e| match e { + Event::Error { message, .. } => Some(message), + _ => None, + }) + .await; + assert!(error.contains("streams"), "{error}"); + assert!(conn.cmds.try_recv().is_err(), "nothing reached the link"); + + // A link with streams: stream commands go to it, and end with the connection. + let mut with_streams = { + let link_engine = h.engine.clone(); + link_engine.send(Command::ConnectVoice { + session: SESSION, + options: Box::new(VoiceOptions::new("fake.test:9987", "tester")), + }); + h.conns.recv().await.expect("the second connection") + }; + // The replaced connection is told to go. + assert!(matches!(conn.cmd().await, LinkCmd::Disconnect)); + with_streams.play([connected(true)]); + h.next(|e| match e { + Event::ServerInfo { capabilities, .. } if capabilities.streams => Some(()), + _ => None, + }) + .await; + // A connection with streams is given the (empty) stream directory first. + let LinkCmd::Stream(StreamCmd::Directory(directory)) = with_streams.cmd().await else { + panic!("the stream directory") + }; + assert!(directory.is_empty()); + engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true }); + let LinkCmd::Stream(StreamCmd::Start { setup, auto_accept }) = with_streams.cmd().await else { + panic!("a stream start") + }; + assert_eq!((setup.name.as_str(), auto_accept), ("screen", true)); + engine.send(Command::StopStream { session: SESSION }); + assert!(matches!(with_streams.cmd().await, LinkCmd::Stream(StreamCmd::Stop))); + engine.send(Command::DisconnectVoice { session: SESSION }); + assert!(matches!(with_streams.cmd().await, LinkCmd::Disconnect)); +} + +/// A message we send is stored at once; the server's copy of it merges +/// into the same row, and is shown (once). +#[tokio::test(flavor = "multi_thread")] +async fn a_sent_message_and_its_echo_are_one_message() { + let mut h = Harness::start(); + let mut conn = h.connect().await; + conn.play([ + connected(false), + LinkEvent::Presence(Box::new(presence())), + LinkEvent::OwnChannel(GAMES), + ]); + h.state(|s| s.own_channel == Some(GAMES)).await; + + h.engine.send(Command::SendChat { + session: SESSION, + target: ChatTarget::Channel(GAMES), + text: "hello".into(), + }); + assert!(matches!(conn.cmd().await, LinkCmd::SendChat(..))); + // The server sends it back to everyone in the channel, to us too. + let mut echo = message("tester", "hello", now_ms()); + echo.author_uid = Some(ME_UID.into()); + echo.author_id = Some(ME); + conn.play([LinkEvent::Chat(echo.clone())]); + let shown = h.chat().await; + assert_eq!((shown.author_name.as_str(), shown.text.as_str()), ("tester", "hello")); + + // A marker: what comes next is the next message, not a second "hello". + conn.play([LinkEvent::Chat(message("alice", "marker", now_ms()))]); + assert_eq!(h.chat().await.text, "marker"); + let rows = h.stored(ChatTarget::Channel(GAMES)).await; + let texts: Vec<_> = rows.iter().map(|m| m.message.text.as_str()).collect(); + assert_eq!(texts, ["hello", "marker"]); + assert_eq!(rows[0].source, MessageSource::Local); +} + +/// A message that comes twice (the server's and a relay's copy, with the +/// relay's `[nick] ` prefix) is shown once. +#[tokio::test(flavor = "multi_thread")] +async fn a_message_that_comes_twice_is_shown_once() { + let mut h = Harness::start(); + let conn = h.connect().await; + h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) }); + conn.play([ + connected(false), + LinkEvent::Presence(Box::new(presence())), + LinkEvent::OwnChannel(GAMES), + ]); + h.state(|s| s.own_channel == Some(GAMES)).await; + + let t = now_ms(); + let mut relayed = message("alice", "[alice] gg everyone", t + 300); + relayed.via_relay = true; + conn.play([ + LinkEvent::Chat(message("alice", "gg everyone", t)), + LinkEvent::Chat(relayed), + // The same words much later are another message. + LinkEvent::Chat(message("alice", "gg everyone", t + 10_000)), + LinkEvent::Chat(message("bob", "gg everyone", t + 10_100)), + ]); + let shown: Vec<_> = { + let mut shown = Vec::new(); + while shown.len() < 3 { + shown.push(h.chat().await); + } + shown + }; + let who: Vec<_> = shown.iter().map(|m| (m.author_name.as_str(), m.ts_ms)).collect(); + assert_eq!(who, [("alice", t), ("alice", t + 10_000), ("bob", t + 10_100)]); +} + +/// Stored messages come back when a chat opens, also after the connection +/// is gone; the server's id keys them. +#[tokio::test(flavor = "multi_thread")] +async fn history_is_kept_across_the_connection() { + let mut h = Harness::start(); + let conn = h.connect().await; + conn.play([ + connected(false), + LinkEvent::Presence(Box::new(presence())), + LinkEvent::OwnChannel(GAMES), + ]); + h.state(|s| s.own_channel == Some(GAMES)).await; + let t = now_ms(); + conn.play([ + LinkEvent::Chat(message("alice", "first", t)), + LinkEvent::Chat(message("bob", "second", t + 1_000)), + // A private message to us is stored under its peer, not the channel. + LinkEvent::Chat(ChatMessage { + target: ChatTarget::Private("alice=".into()), + ..message("alice", "psst", t + 2_000) + }), + ]); + for _ in 0..3 { + h.chat().await; + } + conn.play([LinkEvent::Disconnected(None)]); + h.state(|s| s.voice == VoiceState::Disconnected).await; + + h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) }); + // The stored page (the live batches of the messages came before). + let messages = h + .next(|e| match e { + Event::ChatHistory { messages, source: HistorySource::Local, .. } => Some(messages), + _ => None, + }) + .await; + let texts: Vec<_> = messages.iter().map(|m| m.message.text.as_str()).collect(); + assert_eq!(texts, ["first", "second"]); + let private = h.stored(ChatTarget::Private("alice=".into())).await; + assert_eq!(private.len(), 1); + assert_eq!(private[0].message.text, "psst"); +} + +/// Events of a connection the session replaced do not reach it. +#[tokio::test(flavor = "multi_thread")] +async fn a_replaced_connection_is_ignored() { + let mut h = Harness::start(); + let mut old = h.connect().await; + old.play([ + connected(false), + LinkEvent::Presence(Box::new(presence())), + LinkEvent::OwnChannel(GAMES), + ]); + h.state(|s| s.own_channel == Some(GAMES)).await; + + let new = h.connect().await; + assert!(matches!(old.cmd().await, LinkCmd::Disconnect)); + // The old connection winds down, and says more than it should. + let mut stale = presence(); + stale.clients.insert(10, client(10, "ghost", LOBBY)); + old.play([ + LinkEvent::Presence(Box::new(stale)), + LinkEvent::Chat(message("ghost", "boo", now_ms())), + LinkEvent::Disconnected(None), + ]); + let mut fresh = presence(); + fresh.clients.remove(&9); + new.play([ + connected(false), + LinkEvent::Presence(Box::new(fresh.clone())), + LinkEvent::OwnChannel(LOBBY), + ]); + // Only the new connection's presence is shown (nobody else has 2 clients). + let shown = h + .next(|e| match e { + Event::Presence { presence, .. } if presence.clients.len() == fresh.clients.len() => { + Some(presence) + } + _ => None, + }) + .await; + assert_eq!(*shown, fresh); + let state = h.state(|s| s.own_channel == Some(LOBBY)).await; + assert_eq!(state.voice, VoiceState::Connected, "the old disconnect did not count"); + new.play([LinkEvent::Chat(message("alice", "hello", now_ms()))]); + assert_eq!(h.chat().await.text, "hello", "the old connection's chat never showed"); +} diff --git a/docs/architecture.md b/docs/architecture.md index b2cb0b9..2eaeb38 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -72,7 +72,7 @@ fuzz/ cargo-fuzz targets | `voelin-store` | Identities, bookmarks, settings, chat history (dedupe, paging, sync cursors, where each chat was read), contacts, secrets (keyring / Android Keystore); versioned schema | done | | `voelin-audio` | Capture/playback, Opus, echo cancellation, resampling, jitter buffer, mixer, VAD/push-to-talk; the voice packet types (`TalkerId`, `VoicePacket`, `EncodedVoice`), so it depends on no voice transport | v0 (no AEC yet) | | `voelin-stream` | TS6 stream commands, JSON signalling, str0m peer connections, host/STUN candidates, streamer/viewer sessions, frame-source seam; its frame and simulcast layer types are `voelin-media`'s | sessions + transport | -| `voelin-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API, chat history, the gateway's features, audio settings and volumes, streams on TS6, files, avatar and icon cache, pokes, offline messages, contacts; `media` module (capture → encoder → stream, stream → decoder); the stream types of its API are its own (`stream_types`, see Streams) | done | +| `voelin-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, the `ServerLink` seam the voice source sits behind (`link.rs`; `TsLink` is the TeamSpeak implementation, for now in this crate), event bus, command API, chat history, the gateway's features, audio settings and volumes, streams on TS6, files, avatar and icon cache, pokes, offline messages, contacts; `media` module (capture → encoder → stream, stream → decoder); the stream types of its API are its own (`stream_types`, see Streams) | done | | `voelin-ui` | Slint UI and the desktop binary: streams panel, viewer, share dialog, audio / hotkey / codec settings | done (desktop) | | `voelin-media` | Screen and system-audio capture backends (PipeWire portal, X11, Windows Graphics Capture, Android MediaProjection), video codecs; the frame and simulcast layer types of a stream (`stream::EncodedFrame`, `LayerSpec`, `LayerId`, `LayerSet`) | done (desktop hardware encoders through FFmpeg loaded at runtime, not run on a GPU yet; MediaCodec not run on a device yet) | | `voelin-platform` | Global hotkeys, notifications, paths, crash reports, notices | done | @@ -87,6 +87,60 @@ the native command only when voice-connected *and* in that channel, otherwise th gateway, otherwise a local query relay. UI states: `Offline`, `Observing (Gateway|Query)` (invisible), `Connecting`, `Connected`. +## The server link + +A session's voice source, the connection that is visible on the server and +can talk, is a `voelin_core::link::ServerLink`, not a TeamSpeak connection +the session knows about. The trait has one method, +`spawn(options, ctx, cmds, events)`, which starts a connection on its own +task and returns: + +- `options` is a `ConnectOptions` (the app calls it `VoiceOptions`): address, + nickname, password, channel to join, whether to open the audio devices; +- `ctx` is a `LinkCtx`: the session id, the event bus the link answers + requests on (file lists, transfers, offline messages, stream state), the + bus for the frames of watched streams, and the settings; +- `cmds` carries `LinkCmd`s in: chat, moves, mute, pokes, the encoded + voice frames from the audio thread, the file and offline-message requests, + `Stream(StreamCmd)` and `Disconnect`; +- `events` carries `LinkEvent`s out: `Connected` (name, `BackendInfo`, + `Capabilities`, our client id, the server's unique id), `Presence` (a full + snapshot each time), `OwnChannel`, `Chat`, `Poke`, `Audio` (a received + `VoicePacket`), `Talking`, `OwnStream`, `StreamAudio` (the audio of a watched + stream, for the audio thread's mixer), `Error` and, last, `Disconnected`. + +Everything backend-neutral stays in `session.rs`: merging the three sources, +the dedup of a message that arrives twice, the chat history, contacts, the +privacy rules, the images and the gateway directory. The session tags each +link with a generation, so events of a replaced one are ignored. A link +reports what the server can do as `Capabilities`; with `streams` set it also +runs the stream task (`stream.rs`), which the session reaches only through +`LinkCmd::Stream(StreamCmd)` (start, stop, answer a viewer, watch, layers, +frames, friends, the gateway directory, shutdown) and which reports our own +stream's life back as `LinkEvent::OwnStream`. The stream task's requests +and the server's stream notifications never leave the link. + +`Engine::start_with_link(settings, history, link)` takes the link; +`Engine::start` and `start_with` use `TsLink` (`ts_link.rs`), the +TeamSpeak 3 and 6 connection of `tsclientlib`, which runs `voice.rs` with +`book.rs`, `stream.rs`, `versions.rs` and `identity.rs`. `tests/link_fake.rs` +drives the session with an in-memory link instead: it plays scripted +`LinkEvent`s (connect, presence, a message twice, a disconnect, a replaced +connection) and checks the presence, chat, dedup and history the session +makes of them, and the commands it gives back, with no TeamSpeak server or +crate involved. + +Where this is going: `ServerLink` is this crate's interim seam. `TsLink` and +the modules it owns move to VoelinGateWay (`voelin-gateway-ts`, the +in-process TeamSpeak gateway), and the QUIC transport of VoelinProtocol +becomes the other implementation, both behind the backend-neutral +`voelin_proto::link::Session` that the protocol spec defines (the spec +replaces `voelin_core::link::ServerLink` by it, because the gateway +implements the trait and the client depends on the gateway). What still has +TeamSpeak types in the seam, and leaves with `TsLink`: the identity and +version in `ConnectOptions`, the myTeamSpeak account proof in `LinkCtx`, and the +peer and media vocabulary of the stream API (below). + ## What the engine tells of the server's software `Event::ServerInfo { session, name, backend, capabilities }` is the one place @@ -98,7 +152,7 @@ kinds, files, offline messages). The UI shows `product` on a server's chip and `BackendInfo::label()` in the status line, and branches on capabilities only. The TeamSpeak 3 / 6 classification (`voelin_model::ServerFlavor`, from the `virtualserver_version` string) happens in the voice source -(`voice.rs::backend_of`), which puts both in `VoiceEvent::Connected`; no +(`voice.rs::backend_of`), which puts both in `LinkEvent::Connected`; no `ServerFlavor` appears in the engine's public API, so another link (a Voelin server) can fill the same two fields. @@ -341,17 +395,20 @@ stream task converts what `Streams` reports, and what the UI asks for own types (its `StreamInfo`, `ViewerInfo`, `StreamSetup`, `SrtpProfile`, `EndReason`) no longer show in `Command` and `Event`. Still `voelin-stream`'s in the engine's API are the peer and media vocabulary: -`PeerConfig` (in `VoiceOptions`), `MediaFrame` (the frames of watched +`PeerConfig` (in `ConnectOptions`), `MediaFrame` (the frames of watched streams), `VideoFormat` and `VideoCodec` (on the `StreamSink`), `FrameSource`, `SyntheticSource`; they move out of the core with the stream task (the decoupling plan's next steps). -In `voelin-core` a stream task per voice connection runs `Streams`; the voice task -forwards `MessageEvent`s and sends the requests. Encoders push frames through +In `voelin-core` a stream task per voice connection runs `Streams`. The link +owns the task (see [The server link](#the-server-link)): the TeamSpeak +connection hands it the `MessageEvent`s as notifications and the clients' +channels, and sends its requests; the session talks to it with +`LinkCmd::Stream(StreamCmd)`. Encoders push frames through the `StreamSink` of `StreamState::Live`; received frames of watched streams go to `Engine::subscribe_frames`, not the event bus. The audio of watched streams -goes straight to the session's audio thread, which mixes it like a talker -with its own volume (`Command::SetStreamVolume`). +goes to the session as `LinkEvent::StreamAudio` and on to its audio thread, +which mixes it like a talker with its own volume (`Command::SetStreamVolume`). `voelin-core::media` (feature `media`) connects this to `voelin-media`: `Streamer` captures (screen, window, portal or the test pattern, plus system diff --git a/docs/audio.md b/docs/audio.md index 60ddaa2..99c1b5d 100644 --- a/docs/audio.md +++ b/docs/audio.md @@ -30,7 +30,9 @@ TeamSpeak connection that is `out_audio` and `voice_packet` in `voelin-core/src/voice.rs`, the only place that builds TeamSpeak audio packets from `EncodedVoice` or reads them into `VoicePacket`s (codecs other than Opus are dropped there, as the jitter buffer never played them). The audio thread, -the session and the mixer see only the types above. +the session and the mixer see only the types above, and so does the link's +seam: `LinkCmd::Audio` carries an `EncodedVoice` out and `LinkEvent::Audio` a +`VoicePacket` in (`voelin-core/src/link.rs`). ## Echo cancellation, noise suppression, gain control