From a3969074fd065070a7ec987280a3f47d97cb0499 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 19:48:06 +0000 Subject: [PATCH 01/13] tsc-stream: stream sessions and a frame-source seam Streams drives one connection's TS6 streams without doing connection IO: it takes stream notifications and app decisions, owns the str0m peers and queues requests (to send as commands) and events. - StreamerSession: setupstream, join requests (auto-accept or ask the app), one peer per viewer with the offer in respondjoinstreamrequest, answers and trickled candidates, withdrawal, reconnect (new offer as reconnectOffer), kick, stop (also before the stream went live), merged keyframe requests, frame fan-out to connected viewers - ViewerSession: joinstreamrequest, answer the offer from the response or an offer/reconnectOffer signal, candidates, denial, stop, removal, leave, reconnect after a lost connection (up to three times) - StreamDirectory: streams in the channel from notifications and client_is_streaming - FrameSource + SyntheticSource: decodable 1x1 VP8 keyframes (padded) and Opus silence in real time, for tests and tsctl - Peer: poll_event for driving many peers from one task; trickled local candidates carry the bundle mid Transcript unit tests and an end-to-end test through a fake relay server. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- crates/tsc-stream/src/lib.rs | 11 + crates/tsc-stream/src/peer.rs | 16 +- crates/tsc-stream/src/session.rs | 1539 +++++++++++++++++++++++++++ crates/tsc-stream/src/source.rs | 129 +++ crates/tsc-stream/tests/sessions.rs | 280 +++++ 5 files changed, 1971 insertions(+), 4 deletions(-) create mode 100644 crates/tsc-stream/src/session.rs create mode 100644 crates/tsc-stream/src/source.rs create mode 100644 crates/tsc-stream/tests/sessions.rs diff --git a/crates/tsc-stream/src/lib.rs b/crates/tsc-stream/src/lib.rs index fad7a83..d6fef35 100644 --- a/crates/tsc-stream/src/lib.rs +++ b/crates/tsc-stream/src/lib.rs @@ -4,14 +4,25 @@ //! Only TeamSpeak 6 servers support streams. Media flows peer to peer; the //! server only forwards `respondjoinstreamrequest` (the streamer's offer) and //! `streamsignaling` (answer and ICE candidates). +//! +//! [`Streams`] (module [`session`]) ties it together for one connection: the +//! streams in our channel, our own stream with a peer per viewer, and the +//! streams we watch. [`FrameSource`] is where a streamer's encoded frames come from. pub mod peer; pub mod proto; +pub mod session; pub mod signal; +pub mod source; pub mod stun; pub use peer::{MediaFrame, Peer, PeerConfig, PeerError, PeerEvent, VideoCodec}; pub use proto::{LeaveReason, StreamInfo, StreamKind, StreamNotification, StreamSetup}; +pub use session::{ + EndReason, Output, Request, SessionError, StreamDirectory, StreamEvent, StreamerEvent, + StreamerOptions, Streams, ViewerInfo, ViewerState, WatchEvent, WatchState, +}; pub use signal::{Signal, SignalError}; +pub use source::{EncodedFrame, FrameSource, SyntheticSource}; pub use str0m::format::Codec; pub use str0m::media::{Frequency, MediaKind, MediaTime}; diff --git a/crates/tsc-stream/src/peer.rs b/crates/tsc-stream/src/peer.rs index 90f6e95..b253901 100644 --- a/crates/tsc-stream/src/peer.rs +++ b/crates/tsc-stream/src/peer.rs @@ -9,6 +9,7 @@ use std::collections::HashMap; use std::hash::{BuildHasher, RandomState}; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; +use std::task::{Context, Poll}; use std::time::{Duration, Instant}; use str0m::change::{SdpAnswer, SdpOffer, SdpPendingOffer}; @@ -100,8 +101,9 @@ pub enum PeerEvent { /// ICE and DTLS are up; media can flow. Connected, /// A candidate found after the SDP was sent (server reflexive), as an SDP - /// `candidate:` line for [`crate::Signal::IceCandidate`]. - LocalCandidate(String), + /// `candidate:` line for [`crate::Signal::IceCandidate`], with the mid of + /// the first (bundled) media line. + LocalCandidate { candidate: String, mid: Option }, /// A received frame (depacketized). Media(MediaFrame), /// The viewer asks for a keyframe. @@ -225,6 +227,11 @@ impl Peer { pub fn try_next_event(&mut self) -> Option { self.events.try_recv().ok() } + + /// Poll for the next event, for driving many peers from one task. + pub fn poll_event(&mut self, cx: &mut Context<'_>) -> Poll> { + self.events.poll_recv(cx) + } } impl Drop for Peer { @@ -420,9 +427,10 @@ impl Task { } match Candidate::server_reflexive(mapped, pending.base, "udp") { Ok(c) => { - let line = c.to_sdp_string(); + let candidate = c.to_sdp_string(); + let mid = self.mids.first().map(|(mid, _)| mid.to_string()); if self.rtc.add_local_candidate(c).is_some() { - let _ = self.events.send(PeerEvent::LocalCandidate(line)); + let _ = self.events.send(PeerEvent::LocalCandidate { candidate, mid }); } } Err(e) => debug!("bad reflexive candidate {mapped}: {e}"), diff --git a/crates/tsc-stream/src/session.rs b/crates/tsc-stream/src/session.rs new file mode 100644 index 0000000..9f2a1e1 --- /dev/null +++ b/crates/tsc-stream/src/session.rs @@ -0,0 +1,1539 @@ +//! Stream sessions: the streamer's and the viewer's side of TeamSpeak 6 +//! streams as state machines, and the list of streams in our channel. +//! +//! The sessions do no connection IO. They are fed the stream notifications of +//! one server connection and the app's decisions, and queue [`Output`]s: a +//! [`Request`] to send on the connection or a [`StreamEvent`] for the app. +//! They own the WebRTC [`Peer`]s (one per viewer on the streamer's side, one +//! per watched stream on the viewer's side). [`Streams::wait_peers`] handles +//! peer events and is cancel safe, so it can sit in a `select!` next to the +//! connection: +//! +//! ```ignore +//! loop { +//! tokio::select! { +//! msg = messages.next() => { +//! for n in StreamNotification::from_message(&msg) { +//! streams.handle_notification(n).await; +//! } +//! } +//! () = streams.wait_peers() => {} +//! } +//! while let Some(output) = streams.poll_output() { +//! // Output::Request: send `request.to_command()`, report failures +//! // with `streams.request_failed`. Output::Event: tell the app. +//! } +//! } +//! ``` + +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::sync::Arc; +use std::task::{Context, Poll}; +use std::time::{Duration, Instant}; + +use str0m::media::{MediaKind, MediaTime}; +use tracing::{debug, warn}; +use tsclientlib::ClientId; +use tsproto_packets::packets::OutCommand; + +use crate::peer::{MediaFrame, Peer, PeerConfig, PeerEvent}; +use crate::proto::{self, LeaveReason, StreamInfo, StreamNotification, StreamSetup}; +use crate::signal::Signal; +use crate::source::EncodedFrame; + +/// Keyframe requests closer together than this are merged into one event. +const KEYFRAME_INTERVAL: Duration = Duration::from_millis(250); +/// How often a viewer asks for a new offer after its connection failed. +const MAX_RECONNECTS: u32 = 3; +/// Peer events handled per peer and poll, so one busy peer cannot starve the rest. +const EVENTS_PER_POLL: usize = 64; + +/// A command for the server. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Request { + /// `setupstream`: start our stream. + Setup(StreamSetup), + /// `stopstream`: end our stream. + Stop { id: String }, + /// `joinstreamrequest ... is_remove=0`: ask to watch. + Join { id: String, streamer: ClientId, message: String }, + /// `joinstreamrequest ... is_remove=1`: withdraw the request or stop watching. + Leave { id: String, streamer: ClientId }, + /// `respondjoinstreamrequest`: accept a viewer with our offer, or deny. + Respond { id: String, viewer: ClientId, offer: Option, accept: bool }, + /// `streamsignaling` + Signal { id: String, peer: ClientId, signal: Signal }, + /// `removeclientfromstream` + RemoveViewer { id: String, viewer: ClientId, reason: LeaveReason }, +} + +impl Request { + pub fn to_command(&self) -> OutCommand { + match self { + Self::Setup(setup) => proto::setup(setup), + Self::Stop { id } => proto::stop(id), + Self::Join { id, streamer, message } => { + proto::join_request(id, *streamer, message, false) + } + Self::Leave { id, streamer } => proto::join_request(id, *streamer, "", true), + Self::Respond { id, viewer, offer, accept } => { + proto::respond(id, *viewer, offer.as_deref(), *accept) + } + Self::Signal { id, peer, signal } => proto::signaling(id, *peer, &signal.to_json()), + Self::RemoveViewer { id, viewer, reason } => proto::remove_viewer(id, *viewer, *reason), + } + } +} + +/// Why a stream ended for us. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EndReason { + /// We stopped streaming or watching. + Local, + /// The streamer denied our join request. + Denied, + /// The stream was stopped (or its streamer disconnected). + Stopped, + /// The streamer or the server ended our viewing session. + Removed(Option), + /// A command failed or no connection could be established. + Failed(String), +} + +/// A viewer of our stream, as the streamer sees it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ViewerState { + /// Asked to watch, waiting for our decision. + Requested, + /// Offer sent; waiting for the answer and the connection. + Connecting, + Connected, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ViewerInfo { + pub client: ClientId, + pub state: ViewerState, + /// The message of the join request. + pub message: String, +} + +/// What happens to our own stream. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum StreamerEvent { + /// The server confirmed `setupstream`: the stream is live under `id`. + Live { + id: String, + }, + /// A viewer asks to watch (without auto-accept); answer with [`Streams::respond`]. + Request { + viewer: ClientId, + message: String, + }, + /// The viewers or their states changed (full list). + Viewers(Vec), + /// A viewer connected or lost a frame: the encoder should send a keyframe. + KeyframeRequest, + Ended(EndReason), +} + +/// What happens to a stream we watch. +#[derive(Clone, Debug)] +pub enum WatchEvent { + /// The streamer accepted our join request; connecting. + Accepted, + Connected, + /// An encoded video or audio frame. + Frame(MediaFrame), + Ended(EndReason), +} + +#[derive(Clone, Debug)] +pub enum StreamEvent { + /// The streams in our channel changed (full list). + Streams(Vec), + /// Our own stream. + Streamer(StreamerEvent), + /// A stream we watch. + Watch { id: String, event: WatchEvent }, +} + +#[derive(Clone, Debug)] +pub enum Output { + /// Send `request.to_command()` on the connection. + Request(Request), + Event(StreamEvent), +} + +/// Queue of [`Output`]s the sessions append to. +#[derive(Debug, Default)] +pub struct Outbox(VecDeque); + +impl Outbox { + pub fn request(&mut self, request: Request) { + self.0.push_back(Output::Request(request)); + } + + pub fn event(&mut self, event: StreamEvent) { + self.0.push_back(Output::Event(event)); + } + + pub fn pop(&mut self) -> Option { + self.0.pop_front() + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + +/// A call the sessions cannot carry out. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum SessionError { + #[error("already streaming")] + AlreadyStreaming, + #[error("not streaming")] + NotStreaming, + #[error("the stream is not live yet")] + NotLive, + #[error("client {0} has not asked to watch")] + NoRequest(u16), + #[error("client {0} is not a viewer")] + UnknownViewer(u16), + #[error("unknown stream {0}")] + UnknownStream(String), + #[error("already watching stream {0}")] + AlreadyWatching(String), + #[error("not watching stream {0}")] + NotWatching(String), + #[error("cannot watch our own stream")] + OwnStream, +} + +/// The streams in our channel, from `notifystreamstarted`/`notifystreaminfo`/ +/// `notifystreamstopped` and the clients' `client_is_streaming`. +#[derive(Clone, Debug, Default)] +pub struct StreamDirectory { + streams: BTreeMap, + /// Clients with `client_is_streaming=1`. + streaming: BTreeSet, +} + +impl StreamDirectory { + /// Apply a notification; `true` if the list of streams changed. + pub fn apply(&mut self, n: &StreamNotification) -> bool { + match n { + StreamNotification::Started { info, .. } | StreamNotification::Info(info) => { + self.streaming.insert(info.streamer.0); + self.streams.insert(info.id.clone(), info.clone()).as_ref() != Some(info) + } + StreamNotification::Stopped { id, .. } => self.streams.remove(id).is_some(), + _ => false, + } + } + + /// `client_is_streaming` of a client changed. When it stops, its streams + /// are dropped; returns `true` if the list of streams changed. + pub fn set_streaming(&mut self, client: ClientId, streaming: bool) -> bool { + if streaming { + self.streaming.insert(client.0); + false + } else { + self.streaming.remove(&client.0); + self.retain_streamers(|c| c != client) + } + } + + /// Drop the streams of streamers `keep` rejects (e.g. clients that left). + pub fn retain_streamers(&mut self, mut keep: impl FnMut(ClientId) -> bool) -> bool { + let before = self.streams.len(); + self.streams.retain(|_, s| keep(s.streamer)); + self.streaming.retain(|c| keep(ClientId(*c))); + self.streams.len() != before + } + + pub fn get(&self, id: &str) -> Option<&StreamInfo> { + self.streams.get(id) + } + + pub fn by_streamer(&self, client: ClientId) -> Option<&StreamInfo> { + self.streams.values().find(|s| s.streamer == client) + } + + pub fn iter(&self) -> impl Iterator { + self.streams.values() + } + + pub fn to_vec(&self) -> Vec { + self.streams.values().cloned().collect() + } + + /// Clients that stream, but whose stream id we have not been told. + pub fn unannounced_streamers(&self) -> impl Iterator + '_ { + self.streaming + .iter() + .filter(|c| !self.streams.values().any(|s| s.streamer.0 == **c)) + .map(|c| ClientId(*c)) + } +} + +/// Options for our own stream. +#[derive(Clone, Debug, Default)] +pub struct StreamerOptions { + pub setup: StreamSetup, + /// Accept every join request. Otherwise each one is reported as + /// [`StreamerEvent::Request`] and answered with [`Streams::respond`]. + pub auto_accept: bool, +} + +struct ViewerSlot { + state: ViewerState, + message: String, + /// `None` while the viewer waits for our decision or after its connection closed. + peer: Option, +} + +/// Our own stream: `setupstream`, one peer connection per accepted viewer. +pub struct StreamerSession { + own: ClientId, + options: StreamerOptions, + config: PeerConfig, + id: Option, + ended: bool, + /// Stopped before the server confirmed the setup: stop once it does. + stop_when_live: bool, + viewers: BTreeMap, + last_keyframe_request: Option, +} + +impl StreamerSession { + /// Start streaming: queues `setupstream`. + pub fn start( + own: ClientId, + options: StreamerOptions, + config: PeerConfig, + out: &mut Outbox, + ) -> Self { + out.request(Request::Setup(options.setup.clone())); + Self { + own, + options, + config, + id: None, + ended: false, + stop_when_live: false, + viewers: BTreeMap::new(), + last_keyframe_request: None, + } + } + + /// The stream id, once the server confirmed the setup. + pub fn id(&self) -> Option<&str> { + self.id.as_deref() + } + + pub fn is_ended(&self) -> bool { + self.ended + } + + /// Ended and nothing left to send. + fn is_finished(&self) -> bool { + self.ended && !self.stop_when_live + } + + pub fn viewers(&self) -> Vec { + self.viewers + .iter() + .map(|(clid, v)| ViewerInfo { + client: ClientId(*clid), + state: v.state, + message: v.message.clone(), + }) + .collect() + } + + /// Whether `n` is about this stream. + pub fn wants(&self, n: &StreamNotification) -> bool { + match (&self.id, n) { + (None, StreamNotification::Started { info, .. }) => info.streamer == self.own, + // Responses to join requests are for viewers. + (Some(_), StreamNotification::JoinResponse { .. }) => false, + (Some(id), n) => n.stream_id() == id, + (None, _) => false, + } + } + + pub async fn handle(&mut self, n: &StreamNotification, out: &mut Outbox) { + match n { + StreamNotification::Started { info, .. } if self.id.is_none() => { + self.id = Some(info.id.clone()); + if self.stop_when_live { + self.stop_when_live = false; + out.request(Request::Stop { id: info.id.clone() }); + } else if !self.ended { + out.event(StreamEvent::Streamer(StreamerEvent::Live { id: info.id.clone() })); + } + } + _ if self.ended => {} + StreamNotification::Stopped { .. } => self.end(EndReason::Stopped, out), + StreamNotification::JoinRequest { viewer, message, remove: false, .. } => { + let slot = ViewerSlot { + state: ViewerState::Requested, + message: message.clone(), + peer: None, + }; + self.viewers.insert(viewer.0, slot); + if self.options.auto_accept { + self.offer(*viewer, false, out).await; + } else { + out.event(StreamEvent::Streamer(StreamerEvent::Request { + viewer: *viewer, + message: message.clone(), + })); + self.emit_viewers(out); + } + } + StreamNotification::JoinRequest { viewer, remove: true, .. } + | StreamNotification::ViewerLeft { viewer, .. } => { + if self.viewers.remove(&viewer.0).is_some() { + self.emit_viewers(out); + } + } + StreamNotification::Signaling { peer, json, .. } => { + self.signal(*peer, json, out).await; + } + StreamNotification::ViewerJoined { viewer, .. } => { + debug!(viewer = viewer.0, "viewer joined the stream"); + } + _ => {} + } + } + + async fn signal(&mut self, viewer: ClientId, json: &str, out: &mut Outbox) { + let signal = match Signal::parse(json) { + Ok(s) => s, + Err(e) => { + warn!(viewer = viewer.0, "bad signalling message: {e}"); + return; + } + }; + let Some(slot) = self.viewers.get(&viewer.0) else { + debug!(viewer = viewer.0, "signal from a client that is not a viewer"); + return; + }; + match signal { + Signal::Answer { sdp } => { + let Some(peer) = &slot.peer else { return }; + if let Err(e) = peer.accept_answer(&sdp).await { + warn!(viewer = viewer.0, "cannot apply the viewer's answer: {e}"); + self.remove(viewer, LeaveReason::Failed, out); + } + } + Signal::IceCandidate { candidate, .. } => { + if let Some(peer) = &slot.peer { + peer.add_remote_candidate(&candidate); + } + } + Signal::Reconnect => { + if slot.state != ViewerState::Requested { + self.offer(viewer, true, out).await; + } + } + other => debug!(viewer = viewer.0, "ignoring signal {other:?}"), + } + } + + /// Create a peer for `viewer` and send our offer: in `respondjoinstreamrequest`, + /// or as `reconnectOffer` for a viewer that lost its connection. + async fn offer(&mut self, viewer: ClientId, reconnect: bool, out: &mut Outbox) { + let Some(id) = self.id.clone() else { return }; + match Peer::offer(&self.config, &id).await { + Ok((peer, sdp)) => { + if let Some(slot) = self.viewers.get_mut(&viewer.0) { + slot.peer = Some(peer); + slot.state = ViewerState::Connecting; + } + out.request(if reconnect { + Request::Signal { id, peer: viewer, signal: Signal::Offer { sdp, reconnect } } + } else { + Request::Respond { id, viewer, offer: Some(sdp), accept: true } + }); + } + Err(e) => { + warn!(viewer = viewer.0, "cannot create a peer connection: {e}"); + self.viewers.remove(&viewer.0); + out.request(if reconnect { + Request::RemoveViewer { id, viewer, reason: LeaveReason::Failed } + } else { + Request::Respond { id, viewer, offer: None, accept: false } + }); + } + } + self.emit_viewers(out); + } + + /// Accept or deny a pending join request. + pub async fn respond( + &mut self, + viewer: ClientId, + accept: bool, + out: &mut Outbox, + ) -> Result<(), SessionError> { + let id = self.id.clone().ok_or(SessionError::NotLive)?; + match self.viewers.get(&viewer.0) { + Some(slot) if slot.state == ViewerState::Requested => {} + _ => return Err(SessionError::NoRequest(viewer.0)), + } + if accept { + self.offer(viewer, false, out).await; + } else { + self.viewers.remove(&viewer.0); + out.request(Request::Respond { id, viewer, offer: None, accept: false }); + self.emit_viewers(out); + } + Ok(()) + } + + /// End a viewer's session (`removeclientfromstream` with reason kicked). + pub fn kick(&mut self, viewer: ClientId, out: &mut Outbox) -> Result<(), SessionError> { + if self.id.is_none() { + return Err(SessionError::NotLive); + } + if !self.viewers.contains_key(&viewer.0) { + return Err(SessionError::UnknownViewer(viewer.0)); + } + self.remove(viewer, LeaveReason::Kicked, out); + Ok(()) + } + + fn remove(&mut self, viewer: ClientId, reason: LeaveReason, out: &mut Outbox) { + self.viewers.remove(&viewer.0); + if let Some(id) = &self.id { + out.request(Request::RemoveViewer { id: id.clone(), viewer, reason }); + } + self.emit_viewers(out); + } + + /// End the stream (`stopstream`). + pub fn stop(&mut self, out: &mut Outbox) { + if self.ended { + return; + } + match &self.id { + Some(id) => out.request(Request::Stop { id: id.clone() }), + None => self.stop_when_live = true, + } + self.end(EndReason::Local, out); + } + + fn end(&mut self, reason: EndReason, out: &mut Outbox) { + self.ended = true; + self.viewers.clear(); + out.event(StreamEvent::Streamer(StreamerEvent::Ended(reason))); + } + + /// Send an encoded frame to every connected viewer. + pub fn write(&self, kind: MediaKind, time: MediaTime, data: Arc<[u8]>) { + for slot in self.viewers.values() { + if let (ViewerState::Connected, Some(peer)) = (slot.state, &slot.peer) { + peer.write(kind, time, data.clone()); + } + } + } + + /// Whether any viewer is connected (frames are dropped otherwise). + pub fn has_connected_viewers(&self) -> bool { + self.viewers.values().any(|v| v.state == ViewerState::Connected) + } + + /// A command of this session failed on the server. + pub fn request_failed(&mut self, request: &Request, error: &str, out: &mut Outbox) { + match request { + Request::Setup(_) if self.id.is_none() => { + self.stop_when_live = false; + if !self.ended { + self.end(EndReason::Failed(format!("setupstream: {error}")), out); + } + } + Request::Respond { viewer, accept: true, .. } => { + if self.viewers.remove(&viewer.0).is_some() { + self.emit_viewers(out); + } + } + other => debug!(?other, "stream command failed: {error}"), + } + } + + /// Handle ready peer events; `Pending` if there were none. + pub fn poll_peers(&mut self, cx: &mut Context<'_>, out: &mut Outbox) -> Poll<()> { + let mut events = Vec::new(); + for (clid, slot) in &mut self.viewers { + let Some(peer) = &mut slot.peer else { continue }; + for _ in 0..EVENTS_PER_POLL { + match peer.poll_event(cx) { + Poll::Ready(Some(e)) => events.push((ClientId(*clid), e)), + Poll::Ready(None) => { + events.push((ClientId(*clid), PeerEvent::Closed)); + break; + } + Poll::Pending => break, + } + } + } + if events.is_empty() { + return Poll::Pending; + } + for (viewer, event) in events { + self.peer_event(viewer, event, out); + } + Poll::Ready(()) + } + + fn peer_event(&mut self, viewer: ClientId, event: PeerEvent, out: &mut Outbox) { + let Some(id) = self.id.clone() else { return }; + let Some(slot) = self.viewers.get_mut(&viewer.0) else { return }; + match event { + PeerEvent::Connected => { + slot.state = ViewerState::Connected; + self.emit_viewers(out); + self.keyframe_request(out); + } + PeerEvent::LocalCandidate { candidate, mid } => out.request(Request::Signal { + id, + peer: viewer, + signal: Signal::IceCandidate { candidate, mid, mline_index: Some(0) }, + }), + PeerEvent::KeyframeRequest => self.keyframe_request(out), + PeerEvent::Media(_) => {} + PeerEvent::Closed => { + // The viewer may ask for a new offer (`reconnect`); it stays + // until it leaves. + if slot.peer.take().is_some() { + debug!(viewer = viewer.0, "viewer connection closed"); + slot.state = ViewerState::Connecting; + self.emit_viewers(out); + } + } + } + } + + fn keyframe_request(&mut self, out: &mut Outbox) { + let now = Instant::now(); + if self.last_keyframe_request.is_some_and(|t| now.duration_since(t) < KEYFRAME_INTERVAL) { + return; + } + self.last_keyframe_request = Some(now); + out.event(StreamEvent::Streamer(StreamerEvent::KeyframeRequest)); + } + + fn emit_viewers(&self, out: &mut Outbox) { + out.event(StreamEvent::Streamer(StreamerEvent::Viewers(self.viewers()))); + } +} + +/// State of a stream we watch. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WatchState { + /// Join request sent. + Requested, + /// Accepted; connecting to the streamer. + Connecting, + Connected, + Ended, +} + +/// Watching one stream: `joinstreamrequest`, answer the streamer's offer, receive media. +pub struct ViewerSession { + id: String, + streamer: ClientId, + own: ClientId, + config: PeerConfig, + state: WatchState, + peer: Option, + reconnects: u32, +} + +impl ViewerSession { + /// Ask `streamer` to let us watch stream `id`: queues `joinstreamrequest`. + pub fn join( + own: ClientId, + id: &str, + streamer: ClientId, + message: &str, + config: PeerConfig, + out: &mut Outbox, + ) -> Self { + out.request(Request::Join { id: id.to_owned(), streamer, message: message.to_owned() }); + Self { + id: id.to_owned(), + streamer, + own, + config, + state: WatchState::Requested, + peer: None, + reconnects: 0, + } + } + + pub fn id(&self) -> &str { + &self.id + } + + pub fn streamer(&self) -> ClientId { + self.streamer + } + + pub fn state(&self) -> WatchState { + self.state + } + + /// Whether `n` is for this viewing session. + pub fn wants(&self, n: &StreamNotification) -> bool { + if n.stream_id() != self.id { + return false; + } + match n { + StreamNotification::JoinRequest { .. } => false, + StreamNotification::Signaling { peer, .. } => *peer == self.streamer, + StreamNotification::ViewerJoined { viewer, .. } + | StreamNotification::ViewerLeft { viewer, .. } => *viewer == self.own, + _ => true, + } + } + + pub async fn handle(&mut self, n: &StreamNotification, out: &mut Outbox) { + if self.state == WatchState::Ended { + return; + } + match n { + StreamNotification::JoinResponse { accepted: false, .. } => { + self.end(EndReason::Denied, out); + } + StreamNotification::JoinResponse { accepted: true, offer, .. } => { + self.state = WatchState::Connecting; + self.event(WatchEvent::Accepted, out); + // Without an offer in the response, it follows as an `offer` signal. + if let Some(offer) = offer { + self.answer(offer, out).await; + } + } + StreamNotification::Signaling { json, .. } => match Signal::parse(json) { + Ok(Signal::Offer { sdp, .. }) => self.answer(&sdp, out).await, + Ok(Signal::IceCandidate { candidate, .. }) => { + if let Some(peer) = &self.peer { + peer.add_remote_candidate(&candidate); + } + } + Ok(other) => debug!(stream = self.id, "ignoring signal {other:?}"), + Err(e) => warn!(stream = self.id, "bad signalling message: {e}"), + }, + StreamNotification::Stopped { .. } => self.end(EndReason::Stopped, out), + StreamNotification::ViewerLeft { reason, .. } => { + self.end(EndReason::Removed(*reason), out); + } + _ => {} + } + } + + /// Answer an offer (the first one or a `reconnectOffer`) with a new peer. + async fn answer(&mut self, offer: &str, out: &mut Outbox) { + match Peer::answer(&self.config, offer).await { + Ok((peer, sdp)) => { + self.peer = Some(peer); + self.state = WatchState::Connecting; + self.signal(Signal::Answer { sdp }, out); + } + Err(e) => self.fail(format!("cannot answer the streamer's offer: {e}"), out), + } + } + + fn signal(&self, signal: Signal, out: &mut Outbox) { + out.request(Request::Signal { id: self.id.clone(), peer: self.streamer, signal }); + } + + /// Stop watching (or withdraw the request). + pub fn leave(&mut self, out: &mut Outbox) { + if self.state == WatchState::Ended { + return; + } + out.request(Request::Leave { id: self.id.clone(), streamer: self.streamer }); + self.end(EndReason::Local, out); + } + + /// Ask the streamer for a keyframe (RTCP PLI). + pub fn request_keyframe(&self) { + if let Some(peer) = &self.peer { + peer.request_keyframe(); + } + } + + /// Drop the connection and ask the streamer for a new offer (`reconnect`). + pub fn reconnect(&mut self, out: &mut Outbox) { + if matches!(self.state, WatchState::Connecting | WatchState::Connected) { + self.peer = None; + self.state = WatchState::Connecting; + self.signal(Signal::Reconnect, out); + } + } + + fn fail(&mut self, error: String, out: &mut Outbox) { + warn!(stream = self.id, "{error}"); + out.request(Request::Leave { id: self.id.clone(), streamer: self.streamer }); + self.end(EndReason::Failed(error), out); + } + + fn end(&mut self, reason: EndReason, out: &mut Outbox) { + self.state = WatchState::Ended; + self.peer = None; + self.event(WatchEvent::Ended(reason), out); + } + + fn event(&self, event: WatchEvent, out: &mut Outbox) { + out.event(StreamEvent::Watch { id: self.id.clone(), event }); + } + + /// A command of this session failed on the server. + pub fn request_failed(&mut self, request: &Request, error: &str, out: &mut Outbox) { + match request { + Request::Join { .. } if self.state != WatchState::Ended => { + self.end(EndReason::Failed(format!("joinstreamrequest: {error}")), out); + } + other => debug!(?other, "stream command failed: {error}"), + } + } + + /// Handle ready peer events; `Pending` if there were none. + pub fn poll_peer(&mut self, cx: &mut Context<'_>, out: &mut Outbox) -> Poll<()> { + let mut events = Vec::new(); + if let Some(peer) = &mut self.peer { + for _ in 0..EVENTS_PER_POLL { + match peer.poll_event(cx) { + Poll::Ready(Some(e)) => events.push(e), + Poll::Ready(None) => { + events.push(PeerEvent::Closed); + break; + } + Poll::Pending => break, + } + } + } + if events.is_empty() { + return Poll::Pending; + } + for event in events { + self.peer_event(event, out); + } + Poll::Ready(()) + } + + fn peer_event(&mut self, event: PeerEvent, out: &mut Outbox) { + if self.state == WatchState::Ended { + return; + } + match event { + PeerEvent::Connected => { + self.state = WatchState::Connected; + self.reconnects = 0; + self.event(WatchEvent::Connected, out); + } + PeerEvent::LocalCandidate { candidate, mid } => { + self.signal(Signal::IceCandidate { candidate, mid, mline_index: Some(0) }, out); + } + PeerEvent::Media(frame) => self.event(WatchEvent::Frame(frame), out), + PeerEvent::KeyframeRequest => {} + PeerEvent::Closed => { + if self.peer.take().is_none() { + return; + } + if self.reconnects < MAX_RECONNECTS { + self.reconnects += 1; + debug!( + stream = self.id, + attempt = self.reconnects, + "connection lost, reconnecting" + ); + self.state = WatchState::Connecting; + self.signal(Signal::Reconnect, out); + } else { + self.fail("connection to the streamer lost".into(), out); + } + } + } + } +} + +/// All stream sessions of one server connection: the directory of streams in +/// our channel, our own stream, and the streams we watch. +pub struct Streams { + own: ClientId, + config: PeerConfig, + directory: StreamDirectory, + streamer: Option, + viewers: BTreeMap, + out: Outbox, +} + +impl Streams { + /// `own` is our client id on the connection; `config` is used for every peer. + pub fn new(own: ClientId, config: PeerConfig) -> Self { + Self { + own, + config, + directory: StreamDirectory::default(), + streamer: None, + viewers: BTreeMap::new(), + out: Outbox::default(), + } + } + + pub fn own_client(&self) -> ClientId { + self.own + } + + pub fn directory(&self) -> &StreamDirectory { + &self.directory + } + + /// Our stream, while it has not ended. + pub fn streamer(&self) -> Option<&StreamerSession> { + self.streamer.as_ref().filter(|s| !s.is_ended()) + } + + pub fn watching(&self) -> impl Iterator { + self.viewers.values() + } + + /// The next request or event; call until `None` after every input. + pub fn poll_output(&mut self) -> Option { + self.out.pop() + } + + /// Start our stream (`setupstream`). + pub fn start(&mut self, options: StreamerOptions) -> Result<(), SessionError> { + // Also while a stream stopped before it went live waits for its id. + if self.streamer.is_some() { + return Err(SessionError::AlreadyStreaming); + } + let session = StreamerSession::start(self.own, options, self.config.clone(), &mut self.out); + self.streamer = Some(session); + Ok(()) + } + + /// Stop our stream. + pub fn stop(&mut self) -> Result<(), SessionError> { + let streamer = self.streamer.as_mut().filter(|s| !s.is_ended()); + streamer.ok_or(SessionError::NotStreaming)?.stop(&mut self.out); + self.cleanup(); + Ok(()) + } + + /// Accept or deny a viewer's join request. + pub async fn respond(&mut self, viewer: ClientId, accept: bool) -> Result<(), SessionError> { + let streamer = self.streamer.as_mut().filter(|s| !s.is_ended()); + streamer.ok_or(SessionError::NotStreaming)?.respond(viewer, accept, &mut self.out).await + } + + /// Remove a viewer from our stream. + pub fn kick(&mut self, viewer: ClientId) -> Result<(), SessionError> { + let streamer = self.streamer.as_mut().filter(|s| !s.is_ended()); + streamer.ok_or(SessionError::NotStreaming)?.kick(viewer, &mut self.out) + } + + /// Send an encoded frame of our stream to all connected viewers. + pub fn write(&self, kind: MediaKind, time: MediaTime, data: impl Into>) { + if let Some(s) = self.streamer() { + s.write(kind, time, data.into()); + } + } + + pub fn write_frame(&self, frame: &EncodedFrame) { + self.write(frame.kind, frame.time, frame.data.clone()); + } + + /// Watch a stream from the directory. + pub fn watch(&mut self, id: &str, message: &str) -> Result<(), SessionError> { + let info = self.directory.get(id).ok_or_else(|| SessionError::UnknownStream(id.into()))?; + let streamer = info.streamer; + self.watch_from(id, streamer, message) + } + + /// Watch stream `id` of `streamer`, also if it is not in the directory. + pub fn watch_from( + &mut self, + id: &str, + streamer: ClientId, + message: &str, + ) -> Result<(), SessionError> { + if streamer == self.own || self.streamer().is_some_and(|s| s.id() == Some(id)) { + return Err(SessionError::OwnStream); + } + if self.viewers.get(id).is_some_and(|v| v.state() != WatchState::Ended) { + return Err(SessionError::AlreadyWatching(id.into())); + } + let session = ViewerSession::join( + self.own, + id, + streamer, + message, + self.config.clone(), + &mut self.out, + ); + self.viewers.insert(id.to_owned(), session); + Ok(()) + } + + /// Stop watching a stream. + pub fn leave(&mut self, id: &str) -> Result<(), SessionError> { + let viewer = + self.viewers.get_mut(id).ok_or_else(|| SessionError::NotWatching(id.into()))?; + viewer.leave(&mut self.out); + self.cleanup(); + Ok(()) + } + + /// Ask the streamer of a watched stream for a keyframe. + pub fn request_keyframe(&self, id: &str) { + if let Some(v) = self.viewers.get(id) { + v.request_keyframe(); + } + } + + /// Reconnect to a watched stream: the streamer sends a new offer. + pub fn reconnect(&mut self, id: &str) -> Result<(), SessionError> { + let viewer = + self.viewers.get_mut(id).ok_or_else(|| SessionError::NotWatching(id.into()))?; + viewer.reconnect(&mut self.out); + Ok(()) + } + + /// Stop streaming and watching, e.g. before disconnecting. + pub fn close(&mut self) { + if let Some(s) = &mut self.streamer { + s.stop(&mut self.out); + } + for v in self.viewers.values_mut() { + v.leave(&mut self.out); + } + self.cleanup(); + } + + /// Feed a stream notification from the connection. + pub async fn handle_notification(&mut self, n: StreamNotification) { + if self.directory.apply(&n) { + self.emit_streams(); + } + if let Some(s) = &mut self.streamer + && s.wants(&n) + { + s.handle(&n, &mut self.out).await; + } + if let Some(v) = self.viewers.get_mut(n.stream_id()) + && v.wants(&n) + { + v.handle(&n, &mut self.out).await; + } + self.cleanup(); + } + + /// `client_is_streaming` of a client changed. + pub fn set_client_streaming(&mut self, client: ClientId, streaming: bool) { + if self.directory.set_streaming(client, streaming) { + self.emit_streams(); + } + } + + /// Drop the streams of streamers `keep` rejects (clients that left or stopped). + pub fn retain_streamers(&mut self, keep: impl FnMut(ClientId) -> bool) { + if self.directory.retain_streamers(keep) { + self.emit_streams(); + } + } + + /// A request from [`Output::Request`] failed on the server. + pub fn request_failed(&mut self, request: &Request, error: &str) { + let watched = match request { + Request::Join { id, .. } | Request::Leave { id, .. } | Request::Signal { id, .. } => { + self.viewers.get_mut(id) + } + _ => None, + }; + if let Some(v) = watched { + v.request_failed(request, error, &mut self.out); + } else if let Some(s) = &mut self.streamer { + s.request_failed(request, error, &mut self.out); + } + self.cleanup(); + } + + /// Wait for peer events and handle them. Cancel safe; never returns while + /// there are no peers. + pub async fn wait_peers(&mut self) { + std::future::poll_fn(|cx| self.poll_peers(cx)).await + } + + /// Handle ready peer events; `Pending` if there were none. + pub fn poll_peers(&mut self, cx: &mut Context<'_>) -> Poll<()> { + let mut ready = false; + if let Some(s) = &mut self.streamer { + ready |= s.poll_peers(cx, &mut self.out).is_ready(); + } + for v in self.viewers.values_mut() { + ready |= v.poll_peer(cx, &mut self.out).is_ready(); + } + if ready { + self.cleanup(); + Poll::Ready(()) + } else { + Poll::Pending + } + } + + fn emit_streams(&mut self) { + self.out.event(StreamEvent::Streams(self.directory.to_vec())); + } + + /// Forget sessions that ended. + fn cleanup(&mut self) { + if self.streamer.as_ref().is_some_and(StreamerSession::is_finished) { + self.streamer = None; + } + self.viewers.retain(|_, v| v.state() != WatchState::Ended); + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use tokio::time::timeout; + + use super::*; + use crate::proto::StreamKind; + use crate::{Frequency, SyntheticSource}; + + const OWN: ClientId = ClientId(10); + const OTHER: ClientId = ClientId(20); + + fn text(request: &Request) -> String { + String::from_utf8(request.to_command().0.content().to_vec()).unwrap() + } + + fn texts(requests: &[Request]) -> Vec { + requests.iter().map(text).collect() + } + + fn drain(s: &mut Streams) -> (Vec, Vec) { + let (mut requests, mut events) = (Vec::new(), Vec::new()); + while let Some(o) = s.poll_output() { + match o { + Output::Request(r) => requests.push(r), + Output::Event(e) => events.push(e), + } + } + (requests, events) + } + + fn info(id: &str, streamer: ClientId) -> StreamInfo { + StreamInfo { + id: id.into(), + streamer, + name: "screen".into(), + kind: StreamKind::Screen, + bitrate: 4608, + viewer_limit: 0, + audio: true, + } + } + + fn started(id: &str, streamer: ClientId, own: bool) -> StreamNotification { + StreamNotification::Started { + info: info(id, streamer), + return_code: own.then(|| "1".to_owned()), + } + } + + fn stopped(id: &str) -> StreamNotification { + StreamNotification::Stopped { id: id.into(), streamer: None, reason: None } + } + + fn join(viewer: ClientId, remove: bool) -> StreamNotification { + StreamNotification::JoinRequest { id: "s-1".into(), viewer, message: "hi".into(), remove } + } + + fn signaling(peer: ClientId, signal: &Signal) -> StreamNotification { + StreamNotification::Signaling { id: "s-1".into(), peer, json: signal.to_json() } + } + + fn response(accepted: bool, offer: Option) -> StreamNotification { + StreamNotification::JoinResponse { + id: "s-1".into(), + streamer: Some(OTHER), + accepted, + offer, + message: String::new(), + } + } + + /// The last viewer list in `events`. + fn viewers(events: &[StreamEvent]) -> Option> { + events.iter().rev().find_map(|e| match e { + StreamEvent::Streamer(StreamerEvent::Viewers(v)) => { + Some(v.iter().map(|v| (v.client.0, v.state)).collect()) + } + _ => None, + }) + } + + /// Handle peer events until `f` accepts the collected events. + async fn until(s: &mut Streams, mut f: impl FnMut(&[StreamEvent]) -> bool) -> Vec { + let mut events = Vec::new(); + timeout(Duration::from_secs(10), async { + loop { + events.extend(drain(s).1); + if f(&events) { + return; + } + s.wait_peers().await; + } + }) + .await + .expect("timed out"); + events + } + + #[tokio::test] + async fn streamer_transcript() { + let config = PeerConfig::loopback(); + let mut s = Streams::new(OWN, config.clone()); + let setup = StreamSetup { name: "t".into(), ..Default::default() }; + s.start(StreamerOptions { setup, auto_accept: false }).unwrap(); + assert_eq!(s.start(StreamerOptions::default()), Err(SessionError::AlreadyStreaming)); + let (requests, _) = drain(&mut s); + assert_eq!( + texts(&requests), + [ + "setupstream name=t type=3 bitrate=4608 accessibility=1 mode=1 viewer_limit=0 audio=1" + ] + ); + + // Someone else's stream only goes into the directory. + s.handle_notification(started("x-1", OTHER, false)).await; + let (requests, events) = drain(&mut s); + assert!(requests.is_empty()); + assert!(matches!(&events[..], [StreamEvent::Streams(l)] if l.len() == 1)); + assert_eq!(s.streamer().unwrap().id(), None); + + s.handle_notification(started("s-1", OWN, true)).await; + let (_, events) = drain(&mut s); + assert!(matches!( + &events[..], + [StreamEvent::Streams(l), StreamEvent::Streamer(StreamerEvent::Live { id })] + if l.len() == 2 && id == "s-1" + )); + + // A join request waits for our decision. + s.handle_notification(join(OTHER, false)).await; + let (requests, events) = drain(&mut s); + assert!(requests.is_empty()); + assert!(matches!( + &events[0], + StreamEvent::Streamer(StreamerEvent::Request { viewer: OTHER, message }) if message == "hi" + )); + assert_eq!(viewers(&events), Some(vec![(20, ViewerState::Requested)])); + assert_eq!(s.respond(ClientId(99), true).await, Err(SessionError::NoRequest(99))); + + // Accept: the offer goes into respondjoinstreamrequest. + s.respond(OTHER, true).await.unwrap(); + let (requests, events) = drain(&mut s); + let [Request::Respond { id, viewer: OTHER, offer: Some(offer), accept: true }] = + &requests[..] + else { + panic!("{requests:?}") + }; + assert_eq!(id, "s-1"); + assert!(offer.contains("m=video") && offer.contains("VP8"), "{offer}"); + let command = text(&requests[0]); + assert!( + command.starts_with("respondjoinstreamrequest id=s-1 clid=20 msg offer="), + "{command}" + ); + assert!(command.ends_with("decision=1"), "{command}"); + assert_eq!(viewers(&events), Some(vec![(20, ViewerState::Connecting)])); + + // The viewer's answer arrives through notifystreamsignaling. + let (mut viewer_peer, answer) = Peer::answer(&config, offer).await.unwrap(); + s.handle_notification(signaling(OTHER, &Signal::Answer { sdp: answer })).await; + let events = + until(&mut s, |e| viewers(e) == Some(vec![(20, ViewerState::Connected)])).await; + assert!( + events + .iter() + .any(|e| matches!(e, StreamEvent::Streamer(StreamerEvent::KeyframeRequest))), + "a new viewer needs a keyframe" + ); + // Frames reach the viewer. + timeout(Duration::from_secs(5), async { + loop { + let time = MediaTime::new(0, Frequency::FORTY_EIGHT_KHZ); + s.write(MediaKind::Audio, time, &crate::source::OPUS_SILENCE[..]); + tokio::select! { + e = viewer_peer.next_event() => if let Some(PeerEvent::Media(_)) = e { break }, + () = tokio::time::sleep(Duration::from_millis(20)) => {} + } + } + }) + .await + .expect("no media at the viewer"); + + // Withdrawal. + s.handle_notification(join(OTHER, true)).await; + let (requests, events) = drain(&mut s); + assert!(requests.is_empty()); + assert_eq!(viewers(&events), Some(vec![])); + + // Deny. + s.handle_notification(join(ClientId(21), false)).await; + s.respond(ClientId(21), false).await.unwrap(); + let (requests, _) = drain(&mut s); + assert_eq!(texts(&requests), ["respondjoinstreamrequest id=s-1 clid=21 msg decision=0"]); + + // Kick. + s.handle_notification(join(ClientId(22), false)).await; + s.respond(ClientId(22), true).await.unwrap(); + let _ = drain(&mut s); + s.kick(ClientId(22)).unwrap(); + assert_eq!(s.kick(ClientId(22)), Err(SessionError::UnknownViewer(22))); + let (requests, events) = drain(&mut s); + assert_eq!(texts(&requests), ["removeclientfromstream id=s-1 clid=22 reason=5"]); + assert_eq!(viewers(&events), Some(vec![])); + + // A viewer that asks to reconnect gets a new offer. + s.handle_notification(join(ClientId(23), false)).await; + s.respond(ClientId(23), true).await.unwrap(); + let _ = drain(&mut s); + s.handle_notification(signaling(ClientId(23), &Signal::Reconnect)).await; + let (requests, _) = drain(&mut s); + assert!(matches!( + &requests[..], + [Request::Signal { + peer: ClientId(23), + signal: Signal::Offer { reconnect: true, .. }, + .. + }] + )); + assert!(text(&requests[0]).contains("reconnectOffer")); + + // Stop. + s.stop().unwrap(); + let (requests, events) = drain(&mut s); + assert_eq!(texts(&requests), ["stopstream id=s-1 reason=1"]); + assert!(matches!( + &events[..], + [StreamEvent::Streamer(StreamerEvent::Ended(EndReason::Local))] + )); + assert!(s.streamer().is_none()); + assert_eq!(s.stop(), Err(SessionError::NotStreaming)); + // The server tells everyone. + s.handle_notification(stopped("s-1")).await; + let (requests, events) = drain(&mut s); + assert!(requests.is_empty()); + assert!(matches!(&events[..], [StreamEvent::Streams(l)] if l.len() == 1)); + } + + #[tokio::test] + async fn auto_accept_and_failures() { + let mut s = Streams::new(OWN, PeerConfig::loopback()); + s.start(StreamerOptions { auto_accept: true, ..Default::default() }).unwrap(); + let (requests, _) = drain(&mut s); + s.request_failed(&requests[0], "insufficient client permissions (2568)"); + let (_, events) = drain(&mut s); + assert!(matches!( + &events[..], + [StreamEvent::Streamer(StreamerEvent::Ended(EndReason::Failed(m)))] if m.contains("2568") + )); + assert!(s.streamer().is_none()); + + s.start(StreamerOptions { auto_accept: true, ..Default::default() }).unwrap(); + s.handle_notification(started("s-1", OWN, true)).await; + s.handle_notification(join(OTHER, false)).await; + let (requests, events) = drain(&mut s); + assert!(matches!( + &requests[..], + [Request::Setup(_), Request::Respond { offer: Some(_), accept: true, .. }] + )); + assert!( + !events + .iter() + .any(|e| matches!(e, StreamEvent::Streamer(StreamerEvent::Request { .. }))) + ); + // The server refuses the response: the viewer is dropped. + s.request_failed(&requests[1], "invalid client id"); + let (_, events) = drain(&mut s); + assert_eq!(viewers(&events), Some(vec![])); + // The server ends the stream. + s.handle_notification(stopped("s-1")).await; + let (_, events) = drain(&mut s); + assert!( + events.iter().any(|e| matches!( + e, + StreamEvent::Streamer(StreamerEvent::Ended(EndReason::Stopped)) + )) + ); + assert!(s.streamer().is_none()); + } + + #[tokio::test] + async fn stop_before_live() { + let mut s = Streams::new(OWN, PeerConfig::loopback()); + s.start(StreamerOptions::default()).unwrap(); + s.stop().unwrap(); + let _ = drain(&mut s); + // The stream still needs its id to be stopped. + assert_eq!(s.start(StreamerOptions::default()), Err(SessionError::AlreadyStreaming)); + s.handle_notification(started("s-1", OWN, true)).await; + let (requests, events) = drain(&mut s); + assert_eq!(texts(&requests), ["stopstream id=s-1 reason=1"]); + assert!(!events.iter().any(|e| matches!(e, StreamEvent::Streamer(_)))); + s.start(StreamerOptions::default()).unwrap(); + } + + #[tokio::test] + async fn viewer_transcript() { + let config = PeerConfig::loopback(); + let mut s = Streams::new(OWN, config.clone()); + assert_eq!(s.watch("s-1", ""), Err(SessionError::UnknownStream("s-1".into()))); + s.handle_notification(started("s-1", OTHER, false)).await; + let _ = drain(&mut s); + + // Denied. + s.watch("s-1", "please").unwrap(); + assert_eq!(s.watch("s-1", ""), Err(SessionError::AlreadyWatching("s-1".into()))); + let (requests, _) = drain(&mut s); + assert_eq!(texts(&requests), ["joinstreamrequest id=s-1 clid=20 msg=please is_remove=0"]); + s.handle_notification(response(false, None)).await; + let (_, events) = drain(&mut s); + assert!(matches!( + &events[..], + [StreamEvent::Watch { event: WatchEvent::Ended(EndReason::Denied), .. }] + )); + assert_eq!(s.watching().count(), 0); + + // Accepted: our answer goes back through streamsignaling. + s.watch("s-1", "").unwrap(); + let (mut streamer_peer, offer) = Peer::offer(&config, "s-1").await.unwrap(); + s.handle_notification(response(true, Some(offer))).await; + let (requests, events) = drain(&mut s); + assert_eq!(text(&requests[0]), "joinstreamrequest id=s-1 clid=20 msg is_remove=0"); + let Request::Signal { peer: OTHER, signal: Signal::Answer { sdp }, .. } = &requests[1] + else { + panic!("{requests:?}") + }; + assert!(text(&requests[1]).starts_with("streamsignaling id=s-1 clid=20 json={")); + assert!(matches!(&events[..], [StreamEvent::Watch { event: WatchEvent::Accepted, .. }])); + streamer_peer.accept_answer(sdp).await.unwrap(); + + // Media arrives as frames. + let events = until(&mut s, |e| { + e.iter().any(|e| matches!(e, StreamEvent::Watch { event: WatchEvent::Connected, .. })) + }) + .await; + assert!(events.iter().all(|e| matches!(e, StreamEvent::Watch { .. }))); + timeout(Duration::from_secs(5), async { + while !matches!(streamer_peer.next_event().await, Some(PeerEvent::Connected)) {} + }) + .await + .unwrap(); + let frame: Arc<[u8]> = SyntheticSource::video_frame(0, 2000).into(); + let video = until(&mut s, |e| { + streamer_peer.write(MediaKind::Video, MediaTime::from_90khz(0), frame.clone()); + e.iter().any(|e| matches!(e, StreamEvent::Watch { event: WatchEvent::Frame(_), .. })) + }) + .await; + assert!(video.iter().any(|e| matches!( + e, + StreamEvent::Watch { event: WatchEvent::Frame(f), .. } if f.data.len() == 2000 + ))); + + // The streamer's ICE candidates are added; unknown signals are ignored. + let candidate = Signal::IceCandidate { + candidate: "candidate:1 1 udp 2130706431 127.0.0.1 9 typ host".into(), + mid: Some("0".into()), + mline_index: Some(0), + }; + let unknown = Signal::Unknown { cmd: "future".into(), args: serde_json::json!({}) }; + for signal in [candidate, unknown] { + s.handle_notification(signaling(OTHER, &signal)).await; + } + assert!(drain(&mut s).0.is_empty()); + + // Leave. + s.leave("s-1").unwrap(); + let (requests, events) = drain(&mut s); + assert_eq!(texts(&requests), ["joinstreamrequest id=s-1 clid=20 msg is_remove=1"]); + assert!(matches!( + &events[..], + [StreamEvent::Watch { event: WatchEvent::Ended(EndReason::Local), .. }] + )); + assert_eq!(s.leave("s-1"), Err(SessionError::NotWatching("s-1".into()))); + + // Kicked. + s.watch("s-1", "").unwrap(); + s.handle_notification(StreamNotification::ViewerLeft { + id: "s-1".into(), + viewer: OWN, + reason: Some(LeaveReason::Kicked), + }) + .await; + let (_, events) = drain(&mut s); + assert!(matches!( + &events[..], + [StreamEvent::Watch { + event: WatchEvent::Ended(EndReason::Removed(Some(LeaveReason::Kicked))), + .. + }] + )); + + // The stream stops. + s.watch("s-1", "").unwrap(); + s.handle_notification(stopped("s-1")).await; + let (_, events) = drain(&mut s); + assert!(events.iter().any(|e| matches!( + e, + StreamEvent::Watch { event: WatchEvent::Ended(EndReason::Stopped), .. } + ))); + assert!(events.iter().any(|e| matches!(e, StreamEvent::Streams(l) if l.is_empty()))); + assert_eq!(s.watch("s-1", ""), Err(SessionError::UnknownStream("s-1".into()))); + assert_eq!(s.watch_from("x", OWN, ""), Err(SessionError::OwnStream)); + + // A failed join request ends the session. + s.watch_from("s-2", OTHER, "").unwrap(); + let (requests, _) = drain(&mut s); + s.request_failed(&requests[0], "stream not found"); + let (_, events) = drain(&mut s); + assert!(matches!( + &events[..], + [StreamEvent::Watch { event: WatchEvent::Ended(EndReason::Failed(_)), .. }] + )); + } + + #[test] + fn directory() { + let mut d = StreamDirectory::default(); + assert!(d.apply(&started("a", ClientId(1), false))); + assert!(!d.apply(&started("a", ClientId(1), false)), "unchanged"); + let renamed = StreamInfo { name: "renamed".into(), ..info("a", ClientId(1)) }; + assert!(d.apply(&StreamNotification::Info(renamed))); + assert_eq!(d.get("a").unwrap().name, "renamed"); + assert!(!d.set_streaming(ClientId(2), true)); + assert_eq!(d.unannounced_streamers().collect::>(), [ClientId(2)]); + assert!(d.apply(&started("b", ClientId(2), false))); + assert_eq!(d.unannounced_streamers().count(), 0); + assert_eq!(d.by_streamer(ClientId(2)).unwrap().id, "b"); + assert!(d.set_streaming(ClientId(2), false)); + assert!(d.retain_streamers(|c| c != ClientId(1))); + assert_eq!(d.iter().count(), 0); + assert!(d.apply(&started("c", ClientId(3), false))); + assert!(d.apply(&stopped("c"))); + assert!(!d.apply(&join(ClientId(3), false))); + } +} diff --git a/crates/tsc-stream/src/source.rs b/crates/tsc-stream/src/source.rs new file mode 100644 index 0000000..23bb948 --- /dev/null +++ b/crates/tsc-stream/src/source.rs @@ -0,0 +1,129 @@ +//! Where a streamer's encoded frames come from. +//! +//! [`FrameSource`] is the seam between capture/encoding (`tsc-media`) and the +//! stream sessions. [`SyntheticSource`] produces decodable placeholder media +//! without any encoder, for tests and `tsctl stream start --synthetic`. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use str0m::media::{Frequency, MediaKind, MediaTime}; + +/// One encoded video or audio frame. +#[derive(Clone, Debug)] +pub struct EncodedFrame { + pub kind: MediaKind, + /// RTP time: 90 kHz for video, 48 kHz for Opus. + pub time: MediaTime, + pub data: Arc<[u8]>, +} + +/// Produces encoded frames in real time. +pub trait FrameSource: Send { + /// Append the frames that are due at `now`. + fn poll_frames(&mut self, now: Instant, out: &mut Vec); + + /// A viewer needs a keyframe soon. + fn request_keyframe(&mut self) {} + + /// How often `poll_frames` should be called. + fn interval(&self) -> Duration { + Duration::from_millis(10) + } +} + +/// A complete 1x1 VP8 keyframe (the image of the smallest lossy WebP). +/// Decoders accept it, so browsers count decoded frames. +pub const VP8_KEYFRAME_1X1: [u8; 22] = [ + 0x30, 0x01, 0x00, 0x9d, 0x01, 0x2a, 0x01, 0x00, 0x01, 0x00, 0x0e, 0xc0, 0xfe, 0x25, 0xa4, 0x00, + 0x03, 0x70, 0x00, 0x00, 0x00, 0x00, +]; + +/// A 20 ms Opus frame of silence (CELT, fullband, mono). +pub const OPUS_SILENCE: [u8; 3] = [0xf8, 0xff, 0xfe]; + +/// Opus frame length at 48 kHz (20 ms). +const OPUS_FRAME: u64 = 960; + +/// Synthetic media: every video frame is [`VP8_KEYFRAME_1X1`] padded to a +/// chosen size (large frames span several RTP packets), audio is +/// [`OPUS_SILENCE`] every 20 ms. Byte `VP8_KEYFRAME_1X1.len()` of each video +/// frame holds the low byte of its sequence number. +pub struct SyntheticSource { + start: Instant, + fps: u32, + video_size: usize, + audio: bool, + video_frames: u64, + audio_frames: u64, +} + +impl SyntheticSource { + /// `fps` video frames of `video_size` bytes per second, plus audio if `audio`. + pub fn new(fps: u32, video_size: usize, audio: bool) -> Self { + Self { + start: Instant::now(), + fps: fps.max(1), + video_size: video_size.max(VP8_KEYFRAME_1X1.len() + 1), + audio, + video_frames: 0, + audio_frames: 0, + } + } + + pub fn video_frame(seq: u64, size: usize) -> Vec { + let mut frame = VP8_KEYFRAME_1X1.to_vec(); + frame.push(seq as u8); + frame.extend((frame.len()..size).map(|i| (i as u8).wrapping_mul(31) ^ seq as u8)); + frame + } +} + +impl FrameSource for SyntheticSource { + fn poll_frames(&mut self, now: Instant, out: &mut Vec) { + let elapsed = now.saturating_duration_since(self.start); + let due_video = elapsed.as_micros() as u64 * u64::from(self.fps) / 1_000_000 + 1; + while self.video_frames < due_video { + let n = self.video_frames; + out.push(EncodedFrame { + kind: MediaKind::Video, + time: MediaTime::from_90khz(n * 90_000 / u64::from(self.fps)), + data: Self::video_frame(n, self.video_size).into(), + }); + self.video_frames += 1; + } + if self.audio { + let due_audio = elapsed.as_millis() as u64 / 20 + 1; + while self.audio_frames < due_audio { + let time = + MediaTime::new(self.audio_frames * OPUS_FRAME, Frequency::FORTY_EIGHT_KHZ); + let data = Arc::from(&OPUS_SILENCE[..]); + out.push(EncodedFrame { kind: MediaKind::Audio, time, data }); + self.audio_frames += 1; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn paced_frames() { + let mut source = SyntheticSource::new(30, 3000, true); + let start = source.start; + let mut out = Vec::new(); + source.poll_frames(start, &mut out); + assert_eq!(out.len(), 2, "one video and one audio frame at the start"); + out.clear(); + source.poll_frames(start + Duration::from_millis(1000), &mut out); + let video: Vec<_> = out.iter().filter(|f| f.kind == MediaKind::Video).collect(); + let audio = out.len() - video.len(); + assert_eq!((video.len(), audio), (30, 50)); + assert_eq!(video[29].time, MediaTime::from_90khz(90_000)); + assert_eq!(video[0].data.len(), 3000); + assert_eq!(video[0].data[..22], VP8_KEYFRAME_1X1); + assert_eq!(video[0].data[22], 1); + } +} diff --git a/crates/tsc-stream/tests/sessions.rs b/crates/tsc-stream/tests/sessions.rs new file mode 100644 index 0000000..acba1ab --- /dev/null +++ b/crates/tsc-stream/tests/sessions.rs @@ -0,0 +1,280 @@ +//! Two stream session managers talking through a fake server that relays the +//! commands like the TeamSpeak 6 server does (see +//! `docs/protocol-notes/ts6-streaming.md`), with real peers on loopback. + +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +use tokio::time::timeout; +use tsc_stream::{ + EndReason, FrameSource, LeaveReason, MediaKind, Output, PeerConfig, Request, StreamEvent, + StreamInfo, StreamKind, StreamNotification, StreamSetup, StreamerEvent, StreamerOptions, + Streams, SyntheticSource, ViewerState, WatchEvent, +}; +use tsclientlib::ClientId; + +const STREAMER: usize = 0; +const VIEWER: usize = 1; +const IDS: [ClientId; 2] = [ClientId(5), ClientId(6)]; + +/// Relays requests to notifications, as observed on a TS6 server. +#[derive(Default)] +struct FakeServer { + streams: HashMap, + next: u32, +} + +impl FakeServer { + fn relay(&mut self, from: ClientId, request: Request) -> Vec<(usize, StreamNotification)> { + let everyone = |n: StreamNotification| (0..2).map(move |i| (i, n.clone())); + let to = |client: ClientId| IDS.iter().position(|c| *c == client).unwrap(); + match request { + Request::Setup(setup) => { + self.next += 1; + let id = format!("stream-{}", self.next); + self.streams.insert(id.clone(), from); + let info = StreamInfo { + id, + streamer: from, + name: setup.name, + kind: setup.kind, + bitrate: setup.bitrate, + viewer_limit: setup.viewer_limit, + audio: setup.audio, + }; + (0..2) + .map(|i| { + let own = IDS[i] == from; + let return_code = own.then(|| "1".to_owned()); + (i, StreamNotification::Started { info: info.clone(), return_code }) + }) + .collect() + } + Request::Stop { id } => { + self.streams.remove(&id); + everyone(StreamNotification::Stopped { id, streamer: Some(from), reason: None }) + .collect() + } + Request::Join { id, streamer, message } => vec![( + to(streamer), + StreamNotification::JoinRequest { id, viewer: from, message, remove: false }, + )], + Request::Leave { id, streamer } => vec![( + to(streamer), + StreamNotification::JoinRequest { + id, + viewer: from, + message: String::new(), + remove: true, + }, + )], + Request::Respond { id, viewer, offer, accept } => vec![( + to(viewer), + StreamNotification::JoinResponse { + id, + streamer: Some(from), + accepted: accept, + offer, + message: String::new(), + }, + )], + Request::Signal { id, peer, signal } => vec![( + to(peer), + StreamNotification::Signaling { id, peer: from, json: signal.to_json() }, + )], + Request::RemoveViewer { id, viewer, reason } => { + everyone(StreamNotification::ViewerLeft { id, viewer, reason: Some(reason) }) + .collect() + } + } + } +} + +struct Net { + server: FakeServer, + clients: [Streams; 2], + /// Events not looked at yet, with the client index. + events: Vec<(usize, StreamEvent)>, + source: Option, + video: usize, + audio: usize, +} + +impl Net { + fn new() -> Self { + let config = PeerConfig::loopback(); + Self { + server: FakeServer::default(), + clients: IDS.map(|id| Streams::new(id, config.clone())), + events: Vec::new(), + source: None, + video: 0, + audio: 0, + } + } + + /// Deliver queued requests until nothing is left. + async fn flush(&mut self) { + loop { + let mut notes = Vec::new(); + for (i, client) in self.clients.iter_mut().enumerate() { + while let Some(output) = client.poll_output() { + match output { + Output::Request(r) => notes.extend(self.server.relay(IDS[i], r)), + Output::Event(StreamEvent::Watch { + event: WatchEvent::Frame(f), .. + }) => match f.kind { + MediaKind::Video => self.video += 1, + MediaKind::Audio => self.audio += 1, + }, + Output::Event(e) => self.events.push((i, e)), + } + } + } + if notes.is_empty() { + return; + } + for (to, n) in notes { + self.clients[to].handle_notification(n).await; + } + } + } + + /// Handle queued requests, then wait for peer events or the next frame tick. + async fn step(&mut self) { + self.flush().await; + let [a, b] = &mut self.clients; + tokio::select! { + () = a.wait_peers() => {} + () = b.wait_peers() => {} + () = tokio::time::sleep(Duration::from_millis(10)) => {} + } + if let Some(source) = &mut self.source { + let mut frames = Vec::new(); + source.poll_frames(Instant::now(), &mut frames); + for frame in &frames { + self.clients[STREAMER].write_frame(frame); + } + } + } + + /// Run the network until `f` accepts an event; earlier events are dropped. + async fn until(&mut self, what: &str, mut f: impl FnMut(usize, &StreamEvent) -> bool) { + timeout(Duration::from_secs(10), async { + loop { + self.flush().await; + if let Some(pos) = self.events.iter().position(|(i, e)| f(*i, e)) { + self.events.drain(..=pos); + return; + } + self.step().await; + } + }) + .await + .unwrap_or_else(|_| panic!("timed out waiting for {what}; events: {:?}", self.events)); + } + + /// Run until the viewer received `n` more video and audio frames. + async fn frames(&mut self, n: usize) { + let (video, audio) = (self.video + n, self.audio + n); + let deadline = Instant::now() + Duration::from_secs(10); + while self.video < video || self.audio < audio { + assert!( + Instant::now() < deadline, + "got {} video / {} audio frames", + self.video, + self.audio + ); + self.step().await; + } + } +} + +fn watch_event(event: &StreamEvent, f: impl Fn(&WatchEvent) -> bool) -> bool { + matches!(event, StreamEvent::Watch { event, .. } if f(event)) +} + +#[tokio::test(flavor = "multi_thread")] +async fn stream_between_sessions() { + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let mut net = Net::new(); + let setup = StreamSetup { name: "fake".into(), kind: StreamKind::Screen, ..Default::default() }; + net.clients[STREAMER].start(StreamerOptions { setup, auto_accept: false }).unwrap(); + net.until("live", |i, e| { + i == STREAMER && matches!(e, StreamEvent::Streamer(StreamerEvent::Live { .. })) + }) + .await; + net.until("stream in the viewer's list", |i, e| { + i == VIEWER && matches!(e, StreamEvent::Streams(l) if l.len() == 1) + }) + .await; + let id = net.clients[VIEWER].directory().by_streamer(IDS[STREAMER]).unwrap().id.clone(); + + // Join, accepted by the streamer. + net.clients[VIEWER].watch(&id, "let me see").unwrap(); + net.until("join request", |i, e| { + i == STREAMER && matches!(e, StreamEvent::Streamer(StreamerEvent::Request { .. })) + }) + .await; + net.clients[STREAMER].respond(IDS[VIEWER], true).await.unwrap(); + net.until("viewer connected", |i, e| { + i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected)) + }) + .await; + net.until("streamer sees the viewer", |i, e| { + i == STREAMER + && matches!(e, StreamEvent::Streamer(StreamerEvent::Viewers(v)) + if v.len() == 1 && v[0].state == ViewerState::Connected) + }) + .await; + + // Media. + net.source = Some(SyntheticSource::new(30, 4000, true)); + net.frames(20).await; + + // The viewer reconnects: new offer, new answer, media again. + net.clients[VIEWER].reconnect(&id).unwrap(); + net.until("reconnected", |i, e| { + i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected)) + }) + .await; + net.frames(20).await; + + // The streamer kicks the viewer. + net.clients[STREAMER].kick(IDS[VIEWER]).unwrap(); + net.until("kicked", |i, e| { + i == VIEWER + && watch_event(e, |e| { + matches!(e, WatchEvent::Ended(EndReason::Removed(Some(LeaveReason::Kicked)))) + }) + }) + .await; + assert_eq!(net.clients[VIEWER].watching().count(), 0); + + // Watch again, then the viewer leaves by itself. + net.clients[VIEWER].watch(&id, "").unwrap(); + net.until("second join request", |i, e| { + i == STREAMER && matches!(e, StreamEvent::Streamer(StreamerEvent::Request { .. })) + }) + .await; + net.clients[STREAMER].respond(IDS[VIEWER], true).await.unwrap(); + net.until("viewer connected again", |i, e| { + i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected)) + }) + .await; + net.frames(5).await; + net.clients[VIEWER].leave(&id).unwrap(); + net.until("viewer gone", |i, e| { + i == STREAMER + && matches!(e, StreamEvent::Streamer(StreamerEvent::Viewers(v)) if v.is_empty()) + }) + .await; + + // The streamer stops; the viewer's list empties. + net.clients[STREAMER].stop().unwrap(); + net.until("stream gone", |i, e| { + i == VIEWER && matches!(e, StreamEvent::Streams(l) if l.is_empty()) + }) + .await; + assert!(net.clients[STREAMER].streamer().is_none()); +} From b3737c00a661d8dfb530c77f76aecd88c894332b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 19:48:23 +0000 Subject: [PATCH 02/13] tsc-audio: echo cancellation, noise suppression, gain control, VAD, client volume, device hotplug - process: Processor on sonora (pure Rust WebRTC APM: AEC3, NS, AGC2, high-pass) with serde ProcessingSettings; far end fed from what is played - vad: level gate with hangover, optional RNN speech probability - mixer: Mixer wraps the vendored AudioHandler with per-client volume/mute - settings: AudioSettings bundles transmit mode, processing, VAD, devices - device: stable device ids, default flags, loss detection through the error callback, Managed reopen/fallback policy - tests: synthetic echo >= 10 dB, noise suppression keeps tone bursts, per-client gain, one-hour drift simulation at +-200 ppm - dev profile optimises the sonora crates (real-time in debug builds) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- Cargo.lock | 78 +++++ Cargo.toml | 17 ++ crates/tsc-audio/Cargo.toml | 7 + crates/tsc-audio/src/device.rs | 476 +++++++++++++++++++++++++++++-- crates/tsc-audio/src/lib.rs | 21 +- crates/tsc-audio/src/mixer.rs | 219 ++++++++++++++ crates/tsc-audio/src/pcm.rs | 25 ++ crates/tsc-audio/src/process.rs | 363 +++++++++++++++++++++++ crates/tsc-audio/src/settings.rs | 80 ++++++ crates/tsc-audio/src/vad.rs | 250 ++++++++++++++++ crates/tsc-audio/tests/drift.rs | 129 +++++++++ docs/audio.md | 77 +++++ 12 files changed, 1716 insertions(+), 26 deletions(-) create mode 100644 crates/tsc-audio/src/mixer.rs create mode 100644 crates/tsc-audio/src/process.rs create mode 100644 crates/tsc-audio/src/settings.rs create mode 100644 crates/tsc-audio/src/vad.rs create mode 100644 crates/tsc-audio/tests/drift.rs create mode 100644 docs/audio.md diff --git a/Cargo.lock b/Cargo.lock index 224f3cb..7341cc5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7370,6 +7370,79 @@ dependencies = [ "x11rb", ] +[[package]] +name = "sonora" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e1ce442ab5cb392c4067b8f2cced20be4cf12e479f6dfbf44acbe9b14ac9250" +dependencies = [ + "sonora-aec3", + "sonora-agc2", + "sonora-common-audio", + "sonora-ns", + "sonora-simd", + "tracing", +] + +[[package]] +name = "sonora-aec3" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50280e31256d09f7838aff6715ed4b7640e514dc1092a1e14013c01e552380db" +dependencies = [ + "sonora-common-audio", + "sonora-fft", + "sonora-simd", +] + +[[package]] +name = "sonora-agc2" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a93a9fa8373a33e61a7fb441d8a9e725ac6024079d2c77a845cf6abe1790b9f" +dependencies = [ + "bytemuck", + "derive_more", + "sonora-common-audio", + "sonora-fft", + "sonora-simd", + "tracing", +] + +[[package]] +name = "sonora-common-audio" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6635bc61b24807ceac93ad0807b1292b6b0620caa6cd360d3be89fc616b833cc" +dependencies = [ + "derive_more", + "sonora-simd", +] + +[[package]] +name = "sonora-fft" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012" + +[[package]] +name = "sonora-ns" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d511feef19302c716d245c4555087d161ba91c178735ea11107dcce0d0b7a86f" +dependencies = [ + "sonora-fft", +] + +[[package]] +name = "sonora-simd" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7cf0804e4752a5562262e143014f53043080ead4cd5a98f9278d3ceaf32d868" +dependencies = [ + "cpufeatures 0.3.1", +] + [[package]] name = "spin_on" version = "0.1.1" @@ -8243,6 +8316,11 @@ dependencies = [ "opus2", "rtrb", "rubato", + "serde", + "serde_json", + "sonora", + "sonora-agc2", + "sonora-simd", "thiserror 2.0.21", "tracing", "tsclientlib", diff --git a/Cargo.toml b/Cargo.toml index 0b53143..06a0379 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,6 +59,23 @@ all = { level = "warn", priority = -1 } # it takes seconds. opt-level = 3 +# Audio processing (echo cancellation, noise suppression) runs in real time on +# every 10 ms of microphone audio; unoptimized it needs about a third of a core. +[profile.dev.package.sonora] +opt-level = 3 +[profile.dev.package.sonora-aec3] +opt-level = 3 +[profile.dev.package.sonora-agc2] +opt-level = 3 +[profile.dev.package.sonora-common-audio] +opt-level = 3 +[profile.dev.package.sonora-fft] +opt-level = 3 +[profile.dev.package.sonora-ns] +opt-level = 3 +[profile.dev.package.sonora-simd] +opt-level = 3 + [profile.dev] # Line tables (for backtraces) for workspace crates, no debug info for # dependencies: keeps target/ several times smaller. Override locally for diff --git a/crates/tsc-audio/Cargo.toml b/crates/tsc-audio/Cargo.toml index 6991483..44bb56f 100644 --- a/crates/tsc-audio/Cargo.toml +++ b/crates/tsc-audio/Cargo.toml @@ -19,10 +19,17 @@ hound = "3.5.1" opus2 = "0.4" rtrb = { version = "0.4.0", optional = true } rubato = "5.0.0" +serde = { version = "1.0.228", features = ["derive"] } +sonora = "0.2" +sonora-agc2 = "0.2" +sonora-simd = "0.2" thiserror = "2.0.21" tracing = "0.1.44" tsclientlib = { path = "../proto/tsclientlib" } tsproto-packets = { path = "../proto/tsproto-packets" } +[dev-dependencies] +serde_json = "1" + [lints] workspace = true diff --git a/crates/tsc-audio/src/device.rs b/crates/tsc-audio/src/device.rs index 5b0ad81..69ecb94 100644 --- a/crates/tsc-audio/src/device.rs +++ b/crates/tsc-audio/src/device.rs @@ -2,42 +2,140 @@ //! //! The device callbacks only move samples through lock-free ring buffers; all //! processing happens on the caller's side. +//! +//! Devices are identified by cpal's stable device id (`host:device`, e.g. +//! `alsa:hw:1,0`), which survives restarts and replugging. A stream notices +//! when its device goes away through cpal's error callback +//! ([`Capture::is_lost`]); [`Managed`] reopens it, on the default device when +//! the selected one is gone, and moves back when it returns. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; +use cpal::{ErrorKind, SampleFormat}; use rtrb::{Consumer, Producer, RingBuffer}; -use tracing::warn; +use tracing::{debug, warn}; use crate::{Error, Result}; /// A device as shown in settings. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct DeviceInfo { + /// Stable id to store in settings (`AudioSettings::input_device`). + pub id: String, + /// Human-readable name. pub name: String, pub input: bool, pub output: bool, + /// The system's default input device. + pub default_input: bool, + /// The system's default output device. + pub default_output: bool, } fn device_error(e: impl std::fmt::Display) -> Error { Error::Device(e.to_string()) } +fn device_name(device: &cpal::Device) -> String { + device.description().map(|d| d.name().to_string()).unwrap_or_else(|_| device.to_string()) +} + +fn device_id(device: &cpal::Device) -> Option { + device.id().ok().map(|id| id.to_string()) +} + /// All devices of the default host. pub fn list_devices() -> Result> { let host = cpal::default_host(); + let default_input = host.default_input_device().and_then(|d| device_id(&d)); + let default_output = host.default_output_device().and_then(|d| device_id(&d)); let devices = host.devices().map_err(device_error)?; Ok(devices - .map(|d| DeviceInfo { - name: d.description().map(|d| d.name().to_string()).unwrap_or_default(), - input: d.supports_input(), - output: d.supports_output(), + .filter_map(|d| { + let id = device_id(&d)?; + Some(DeviceInfo { + name: device_name(&d), + input: d.supports_input(), + output: d.supports_output(), + default_input: default_input.as_deref() == Some(id.as_str()), + default_output: default_output.as_deref() == Some(id.as_str()), + id, + }) }) .collect()) } +/// Devices that can record. +pub fn input_devices() -> Result> { + Ok(list_devices()?.into_iter().filter(|d| d.input).collect()) +} + +/// Devices that can play. +pub fn output_devices() -> Result> { + Ok(list_devices()?.into_iter().filter(|d| d.output).collect()) +} + +/// The device with this id, or the default one for `None`. +fn find_device(id: Option<&str>, input: bool) -> Result { + let host = cpal::default_host(); + let kind = if input { "input" } else { "output" }; + let Some(id) = id else { + let device = if input { host.default_input_device() } else { host.default_output_device() }; + return device.ok_or_else(|| Error::Device(format!("no {kind} device"))); + }; + let parsed = id.parse().map_err(device_error)?; + host.device_by_id(&parsed).ok_or_else(|| Error::Device(format!("{kind} device {id} not found"))) +} + +/// Whether a device with this id is present. +pub fn device_exists(id: &str) -> bool { + id.parse().ok().and_then(|id| cpal::default_host().device_by_id(&id)).is_some() +} + +/// Errors after which a stream will not recover by itself. +fn is_fatal(kind: ErrorKind) -> bool { + !matches!(kind, ErrorKind::DeviceChanged | ErrorKind::Xrun | ErrorKind::RealtimeDenied) +} + +/// The error callback: log, and flag the stream lost on fatal errors. +fn error_callback(what: &'static str, lost: Arc) -> impl FnMut(cpal::Error) + Send { + move |error| { + if is_fatal(error.kind()) { + warn!(%error, "{what} stream lost"); + lost.store(true, Ordering::Relaxed); + } else { + debug!(%error, "{what} stream"); + } + } +} + +/// The default config, but with f32 samples if the device offers them at the +/// same rate (streams here are f32 only). +fn f32_config( + default: cpal::SupportedStreamConfig, + supported: impl Iterator, +) -> cpal::StreamConfig { + if default.sample_format() == SampleFormat::F32 { + return default.config(); + } + let rate = default.sample_rate(); + supported + .filter(|r| r.sample_format() == SampleFormat::F32) + .find_map(|r| r.try_with_sample_rate(rate)) + .map(|c| c.config()) + .unwrap_or_else(|| default.config()) +} + /// Running capture stream. Samples are interleaved at the device's rate. pub struct Capture { _stream: cpal::Stream, consumer: Consumer, + lost: Arc, + id: Option, + name: String, pub channels: usize, pub rate: u32, } @@ -45,14 +143,21 @@ pub struct Capture { impl Capture { /// Open the default input device, buffering up to `buffer_ms` of audio. pub fn open_default(buffer_ms: u32) -> Result { - let device = cpal::default_host() - .default_input_device() - .ok_or_else(|| Error::Device("no input device".into()))?; - let config = device.default_input_config().map_err(device_error)?.config(); + Self::open(None, buffer_ms) + } + + /// Open the input device with this id (see [`DeviceInfo::id`]), or the + /// default one for `None`. + pub fn open(id: Option<&str>, buffer_ms: u32) -> Result { + let device = find_device(id, true)?; + let default = device.default_input_config().map_err(device_error)?; + let supported = device.supported_input_configs().map_err(device_error)?; + let config = f32_config(default, supported); let channels = config.channels as usize; let rate = config.sample_rate; let (mut producer, consumer) = RingBuffer::new((rate * buffer_ms / 1000) as usize * channels); + let lost = Arc::new(AtomicBool::new(false)); let stream = device .build_input_stream( config, @@ -62,12 +167,20 @@ impl Capture { chunk.fill_from_iter(data[..n].iter().copied()); } }, - |error| warn!(%error, "capture stream error"), + error_callback("capture", lost.clone()), None, ) .map_err(device_error)?; stream.play().map_err(device_error)?; - Ok(Self { _stream: stream, consumer, channels, rate }) + Ok(Self { + _stream: stream, + consumer, + lost, + id: device_id(&device), + name: device_name(&device), + channels, + rate, + }) } /// Move everything captured so far into `out`. @@ -77,26 +190,45 @@ impl Capture { out.extend(chunk); } } + + /// The device went away or the stream broke; reopen it. + pub fn is_lost(&self) -> bool { + self.lost.load(Ordering::Relaxed) + } + + pub fn name(&self) -> &str { + &self.name + } } /// Running playback stream. Write interleaved samples at the device's rate. pub struct Playback { _stream: cpal::Stream, producer: Producer, + lost: Arc, + id: Option, + name: String, + capacity: usize, pub channels: usize, pub rate: u32, } impl Playback { pub fn open_default(buffer_ms: u32) -> Result { - let device = cpal::default_host() - .default_output_device() - .ok_or_else(|| Error::Device("no output device".into()))?; - let config = device.default_output_config().map_err(device_error)?.config(); + Self::open(None, buffer_ms) + } + + /// Open the output device with this id, or the default one for `None`. + pub fn open(id: Option<&str>, buffer_ms: u32) -> Result { + let device = find_device(id, false)?; + let default = device.default_output_config().map_err(device_error)?; + let supported = device.supported_output_configs().map_err(device_error)?; + let config = f32_config(default, supported); let channels = config.channels as usize; let rate = config.sample_rate; - let (producer, mut consumer) = - RingBuffer::::new((rate * buffer_ms / 1000) as usize * channels); + let capacity = (rate * buffer_ms / 1000) as usize * channels; + let (producer, mut consumer) = RingBuffer::::new(capacity); + let lost = Arc::new(AtomicBool::new(false)); let stream = device .build_output_stream( config, @@ -110,12 +242,21 @@ impl Playback { // Underrun: play silence. data[n..].fill(0.0); }, - |error| warn!(%error, "playback stream error"), + error_callback("playback", lost.clone()), None, ) .map_err(device_error)?; stream.play().map_err(device_error)?; - Ok(Self { _stream: stream, producer, channels, rate }) + Ok(Self { + _stream: stream, + producer, + lost, + id: device_id(&device), + name: device_name(&device), + capacity, + channels, + rate, + }) } /// Queue samples; returns how many fit into the buffer. @@ -131,4 +272,299 @@ impl Playback { pub fn free(&self) -> usize { self.producer.slots() } + + /// Samples (all channels) queued and not yet handed to the device. + pub fn queued(&self) -> usize { + self.capacity - self.producer.slots() + } + + /// Queued audio in milliseconds. + pub fn queued_ms(&self) -> u32 { + (self.queued() / self.channels.max(1)) as u32 * 1000 / self.rate.max(1) + } + + /// The device went away or the stream broke; reopen it. + pub fn is_lost(&self) -> bool { + self.lost.load(Ordering::Relaxed) + } + + pub fn name(&self) -> &str { + &self.name + } +} + +/// What [`Managed`] needs from a stream; implemented by [`Capture`] and +/// [`Playback`]. +pub trait DeviceStream: Sized { + fn open(id: Option<&str>, buffer_ms: u32) -> Result; + fn is_lost(&self) -> bool; + /// Id of the device actually opened. + fn device_id(&self) -> Option<&str>; + fn name(&self) -> &str; + fn device_exists(id: &str) -> bool; +} + +impl DeviceStream for Capture { + fn open(id: Option<&str>, buffer_ms: u32) -> Result { + Capture::open(id, buffer_ms) + } + fn is_lost(&self) -> bool { + Capture::is_lost(self) + } + fn device_id(&self) -> Option<&str> { + self.id.as_deref() + } + fn name(&self) -> &str { + &self.name + } + fn device_exists(id: &str) -> bool { + device_exists(id) + } +} + +impl DeviceStream for Playback { + fn open(id: Option<&str>, buffer_ms: u32) -> Result { + Playback::open(id, buffer_ms) + } + fn is_lost(&self) -> bool { + Playback::is_lost(self) + } + fn device_id(&self) -> Option<&str> { + self.id.as_deref() + } + fn name(&self) -> &str { + &self.name + } + fn device_exists(id: &str) -> bool { + device_exists(id) + } +} + +/// What happened to a [`Managed`] stream, for the user. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum DeviceEvent { + /// Opened a device. `fallback` is set when it is the default device + /// because the selected one is missing. + Opened { name: String, fallback: bool }, + /// The open device went away. + Lost { name: String }, + /// No device could be opened; retrying in the background. Reported once + /// until a device opens again. + Unavailable(String), +} + +/// Retry opening a device this often while none is open. +pub const RETRY_INTERVAL: Duration = Duration::from_secs(2); +/// While on the default device instead of the selected one, look for the +/// selected one this often. +pub const RETURN_INTERVAL: Duration = Duration::from_secs(5); + +/// Keeps a stream open across device loss and selection changes. Call +/// [`poll`](Self::poll) regularly from the audio loop. +pub struct Managed { + stream: Option, + wanted: Option, + buffer_ms: u32, + retry_at: Instant, + return_at: Instant, + failing: bool, +} + +impl Managed { + /// Nothing is opened until the first [`poll`](Self::poll). + pub fn new(wanted: Option, buffer_ms: u32) -> Self { + let now = Instant::now(); + Self { stream: None, wanted, buffer_ms, retry_at: now, return_at: now, failing: false } + } + + /// Select another device (`None`: the default); reopens on the next poll. + pub fn select(&mut self, wanted: Option) { + if wanted != self.wanted { + self.wanted = wanted; + self.stream = None; + self.retry_at = Instant::now(); + } + } + + pub fn wanted(&self) -> Option<&str> { + self.wanted.as_deref() + } + + pub fn stream(&mut self) -> Option<&mut S> { + self.stream.as_mut() + } + + /// Whether the stream was replaced since the caller last saw it matters + /// for resamplers; callers compare [`DeviceEvent::Opened`]. + pub fn poll(&mut self) -> Option { + self.poll_at(Instant::now()) + } + + fn poll_at(&mut self, now: Instant) -> Option { + if let Some(stream) = &self.stream { + if stream.is_lost() { + let name = stream.name().to_string(); + self.stream = None; + self.retry_at = now; + return Some(DeviceEvent::Lost { name }); + } + // On the default device although another one is selected: move + // back once it is present again. + let on_fallback = self.wanted.is_some() && stream.device_id() != self.wanted.as_deref(); + if !on_fallback || now < self.return_at { + return None; + } + self.return_at = now + RETURN_INTERVAL; + match self.wanted.as_deref() { + Some(id) if S::device_exists(id) => self.stream = None, + _ => return None, + } + } + if now < self.retry_at { + return None; + } + let wanted = self.wanted.clone(); + let opened = match S::open(wanted.as_deref(), self.buffer_ms) { + Ok(s) => Ok((s, false)), + Err(e) if wanted.is_some() => { + S::open(None, self.buffer_ms).map(|s| (s, true)).map_err(|default_error| { + Error::Device(format!("{e}; default device: {default_error}")) + }) + } + Err(e) => Err(e), + }; + match opened { + Ok((stream, fallback)) => { + let name = stream.name().to_string(); + self.stream = Some(stream); + self.failing = false; + self.return_at = now + RETURN_INTERVAL; + Some(DeviceEvent::Opened { name, fallback }) + } + Err(e) => { + self.retry_at = now + RETRY_INTERVAL; + let first = !self.failing; + self.failing = true; + first.then(|| DeviceEvent::Unavailable(e.to_string())) + } + } + } +} + +#[cfg(test)] +mod tests { + use std::cell::RefCell; + use std::collections::HashSet; + + use super::*; + + thread_local! { + /// Plugged-in fake devices; "default" is the system default. + static PLUGGED: RefCell> = RefCell::new(HashSet::new()); + } + + fn plug(id: &str, on: bool) { + PLUGGED.with(|p| { + let mut p = p.borrow_mut(); + if on { p.insert(id.into()) } else { p.remove(id) } + }); + } + + fn plugged(id: &str) -> bool { + PLUGGED.with(|p| p.borrow().contains(id)) + } + + struct Fake { + id: String, + } + + impl DeviceStream for Fake { + fn open(id: Option<&str>, _: u32) -> Result { + let id = id.unwrap_or("default"); + if plugged(id) { + Ok(Fake { id: id.into() }) + } else { + Err(Error::Device(format!("{id} not found"))) + } + } + fn is_lost(&self) -> bool { + !plugged(&self.id) + } + fn device_id(&self) -> Option<&str> { + Some(&self.id) + } + fn name(&self) -> &str { + &self.id + } + fn device_exists(id: &str) -> bool { + plugged(id) + } + } + + fn opened(name: &str, fallback: bool) -> Option { + Some(DeviceEvent::Opened { name: name.into(), fallback }) + } + + #[test] + fn fatal_errors() { + assert!(is_fatal(ErrorKind::DeviceNotAvailable)); + assert!(is_fatal(ErrorKind::StreamInvalidated)); + assert!(!is_fatal(ErrorKind::Xrun)); + assert!(!is_fatal(ErrorKind::DeviceChanged)); + } + + /// Headset selected, unplugged mid-call, plugged back in. + #[test] + fn reopens_and_falls_back() { + plug("default", true); + plug("headset", true); + let mut m = Managed::::new(Some("headset".into()), 100); + let t0 = Instant::now(); + assert_eq!(m.poll_at(t0), opened("headset", false)); + assert_eq!(m.poll_at(t0), None); + + plug("headset", false); + assert_eq!(m.poll_at(t0), Some(DeviceEvent::Lost { name: "headset".into() })); + assert_eq!(m.poll_at(t0), opened("default", true)); + assert_eq!(m.stream().unwrap().id, "default"); + + // Back only after the return interval. + plug("headset", true); + assert_eq!(m.poll_at(t0 + Duration::from_secs(1)), None); + assert_eq!(m.poll_at(t0 + RETURN_INTERVAL), opened("headset", false)); + + // Selecting the default device switches right away. + m.select(None); + assert_eq!(m.poll_at(t0 + RETURN_INTERVAL), opened("default", false)); + } + + /// Nothing plugged in: one report, retries every interval, recovers. + #[test] + fn retries_when_unavailable() { + plug("default", false); + let mut m = Managed::::new(None, 100); + let t0 = Instant::now(); + assert!(matches!(m.poll_at(t0), Some(DeviceEvent::Unavailable(_)))); + assert!(m.stream().is_none()); + plug("default", true); + // Not before the retry interval, and no repeated report. + assert_eq!(m.poll_at(t0 + Duration::from_millis(500)), None); + assert_eq!(m.poll_at(t0 + RETRY_INTERVAL), opened("default", false)); + plug("default", false); + assert!(matches!(m.poll_at(t0 + RETRY_INTERVAL), Some(DeviceEvent::Lost { .. }))); + assert!(matches!(m.poll_at(t0 + RETRY_INTERVAL), Some(DeviceEvent::Unavailable(_)))); + assert_eq!(m.poll_at(t0 + RETRY_INTERVAL * 2), None); + } + + /// Opening real devices needs hardware; just make sure enumeration does + /// not fail or panic without any. + #[test] + fn enumeration_without_hardware() { + if let Ok(devices) = list_devices() { + for d in devices { + assert!(!d.id.is_empty()); + } + } + assert!(!device_exists("no-such-host:nothing")); + } } diff --git a/crates/tsc-audio/src/lib.rs b/crates/tsc-audio/src/lib.rs index 9d71539..80693e8 100644 --- a/crates/tsc-audio/src/lib.rs +++ b/crates/tsc-audio/src/lib.rs @@ -5,14 +5,22 @@ //! - [`framer`]: slice an arbitrary sample stream into codec frames //! - [`resample`]: sample-rate conversion to the 48 kHz the codec uses //! - [`wav`]: WAV file input/output -//! - [`Mixer`]: per-client jitter buffer, decoder and mixer (from the vendored -//! `tsclientlib::audio::AudioHandler`) -//! - `device` (feature `device`): capture and playback through cpal +//! - [`process`]: echo cancellation, noise suppression and gain control +//! - [`vad`]: voice activity detection +//! - [`mixer`]: per-client jitter buffer, decoder, volume and mixing (on the +//! vendored `tsclientlib::audio::AudioHandler`) +//! - [`settings`]: all user audio settings in one serde struct +//! - `device` (feature `device`): capture and playback through cpal, device +//! lists and loss detection pub mod encode; pub mod framer; +pub mod mixer; pub mod pcm; +pub mod process; pub mod resample; +pub mod settings; +pub mod vad; pub mod wav; #[cfg(feature = "device")] @@ -20,10 +28,11 @@ pub mod device; pub use encode::{VoiceCodec, VoiceEncoder}; pub use framer::Framer; +pub use mixer::Mixer; +pub use process::{ProcessingSettings, Processor}; +pub use settings::AudioSettings; pub use tsclientlib::audio::AudioHandler; - -/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender. -pub type Mixer = AudioHandler; +pub use vad::{Vad, VadSettings}; #[derive(Debug, thiserror::Error)] pub enum Error { diff --git a/crates/tsc-audio/src/mixer.rs b/crates/tsc-audio/src/mixer.rs new file mode 100644 index 0000000..1b56142 --- /dev/null +++ b/crates/tsc-audio/src/mixer.rs @@ -0,0 +1,219 @@ +//! Incoming voice: per-client jitter buffer, decoder and mixer, with a +//! volume and mute per client. +//! +//! The jitter buffer is the vendored `tsclientlib::audio::AudioHandler`. Per +//! sender it keeps a queue of Opus packets and adapts its length: +//! +//! - a new talker starts after a pre-buffer derived from the queue lengths of +//! the other talkers (none for the first one); +//! - a queue that underruns plays Opus packet-loss concealment for the +//! missing packet (one inserted frame) and drops the talker after three +//! frames in a row without data, so a slow sender never lets latency grow; +//! - when the smallest queue length over the last 255 decoded packets exceeds +//! its spread (a fast sender, or a jitter spike that passed), every 100th +//! sample of the decoded frame is dropped (1 % faster playback) until the +//! surplus is gone; above 0.5 s the queue is truncated outright. +//! +//! So sender clock drift is absorbed by occasional 1 % speed-ups (fast +//! sender) or concealment frames (slow sender) and latency stays bounded; the +//! `drift` integration test simulates an hour at ±200 ppm to check that. + +use std::collections::{HashMap, HashSet}; + +use tsclientlib::ClientId; +use tsclientlib::audio::{AudioHandler, Error as QueueError}; +use tsproto_packets::packets::InAudioBuf; + +/// Loudest per-client volume: +12 dB. +pub const MAX_CLIENT_VOLUME: f32 = 4.0; + +/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender. +/// Output is interleaved stereo at 48 kHz. +#[derive(Default)] +pub struct Mixer { + handler: AudioHandler, + volumes: HashMap, + muted: HashSet, +} + +impl Mixer { + pub fn new() -> Self { + Self::default() + } + + /// Queue a voice packet from `id`. Returns `Some(id)` when this client + /// just started talking. Late, duplicate and malformed packets are + /// errors; on UDP they are expected and can be ignored. + pub fn handle_packet( + &mut self, + id: ClientId, + packet: InAudioBuf, + ) -> Result, QueueError> { + self.handler.handle_packet(id, packet) + } + + /// Add the next `buf.len() / 2` stereo frames of all talkers to `buf` + /// (not cleared first), each scaled by its volume. Returns the clients + /// that stopped talking. + pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec { + for (id, queue) in self.handler.get_mut_queues() { + queue.volume = if self.muted.contains(id) { + 0.0 + } else { + self.volumes.get(id).copied().unwrap_or(1.0) + }; + } + // Muted talkers are still decoded so their queues stay in sync. + self.handler.fill_buffer(buf) + } + + /// Linear gain for one client, clamped to `0..=`[`MAX_CLIENT_VOLUME`]. + /// Kept when the client stops and starts talking again. + pub fn set_volume(&mut self, id: ClientId, volume: f32) { + let volume = if volume.is_finite() { volume.clamp(0.0, MAX_CLIENT_VOLUME) } else { 1.0 }; + if volume == 1.0 { + self.volumes.remove(&id); + } else { + self.volumes.insert(id, volume); + } + } + + /// Like [`set_volume`](Self::set_volume), in dB (0 dB = unchanged). + pub fn set_volume_db(&mut self, id: ClientId, db: f32) { + self.set_volume(id, 10f32.powf(db / 20.0)); + } + + pub fn volume(&self, id: ClientId) -> f32 { + self.volumes.get(&id).copied().unwrap_or(1.0) + } + + pub fn set_muted(&mut self, id: ClientId, muted: bool) { + if muted { + self.muted.insert(id); + } else { + self.muted.remove(&id); + } + } + + pub fn is_muted(&self, id: ClientId) -> bool { + self.muted.contains(&id) + } + + /// Forget volume and mute of a client (e.g. it left the server; client + /// ids are reused). + pub fn forget(&mut self, id: ClientId) { + self.volumes.remove(&id); + self.muted.remove(&id); + self.handler.get_mut_queues().remove(&id); + } + + /// Clients with a queue, i.e. currently talking or buffering. + pub fn talkers(&self) -> impl Iterator + '_ { + self.handler.get_queues().keys().copied() + } + + /// Drop all queues; volumes and mutes are kept. + pub fn reset(&mut self) { + self.handler.reset(); + } + + /// The underlying jitter buffer. + pub fn handler(&self) -> &AudioHandler { + &self.handler + } +} + +impl std::fmt::Debug for Mixer { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Mixer") + .field("talkers", &self.handler.get_queues().len()) + .field("volumes", &self.volumes) + .field("muted", &self.muted) + .finish() + } +} + +#[cfg(test)] +mod tests { + use tsproto_packets::packets::{AudioData, CodecType, Direction, OutAudio}; + + use super::*; + use crate::VoiceEncoder; + use crate::encode::VoiceCodec; + use crate::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE}; + + fn packet(from: u16, id: u16, data: &[u8]) -> InAudioBuf { + let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data }); + InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap() + } + + /// Two clients send tones at the same level; after setting volumes the + /// mix carries each at its own gain, and a muted one not at all. + #[test] + fn volume_per_client() { + let (a, b) = (ClientId(3), ClientId(4)); + let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + let mut enc_b = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + let tone_a = pcm::sine(500.0, 2.0, 0.2); + let tone_b = pcm::sine(1300.0, 2.0, 0.2); + + let mut mixer = Mixer::new(); + mixer.set_volume(a, 0.25); + mixer.set_volume_db(b, 6.0); + assert!((mixer.volume(b) - 1.995).abs() < 0.01); + let mut out = Vec::new(); + let frames = tone_a.chunks_exact(FRAME_SAMPLES).zip(tone_b.chunks_exact(FRAME_SAMPLES)); + for (i, (fa, fb)) in frames.enumerate() { + let id = i as u16; + let started = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap())); + if i == 0 { + assert_eq!(started.unwrap(), Some(a)); + } + mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap(); + let mut buf = vec![0.0; FRAME_SAMPLES * 2]; + mixer.fill_buffer(&mut buf); + out.extend(pcm::to_mono(&buf, 2)); + } + assert_eq!(mixer.talkers().count(), 2); + let tail = &out[out.len() / 2..]; + let power = |f| pcm::goertzel_power(tail, f, SAMPLE_RATE); + // Amplitude ratio 0.25 / 2 = 1/8, power ratio 1/64 (-18 dB). + let ratio_db = 10.0 * (power(500.0) / power(1300.0)).log10(); + assert!((ratio_db + 18.0).abs() < 1.5, "ratio {ratio_db} dB"); + + // Mute b: only a remains. + mixer.set_muted(b, true); + let mut out = Vec::new(); + for i in 0..20u16 { + let id = 100 + i; + let fa = &tone_a[..FRAME_SAMPLES]; + let fb = &tone_b[..FRAME_SAMPLES]; + let _ = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap())); + let _ = mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap())); + let mut buf = vec![0.0; FRAME_SAMPLES * 2]; + mixer.fill_buffer(&mut buf); + out.extend(pcm::to_mono(&buf, 2)); + } + let tail = &out[out.len() / 2..]; + assert!(pcm::goertzel_power(tail, 1300.0, SAMPLE_RATE) < 1e-6); + assert!(pcm::goertzel_power(tail, 500.0, SAMPLE_RATE) > 1e-4); + } + + #[test] + fn volume_bounds_and_forget() { + let mut mixer = Mixer::new(); + let id = ClientId(9); + mixer.set_volume(id, 100.0); + assert_eq!(mixer.volume(id), MAX_CLIENT_VOLUME); + mixer.set_volume(id, -1.0); + assert_eq!(mixer.volume(id), 0.0); + mixer.set_volume(id, f32::NAN); + assert_eq!(mixer.volume(id), 1.0); + mixer.set_volume(id, 0.5); + mixer.set_muted(id, true); + assert!(mixer.is_muted(id)); + mixer.forget(id); + assert!(!mixer.is_muted(id)); + assert_eq!(mixer.volume(id), 1.0); + } +} diff --git a/crates/tsc-audio/src/pcm.rs b/crates/tsc-audio/src/pcm.rs index ade1a22..15b1c64 100644 --- a/crates/tsc-audio/src/pcm.rs +++ b/crates/tsc-audio/src/pcm.rs @@ -13,6 +13,20 @@ pub fn sine(freq: f32, seconds: f32, amplitude: f32) -> Vec { (0..n).map(|i| amplitude * (TAU * freq * i as f32 / SAMPLE_RATE as f32).sin()).collect() } +/// Deterministic white noise, uniform in `[-amplitude, amplitude]`, for tests +/// and calibration. +pub fn white_noise(n: usize, amplitude: f32, seed: u64) -> Vec { + // PCG-style LCG; the top 24 bits are uniform enough. + let mut state = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (0..n) + .map(|_| { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let x = (state >> 40) as f32 / (1u64 << 24) as f32; + amplitude * (2.0 * x - 1.0) + }) + .collect() +} + /// Average interleaved channels into mono. pub fn to_mono(interleaved: &[f32], channels: usize) -> Vec { if channels <= 1 { @@ -93,6 +107,17 @@ mod tests { assert_eq!(voiced_tone_ratio(&[0.0; 48_000], 1000.0, SAMPLE_RATE), 0.0); } + #[test] + fn noise_is_white_and_deterministic() { + let n = white_noise(48_000, 0.5, 1); + assert_eq!(n, white_noise(48_000, 0.5, 1)); + assert_ne!(n, white_noise(48_000, 0.5, 2)); + assert!(n.iter().all(|s| s.abs() <= 0.5)); + // Uniform in ±a has energy a²/3. + assert!((energy(&n) - 0.25 / 3.0).abs() < 0.005); + assert!(tone_ratio(&n, 1000.0, SAMPLE_RATE) < 0.01); + } + #[test] fn channel_conversion() { assert_eq!(to_mono(&[1.0, 3.0, 2.0, 4.0], 2), vec![2.0, 3.0]); diff --git a/crates/tsc-audio/src/process.rs b/crates/tsc-audio/src/process.rs new file mode 100644 index 0000000..ee36b09 --- /dev/null +++ b/crates/tsc-audio/src/process.rs @@ -0,0 +1,363 @@ +//! Microphone processing: echo cancellation, noise suppression and automatic +//! gain control. +//! +//! Backed by [sonora](https://crates.io/crates/sonora) (BSD-3-Clause), a pure +//! Rust port of the WebRTC audio processing module (AEC3, NS, AGC2): no C++ +//! toolchain or system library needed, so it builds the same on Linux, +//! Windows and Android. +//! +//! The [`Processor`] runs on 10 ms mono frames at 48 kHz. The far end, i.e. +//! exactly what goes to the speakers (the mixer output after per-client volume +//! and output mute), is fed through [`Processor::render`]; the microphone +//! through [`Processor::capture`]. Both accept any length and frame internally. + +use serde::{Deserialize, Serialize}; +use sonora::config::{ + AdaptiveDigital, CaptureLevelAdjustment, EchoCanceller, GainController2, HighPassFilter, + MaxProcessingRate, NoiseSuppression, NoiseSuppressionLevel, Pipeline, +}; +use sonora::{AudioProcessing, Config, StreamConfig}; + +use crate::Framer; +use crate::pcm::SAMPLE_RATE; + +/// Samples in one 10 ms processing frame (mono, 48 kHz). +pub const PROCESS_FRAME: usize = SAMPLE_RATE as usize / 100; + +/// How hard noise suppression works. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum NoiseLevel { + /// About 6 dB. + Low, + /// About 12 dB. + #[default] + Moderate, + /// About 18 dB. + High, + /// About 21 dB. + VeryHigh, +} + +impl From for NoiseSuppressionLevel { + fn from(level: NoiseLevel) -> Self { + match level { + NoiseLevel::Low => Self::Low, + NoiseLevel::Moderate => Self::Moderate, + NoiseLevel::High => Self::High, + NoiseLevel::VeryHigh => Self::VeryHigh, + } + } +} + +/// User settings for microphone processing. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ProcessingSettings { + /// Remove what the speakers play from the microphone signal. + pub echo_cancellation: bool, + /// Remove steady background noise (fans, hum, hiss). + pub noise_suppression: bool, + pub noise_level: NoiseLevel, + /// Bring speech to a steady level (adaptive digital gain and limiter). + pub auto_gain: bool, + /// Manual microphone gain in dB, applied before everything else. + /// Clamped to ±[`MAX_INPUT_GAIN_DB`]. + pub input_gain_db: f32, + /// Remove rumble below ~80 Hz. Always on while echo cancellation is. + pub high_pass: bool, +} + +/// Limit of [`ProcessingSettings::input_gain_db`]. +pub const MAX_INPUT_GAIN_DB: f32 = 30.0; + +impl Default for ProcessingSettings { + fn default() -> Self { + Self { + echo_cancellation: true, + noise_suppression: true, + noise_level: NoiseLevel::Moderate, + auto_gain: true, + input_gain_db: 0.0, + high_pass: true, + } + } +} + +impl ProcessingSettings { + /// Everything off: the processor passes audio through untouched. + pub fn off() -> Self { + Self { + echo_cancellation: false, + noise_suppression: false, + noise_level: NoiseLevel::Moderate, + auto_gain: false, + input_gain_db: 0.0, + high_pass: false, + } + } + + fn input_gain(&self) -> f32 { + let db = if self.input_gain_db.is_finite() { self.input_gain_db } else { 0.0 }; + 10f32.powf(db.clamp(-MAX_INPUT_GAIN_DB, MAX_INPUT_GAIN_DB) / 20.0) + } + + fn is_passthrough(&self) -> bool { + !self.echo_cancellation + && !self.noise_suppression + && !self.auto_gain + && !self.high_pass + && self.input_gain() == 1.0 + } + + fn to_config(&self) -> Config { + let gain = self.input_gain(); + Config { + pipeline: Pipeline { + // Full band: voice is Opus at 48 kHz. + maximum_internal_processing_rate: MaxProcessingRate::Rate48kHz, + ..Default::default() + }, + capture_level_adjustment: (gain != 1.0) + .then(|| CaptureLevelAdjustment { pre_gain_factor: gain, ..Default::default() }), + high_pass_filter: self.high_pass.then(HighPassFilter::default), + echo_canceller: self.echo_cancellation.then(EchoCanceller::default), + noise_suppression: self + .noise_suppression + .then(|| NoiseSuppression { level: self.noise_level.into(), ..Default::default() }), + gain_controller2: self.auto_gain.then(|| GainController2 { + adaptive_digital: Some(AdaptiveDigital::default()), + ..Default::default() + }), + ..Default::default() + } + } +} + +/// Echo canceller statistics, for diagnostics. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct ProcessingStats { + /// Echo return loss enhancement in dB: how much echo the canceller removes. + pub erle_db: Option, + /// Render-to-capture delay the canceller estimated. + pub delay_ms: Option, +} + +/// Microphone processing pipeline stage. See the [module docs](self). +pub struct Processor { + apm: AudioProcessing, + settings: ProcessingSettings, + passthrough: bool, + delay_ms: u32, + render_framer: Framer, + capture_framer: Framer, + frame: Vec, +} + +impl Processor { + pub fn new(settings: &ProcessingSettings) -> Self { + let stream = StreamConfig::new(SAMPLE_RATE, 1); + let apm = AudioProcessing::builder() + .config(settings.to_config()) + .capture_config(stream) + .render_config(stream) + .build(); + Self { + apm, + settings: settings.clone(), + passthrough: settings.is_passthrough(), + delay_ms: 0, + render_framer: Framer::new(PROCESS_FRAME), + capture_framer: Framer::new(PROCESS_FRAME), + frame: vec![0.0; PROCESS_FRAME], + } + } + + pub fn settings(&self) -> &ProcessingSettings { + &self.settings + } + + /// Change settings. Only reconfigures when something changed, since that + /// resets the adaptive filters. + pub fn apply(&mut self, settings: &ProcessingSettings) { + if *settings == self.settings { + return; + } + self.apm.apply_config(settings.to_config()); + self.settings = settings.clone(); + self.passthrough = settings.is_passthrough(); + } + + /// Hint for the echo canceller: time from handing a frame to + /// [`render`](Self::render) until it is heard, plus time from the + /// microphone picking a sample up until it reaches + /// [`capture`](Self::capture). The canceller estimates the rest itself. + pub fn set_delay_ms(&mut self, delay_ms: u32) { + if delay_ms != self.delay_ms { + self.delay_ms = delay_ms; + // Values above 500 ms are clamped, which is fine for a hint. + let _ = self.apm.set_stream_delay_ms(delay_ms.min(500) as i32); + } + } + + /// Feed far-end audio: mono 48 kHz, exactly as played. + pub fn render(&mut self, samples: &[f32]) { + if !self.settings.echo_cancellation { + return; + } + let Self { apm, render_framer, frame, .. } = self; + render_framer.push(samples, |f| { + // Render output is not used: no render-side processing is enabled. + let _ = apm.process_render_f32(&[f], &mut [frame.as_mut_slice()]); + }); + } + + /// Process microphone audio (mono 48 kHz), appending the result to `out`. + /// Output comes in whole 10 ms frames, so up to 10 ms stay buffered. + pub fn capture(&mut self, samples: &[f32], out: &mut Vec) { + if self.passthrough && self.capture_framer.buffered() == 0 { + out.extend_from_slice(samples); + return; + } + let Self { apm, capture_framer, frame, passthrough, .. } = self; + capture_framer.push(samples, |f| { + if *passthrough { + out.extend_from_slice(f); + } else if apm.process_capture_f32(&[f], &mut [frame.as_mut_slice()]).is_ok() { + out.extend_from_slice(frame); + } else { + out.extend_from_slice(f); + } + }); + } + + pub fn stats(&self) -> ProcessingStats { + let stats = self.apm.statistics(); + ProcessingStats { erle_db: stats.echo_return_loss_enhancement, delay_ms: stats.delay_ms } + } +} + +impl std::fmt::Debug for Processor { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Processor").field("settings", &self.settings).finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use std::f32::consts::TAU; + + use super::*; + use crate::pcm::{self, energy, white_noise as noise}; + + fn db(ratio: f32) -> f32 { + 10.0 * ratio.max(1e-20).log10() + } + + #[test] + fn passthrough_when_off() { + let mut p = Processor::new(&ProcessingSettings::off()); + let input = pcm::sine(440.0, 0.05, 0.3); + let mut out = Vec::new(); + p.capture(&input[..100], &mut out); + p.capture(&input[100..], &mut out); + assert_eq!(out, input); + } + + #[test] + fn input_gain_is_clamped() { + let s = ProcessingSettings { input_gain_db: 1000.0, ..ProcessingSettings::off() }; + assert!((s.input_gain() - 10f32.powf(1.5)).abs() < 1e-3); + let s = ProcessingSettings { input_gain_db: f32::NAN, ..ProcessingSettings::off() }; + assert_eq!(s.input_gain(), 1.0); + let s = ProcessingSettings { input_gain_db: 6.0, ..ProcessingSettings::off() }; + assert!(!s.is_passthrough()); + } + + #[test] + fn settings_serde_defaults() { + let s: ProcessingSettings = serde_json::from_str(r#"{"noise_level":"very_high"}"#).unwrap(); + assert_eq!(s.noise_level, NoiseLevel::VeryHigh); + assert!(s.echo_cancellation); + } + + /// The far end leaks into the microphone 40 ms later at -6 dB; after the + /// canceller converged the echo must be at least 10 dB quieter. + #[test] + fn cancels_synthetic_echo() { + let settings = ProcessingSettings { + echo_cancellation: true, + high_pass: true, + ..ProcessingSettings::off() + }; + let mut p = Processor::new(&settings); + p.set_delay_ms(40); + let seconds = 6; + let delay = 40 * PROCESS_FRAME / 10; + // Speech-like far end: noise with a syllable-rate envelope. + let far: Vec = noise(SAMPLE_RATE as usize * seconds, 0.4, 1) + .into_iter() + .enumerate() + .map(|(i, s)| s * (0.6 + 0.4 * (i as f32 * 4.0 / SAMPLE_RATE as f32 * TAU).sin())) + .collect(); + let mut near = vec![0.0; delay]; + near.extend(far.iter().map(|s| s * 0.5)); + near.truncate(far.len()); + + let mut out = Vec::new(); + for (f, n) in far.chunks(PROCESS_FRAME).zip(near.chunks(PROCESS_FRAME)) { + p.render(f); + p.capture(n, &mut out); + } + assert_eq!(out.len(), near.len()); + let tail = SAMPLE_RATE as usize * 2; + let before = energy(&near[near.len() - tail..]); + let after = energy(&out[out.len() - tail..]); + let attenuation = db(before / after); + assert!(attenuation >= 10.0, "echo attenuated by {attenuation:.1} dB"); + } + + /// White noise gets quieter while a tone on top of it survives. The tone + /// comes in 200 ms bursts like syllables: a steady tone is stationary and + /// a noise suppressor rightly learns it as noise. + #[test] + fn suppresses_noise_keeps_tone() { + let settings = ProcessingSettings { + noise_suppression: true, + noise_level: NoiseLevel::High, + ..ProcessingSettings::off() + }; + let seconds = 4; + let n = SAMPLE_RATE as usize * seconds; + let hiss = noise(n, 0.05, 7); + + let mut p = Processor::new(&settings); + let mut out = Vec::new(); + p.capture(&hiss, &mut out); + let tail = SAMPLE_RATE as usize; + let reduction = db(energy(&hiss[n - tail..]) / energy(&out[n - tail..])); + assert!(reduction >= 10.0, "noise reduced by {reduction:.1} dB"); + + let ms = |ms: usize| ms * SAMPLE_RATE as usize / 1000; + let tone: Vec = pcm::sine(600.0, seconds as f32, 0.3) + .into_iter() + .enumerate() + .map(|(i, s)| if i % ms(400) < ms(200) { s } else { 0.0 }) + .collect(); + let mixed: Vec = tone.iter().zip(&hiss).map(|(a, b)| a + b).collect(); + let mut p = Processor::new(&settings); + let mut out = Vec::new(); + p.capture(&mixed, &mut out); + // The last two seconds, away from the burst edges. + for start in (n - ms(2000)..n).step_by(ms(400)) { + let on = start + ms(40)..start + ms(160); + let tone_in = pcm::goertzel_power(&tone[on.clone()], 600.0, SAMPLE_RATE); + let tone_out = pcm::goertzel_power(&out[on], 600.0, SAMPLE_RATE); + let loss = db(tone_in / tone_out); + assert!(loss.abs() < 3.0, "tone changed by {loss:.1} dB"); + let off = start + ms(240)..start + ms(360); + let reduction = db(energy(&hiss[off.clone()]) / energy(&out[off])); + assert!(reduction >= 6.0, "noise between bursts reduced by {reduction:.1} dB"); + } + } +} diff --git a/crates/tsc-audio/src/settings.rs b/crates/tsc-audio/src/settings.rs new file mode 100644 index 0000000..450195a --- /dev/null +++ b/crates/tsc-audio/src/settings.rs @@ -0,0 +1,80 @@ +//! All user audio settings in one serde struct, e.g. for +//! `tsc_store::Store::set_setting("audio", &settings)`. Missing fields take +//! their defaults, so stored settings survive new options. + +use serde::{Deserialize, Serialize}; + +use crate::process::ProcessingSettings; +use crate::vad::VadSettings; + +/// When the microphone is sent. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TransmitMode { + /// While the push-to-talk key or button is held. + #[default] + PushToTalk, + /// While the voice activity detector hears speech. + VoiceActivation, + /// Always (unless muted). + Continuous, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct AudioSettings { + pub transmit: TransmitMode, + pub processing: ProcessingSettings, + pub vad: VadSettings, + /// Microphone by device id (`device::DeviceInfo::id`); `None` follows + /// the system default. + pub input_device: Option, + /// Speakers by device id; `None` follows the system default. + pub output_device: Option, + /// Output volume for everyone, linear (1 = unchanged), applied before + /// the echo canceller sees the signal. + pub output_volume: f32, + /// Audio kept queued for the speakers. Lower is snappier, higher + /// survives scheduling hiccups. + pub playback_buffer_ms: u32, +} + +impl Default for AudioSettings { + fn default() -> Self { + Self { + transmit: TransmitMode::PushToTalk, + processing: ProcessingSettings::default(), + vad: VadSettings::default(), + input_device: None, + output_device: None, + output_volume: 1.0, + playback_buffer_ms: 60, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn json_roundtrip_and_defaults() { + let mut s = AudioSettings { + transmit: TransmitMode::VoiceActivation, + input_device: Some("alsa:hw:1,0".into()), + ..Default::default() + }; + s.processing.echo_cancellation = false; + s.vad.threshold_db = -35.0; + let json = serde_json::to_string(&s).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), s); + + // Older or partial settings fill in defaults. + let partial: AudioSettings = + serde_json::from_str(r#"{"transmit":"continuous","vad":{"hangover_ms":100}}"#).unwrap(); + assert_eq!(partial.transmit, TransmitMode::Continuous); + assert_eq!(partial.vad.hangover_ms, 100); + assert_eq!(partial.vad.threshold_db, VadSettings::default().threshold_db); + assert_eq!(partial.processing, ProcessingSettings::default()); + } +} diff --git a/crates/tsc-audio/src/vad.rs b/crates/tsc-audio/src/vad.rs new file mode 100644 index 0000000..1f1dc43 --- /dev/null +++ b/crates/tsc-audio/src/vad.rs @@ -0,0 +1,250 @@ +//! Voice activity detection for voice-activated transmission. +//! +//! A level gate with hangover, optionally combined with the RNN speech +//! detector of WebRTC's AGC2 (through sonora), which ignores noise such as +//! typing, fans or breathing that is loud enough to pass the level gate. +//! Works on 10 ms mono frames at 48 kHz, after [`Processor`](crate::process::Processor). + +use serde::{Deserialize, Serialize}; +use sonora_agc2::vad_wrapper::VoiceActivityDetectorWrapper; + +use crate::pcm::SAMPLE_RATE; +use crate::process::PROCESS_FRAME; + +/// What opens the gate. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum VadMode { + /// The level is above the threshold. + #[default] + Level, + /// The level is above the threshold and the frame sounds like speech. + Speech, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct VadSettings { + pub mode: VadMode, + /// Level in dBFS (RMS of a 10 ms frame; a full-scale sine is -3 dBFS) + /// that opens the gate. + pub threshold_db: f32, + /// Keep transmitting this long after the last active frame, so word + /// endings and short pauses are not cut. + pub hangover_ms: u32, + /// Speech probability (0 to 1) needed in [`VadMode::Speech`]. + pub speech_probability: f32, +} + +impl Default for VadSettings { + fn default() -> Self { + // Speech after automatic gain control sits around -20 dBFS and the + // controller keeps noise below -50 dBFS. + Self { + mode: VadMode::Level, + threshold_db: -40.0, + hangover_ms: 300, + speech_probability: 0.6, + } + } +} + +/// Level of silence, so the meter has a floor. +pub const SILENCE_DB: f32 = -100.0; + +/// RMS level in dBFS. +pub fn level_db(samples: &[f32]) -> f32 { + let e = crate::pcm::energy(samples); + if e > 0.0 { (10.0 * e.log10()).max(SILENCE_DB) } else { SILENCE_DB } +} + +/// Voice activity detector. See the [module docs](self). +pub struct Vad { + settings: VadSettings, + rnn: Option, + scaled: Vec, + hang_remaining_ms: u32, + level_db: f32, + probability: f32, +} + +impl Vad { + pub fn new(settings: &VadSettings) -> Self { + let mut vad = Self { + settings: settings.clone(), + rnn: None, + scaled: vec![0.0; PROCESS_FRAME], + hang_remaining_ms: 0, + level_db: SILENCE_DB, + probability: 0.0, + }; + vad.apply(settings); + vad + } + + pub fn settings(&self) -> &VadSettings { + &self.settings + } + + pub fn apply(&mut self, settings: &VadSettings) { + if settings.mode == VadMode::Speech && self.rnn.is_none() { + self.rnn = Some(VoiceActivityDetectorWrapper::new( + sonora_simd::detect_backend(), + SAMPLE_RATE as i32, + )); + } else if settings.mode != VadMode::Speech { + self.rnn = None; + self.probability = 0.0; + } + self.settings = settings.clone(); + } + + /// Analyse mono 48 kHz audio, a whole number of 10 ms frames (a + /// trailing partial frame is ignored). Returns whether to transmit. + pub fn process(&mut self, samples: &[f32]) -> bool { + for frame in samples.chunks_exact(PROCESS_FRAME) { + self.level_db = level_db(frame); + let mut active = self.level_db >= self.settings.threshold_db; + if let Some(rnn) = &mut self.rnn { + // The detector works on 16-bit scale floats. + for (dst, src) in self.scaled.iter_mut().zip(frame) { + *dst = src * 32768.0; + } + self.probability = rnn.analyze(&self.scaled); + active &= self.probability >= self.settings.speech_probability; + } + if active { + // Plus this frame itself. + self.hang_remaining_ms = self.settings.hangover_ms + 10; + } else { + self.hang_remaining_ms = self.hang_remaining_ms.saturating_sub(10); + } + } + self.is_active() + } + + /// Whether the gate is open after the last frame. + pub fn is_active(&self) -> bool { + self.hang_remaining_ms > 0 + } + + /// Level of the last frame in dBFS, for a microphone meter. + pub fn level_db(&self) -> f32 { + self.level_db + } + + /// Speech probability of the last frame, 0 unless in [`VadMode::Speech`]. + pub fn speech_probability(&self) -> f32 { + self.probability + } + + /// Close the gate immediately (e.g. when switching to push-to-talk). + pub fn reset(&mut self) { + self.hang_remaining_ms = 0; + } +} + +impl std::fmt::Debug for Vad { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Vad") + .field("settings", &self.settings) + .field("level_db", &self.level_db) + .field("active", &self.is_active()) + .finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::pcm::{self, white_noise as noise}; + + /// A voiced sound: a 120 Hz pulse train through three vowel formants, + /// scaled to `amplitude` peak. + pub(crate) fn vowel(seconds: f32, amplitude: f32) -> Vec { + let n = (seconds * SAMPLE_RATE as f32) as usize; + let pulses: Vec = + (0..n).map(|i| if i % (SAMPLE_RATE as usize / 120) == 0 { 1.0 } else { 0.0 }).collect(); + let resonate = |freq: f32, bandwidth: f32| -> Vec { + let r = (-std::f32::consts::PI * bandwidth / SAMPLE_RATE as f32).exp(); + let c = 2.0 * r * (std::f32::consts::TAU * freq / SAMPLE_RATE as f32).cos(); + let (mut y1, mut y2) = (0.0f32, 0.0f32); + pulses + .iter() + .map(|&x| { + let y = x * (1.0 - r) + c * y1 - r * r * y2; + (y2, y1) = (y1, y); + y + }) + .collect() + }; + let (f1, f2, f3) = (resonate(700.0, 80.0), resonate(1200.0, 90.0), resonate(2600.0, 120.0)); + let mix: Vec = (0..n).map(|i| f1[i] + 0.6 * f2[i] + 0.3 * f3[i]).collect(); + let peak = mix.iter().fold(0.0f32, |m, s| m.max(s.abs())); + mix.iter().map(|s| s / peak * amplitude).collect() + } + + fn active_fraction(vad: &mut Vad, signal: &[f32]) -> f32 { + let frames: Vec = + signal.chunks_exact(PROCESS_FRAME).map(|f| vad.process(f)).collect(); + frames.iter().filter(|&&a| a).count() as f32 / frames.len() as f32 + } + + #[test] + fn level() { + assert_eq!(level_db(&[0.0; 480]), SILENCE_DB); + assert!((level_db(&pcm::sine(1000.0, 0.01, 1.0)) + 3.01).abs() < 0.1); + assert!((level_db(&[0.1; 480]) + 20.0).abs() < 0.01); + } + + #[test] + fn gate_and_hangover() { + let settings = VadSettings { hangover_ms: 50, ..Default::default() }; + let mut vad = Vad::new(&settings); + let loud = pcm::sine(300.0, 0.01, 0.1); + let quiet = vec![0.001; PROCESS_FRAME]; + assert!(!vad.process(&quiet)); + assert!(vad.process(&loud)); + // 50 ms of hangover after the last loud frame, then closed. + for _ in 0..5 { + assert!(vad.process(&quiet)); + } + assert!(!vad.process(&quiet)); + // A 20 ms frame is analysed as two 10 ms frames. + assert!(vad.process(&[loud.clone(), loud].concat())); + vad.reset(); + assert!(!vad.is_active()); + } + + #[test] + fn threshold_is_respected() { + let mut vad = + Vad::new(&VadSettings { threshold_db: -30.0, hangover_ms: 0, ..Default::default() }); + // -33 dBFS stays closed, -23 dBFS opens. + assert!(!vad.process(&pcm::sine(300.0, 0.01, 0.0316))); + assert!(vad.process(&pcm::sine(300.0, 0.01, 0.1))); + } + + /// In speech mode, noise loud enough for the level gate stays out, a + /// voiced sound gets through. + #[test] + fn speech_mode_rejects_noise() { + let settings = VadSettings { mode: VadMode::Speech, hangover_ms: 0, ..Default::default() }; + let hiss = noise(SAMPLE_RATE as usize * 2, 0.05, 3); + assert!(level_db(&hiss) > settings.threshold_db); + let mut level_only = Vad::new(&VadSettings { mode: VadMode::Level, ..settings.clone() }); + assert!(active_fraction(&mut level_only, &hiss) > 0.99); + let mut vad = Vad::new(&settings); + let noise_active = active_fraction(&mut vad, &hiss); + assert!(noise_active < 0.1, "noise active {noise_active}"); + + let mut vad = Vad::new(&settings); + let voice_active = active_fraction(&mut vad, &vowel(2.0, 0.3)); + assert!(voice_active > 0.8, "voice active {voice_active}"); + assert!(vad.speech_probability() > 0.5); + + // Switching back to level mode drops the detector. + vad.apply(&VadSettings::default()); + assert_eq!(vad.speech_probability(), 0.0); + } +} diff --git a/crates/tsc-audio/tests/drift.rs b/crates/tsc-audio/tests/drift.rs new file mode 100644 index 0000000..306c5d6 --- /dev/null +++ b/crates/tsc-audio/tests/drift.rs @@ -0,0 +1,129 @@ +//! A one-hour call with a sender whose clock runs ±200 ppm off ours: the +//! jitter buffer must keep the latency bounded instead of drifting by the +//! 720 ms the clocks disagree over an hour. +//! +//! The sender transmits continuously (the worst case: talk spurts would reset +//! the queue) over a network with 20–60 ms of jitter, reordering and 0.5 % +//! loss. Every 30 s it sends a loud marker frame instead of the quiet one; +//! the latency is the time from generating a marker to it leaving the mixer. + +use tsc_audio::pcm::{FRAME_SAMPLES, SAMPLE_RATE, energy, sine, white_noise}; +use tsc_audio::{Mixer, VoiceCodec, VoiceEncoder}; +use tsclientlib::ClientId; +use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio}; + +/// The receiver pulls 10 ms at a time, like a playback loop. +const PULL: usize = SAMPLE_RATE as usize / 100; +const MARKER_EVERY: u64 = 1500; + +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> f64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 + } +} + +/// Returns the latency of each marker in ms, in order. +fn simulate(ppm: f64, hours: f64) -> Vec { + let mut encoder = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + // A quiet frame (-65 dBFS noise) and a loud marker, encoded once. + let quiet = white_noise(FRAME_SAMPLES, 0.001, 1); + for _ in 0..5 { + encoder.encode_to_bytes(&quiet).unwrap(); + } + let quiet = encoder.encode_to_bytes(&quiet).unwrap().to_vec(); + let marker = encoder.encode_to_bytes(&sine(1000.0, 0.02, 0.5)).unwrap().to_vec(); + + let mut rng = Rng(ppm.to_bits()); + let mut mixer = Mixer::new(); + let client = ClientId(5); + let total = (hours * 3600.0 * SAMPLE_RATE as f64) as u64; + // Sender frame n is made at n * 20 ms of the sender's clock. + let frame_time = |n: u64| n as f64 * FRAME_SAMPLES as f64 / (1.0 + ppm * 1e-6); + + // (arrival time, packet id), kept sorted by arrival. + let mut in_flight: Vec<(f64, u64)> = Vec::new(); + let mut next_frame = 0u64; + let mut markers_sent = Vec::new(); + let mut latencies = Vec::new(); + let mut out = vec![0.0f32; PULL * 2]; + let mut now = 0u64; + while now < total { + // Everything the sender produced up to now goes on the wire. + while frame_time(next_frame) <= now as f64 { + let is_marker = next_frame % MARKER_EVERY == MARKER_EVERY / 2; + if is_marker { + markers_sent.push(frame_time(next_frame)); + } + // Markers are never lost, so each one can be matched. + if is_marker || rng.next() >= 0.005 { + let jitter = (0.02 + 0.04 * rng.next()) * SAMPLE_RATE as f64; + in_flight.push((frame_time(next_frame) + jitter, next_frame)); + } + next_frame += 1; + } + in_flight.sort_by(|a, b| a.0.total_cmp(&b.0)); + let arrived = in_flight.partition_point(|&(t, _)| t <= now as f64); + for (_, n) in in_flight.drain(..arrived) { + let data = if n % MARKER_EVERY == MARKER_EVERY / 2 { &marker } else { &quiet }; + let packet = OutAudio::new(&AudioData::S2C { + id: n as u16, + codec: CodecType::OpusVoice, + from: 5, + data, + }); + let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap(); + // Late packets are dropped by the jitter buffer, as on a real network. + let _ = mixer.handle_packet(client, packet); + } + + out.fill(0.0); + mixer.fill_buffer(&mut out); + let left: Vec = out.iter().step_by(2).copied().collect(); + if energy(&left) > 1e-3 { + // The latest marker made before now; they are 30 s apart. + let sent = markers_sent.iter().rev().find(|&&t| t <= now as f64).copied(); + if let Some(sent) = sent { + let latency = (now as f64 - sent) * 1000.0 / SAMPLE_RATE as f64; + // One detection per marker (it spans two 10 ms pulls). + if latencies.len() < markers_sent.len() && latency < 5000.0 { + let index = markers_sent.iter().position(|&t| t == sent).unwrap(); + if index == latencies.len() { + latencies.push(latency); + } + } + } + } + now += PULL as u64; + } + assert_eq!(latencies.len(), markers_sent.len(), "every marker must come out (ppm {ppm})"); + latencies +} + +fn check(ppm: f64) { + let latencies = simulate(ppm, 1.0); + assert_eq!(latencies.len(), 120); + let max = latencies.iter().copied().fold(0.0, f64::max); + let min = latencies.iter().copied().fold(f64::MAX, f64::min); + let first: f64 = latencies[..20].iter().sum::() / 20.0; + let last: f64 = latencies[latencies.len() - 20..].iter().sum::() / 20.0; + println!( + "{ppm:+} ppm: latency min {min:.0} ms, max {max:.0} ms, first 10 min avg {first:.0} ms, last 10 min avg {last:.0} ms" + ); + // The network alone adds 20-60 ms; unchecked drift would add 720 ms. + assert!(min >= 20.0, "latency {min} ms is below the network delay"); + assert!(max < 250.0, "latency grew to {max} ms"); + assert!((last - first).abs() < 60.0, "latency drifted from {first} ms to {last} ms"); +} + +#[test] +fn fast_sender_one_hour() { + check(200.0); +} + +#[test] +fn slow_sender_one_hour() { + check(-200.0); +} diff --git a/docs/audio.md b/docs/audio.md new file mode 100644 index 0000000..21bbac8 --- /dev/null +++ b/docs/audio.md @@ -0,0 +1,77 @@ +# Audio pipeline + +``` +microphone ─ cpal ─ resample 48 kHz mono ─ Processor (AEC3, NS, AGC2) ─ 20 ms frames + ─ Vad / push-to-talk / continuous ─ Opus ─ voice connection + +voice connection ─ Mixer (jitter buffer, Opus decode, per-client volume/mute) + ─ output volume ─┬─ resample to device ─ cpal ─ speakers + └─ Processor::render (echo canceller reference) +``` + +The audio thread lives in `tsc-core/src/audio.rs`; the building blocks are in +`tsc-audio`. All user settings are one serde struct, `tsc_audio::AudioSettings`. + +## Echo cancellation, noise suppression, gain control + +[sonora](https://crates.io/crates/sonora) 0.2 (BSD-3-Clause), a pure Rust port of +the WebRTC audio processing module: AEC3, the WebRTC noise suppressor, AGC2 +(adaptive digital gain + limiter) and a high-pass filter. Chosen over: + +- `webrtc-audio-processing`: binds the C++ library (a system package or a bundled + C++ build via meson), a licence field that cargo-deny does not recognise, and + extra toolchain work on Windows and Android; +- `nnnoiseless` (RNNoise port): noise suppression only, no echo cancellation. + +sonora needs no C/C++ toolchain, so it builds the same everywhere. It runs on 10 ms +frames; `Processor` frames arbitrary lengths internally. The dev profile compiles +the sonora crates with `opt-level = 3`: unoptimised, AEC alone takes a third of a +core; optimised, the full chain takes about 0.3 ms per 10 ms frame. + +Measured with the unit tests (synthetic signals): + +| | Result | +|---|---| +| Echo (far end delayed 20–120 ms, -6 dB) | about 25–33 dB attenuation within the first second, 50 dB after two; the delay estimate matches | +| Double talk (near-end tone during echo) | near-end tone loses about 3 dB | +| White noise, suppression `High` | 10 dB or more lower; a tone in 200 ms bursts keeps its level within 3 dB | + +A steady tone is treated as stationary noise and suppressed, as expected from +this kind of noise suppressor, so the test uses bursts like syllables. + +## Voice activity + +`Vad`: a level gate in dBFS with hangover (default -40 dBFS, 300 ms). The optional +`Speech` mode also requires the RNN speech probability of WebRTC's AGC2 VAD +(`sonora-agc2`), which rejects noise loud enough to pass the gate. The RNN also +fires on pure tones, and on synthetic vowels only at low pitch, so the plain gate +stays the default until it is checked with real voices. With voice activation the +two 20 ms frames before the gate opened are sent too, so onsets are not cut. + +## Jitter buffer and clock drift + +`Mixer` wraps the vendored `tsclientlib::audio::AudioHandler` (one queue per +talker) and adds per-client volume and mute. The handler absorbs sender clock +drift: an underrun plays Opus loss concealment for the missing frame (one inserted +frame, and the talker is dropped after three in a row), and when the smallest +queue length over the last 255 packets exceeds its spread, it drops every 100th +sample (1 % faster) until the surplus is gone; queues above 0.5 s are truncated. + +`crates/tsc-audio/tests/drift.rs` simulates one hour of continuous speech with +20–60 ms network jitter, reordering and 0.5 % loss, with the sender clock at ++200 and -200 ppm (720 ms of disagreement per hour). Marker frames every 30 s +measure the end-to-end latency: + +| Sender clock | Latency min / max | First 10 min avg | Last 10 min avg | +|---|---|---|---| +| +200 ppm | 73 / 131 ms | 112 ms | 125 ms | +| -200 ppm | 67 / 95 ms | 82 ms | 84 ms | + +## Devices + +Devices are selected by cpal's stable id (`host:device`, e.g. `alsa:hw:1,0`); +`device::input_devices()` / `output_devices()` list them with the system defaults +marked. cpal's error callback flags a stream as lost on fatal errors (not on xruns +or rerouting); `device::Managed` then reopens the selected device, or the default +one while the selected one is missing (retrying every 2 s, moving back within 5 s +of it reappearing). The audio thread reports these changes as session errors. From 5fb64b8189820434ff5e5c3db1ca358c92ef609d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 19:48:43 +0000 Subject: [PATCH 03/13] tsc-core: audio thread with processing, voice activation, client volume, device reopening The device-independent part is a Pipeline (unit tested without hardware): microphone -> Processor -> VAD / push-to-talk / continuous (with pre-roll) -> Opus; mixer (per-client volume) -> output volume -> speakers, with the played signal as the echo canceller reference. Devices go through tsc_audio::device::Managed, so a lost microphone or headset is reopened or replaced by the default device, and the playback queue is kept at the configured latency instead of full. New AudioIn messages (Settings, ClientVolume, ClientMuted, ClientLeft) are ready for the session to send. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- crates/tsc-core/src/audio.rs | 574 ++++++++++++++++++++++++++++------- docs/audio.md | 6 +- 2 files changed, 460 insertions(+), 120 deletions(-) diff --git a/crates/tsc-core/src/audio.rs b/crates/tsc-core/src/audio.rs index 0fac225..cf97582 100644 --- a/crates/tsc-core/src/audio.rs +++ b/crates/tsc-core/src/audio.rs @@ -1,18 +1,23 @@ -//! Audio thread: capture → encode → voice connection, and incoming voice → -//! jitter buffer/mixer → playback. +//! Audio thread: capture → processing (echo cancellation, noise suppression, +//! gain) → voice activity / push-to-talk → encode → voice connection, and +//! incoming voice → jitter buffer/mixer (per-client volume) → playback, with +//! what is played fed back to the echo canceller as its reference. //! //! Devices live on their own OS thread (cpal streams are not `Send` on every -//! platform); the connection task talks to it through channels. +//! platform); the connection task talks to it through channels. The device +//! independent part is [`Pipeline`]; the thread loop only moves samples +//! between it and the devices, reopening devices that go away. +use std::collections::VecDeque; use std::sync::mpsc as std_mpsc; use std::thread; -use std::time::Duration; +use std::time::{Duration, Instant}; use tokio::sync::mpsc; use tracing::{debug, warn}; -use tsc_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE}; -use tsc_audio::resample::Linear; -use tsc_audio::{Framer, Mixer, VoiceCodec, VoiceEncoder}; +use tsc_audio::pcm::{self, FRAME_SAMPLES}; +use tsc_audio::settings::TransmitMode; +use tsc_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder}; use tsclientlib::ClientId; use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket}; @@ -21,6 +26,23 @@ pub(crate) enum AudioIn { Transmit(bool), InputMuted(bool), OutputMuted(bool), + /// Devices, processing, voice activation and transmit mode. + #[allow(dead_code, reason = "sent once the session exposes audio settings")] + Settings(Box), + /// Playback volume of one client, linear (1 = unchanged, up to 4). + #[allow(dead_code, reason = "sent once the session exposes client volumes")] + ClientVolume { + client: ClientId, + volume: f32, + }, + #[allow(dead_code, reason = "sent once the session exposes client volumes")] + ClientMuted { + client: ClientId, + muted: bool, + }, + /// The client left; client ids are reused, so forget its volume. + #[allow(dead_code, reason = "sent once the session exposes client volumes")] + ClientLeft(ClientId), } pub(crate) struct AudioHandle { @@ -33,24 +55,19 @@ impl AudioHandle { } } -/// Voice activity: transmit while the level is above the threshold, with a -/// short hang time so word endings are not cut. -struct Vad { - threshold: f32, - hang_frames: u32, - remaining: u32, -} - -impl Vad { - fn active(&mut self, frame: &[f32]) -> bool { - if pcm::energy(frame) > self.threshold { - self.remaining = self.hang_frames; - } else if self.remaining > 0 { - self.remaining -= 1; - } - self.remaining > 0 - } -} +/// With voice activation, also send this many 20 ms frames from before the +/// detector opened, so word onsets are not cut. +const PRE_ROLL_FRAMES: usize = 2; +/// Capacity of the speaker queue; [`AudioSettings::playback_buffer_ms`] is +/// clamped below it. +#[cfg(feature = "audio-device")] +const PLAYBACK_CAPACITY_MS: u32 = 200; +/// Latency of the devices beyond our queues, as a hint for the echo +/// canceller (it estimates the actual delay itself). +#[cfg(feature = "audio-device")] +const DEVICE_LATENCY_MS: u32 = 20; +/// How long the loop sleeps between rounds. +const TICK: Duration = Duration::from_millis(5); /// Start the audio thread. Encoded packets go to `outgoing`; problems (e.g. /// no device) are reported through `errors`. @@ -59,141 +76,464 @@ pub(crate) fn spawn( errors: mpsc::UnboundedSender, voice_activation: bool, ) -> AudioHandle { + let transmit = + if voice_activation { TransmitMode::VoiceActivation } else { TransmitMode::PushToTalk }; + let settings = AudioSettings { transmit, ..Default::default() }; let (tx, rx) = std_mpsc::channel(); thread::Builder::new() .name("tsc-audio".into()) - .spawn(move || run(rx, outgoing, errors, voice_activation)) + .spawn(move || run(rx, outgoing, errors, settings)) .expect("spawn audio thread"); AudioHandle { tx } } +/// Everything between the devices and the connection. +struct Pipeline { + settings: AudioSettings, + encoder: VoiceEncoder, + mixer: Mixer, + processor: Processor, + vad: Vad, + framer: Framer, + processed: Vec, + pre_roll: VecDeque>, + ptt: bool, + input_muted: bool, + output_muted: bool, + was_sending: bool, + /// Processed microphone audio, for tests. + #[cfg(test)] + tap: Vec, +} + +impl Pipeline { + fn new(settings: AudioSettings) -> tsc_audio::Result { + let settings = sanitize(settings); + Ok(Self { + encoder: VoiceEncoder::new(VoiceCodec::Voice)?, + mixer: Mixer::new(), + processor: Processor::new(&settings.processing), + vad: Vad::new(&settings.vad), + framer: Framer::new(FRAME_SAMPLES), + processed: Vec::new(), + pre_roll: VecDeque::new(), + ptt: false, + input_muted: false, + output_muted: false, + was_sending: false, + settings, + #[cfg(test)] + tap: Vec::new(), + }) + } + + fn handle(&mut self, msg: AudioIn) { + match msg { + AudioIn::Packet(packet) => { + let from = match packet.data().data() { + AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from, + _ => return, + }; + if let Err(error) = self.mixer.handle_packet(ClientId(from), packet) { + debug!(%error, "dropped voice packet"); + } + } + AudioIn::Transmit(on) => self.ptt = on, + AudioIn::InputMuted(m) => self.input_muted = m, + AudioIn::OutputMuted(m) => self.output_muted = m, + AudioIn::Settings(settings) => { + let settings = sanitize(*settings); + self.processor.apply(&settings.processing); + self.vad.apply(&settings.vad); + if settings.transmit != TransmitMode::VoiceActivation { + self.vad.reset(); + self.pre_roll.clear(); + } + self.settings = settings; + } + AudioIn::ClientVolume { client, volume } => self.mixer.set_volume(client, volume), + AudioIn::ClientMuted { client, muted } => self.mixer.set_muted(client, muted), + AudioIn::ClientLeft(client) => self.mixer.forget(client), + } + } + + /// Microphone audio in (mono, 48 kHz, any length); voice packets out. + /// `delay_ms` is the playback-to-capture delay hint for the echo canceller. + fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(OutPacket)) { + self.processor.set_delay_ms(delay_ms); + self.processed.clear(); + self.processor.capture(samples, &mut self.processed); + #[cfg(test)] + self.tap.extend_from_slice(&self.processed); + let mut frames = Vec::new(); + self.framer.push(&self.processed, |f| frames.push(f.to_vec())); + for frame in frames { + self.transmit(frame, send); + } + } + + fn transmit(&mut self, frame: Vec, send: &mut impl FnMut(OutPacket)) { + // Always analysed, so the detector's state is current when needed. + let voice = self.vad.process(&frame); + let wanted = match self.settings.transmit { + TransmitMode::PushToTalk => self.ptt, + TransmitMode::VoiceActivation => voice, + TransmitMode::Continuous => true, + }; + let sending = wanted && !self.input_muted; + if sending { + let pre_roll: Vec<_> = self.pre_roll.drain(..).collect(); + for f in pre_roll.iter().chain([&frame]) { + match self.encoder.encode(f) { + Ok(packet) => send(packet), + Err(e) => warn!(%e, "encoding failed"), + } + } + } else { + if self.was_sending { + send(self.encoder.end_of_stream()); + } + if self.settings.transmit == TransmitMode::VoiceActivation { + self.pre_roll.push_back(frame); + if self.pre_roll.len() > PRE_ROLL_FRAMES { + self.pre_roll.pop_front(); + } + } + } + self.was_sending = sending; + } + + /// The next 20 ms for the speakers (mono, 48 kHz), which also becomes + /// the echo canceller's reference. + fn playback_frame(&mut self) -> Vec { + let mut stereo = vec![0.0; FRAME_SAMPLES * 2]; + self.mixer.fill_buffer(&mut stereo); + let gain = if self.output_muted { 0.0 } else { self.settings.output_volume }; + let mut mono = pcm::to_mono(&stereo, 2); + for s in &mut mono { + *s = (*s * gain).clamp(-1.0, 1.0); + } + self.processor.render(&mono); + mono + } +} + +fn sanitize(mut settings: AudioSettings) -> AudioSettings { + let volume = settings.output_volume; + settings.output_volume = if volume.is_finite() { volume.clamp(0.0, 4.0) } else { 1.0 }; + #[cfg(feature = "audio-device")] + { + settings.playback_buffer_ms = + settings.playback_buffer_ms.clamp(20, PLAYBACK_CAPACITY_MS - 20); + } + settings +} + fn run( rx: std_mpsc::Receiver, outgoing: mpsc::UnboundedSender, errors: mpsc::UnboundedSender, - voice_activation: bool, + settings: AudioSettings, ) { #[cfg(feature = "audio-device")] - let mut capture = match tsc_audio::device::Capture::open_default(500) { - Ok(c) => Some(c), - Err(e) => { - let _ = errors.send(format!("no microphone: {e}")); - None - } - }; - #[cfg(feature = "audio-device")] - let mut playback = match tsc_audio::device::Playback::open_default(200) { - Ok(p) => Some(p), - Err(e) => { - let _ = errors.send(format!("no speakers: {e}")); - None - } - }; + let mut devices = devices::Devices::new(&settings); #[cfg(not(feature = "audio-device"))] let _ = errors.send("built without audio device support".to_string()); - let mut encoder = match VoiceEncoder::new(VoiceCodec::Voice) { - Ok(e) => e, + let mut pipeline = match Pipeline::new(settings) { + Ok(p) => p, Err(e) => { let _ = errors.send(e.to_string()); return; } }; - let mut mixer = Mixer::new(); - let mut framer = Framer::new(FRAME_SAMPLES); - let mut vad = Vad { threshold: 1e-4, hang_frames: 15, remaining: 0 }; - let (mut ptt, mut input_muted, mut output_muted) = (false, false, false); - let mut was_sending = false; - - #[cfg(feature = "audio-device")] - let mut capture_resampler = capture.as_ref().map(|c| Linear::new(c.rate, SAMPLE_RATE)); - #[cfg(feature = "audio-device")] - let mut playback_resampler = playback.as_ref().map(|p| Linear::new(SAMPLE_RATE, p.rate)); - let mut captured = Vec::new(); - let mut resampled = Vec::new(); + let mut send = |packet| { + let _ = outgoing.send(packet); + }; + // Without speakers the mixer is drained at real time, so queues do not + // fill up and talkers still end. + let mut idle_clock = Instant::now(); loop { // Control messages and incoming voice. loop { match rx.try_recv() { - Ok(AudioIn::Packet(packet)) => { - let from = match packet.data().data() { - AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from, - _ => continue, - }; - if let Err(error) = mixer.handle_packet(ClientId(from), packet) { - debug!(%error, "dropped voice packet"); + Ok(msg) => { + #[cfg(feature = "audio-device")] + if let AudioIn::Settings(s) = &msg { + devices.select(s); } + pipeline.handle(msg); } - Ok(AudioIn::Transmit(on)) => ptt = on, - Ok(AudioIn::InputMuted(m)) => input_muted = m, - Ok(AudioIn::OutputMuted(m)) => output_muted = m, Err(std_mpsc::TryRecvError::Empty) => break, Err(std_mpsc::TryRecvError::Disconnected) => return, } } - // Capture → 48 kHz mono → 20 ms frames → Opus. - captured.clear(); - resampled.clear(); #[cfg(feature = "audio-device")] - if let (Some(c), Some(r)) = (&mut capture, &mut capture_resampler) { - c.read_available(&mut captured); - let mono = pcm::to_mono(&captured, c.channels); - r.process(&mono, &mut resampled); - } - let mut frames = Vec::new(); - framer.push(&resampled, |f| frames.push(f.to_vec())); - for frame in frames { - let send = !input_muted && if voice_activation { vad.active(&frame) } else { ptt }; - if send { - match encoder.encode(&frame) { - Ok(packet) => { - let _ = outgoing.send(packet); - } - Err(e) => warn!(%e, "encoding failed"), - } - } else if was_sending { - let _ = outgoing.send(encoder.end_of_stream()); - } - was_sending = send; - } - - // Mixer → device rate/channels → playback. - #[cfg(feature = "audio-device")] - if let (Some(p), Some(r)) = (&mut playback, &mut playback_resampler) { - let needed_48k = (p.free() / p.channels) as u64 * SAMPLE_RATE as u64 / p.rate as u64; - if needed_48k as usize >= FRAME_SAMPLES { - let mut stereo = vec![0.0; FRAME_SAMPLES * 2]; - mixer.fill_buffer(&mut stereo); - if output_muted { - stereo.fill(0.0); - } - let mono = pcm::to_mono(&stereo, 2); - let mut out = Vec::with_capacity(mono.len()); - r.process(&mono, &mut out); - p.write(&pcm::from_mono(&out, p.channels)); - } - } + let playing = devices.step(&mut pipeline, &mut send, &errors); #[cfg(not(feature = "audio-device"))] - let _ = (output_muted, &mut mixer); + let playing = { + // No microphone: nothing to process, but keep the path alive. + pipeline.capture(&[], 0, &mut send); + false + }; - thread::sleep(Duration::from_millis(5)); + if playing { + idle_clock = Instant::now(); + } else { + let frame = Duration::from_millis(20); + while idle_clock + frame <= Instant::now() { + pipeline.playback_frame(); + idle_clock += frame; + } + } + + thread::sleep(TICK); + } +} + +#[cfg(feature = "audio-device")] +mod devices { + use tokio::sync::mpsc; + use tracing::debug; + use tsc_audio::AudioSettings; + use tsc_audio::device::{Capture, DeviceEvent, Managed, Playback}; + use tsc_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE}; + use tsc_audio::resample::Linear; + use tsproto_packets::packets::OutPacket; + + use super::{DEVICE_LATENCY_MS, PLAYBACK_CAPACITY_MS, Pipeline}; + + /// The microphone and speakers, reopened when they go away. + pub(super) struct Devices { + capture: Managed, + playback: Managed, + capture_resampler: Option<(u32, Linear)>, + playback_resampler: Option<(u32, Linear)>, + captured: Vec, + resampled: Vec, + } + + /// A resampler for this device rate, recreated when the rate changes + /// (another device was opened). + fn resampler(slot: &mut Option<(u32, Linear)>, from: u32, to: u32, rate: u32) -> &mut Linear { + if slot.as_ref().is_none_or(|(r, _)| *r != rate) { + *slot = Some((rate, Linear::new(from, to))); + } + &mut slot.as_mut().expect("just set").1 + } + + fn report(errors: &mpsc::UnboundedSender, what: &str, event: DeviceEvent) { + let message = match event { + DeviceEvent::Opened { name, fallback: false } => { + debug!(%name, "{what} opened"); + return; + } + DeviceEvent::Opened { name, fallback: true } => { + format!("selected {what} not found, using {name}") + } + DeviceEvent::Lost { name } => format!("{what} disconnected: {name}"), + DeviceEvent::Unavailable(e) => format!("no {what}: {e}"), + }; + let _ = errors.send(message); + } + + impl Devices { + pub fn new(settings: &AudioSettings) -> Self { + Self { + capture: Managed::new(settings.input_device.clone(), 500), + playback: Managed::new(settings.output_device.clone(), PLAYBACK_CAPACITY_MS), + capture_resampler: None, + playback_resampler: None, + captured: Vec::new(), + resampled: Vec::new(), + } + } + + pub fn select(&mut self, settings: &AudioSettings) { + self.capture.select(settings.input_device.clone()); + self.playback.select(settings.output_device.clone()); + } + + /// One round: top up the speakers, then process what the microphone + /// recorded. Returns whether speakers are open. + pub fn step( + &mut self, + pipeline: &mut Pipeline, + send: &mut impl FnMut(OutPacket), + errors: &mpsc::UnboundedSender, + ) -> bool { + if let Some(event) = self.playback.poll() { + report(errors, "speakers", event); + } + if let Some(event) = self.capture.poll() { + report(errors, "microphone", event); + } + + // Mixer → speakers, keeping the configured amount queued. + let mut delay_ms = DEVICE_LATENCY_MS; + let playing = if let Some(p) = self.playback.stream() { + let r = resampler(&mut self.playback_resampler, SAMPLE_RATE, p.rate, p.rate); + let frame_len = + (FRAME_SAMPLES * p.rate as usize).div_ceil(SAMPLE_RATE as usize) + 1; + while p.queued_ms() < pipeline.settings.playback_buffer_ms + && p.free() >= frame_len * p.channels + { + let mono = pipeline.playback_frame(); + let mut out = Vec::with_capacity(frame_len); + r.process(&mono, &mut out); + p.write(&pcm::from_mono(&out, p.channels)); + } + delay_ms += p.queued_ms(); + true + } else { + false + }; + + // Microphone → 48 kHz mono → pipeline. + if let Some(c) = self.capture.stream() { + self.captured.clear(); + self.resampled.clear(); + c.read_available(&mut self.captured); + let mono = pcm::to_mono(&self.captured, c.channels); + let r = resampler(&mut self.capture_resampler, c.rate, SAMPLE_RATE, c.rate); + r.process(&mono, &mut self.resampled); + pipeline.capture(&self.resampled, delay_ms, send); + } + playing + } } } #[cfg(test)] mod tests { + use tsc_audio::pcm::{SAMPLE_RATE, energy, sine, white_noise}; + use tsc_audio::{ProcessingSettings, VadSettings}; + use tsproto_packets::packets::{CodecType, Direction, OutAudio}; + use super::*; + fn pipeline(transmit: TransmitMode) -> Pipeline { + Pipeline::new(AudioSettings { + transmit, + processing: ProcessingSettings::off(), + vad: VadSettings { hangover_ms: 40, ..Default::default() }, + ..Default::default() + }) + .unwrap() + } + + /// Run `samples` through the capture side; returns (voice packets, + /// end-of-stream packets). + fn capture(p: &mut Pipeline, samples: &[f32]) -> (usize, usize) { + let (mut voice, mut end) = (0, 0); + p.capture(samples, 0, &mut |packet: OutPacket| { + // Header of 3 bytes (id + codec) for C2S audio. + if packet.content().len() > 3 { voice += 1 } else { end += 1 } + }); + (voice, end) + } + + fn incoming(from: u16, id: u16, data: &[u8]) -> AudioIn { + let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data }); + AudioIn::Packet(InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap()) + } + #[test] - fn vad_hangs_after_speech() { - let mut vad = Vad { threshold: 1e-3, hang_frames: 2, remaining: 0 }; - let loud = vec![0.5; 960]; - let quiet = vec![0.0; 960]; - assert!(!vad.active(&quiet)); - assert!(vad.active(&loud)); - assert!(vad.active(&quiet)); - assert!(!vad.active(&quiet)); + fn push_to_talk_and_mute() { + let mut p = pipeline(TransmitMode::PushToTalk); + let tone = sine(440.0, 0.2, 0.3); + assert_eq!(capture(&mut p, &tone), (0, 0)); + p.handle(AudioIn::Transmit(true)); + assert_eq!(capture(&mut p, &tone), (10, 0)); + p.handle(AudioIn::InputMuted(true)); + assert_eq!(capture(&mut p, &tone), (0, 1)); + p.handle(AudioIn::InputMuted(false)); + p.handle(AudioIn::Transmit(false)); + assert_eq!(capture(&mut p, &tone), (0, 0)); + } + + #[test] + fn voice_activation_with_pre_roll() { + let mut p = pipeline(TransmitMode::VoiceActivation); + let quiet = vec![0.0; FRAME_SAMPLES * 5]; + assert_eq!(capture(&mut p, &quiet), (0, 0)); + // Speech opens the gate: the frame itself plus the pre-roll. + assert_eq!(capture(&mut p, &sine(440.0, 0.02, 0.3)), (1 + PRE_ROLL_FRAMES, 0)); + // 40 ms of hangover, then the stream ends. + assert_eq!(capture(&mut p, &quiet), (2, 1)); + + // Switching modes through settings. + let settings = AudioSettings { transmit: TransmitMode::Continuous, ..p.settings.clone() }; + p.handle(AudioIn::Settings(Box::new(settings))); + assert_eq!(capture(&mut p, &quiet), (5, 0)); + } + + /// Two talkers; one turned down, one muted, then forgotten. + #[test] + fn client_volume() { + let mut p = pipeline(TransmitMode::PushToTalk); + let mut encoder = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + let tone = sine(700.0, 1.0, 0.4); + let mut play = |p: &mut Pipeline, from: u16| -> f32 { + let mut out = Vec::new(); + for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() { + p.handle(incoming(from, i as u16, encoder.encode_to_bytes(frame).unwrap())); + out.extend(p.playback_frame()); + } + energy(&out[out.len() / 2..]) + }; + let full = play(&mut p, 1); + p.handle(AudioIn::ClientVolume { client: ClientId(2), volume: 0.5 }); + let half = play(&mut p, 2); + let ratio_db = 10.0 * (half / full).log10(); + assert!((ratio_db + 6.0).abs() < 1.0, "volume 0.5 gave {ratio_db} dB"); + p.handle(AudioIn::ClientMuted { client: ClientId(3), muted: true }); + assert!(play(&mut p, 3) < 1e-8); + p.handle(AudioIn::ClientLeft(ClientId(3))); + assert!(!p.mixer.is_muted(ClientId(3))); + } + + /// End to end: a remote talker is played, the speakers leak into the + /// microphone 30 ms later, and the echo canceller (fed with what was + /// played) removes it from what we would send. + #[test] + fn echo_of_playback_is_cancelled() { + let mut p = Pipeline::new(AudioSettings { + transmit: TransmitMode::Continuous, + processing: ProcessingSettings { echo_cancellation: true, ..ProcessingSettings::off() }, + ..Default::default() + }) + .unwrap(); + let mut encoder = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + let far = white_noise(SAMPLE_RATE as usize * 6, 0.3, 11); + let delay = SAMPLE_RATE as usize * 30 / 1000; + let mut played = vec![0.0; delay]; + let mut echo = Vec::new(); + for (i, frame) in far.chunks_exact(FRAME_SAMPLES).enumerate() { + p.handle(incoming(9, i as u16, encoder.encode_to_bytes(frame).unwrap())); + played.extend(p.playback_frame()); + let mic: Vec = played[played.len() - delay - FRAME_SAMPLES..played.len() - delay] + .iter() + .map(|s| s * 0.5) + .collect(); + p.capture(&mic, 30, &mut |_| {}); + echo.extend(mic); + } + let tail = SAMPLE_RATE as usize * 2; + let before = energy(&echo[echo.len() - tail..]); + let after = energy(&p.tap[p.tap.len() - tail..]); + let attenuation = 10.0 * (before / after).log10(); + assert!(before > 1e-3, "the echo must be audible"); + assert!(attenuation >= 10.0, "echo attenuated by {attenuation:.1} dB"); + } + + #[test] + fn settings_are_sanitized() { + let mut p = pipeline(TransmitMode::PushToTalk); + let settings = AudioSettings { output_volume: f32::INFINITY, ..Default::default() }; + p.handle(AudioIn::Settings(Box::new(settings))); + assert_eq!(p.settings.output_volume, 1.0); } } diff --git a/docs/audio.md b/docs/audio.md index 21bbac8..b66c796 100644 --- a/docs/audio.md +++ b/docs/audio.md @@ -18,9 +18,9 @@ The audio thread lives in `tsc-core/src/audio.rs`; the building blocks are in the WebRTC audio processing module: AEC3, the WebRTC noise suppressor, AGC2 (adaptive digital gain + limiter) and a high-pass filter. Chosen over: -- `webrtc-audio-processing`: binds the C++ library (a system package or a bundled - C++ build via meson), a licence field that cargo-deny does not recognise, and - extra toolchain work on Windows and Android; +- `webrtc-audio-processing`: binds the C++ library, either a system package found + through pkg-config or a bundled C++ build (autotools, bindgen/libclang); its + licence is not an SPDX expression, and Windows/Android need extra toolchain work; - `nnnoiseless` (RNNoise port): noise suppression only, no echo cancellation. sonora needs no C/C++ toolchain, so it builds the same everywhere. It runs on 10 ms From ee57b130c64e88467215f38a30ed77224bbffa41 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 19:56:58 +0000 Subject: [PATCH 04/13] tsc-stream: interop with Chromium's WebRTC stack, codec order fixes tests/interop/browser-peer.cjs runs headless Chromium (Playwright) as the remote peer; crates/tsc-stream/tests/browser_interop.rs (TSC_INTEROP=1) exchanges SDP with it over stdin/stdout: - our loopback streamer offer (VP8 + Opus) answered by Chromium: packets, bytes and decoded frames of the synthetic VP8 keyframes, Opus packets - Chromium offers canvas video + oscillator audio with VP8, VP9, H264 and AV1 preferred in turn; our viewer peer receives that codec and Opus, with trickled browser candidates and a keyframe after a PLI - a server-reflexive candidate (fake STUN server) trickled with the peer's mid is accepted by addIceCandidate Fixes found on the way: - the viewer's answer followed str0m's codec order, so the streamer's preference was ignored; the answer now keeps the offer's order (accept_video_codecs filters it) - streamers offered VP8 and H264 by default while frames are sent on the first negotiated payload type: offer only VP8 by default - H.264 offers include Constrained High (640c1f), reportedly the only profile the TeamSpeak client decodes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- crates/tsc-stream/Cargo.toml | 2 +- crates/tsc-stream/src/peer.rs | 151 ++++++++-- crates/tsc-stream/tests/browser_interop.rs | 320 +++++++++++++++++++++ tests/interop/README.md | 46 +++ tests/interop/browser-peer.cjs | 198 +++++++++++++ 5 files changed, 698 insertions(+), 19 deletions(-) create mode 100644 crates/tsc-stream/tests/browser_interop.rs create mode 100644 tests/interop/README.md create mode 100644 tests/interop/browser-peer.cjs diff --git a/crates/tsc-stream/Cargo.toml b/crates/tsc-stream/Cargo.toml index 7574ae1..1464d8b 100644 --- a/crates/tsc-stream/Cargo.toml +++ b/crates/tsc-stream/Cargo.toml @@ -21,7 +21,7 @@ tsproto-packets = { path = "../proto/tsproto-packets" } [dev-dependencies] anyhow = "1" futures = "0.3" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "sync", "time"] } +tokio = { version = "1", features = ["io-util", "macros", "net", "process", "rt-multi-thread", "sync", "time"] } tracing-subscriber = { version = "0.3", features = ["env-filter"] } [lints] diff --git a/crates/tsc-stream/src/peer.rs b/crates/tsc-stream/src/peer.rs index b253901..32f50f5 100644 --- a/crates/tsc-stream/src/peer.rs +++ b/crates/tsc-stream/src/peer.rs @@ -33,6 +33,8 @@ pub enum VideoCodec { } impl VideoCodec { + pub const ALL: [Self; 4] = [Self::Vp8, Self::Vp9, Self::H264, Self::Av1]; + pub fn from_codec(c: Codec) -> Option { match c { Codec::Vp8 => Some(Self::Vp8), @@ -42,6 +44,20 @@ impl VideoCodec { _ => None, } } + + /// From an SDP encoding name (`a=rtpmap: VP8/90000`). + pub fn from_sdp_name(name: &str) -> Option { + Self::ALL.into_iter().find(|c| c.sdp_name().eq_ignore_ascii_case(name)) + } + + pub fn sdp_name(self) -> &'static str { + match self { + Self::Vp8 => "VP8", + Self::Vp9 => "VP9", + Self::H264 => "H264", + Self::Av1 => "AV1", + } + } } #[derive(Clone, Debug)] @@ -50,8 +66,12 @@ pub struct PeerConfig { pub hosts: Vec, /// STUN servers (`host:port`) for a server-reflexive candidate. pub stun_servers: Vec, - /// Video codecs, used for the streamer's offer; a viewer accepts all it knows. + /// Video codecs a streamer offers, in order of preference. Frames are sent + /// with the codec the viewer picks, so offer only what the encoder produces. pub video_codecs: Vec, + /// Video codecs a viewer accepts (what it can decode). The answer keeps + /// the order of the streamer's offer, so the streamer's preference wins. + pub accept_video_codecs: Vec, pub video: bool, pub audio: bool, } @@ -61,7 +81,8 @@ impl Default for PeerConfig { Self { hosts: Vec::new(), stun_servers: stun::TEAMSPEAK_STUN.iter().map(|s| (*s).to_owned()).collect(), - video_codecs: vec![VideoCodec::Vp8, VideoCodec::H264], + video_codecs: vec![VideoCodec::Vp8], + accept_video_codecs: VideoCodec::ALL.to_vec(), video: true, audio: true, } @@ -142,7 +163,7 @@ impl Peer { /// Streamer side: create a connection that sends our media; returns the SDP /// offer for `respondjoinstreamrequest`. pub async fn offer(config: &PeerConfig, stream_id: &str) -> Result<(Self, String), PeerError> { - let mut rtc = build_rtc(config, true); + let mut rtc = build_rtc(config, &config.video_codecs); let net = Net::bind(config, &mut rtc).await?; let mut api = rtc.sdp_api(); let msid = Some(stream_id.to_owned()); @@ -163,8 +184,18 @@ impl Peer { /// Viewer side: accept the streamer's offer; returns our SDP answer. pub async fn answer(config: &PeerConfig, offer: &str) -> Result<(Self, String), PeerError> { + // Our codecs in the order of the offer, then the rest. + let mut codecs: Vec<_> = offered_video_codecs(offer) + .into_iter() + .filter(|c| config.accept_video_codecs.contains(c)) + .collect(); + for c in &config.accept_video_codecs { + if !codecs.contains(c) { + codecs.push(*c); + } + } let offer = SdpOffer::from_sdp_string(offer).map_err(|e| PeerError::Sdp(e.to_string()))?; - let mut rtc = build_rtc(config, false); + let mut rtc = build_rtc(config, &codecs); let net = Net::bind(config, &mut rtc).await?; let answer = rtc.sdp_api().accept_offer(offer)?; Ok((Self::spawn(rtc, net, config, None, Vec::new()), answer.to_sdp_string())) @@ -240,24 +271,66 @@ impl Drop for Peer { } } -fn build_rtc(config: &PeerConfig, offering: bool) -> Rtc { - let mut rtc_config = - RtcConfig::new().set_crypto_provider(Arc::new(str0m::crypto::from_feature_flags())); - if offering { - // Offer only the codecs we can encode, in our order of preference. - rtc_config = rtc_config.clear_codecs().enable_opus(config.audio); - for codec in &config.video_codecs { - rtc_config = match codec { - VideoCodec::Vp8 => rtc_config.enable_vp8(true), - VideoCodec::Vp9 => rtc_config.enable_vp9(true), - VideoCodec::H264 => rtc_config.enable_h264(true), - VideoCodec::Av1 => rtc_config.enable_av1(true), - }; - } +/// H.264 Constrained High, level 3.1: reportedly the only H.264 profile the +/// TeamSpeak client decodes; str0m's defaults lack it. +const H264_CONSTRAINED_HIGH: u32 = 0x640c1f; + +/// An RTC with Opus and `video` codecs, in this order of preference. +fn build_rtc(config: &PeerConfig, video: &[VideoCodec]) -> Rtc { + let mut rtc_config = RtcConfig::new() + .set_crypto_provider(Arc::new(str0m::crypto::from_feature_flags())) + .clear_codecs() + .enable_opus(config.audio); + for codec in video { + rtc_config = match codec { + VideoCodec::Vp8 => rtc_config.enable_vp8(true), + VideoCodec::Vp9 => rtc_config.enable_vp9(true), + VideoCodec::H264 => { + let mut c = rtc_config.enable_h264(true); + c.codec_config().add_h264( + 112.into(), + Some(113.into()), + true, + H264_CONSTRAINED_HIGH, + ); + c + } + VideoCodec::Av1 => rtc_config.enable_av1(true), + }; } rtc_config.build(Instant::now()) } +/// The video codecs of the first video media line of `sdp`, in offered order. +fn offered_video_codecs(sdp: &str) -> Vec { + let mut pts: Vec<&str> = Vec::new(); + let mut names: Vec<(&str, VideoCodec)> = Vec::new(); + let mut in_video = false; + for line in sdp.lines().map(str::trim) { + if let Some(media) = line.strip_prefix("m=") { + in_video = pts.is_empty() && media.starts_with("video "); + if in_video { + pts = media.split_whitespace().skip(3).collect(); + } + } else if in_video + && let Some((pt, encoding)) = + line.strip_prefix("a=rtpmap:").and_then(|r| r.split_once(' ')) + && let Some(codec) = encoding.split('/').next().and_then(VideoCodec::from_sdp_name) + { + names.push((pt, codec)); + } + } + let mut codecs = Vec::new(); + for pt in pts { + if let Some((_, codec)) = names.iter().find(|(p, _)| *p == pt) + && !codecs.contains(codec) + { + codecs.push(*codec); + } + } + codecs +} + /// The primary local IPv4 address (the one used for the default route). fn primary_ipv4() -> Option { let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?; @@ -591,3 +664,45 @@ impl Task { Some((mid, pt)) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn offered_codec_order() { + let sdp = "v=0\r\n\ + m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n\ + a=rtpmap:111 opus/48000/2\r\n\ + m=video 9 UDP/TLS/RTP/SAVPF 98 99 96 97 45 102\r\n\ + a=rtpmap:96 VP8/90000\r\n\ + a=rtpmap:97 rtx/90000\r\n\ + a=rtpmap:98 VP9/90000\r\n\ + a=rtpmap:99 rtx/90000\r\n\ + a=rtpmap:45 AV1/90000\r\n\ + a=rtpmap:102 H264/90000\r\n\ + m=video 9 UDP/TLS/RTP/SAVPF 96\r\n\ + a=rtpmap:96 H264/90000\r\n"; + assert_eq!( + offered_video_codecs(sdp), + [VideoCodec::Vp9, VideoCodec::Vp8, VideoCodec::Av1, VideoCodec::H264] + ); + assert!(offered_video_codecs("v=0\r\n").is_empty()); + } + + #[tokio::test] + async fn answer_follows_offer_order() { + let streamer = PeerConfig { + video_codecs: vec![VideoCodec::H264, VideoCodec::Vp8], + ..PeerConfig::loopback() + }; + let (_peer, offer) = Peer::offer(&streamer, "s").await.unwrap(); + assert!(offer.contains("profile-level-id=640c1f"), "{offer}"); + let (_peer, answer) = Peer::answer(&PeerConfig::loopback(), &offer).await.unwrap(); + assert_eq!(offered_video_codecs(&answer)[0], VideoCodec::H264, "{answer}"); + let vp8_only = + PeerConfig { accept_video_codecs: vec![VideoCodec::Vp8], ..PeerConfig::loopback() }; + let (_peer, answer) = Peer::answer(&vp8_only, &offer).await.unwrap(); + assert_eq!(offered_video_codecs(&answer), [VideoCodec::Vp8], "{answer}"); + } +} diff --git a/crates/tsc-stream/tests/browser_interop.rs b/crates/tsc-stream/tests/browser_interop.rs new file mode 100644 index 0000000..2d0cf13 --- /dev/null +++ b/crates/tsc-stream/tests/browser_interop.rs @@ -0,0 +1,320 @@ +//! Interop with a browser WebRTC stack: headless Chromium (Playwright) is the +//! other peer, driven by `tests/interop/browser-peer.cjs` over stdin/stdout. +//! No TeamSpeak server is involved; SDP goes straight between the peers. +//! +//! Runs only with `TSC_INTEROP=1` (see `tests/interop/README.md`). + +use std::path::PathBuf; +use std::process::Stdio; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines}; +use tokio::process::{Child, ChildStdin, ChildStdout, Command}; +use tokio::time::timeout; +use tsc_stream::{ + Codec, FrameSource, MediaKind, Peer, PeerConfig, PeerEvent, Signal, SyntheticSource, +}; + +fn enabled() -> bool { + std::env::var("TSC_INTEROP").is_ok_and(|v| v == "1") +} + +/// The Node.js side (headless Chromium). +struct Browser { + _child: Child, + stdin: ChildStdin, + stdout: Lines>, +} + +impl Browser { + async fn start() -> Self { + let script = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../tests/interop/browser-peer.cjs") + .canonicalize() + .expect("tests/interop/browser-peer.cjs"); + let node = std::env::var("TSC_NODE").unwrap_or_else(|_| "node".into()); + let mut command = Command::new(node); + command + .arg(script) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true); + // Playwright is usually installed globally. + if std::env::var_os("NODE_PATH").is_none() + && let Ok(out) = std::process::Command::new("npm").args(["root", "-g"]).output() + { + command.env("NODE_PATH", String::from_utf8_lossy(&out.stdout).trim()); + } + let mut child = command.spawn().expect("cannot start node (set TSC_NODE)"); + let stdin = child.stdin.take().unwrap(); + let stdout = BufReader::new(child.stdout.take().unwrap()).lines(); + let mut browser = Self { _child: child, stdin, stdout }; + let ready = browser.read().await; + eprintln!("browser: {}", ready["userAgent"]); + browser + } + + async fn read(&mut self) -> Value { + let line = timeout(Duration::from_secs(60), self.stdout.next_line()) + .await + .expect("browser did not answer") + .unwrap() + .expect("browser exited"); + let value: Value = serde_json::from_str(&line).unwrap(); + if let Some(error) = value.get("error") { + panic!("browser: {error}"); + } + value + } + + async fn call(&mut self, command: Value) -> Value { + let mut line = command.to_string(); + line.push('\n'); + self.stdin.write_all(line.as_bytes()).await.unwrap(); + self.read().await + } + + async fn quit(mut self) { + let _ = self.call(json!({ "op": "quit" })).await; + } +} + +async fn wait_connected(peer: &mut Peer) { + timeout(Duration::from_secs(15), async { + loop { + match peer.next_event().await { + Some(PeerEvent::Connected) => return, + Some(PeerEvent::Closed) | None => panic!("closed before connecting"), + _ => {} + } + } + }) + .await + .expect("no connection with the browser"); +} + +/// Our streamer peer (as in a TeamSpeak stream) sends VP8 + Opus to Chromium. +#[tokio::test(flavor = "multi_thread")] +async fn rust_streams_to_browser() { + if !enabled() { + eprintln!("skipped: set TSC_INTEROP=1 (needs node, Playwright and Chromium)"); + return; + } + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let mut browser = Browser::start().await; + let config = PeerConfig::loopback(); + let (mut peer, offer) = Peer::offer(&config, "interop").await.unwrap(); + let answer = browser.call(json!({ "op": "answer", "sdp": offer })).await; + let answer = answer["sdp"].as_str().unwrap(); + eprintln!("browser answer:\n{answer}"); + peer.accept_answer(answer).await.unwrap(); + wait_connected(&mut peer).await; + + // Three seconds of synthetic media. + let mut source = SyntheticSource::new(30, 3000, true); + let mut frames = Vec::new(); + let mut keyframe_requests = 0; + let end = Instant::now() + Duration::from_secs(3); + while Instant::now() < end { + source.poll_frames(Instant::now(), &mut frames); + for f in frames.drain(..) { + peer.write(f.kind, f.time, f.data); + } + while let Some(event) = peer.try_next_event() { + if let PeerEvent::KeyframeRequest = event { + keyframe_requests += 1; + } + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + let stats = browser.call(json!({ "op": "stats" })).await; + eprintln!("browser stats: {stats:#}\nkeyframe requests from the browser: {keyframe_requests}"); + assert_eq!(stats["connectionState"], "connected"); + let video = &stats["inbound"]["video"]; + let audio = &stats["inbound"]["audio"]; + assert_eq!(video["codec"], "video/VP8"); + assert!(video["packetsReceived"].as_u64().unwrap() > 100, "video packets: {video}"); + assert!(video["bytesReceived"].as_u64().unwrap() > 100_000, "video bytes: {video}"); + assert_eq!(audio["codec"], "audio/opus"); + assert!(audio["packetsReceived"].as_u64().unwrap() > 50, "audio packets: {audio}"); + // The synthetic frames are real (tiny) VP8 keyframes. + assert!(video["framesDecoded"].as_u64().unwrap() > 30, "decoded: {video}"); + browser.quit().await; +} + +/// Answer STUN binding requests with a made-up public address, so a peer +/// reports a server-reflexive candidate without internet access. +async fn fake_stun_server() -> std::net::SocketAddr { + let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let addr = socket.local_addr().unwrap(); + tokio::spawn(async move { + let mut buf = [0; 1500]; + while let Ok((n, from)) = socket.recv_from(&mut buf).await { + if n < 20 || buf[..2] != [0, 1] { + continue; + } + // Binding success with XOR-MAPPED-ADDRESS 203.0.113.9:40000. + let mut resp = vec![0x01, 0x01, 0, 12]; + resp.extend_from_slice(&buf[4..20]); + resp.extend_from_slice(&[0, 0x20, 0, 8, 0, 1]); + resp.extend_from_slice(&(40000u16 ^ 0x2112).to_be_bytes()); + let ip = u32::from(std::net::Ipv4Addr::new(203, 0, 113, 9)) ^ 0x2112_A442; + resp.extend_from_slice(&ip.to_be_bytes()); + let _ = socket.send_to(&resp, from).await; + } + }); + addr +} + +/// A trickled candidate as our sessions send it (`iceCandidate` signal with +/// the peer's mid) must be accepted by the browser. +#[tokio::test(flavor = "multi_thread")] +async fn trickled_candidates_reach_browser() { + if !enabled() { + eprintln!("skipped: set TSC_INTEROP=1 (needs node, Playwright and Chromium)"); + return; + } + let mut browser = Browser::start().await; + // Primary address (STUN is not sent from loopback) and the fake STUN server. + let stun = fake_stun_server().await; + let config = PeerConfig { + hosts: Vec::new(), + stun_servers: vec![stun.to_string()], + ..PeerConfig::loopback() + }; + let (mut peer, offer) = Peer::offer(&config, "interop").await.unwrap(); + let answer = browser.call(json!({ "op": "answer", "sdp": offer })).await; + peer.accept_answer(answer["sdp"].as_str().unwrap()).await.unwrap(); + let (candidate, mid) = timeout(Duration::from_secs(10), async { + loop { + match peer.next_event().await { + Some(PeerEvent::LocalCandidate { candidate, mid }) => return (candidate, mid), + Some(PeerEvent::Closed) | None => panic!("closed"), + _ => {} + } + } + }) + .await + .expect("no server-reflexive candidate"); + assert!(candidate.contains("203.0.113.9 40000 typ srflx"), "{candidate}"); + let first_mid = offer.lines().find_map(|l| l.strip_prefix("a=mid:")).unwrap().trim(); + assert_eq!(mid.as_deref(), Some(first_mid)); + // Through the signal JSON, as the server relays it. + let json = Signal::IceCandidate { candidate, mid, mline_index: Some(0) }.to_json(); + let Signal::IceCandidate { candidate, mid, mline_index } = Signal::parse(&json).unwrap() else { + unreachable!() + }; + let add = json!({ + "op": "candidate", "candidate": candidate, "sdpMid": mid, "sdpMLineIndex": mline_index + }); + browser.call(add).await; + wait_connected(&mut peer).await; + browser.quit().await; +} + +/// Frames per codec. +#[derive(Debug, Default)] +struct Counts(Vec<(Codec, usize)>); + +impl Counts { + fn add(&mut self, codec: Codec) { + match self.0.iter_mut().find(|(c, _)| *c == codec) { + Some((_, n)) => *n += 1, + None => self.0.push((codec, 1)), + } + } + + fn get(&self, codec: Codec) -> usize { + self.0.iter().find(|(c, _)| *c == codec).map_or(0, |(_, n)| *n) + } + + fn total(&self) -> usize { + self.0.iter().map(|(_, n)| n).sum() + } +} + +struct Received { + video: Counts, + audio: Counts, + /// VP8 keyframes (frame tag bit 0 clear). + vp8_keyframes: usize, +} + +/// Collect frames from `peer` for up to `limit` or until `enough`. +async fn receive(peer: &mut Peer, limit: Duration, enough: usize) -> Received { + let mut r = Received { video: Counts::default(), audio: Counts::default(), vp8_keyframes: 0 }; + let _ = timeout(limit, async { + while let Some(event) = peer.next_event().await { + if let PeerEvent::Media(frame) = event { + let map = match frame.kind { + MediaKind::Video => &mut r.video, + MediaKind::Audio => &mut r.audio, + }; + map.add(frame.codec); + if frame.codec == Codec::Vp8 && frame.data.first().is_some_and(|b| b & 1 == 0) { + r.vp8_keyframes += 1; + } + if r.video.total() >= enough && r.audio.total() >= enough { + return; + } + } + } + }) + .await; + r +} + +/// Chromium sends a canvas stream and an oscillator; our viewer peer answers. +#[tokio::test(flavor = "multi_thread")] +async fn browser_streams_to_rust() { + if !enabled() { + eprintln!("skipped: set TSC_INTEROP=1 (needs node, Playwright and Chromium)"); + return; + } + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let mut browser = Browser::start().await; + let config = PeerConfig::loopback(); + let mut tested = Vec::new(); + for (name, codec) in + [("VP8", Codec::Vp8), ("VP9", Codec::Vp9), ("H264", Codec::H264), ("AV1", Codec::Av1)] + { + // VP8 with trickled browser candidates, the others with candidates in the SDP. + let trickle = codec == Codec::Vp8; + let offer = browser.call(json!({ "op": "offer", "codec": name, "trickle": trickle })).await; + if offer.get("unsupported").is_some() { + eprintln!("{name}: the browser cannot send it, skipped"); + continue; + } + let offer = offer["sdp"].as_str().unwrap(); + let (mut peer, answer) = Peer::answer(&config, offer).await.unwrap(); + browser.call(json!({ "op": "accept", "sdp": answer })).await; + if trickle { + let candidates = browser.call(json!({ "op": "candidates" })).await; + let candidates = candidates["candidates"].as_array().unwrap(); + assert!(!candidates.is_empty(), "no browser candidates"); + for c in candidates { + peer.add_remote_candidate(c["candidate"].as_str().unwrap()); + } + } + wait_connected(&mut peer).await; + let received = receive(&mut peer, Duration::from_secs(8), 60).await; + eprintln!( + "{name}: video {:?}, audio {:?}, VP8 keyframes {}", + received.video, received.audio, received.vp8_keyframes + ); + assert!(received.video.get(codec) >= 30, "{name} video frames"); + assert!(received.audio.get(Codec::Opus) >= 30, "{name} Opus frames"); + if codec == Codec::Vp8 { + // A keyframe request (PLI) makes the browser's encoder send one. + let before = received.vp8_keyframes; + peer.request_keyframe(); + let after = receive(&mut peer, Duration::from_secs(3), 90).await; + assert!(after.vp8_keyframes > 0, "no keyframe after PLI (had {before} before)"); + } + tested.push(name); + } + assert!(tested.contains(&"VP8") && tested.contains(&"VP9"), "tested {tested:?}"); + browser.quit().await; +} diff --git a/tests/interop/README.md b/tests/interop/README.md new file mode 100644 index 0000000..4f7a0a2 --- /dev/null +++ b/tests/interop/README.md @@ -0,0 +1,46 @@ +# Browser interop test + +`crates/tsc-stream/tests/browser_interop.rs` checks our str0m peers against +the WebRTC stack of Chromium (libwebrtc, the same stack as the official +TeamSpeak 6 client). `browser-peer.cjs` runs headless Chromium through +Playwright and exchanges SDP and candidates with the Rust test as JSON lines +on stdin/stdout. No TeamSpeak server is involved. + +| Test | What it checks | +|---|---| +| `rust_streams_to_browser` | Our streamer offer (`PeerConfig::loopback()`, VP8 + Opus) answered by an `RTCPeerConnection`; `SyntheticSource` media for 3 s; `inbound-rtp` stats: VP8 packets and bytes, decoded frames (the synthetic frames are real 1x1 VP8 keyframes), Opus packets | +| `browser_streams_to_rust` | Chromium offers a canvas `captureStream` and an oscillator with VP8, VP9, H264 and AV1 preferred in turn (codecs the browser cannot send are skipped); our viewer `Peer::answer` must receive frames of that codec and Opus. VP8 also uses trickled browser candidates and checks that a PLI brings a keyframe | +| `trickled_candidates_reach_browser` | A server-reflexive candidate (from a fake STUN server) as our sessions trickle it (`iceCandidate` signal with the peer's mid) is accepted by `addIceCandidate` | + +## Running + +Needs Node.js with Playwright and its Chromium (`npx playwright install +chromium` on a new machine; `PLAYWRIGHT_BROWSERS_PATH` if the browsers live +elsewhere). + +```sh +TSC_INTEROP=1 cargo test -p tsc-stream --test browser_interop -- --nocapture +``` + +Without `TSC_INTEROP=1` the tests return immediately, so `cargo test` passes on +machines without a browser. `TSC_NODE` selects the node binary; `NODE_PATH` +defaults to `npm root -g` so a global Playwright is found. + +Chromium is started with `--disable-features=WebRtcHideLocalIpsWithMdns`: +without camera/microphone permission it would hide host candidates behind +mDNS names (`.local`), which str0m cannot resolve. The official client +may do the same; see `docs/protocol-notes/ts6-streaming.md`. + +## Findings + +- Chromium 141 (Playwright 1.56) connects to a str0m peer on 127.0.0.1 from its + own host candidate on the primary interface; it gathers no loopback candidates. +- str0m's answer lists codecs in its own configured order, and the offerer + sends the first one. `Peer::answer` therefore configures the viewer's codecs + in the order of the offer (`accept_video_codecs` filters them). +- `Peer::write` sends on the first negotiated payload type of a kind, so a + streamer offers only the codecs its encoder produces (`video_codecs`, + default VP8 only). +- str0m mids are random strings (`a=mid:fhs`), not `0`/`1`; trickled + candidates must carry the real mid, or browsers reject them. +- Playwright's Chromium build sends VP8, VP9 and AV1, not H.264. diff --git a/tests/interop/browser-peer.cjs b/tests/interop/browser-peer.cjs new file mode 100644 index 0000000..1dd052e --- /dev/null +++ b/tests/interop/browser-peer.cjs @@ -0,0 +1,198 @@ +// Headless Chromium as the remote WebRTC peer for +// crates/tsc-stream/tests/browser_interop.rs (see README.md here). +// +// Reads one JSON command per line on stdin and writes one JSON reply per line +// on stdout; logs go to stderr. Commands (`op`): +// answer {sdp} answer an offer, wait for ICE gathering -> {sdp} +// offer {codec, trickle} send canvas video + oscillator audio; offer with +// `codec` preferred -> {sdp} or {unsupported}; +// with `trickle` the SDP has no candidates +// candidates candidates gathered so far -> {candidates: [{candidate, sdpMid, sdpMLineIndex}]} +// accept {sdp} apply the answer to our offer +// candidate {candidate, sdpMid, sdpMLineIndex} add a remote candidate +// stats connection state, inbound/outbound RTP counters, +// frames shown by a