Merge wip/stream-sessions: stream sessions, engine streams, tsctl stream, browser interop

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-26 05:09:50 +00:00
commit f189370b39
23 files changed
+4286 -40

No files matched your search

Generated
+2
View File
@@ -8493,6 +8493,7 @@ dependencies = [
"tsc-model",
"tsc-observer",
"tsc-query",
"tsc-stream",
"tsclientlib",
"tsproto-packets",
]
@@ -8697,6 +8698,7 @@ dependencies = [
"tsc-model",
"tsc-observer",
"tsc-query",
"tsc-stream",
"tsclientlib",
"tsproto-packets",
]
+1
View File
@@ -26,6 +26,7 @@ tsc-gateway-proto = { path = "../tsc-gateway-proto" }
tsc-model = { path = "../tsc-model" }
tsc-observer = { path = "../tsc-observer" }
tsc-query = { path = "../tsc-query" }
tsc-stream = { path = "../tsc-stream" }
tsclientlib = { path = "../proto/tsclientlib" }
tsproto-packets = { path = "../proto/tsproto-packets" }
+105 -4
View File
@@ -10,12 +10,17 @@
//! Presence comes from the most authoritative connected source
//! (voice > gateway > query). Channel chat goes through the voice connection
//! when the user is in that channel, otherwise through a relay.
//!
//! On TeamSpeak 6 servers the voice connection also carries streams (screen
//! sharing): see the `*Stream*` commands and events, and
//! [`Engine::subscribe_frames`] for the frames of watched streams.
mod audio;
mod gateway;
mod query;
mod route;
mod session;
pub mod stream;
mod voice;
use std::collections::HashMap;
@@ -25,6 +30,8 @@ use tokio::sync::{broadcast, mpsc};
use tsc_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
pub use route::{ChatRoute, Dedup, route_chat};
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
use tsc_stream::{EncodedFrame, StreamInfo, StreamSetup, ViewerInfo};
pub use voice::VoiceOptions;
pub type SessionId = u64;
@@ -84,6 +91,49 @@ pub enum Command {
session: SessionId,
on: bool,
},
/// Start streaming in our channel (TeamSpeak 6 only). Progress comes as
/// [`Event::StreamState`]; frames go in through the sink of
/// [`StreamState::Live`] or [`Command::SendStreamFrame`].
StartStream {
session: SessionId,
setup: StreamSetup,
/// Accept every viewer instead of asking with [`Event::StreamViewerRequest`].
auto_accept: bool,
},
StopStream {
session: SessionId,
},
/// Answer an [`Event::StreamViewerRequest`].
AcceptViewer {
session: SessionId,
viewer: u16,
accept: bool,
},
/// Remove a viewer from our stream.
KickViewer {
session: SessionId,
viewer: u16,
},
/// An encoded frame for our stream.
SendStreamFrame {
session: SessionId,
frame: EncodedFrame,
},
/// Watch a stream from [`Event::StreamsChanged`]. Frames arrive through
/// [`Engine::subscribe_frames`].
WatchStream {
session: SessionId,
stream_id: String,
},
LeaveStream {
session: SessionId,
stream_id: String,
},
/// Ask the streamer of a watched stream for a keyframe.
RequestStreamKeyframe {
session: SessionId,
stream_id: String,
},
/// Close everything of a session.
CloseSession {
session: SessionId,
@@ -159,6 +209,37 @@ pub enum Event {
session: SessionId,
message: String,
},
/// The streams in our channel (TeamSpeak 6), full list.
StreamsChanged {
session: SessionId,
streams: Vec<StreamInfo>,
},
/// Our own stream.
StreamState {
session: SessionId,
state: StreamState,
},
/// Someone asks to watch our stream; answer with [`Command::AcceptViewer`].
StreamViewerRequest {
session: SessionId,
viewer: u16,
message: String,
},
/// The viewers of our stream and their state, full list.
StreamViewers {
session: SessionId,
viewers: Vec<ViewerInfo>,
},
/// A viewer needs a keyframe (also flagged on the [`StreamSink`]).
StreamKeyframeRequest {
session: SessionId,
},
/// A stream we watch.
WatchState {
session: SessionId,
stream_id: String,
state: WatchState,
},
}
/// Handle to the engine. Cheap to clone; all methods are non-blocking.
@@ -166,6 +247,7 @@ pub enum Event {
pub struct Engine {
commands: mpsc::UnboundedSender<Command>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
}
impl Engine {
@@ -173,8 +255,10 @@ impl Engine {
pub fn start() -> Self {
let (commands, rx) = mpsc::unbounded_channel();
let (events, _) = broadcast::channel(4096);
tokio::spawn(run(rx, events.clone()));
Self { commands, events }
// About a minute of one watched stream.
let (frames, _) = broadcast::channel(4096);
tokio::spawn(run(rx, events.clone(), frames.clone()));
Self { commands, events, frames }
}
pub fn send(&self, command: Command) {
@@ -184,9 +268,18 @@ impl Engine {
pub fn subscribe(&self) -> broadcast::Receiver<Event> {
self.events.subscribe()
}
/// Encoded frames of the streams we watch (kept off the event bus).
pub fn subscribe_frames(&self) -> broadcast::Receiver<StreamFrame> {
self.frames.subscribe()
}
}
async fn run(mut commands: mpsc::UnboundedReceiver<Command>, events: broadcast::Sender<Event>) {
async fn run(
mut commands: mpsc::UnboundedReceiver<Command>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
) {
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
while let Some(command) = commands.recv().await {
let id = command_session(&command);
@@ -198,7 +291,7 @@ async fn run(mut commands: mpsc::UnboundedReceiver<Command>, events: broadcast::
}
sessions
.entry(id)
.or_insert_with(|| session::SessionHandle::spawn(id, events.clone()))
.or_insert_with(|| session::SessionHandle::spawn(id, events.clone(), frames.clone()))
.send(command);
}
}
@@ -217,6 +310,14 @@ fn command_session(command: &Command) -> SessionId {
| Command::SetInputMuted { session, .. }
| Command::SetOutputMuted { session, .. }
| Command::SetTransmitting { session, .. }
| Command::StartStream { session, .. }
| Command::StopStream { session }
| Command::AcceptViewer { session, .. }
| Command::KickViewer { session, .. }
| Command::SendStreamFrame { session, .. }
| Command::WatchStream { session, .. }
| Command::LeaveStream { session, .. }
| Command::RequestStreamKeyframe { session, .. }
| Command::CloseSession { session } => *session,
}
}
+98 -5
View File
@@ -1,6 +1,6 @@
//! One server session: merges its sources and routes commands.
use std::collections::HashSet;
use std::collections::{BTreeMap, HashSet};
use std::sync::Arc;
use tokio::sync::{broadcast, mpsc};
@@ -11,6 +11,7 @@ use crate::audio::{self, AudioHandle, AudioIn};
use crate::gateway::{self, GatewayCmd, GatewayEvent};
use crate::query::{self, QueryCmd, QueryEvent};
use crate::route::{ChatRoute, Dedup, route_chat};
use crate::stream::{PeerConfig, StreamFrame, StreamHandle, StreamInput};
use crate::voice::{self, VoiceCmd, VoiceEvent};
use crate::{Command, Event, ObserveState, SessionId, SessionState, Source, VoiceState};
@@ -19,9 +20,13 @@ pub(crate) struct SessionHandle {
}
impl SessionHandle {
pub fn spawn(id: SessionId, events: broadcast::Sender<Event>) -> Self {
pub fn spawn(
id: SessionId,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
tokio::spawn(Session::new(id, events).run(rx));
tokio::spawn(Session::new(id, events, frames).run(rx));
Self { tx }
}
@@ -53,6 +58,12 @@ struct Session {
query: Option<(u64, mpsc::UnboundedSender<QueryCmd>)>,
query_presence: Option<Presence>,
audio: Option<AudioHandle>,
/// Streams of the voice connection (TeamSpeak 6 only).
streams: Option<StreamHandle>,
stream_peer: PeerConfig,
frames: broadcast::Sender<StreamFrame>,
/// `client_is_streaming` of the voice presence, as last told to the streams.
streaming_clients: BTreeMap<u16, Option<bool>>,
open_chats: HashSet<ChatTarget>,
dedup: Dedup,
sources_tx: mpsc::UnboundedSender<SourceEvent>,
@@ -60,7 +71,11 @@ struct Session {
}
impl Session {
fn new(id: SessionId, events: broadcast::Sender<Event>) -> Self {
fn new(
id: SessionId,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
) -> Self {
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
Self {
id,
@@ -75,6 +90,10 @@ impl Session {
query: None,
query_presence: None,
audio: None,
streams: None,
stream_peer: PeerConfig::default(),
frames,
streaming_clients: BTreeMap::new(),
open_chats: HashSet::new(),
dedup: Dedup::default(),
sources_tx,
@@ -135,8 +154,10 @@ impl Session {
if let Some((_, tx)) = self.voice.take() {
let _ = tx.send(VoiceCmd::Disconnect);
}
self.stop_streams("voice reconnecting");
let generation = self.next_generation();
self.nickname = options.nickname.clone();
self.stream_peer = options.stream_peer.clone();
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
if options.audio {
@@ -243,10 +264,50 @@ impl Session {
}
self.emit_state();
}
Command::StartStream { setup, auto_accept, .. } => {
self.stream_input(StreamInput::Start { setup, auto_accept });
}
Command::StopStream { .. } => self.stream_input(StreamInput::Stop),
Command::AcceptViewer { viewer, accept, .. } => {
self.stream_input(StreamInput::Respond { viewer, accept });
}
Command::KickViewer { viewer, .. } => self.stream_input(StreamInput::Kick { viewer }),
Command::SendStreamFrame { frame, .. } => {
// Frames without a stream are dropped silently.
if let Some(s) = &self.streams {
s.send(StreamInput::Frame(frame));
}
}
Command::WatchStream { stream_id, .. } => {
self.stream_input(StreamInput::Watch { stream_id });
}
Command::LeaveStream { stream_id, .. } => {
self.stream_input(StreamInput::Leave { stream_id });
}
Command::RequestStreamKeyframe { stream_id, .. } => {
self.stream_input(StreamInput::RequestKeyframe { stream_id });
}
Command::CloseSession { .. } => {}
}
}
fn stream_input(&self, input: StreamInput) {
match &self.streams {
Some(s) => s.send(input),
None if self.state.voice == VoiceState::Connected => {
self.error("streams need a TeamSpeak 6 server");
}
None => self.error("not connected with voice"),
}
}
fn stop_streams(&mut self, reason: &str) {
if let Some(s) = self.streams.take() {
s.send(StreamInput::Shutdown(reason.into()));
}
self.streaming_clients.clear();
}
fn voice_cmd(&self, cmd: VoiceCmd) {
match &self.voice {
Some((_, tx)) => {
@@ -299,6 +360,7 @@ impl Session {
}
fn stop_all(&mut self) {
self.stop_streams("session closed");
if let Some((_, tx)) = self.voice.take() {
let _ = tx.send(VoiceCmd::Disconnect);
}
@@ -334,17 +396,47 @@ impl Session {
fn voice_event(&mut self, e: VoiceEvent) {
match e {
VoiceEvent::Connected { name, flavor } => {
VoiceEvent::Connected { name, flavor, own_client } => {
self.state.voice = VoiceState::Connected;
self.emit_state();
let capabilities = flavor.capabilities();
if capabilities.streams
&& let Some((_, voice)) = &self.voice
{
self.streams = Some(StreamHandle::spawn(
self.id,
own_client,
self.stream_peer.clone(),
voice.clone(),
self.events.clone(),
self.frames.clone(),
));
}
self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities });
self.reopen_relayed_chats();
}
VoiceEvent::Presence(p) => {
if let Some(s) = &self.streams {
let clients: BTreeMap<_, _> =
p.clients.values().map(|c| (c.id, c.streaming)).collect();
if clients != self.streaming_clients {
self.streaming_clients = clients.clone();
s.send(StreamInput::Clients(clients));
}
}
self.voice_presence = Some(p);
self.publish_presence();
}
VoiceEvent::Stream(n) => {
if let Some(s) = &self.streams {
s.send(StreamInput::Notification(n));
}
}
VoiceEvent::StreamRequestFailed(request, error) => {
if let Some(s) = &self.streams {
s.send(StreamInput::RequestFailed(request, error));
}
}
VoiceEvent::OwnChannel(cid) => {
if self.state.own_channel != Some(cid) {
self.state.own_channel = Some(cid);
@@ -361,6 +453,7 @@ impl Session {
self.emit(Event::Talking { session: self.id, client, talking });
}
VoiceEvent::Disconnected(reason) => {
self.stop_streams("voice disconnected");
self.voice = None;
self.voice_presence = None;
self.audio = None;
+530
View File
@@ -0,0 +1,530 @@
//! TeamSpeak 6 streams of a session: a task that runs the stream sessions
//! ([`tsc_stream::Streams`]) of the voice connection.
//!
//! The voice task forwards stream notifications here and sends the resulting
//! commands. Only started for TeamSpeak 6 servers.
use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::{broadcast, mpsc};
use tracing::debug;
pub use tsc_stream::{
Codec, EncodedFrame, EndReason, FrameSource, Frequency, LeaveReason, MediaFrame, MediaKind,
MediaTime, PeerConfig, StreamInfo, StreamKind, StreamSetup, SyntheticSource, VideoCodec,
ViewerInfo, ViewerState,
};
use tsc_stream::{
Output, Request, StreamEvent, StreamNotification, StreamerEvent, StreamerOptions, Streams,
WatchEvent,
};
use tsclientlib::ClientId;
use crate::voice::VoiceCmd;
use crate::{Event, SessionId};
/// Our own stream.
#[derive(Clone, Debug, PartialEq)]
pub enum StreamState {
/// `setupstream` sent.
Starting,
/// Live: frames given to `sink` (or [`crate::Command::SendStreamFrame`])
/// reach every connected viewer.
Live {
id: String,
sink: StreamSink,
},
Ended(EndReason),
}
/// A stream we watch.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum WatchState {
/// Join request sent; waiting for the streamer.
Requested,
/// Accepted; connecting to the streamer.
Connecting,
/// Frames arrive through [`crate::Engine::subscribe_frames`].
Connected,
Ended(EndReason),
}
/// A received frame of a watched stream.
#[derive(Clone, Debug)]
pub struct StreamFrame {
pub session: SessionId,
pub stream_id: String,
pub frame: MediaFrame,
}
/// Hands encoded frames of our stream to the engine, e.g. from an encoder thread.
#[derive(Clone)]
pub struct StreamSink {
tx: mpsc::UnboundedSender<StreamInput>,
live: Arc<AtomicBool>,
keyframe: Arc<AtomicBool>,
}
impl StreamSink {
/// Send one frame; `false` once the stream has ended.
pub fn send(&self, frame: EncodedFrame) -> bool {
self.live.load(Ordering::Relaxed) && self.tx.send(StreamInput::Frame(frame)).is_ok()
}
/// Whether a viewer asked for a keyframe since the last call.
pub fn take_keyframe_request(&self) -> bool {
self.keyframe.swap(false, Ordering::Relaxed)
}
pub fn is_live(&self) -> bool {
self.live.load(Ordering::Relaxed)
}
}
impl fmt::Debug for StreamSink {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StreamSink").field("live", &self.is_live()).finish()
}
}
impl PartialEq for StreamSink {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.live, &other.live)
}
}
pub(crate) enum StreamInput {
Start {
setup: StreamSetup,
auto_accept: bool,
},
Stop,
Respond {
viewer: u16,
accept: bool,
},
Kick {
viewer: u16,
},
Watch {
stream_id: String,
},
Leave {
stream_id: String,
},
RequestKeyframe {
stream_id: String,
},
Frame(EncodedFrame),
Notification(StreamNotification),
RequestFailed(Request, String),
/// Clients on the server with their `client_is_streaming`.
Clients(BTreeMap<u16, Option<bool>>),
/// The voice connection is gone.
Shutdown(String),
}
pub(crate) struct StreamHandle {
tx: mpsc::UnboundedSender<StreamInput>,
}
impl StreamHandle {
pub fn spawn(
session: SessionId,
own_client: u16,
config: PeerConfig,
voice: mpsc::UnboundedSender<VoiceCmd>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
let task = StreamTask {
session,
streams: Streams::new(ClientId(own_client), config),
voice,
events,
frames,
tx: tx.clone(),
sink: None,
clients: BTreeMap::new(),
};
tokio::spawn(task.run(rx));
Self { tx }
}
pub fn send(&self, input: StreamInput) {
let _ = self.tx.send(input);
}
}
struct StreamTask {
session: SessionId,
streams: Streams,
voice: mpsc::UnboundedSender<VoiceCmd>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
/// For the sinks handed out.
tx: mpsc::UnboundedSender<StreamInput>,
/// The sink of our live stream.
sink: Option<StreamSink>,
/// Clients on the server and their `client_is_streaming`.
clients: BTreeMap<u16, Option<bool>>,
}
impl StreamTask {
async fn run(mut self, mut rx: mpsc::UnboundedReceiver<StreamInput>) {
loop {
tokio::select! {
input = rx.recv() => match input {
None => break,
Some(StreamInput::Shutdown(reason)) => {
self.shutdown(reason);
break;
}
Some(input) => self.input(input).await,
},
() = self.streams.wait_peers() => {}
}
self.flush();
}
debug!(session = self.session, "stream task ended");
}
fn emit(&self, event: Event) {
let _ = self.events.send(event);
}
async fn input(&mut self, input: StreamInput) {
let session = self.session;
let result = match input {
StreamInput::Start { setup, auto_accept } => {
self.streams.start(StreamerOptions { setup, auto_accept }).map(|()| {
self.emit(Event::StreamState { session, state: StreamState::Starting });
})
}
StreamInput::Stop => self.streams.stop(),
StreamInput::Respond { viewer, accept } => {
self.streams.respond(ClientId(viewer), accept).await
}
StreamInput::Kick { viewer } => self.streams.kick(ClientId(viewer)),
StreamInput::Watch { stream_id } => self.streams.watch(&stream_id, "").map(|()| {
self.emit(Event::WatchState { session, stream_id, state: WatchState::Requested });
}),
StreamInput::Leave { stream_id } => self.streams.leave(&stream_id),
StreamInput::RequestKeyframe { stream_id } => {
self.streams.request_keyframe(&stream_id);
Ok(())
}
StreamInput::Frame(frame) => {
self.streams.write_frame(&frame);
Ok(())
}
StreamInput::Notification(n) => {
self.streams.handle_notification(n).await;
Ok(())
}
StreamInput::RequestFailed(request, error) => {
self.streams.request_failed(&request, &error);
Ok(())
}
StreamInput::Clients(clients) => {
// Streams of clients that left or stopped streaming are gone.
// Only changes count: a snapshot may predate the streaming flag
// of a stream that was just announced.
for (client, streaming) in &clients {
let was = self.clients.get(client).copied().flatten();
if let (Some(was), Some(now)) = (was, *streaming)
&& was != now
{
self.streams.set_client_streaming(ClientId(*client), now);
}
}
self.streams.retain_streamers(|c| clients.contains_key(&c.0));
self.clients = clients;
Ok(())
}
StreamInput::Shutdown(_) => Ok(()),
};
if let Err(e) = result {
self.emit(Event::Error { session, message: format!("stream: {e}") });
}
}
/// Send the requests on the connection and report the events.
fn flush(&mut self) {
while let Some(output) = self.streams.poll_output() {
match output {
Output::Request(request) => {
let _ = self.voice.send(VoiceCmd::Stream(request));
}
Output::Event(event) => self.event(event),
}
}
}
fn event(&mut self, event: StreamEvent) {
let session = self.session;
match event {
StreamEvent::Streams(streams) => self.emit(Event::StreamsChanged { session, streams }),
StreamEvent::Streamer(StreamerEvent::Live { id }) => {
let sink = StreamSink {
tx: self.tx.clone(),
live: Arc::new(AtomicBool::new(true)),
keyframe: Arc::new(AtomicBool::new(true)),
};
self.sink = Some(sink.clone());
self.emit(Event::StreamState { session, state: StreamState::Live { id, sink } });
}
StreamEvent::Streamer(StreamerEvent::Request { viewer, message }) => {
self.emit(Event::StreamViewerRequest { session, viewer: viewer.0, message });
}
StreamEvent::Streamer(StreamerEvent::Viewers(viewers)) => {
self.emit(Event::StreamViewers { session, viewers });
}
StreamEvent::Streamer(StreamerEvent::KeyframeRequest) => {
if let Some(sink) = &self.sink {
sink.keyframe.store(true, Ordering::Relaxed);
}
self.emit(Event::StreamKeyframeRequest { session });
}
StreamEvent::Streamer(StreamerEvent::Ended(reason)) => {
if let Some(sink) = self.sink.take() {
sink.live.store(false, Ordering::Relaxed);
}
self.emit(Event::StreamState { session, state: StreamState::Ended(reason) });
}
StreamEvent::Watch { id, event } => {
let state = match event {
WatchEvent::Accepted => WatchState::Connecting,
WatchEvent::Connected => WatchState::Connected,
WatchEvent::Ended(reason) => WatchState::Ended(reason),
WatchEvent::Frame(frame) => {
let _ = self.frames.send(StreamFrame { session, stream_id: id, frame });
return;
}
};
self.emit(Event::WatchState { session, stream_id: id, state });
}
}
}
/// The connection is gone: report our stream and watched streams as ended.
fn shutdown(&mut self, reason: String) {
let session = self.session;
let ended = || EndReason::Failed(reason.clone());
if self.streams.streamer().is_some() {
self.emit(Event::StreamState { session, state: StreamState::Ended(ended()) });
}
if let Some(sink) = self.sink.take() {
sink.live.store(false, Ordering::Relaxed);
}
for watched in self.streams.watching() {
let stream_id = watched.id().to_owned();
self.emit(Event::WatchState { session, stream_id, state: WatchState::Ended(ended()) });
}
if self.streams.directory().iter().next().is_some() {
self.emit(Event::StreamsChanged { session, streams: Vec::new() });
}
}
}
#[cfg(test)]
mod tests {
use std::time::{Duration, Instant};
use tokio::time::timeout;
use tsc_stream::{FrameSource, SyntheticSource};
use super::*;
const CLIENTS: [u16; 2] = [5, 6];
/// The notifications the server sends for `request` from `from`, per receiver.
fn relay(from: u16, request: Request) -> Vec<(u16, StreamNotification)> {
let both = |n: StreamNotification| CLIENTS.map(|c| (c, n.clone())).to_vec();
match request {
Request::Setup(setup) => CLIENTS
.map(|c| {
let info = StreamInfo {
id: "s-1".into(),
streamer: ClientId(from),
name: setup.name.clone(),
kind: setup.kind,
bitrate: setup.bitrate,
viewer_limit: setup.viewer_limit,
audio: setup.audio,
};
let return_code = (c == from).then(|| "1".to_owned());
(c, StreamNotification::Started { info, return_code })
})
.to_vec(),
Request::Stop { id } => {
both(StreamNotification::Stopped { id, streamer: None, reason: None })
}
Request::Join { id, streamer, message } => vec![(
streamer.0,
StreamNotification::JoinRequest {
id,
viewer: ClientId(from),
message,
remove: false,
},
)],
Request::Leave { id, streamer } => vec![(
streamer.0,
StreamNotification::JoinRequest {
id,
viewer: ClientId(from),
message: String::new(),
remove: true,
},
)],
Request::Respond { id, viewer, offer, accept } => vec![(
viewer.0,
StreamNotification::JoinResponse {
id,
streamer: Some(ClientId(from)),
accepted: accept,
offer,
message: String::new(),
},
)],
Request::Signal { id, peer, signal } => vec![(
peer.0,
StreamNotification::Signaling { id, peer: ClientId(from), json: signal.to_json() },
)],
Request::RemoveViewer { id, viewer, reason } => {
both(StreamNotification::ViewerLeft { id, viewer, reason: Some(reason) })
}
}
}
async fn wait<T>(
rx: &mut broadcast::Receiver<Event>,
mut f: impl FnMut(Event) -> Option<T>,
) -> T {
timeout(Duration::from_secs(10), async {
loop {
if let Some(t) = f(rx.recv().await.unwrap()) {
return t;
}
}
})
.await
.expect("timed out")
}
/// Two stream tasks (sessions 1 and 2) whose commands go through a fake server.
#[tokio::test(flavor = "multi_thread")]
async fn stream_tasks_through_fake_server() {
let (events, mut rx) = broadcast::channel(4096);
let (frames, mut frames_rx) = broadcast::channel(4096);
let mut voices = Vec::new();
let mut handles = Vec::new();
for (i, clid) in CLIENTS.into_iter().enumerate() {
let (voice, voice_rx) = mpsc::unbounded_channel();
let config = PeerConfig::loopback();
let session = i as u64 + 1;
handles.push(StreamHandle::spawn(
session,
clid,
config,
voice,
events.clone(),
frames.clone(),
));
voices.push(voice_rx);
}
let handles = Arc::new(handles);
// The server: relays requests from one task as notifications to the others.
for (i, mut voice_rx) in voices.into_iter().enumerate() {
let handles = handles.clone();
tokio::spawn(async move {
while let Some(cmd) = voice_rx.recv().await {
if let VoiceCmd::Stream(request) = cmd {
for (to, n) in relay(CLIENTS[i], request) {
let index = CLIENTS.iter().position(|c| *c == to).unwrap();
handles[index].send(StreamInput::Notification(n));
}
}
}
});
}
let setup = StreamSetup { name: "t".into(), ..Default::default() };
handles[0].send(StreamInput::Start { setup, auto_accept: true });
// Live for the streamer and listed for the viewer, in either order.
let (mut sink, mut listed) = (None, false);
wait(&mut rx, |e| {
match e {
Event::StreamState { session: 1, state: StreamState::Live { sink: s, .. } } => {
sink = Some(s);
}
Event::StreamsChanged { session: 2, streams } => listed = streams.len() == 1,
_ => {}
}
(sink.is_some() && listed).then_some(())
})
.await;
let sink = sink.unwrap();
handles[1].send(StreamInput::Watch { stream_id: "s-1".into() });
wait(&mut rx, |e| match e {
Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()),
_ => None,
})
.await;
// Frames from the sink reach the viewer's frame bus.
let feeder = tokio::spawn({
let sink = sink.clone();
async move {
let mut source = SyntheticSource::new(30, 2000, true);
let mut out = Vec::new();
while sink.is_live() {
source.poll_frames(Instant::now(), &mut out);
for f in out.drain(..) {
sink.send(f);
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
});
let (mut video, mut audio) = (0, 0);
timeout(Duration::from_secs(10), async {
while video < 10 || audio < 10 {
let f = frames_rx.recv().await.unwrap();
assert_eq!((f.session, f.stream_id.as_str()), (2, "s-1"));
match f.frame.kind {
MediaKind::Video => video += 1,
MediaKind::Audio => audio += 1,
}
}
})
.await
.expect("no frames");
assert!(sink.take_keyframe_request());
// Stopping ends the sink and tells the viewer.
handles[0].send(StreamInput::Stop);
wait(&mut rx, |e| match e {
Event::WatchState {
session: 2, state: WatchState::Ended(EndReason::Stopped), ..
} => Some(()),
_ => None,
})
.await;
assert!(!sink.is_live());
feeder.await.unwrap();
// Errors surface as events.
handles[1].send(StreamInput::Leave { stream_id: "s-1".into() });
wait(&mut rx, |e| match e {
Event::Error { session: 2, message } if message.contains("not watching") => Some(()),
_ => None,
})
.await;
handles[1].send(StreamInput::Shutdown("bye".into()));
}
}
+37 -3
View File
@@ -1,5 +1,6 @@
//! The voice source: a normal client connection.
use std::collections::HashMap;
use std::time::Duration;
use futures::prelude::*;
@@ -9,12 +10,13 @@ use tracing::{info, warn};
use tsc_model::{
ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerFlavor,
};
use tsc_stream::{PeerConfig, Request, StreamNotification};
use tsclientlib::data;
use tsclientlib::events::Event as BookEvent;
use tsclientlib::prelude::*;
use tsclientlib::{
ClientType, Connection, DisconnectOptions, Identity, MaxClients, MessageTarget, StreamItem,
Version,
ClientType, Connection, DisconnectOptions, Identity, MaxClients, MessageHandle, MessageTarget,
StreamItem, Version,
};
use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket};
@@ -30,6 +32,8 @@ pub struct VoiceOptions {
pub channel: Option<String>,
/// Open the audio devices (capture and playback).
pub audio: bool,
/// Network settings for stream peer connections (TeamSpeak 6).
pub stream_peer: PeerConfig,
}
impl VoiceOptions {
@@ -42,6 +46,7 @@ impl VoiceOptions {
server_password: None,
channel: None,
audio: false,
stream_peer: PeerConfig::default(),
}
}
}
@@ -53,6 +58,8 @@ pub(crate) enum VoiceCmd {
SetOutputMuted(bool),
/// An encoded voice packet from the audio thread.
Audio(OutPacket),
/// A stream command; failures come back as [`VoiceEvent::StreamRequestFailed`].
Stream(Request),
Disconnect,
}
@@ -60,6 +67,7 @@ pub(crate) enum VoiceEvent {
Connected {
name: String,
flavor: ServerFlavor,
own_client: u16,
},
Presence(Presence),
OwnChannel(ChannelId),
@@ -70,6 +78,8 @@ pub(crate) enum VoiceEvent {
client: u16,
talking: bool,
},
Stream(StreamNotification),
StreamRequestFailed(Request, String),
Disconnected(Option<String>),
}
@@ -192,7 +202,11 @@ async fn run_inner(
let state = con.get_state()?;
let flavor = ServerFlavor::from_version_string(&state.server.version);
info!(server = %state.server.name, ?flavor, "voice connected");
let _ = events.send(VoiceEvent::Connected { name: state.server.name.clone(), flavor });
let _ = events.send(VoiceEvent::Connected {
name: state.server.name.clone(),
flavor,
own_client: state.own_client.0,
});
}
// Subscribe to all channels to see everyone.
let cmd = con.get_state()?.server.set_subscribed(true);
@@ -202,6 +216,8 @@ async fn run_inner(
// Who is talking: last voice packet per client.
let mut talking: std::collections::HashMap<u16, Instant> = Default::default();
let mut tick = tokio::time::interval(Duration::from_millis(250));
// Stream commands waiting for the server's answer.
let mut stream_requests: HashMap<MessageHandle, Request> = HashMap::new();
loop {
let input = {
@@ -258,12 +274,27 @@ async fn run_inner(
}
let _ = events.send(VoiceEvent::Audio(packet));
}
StreamItem::MessageEvent(msg) => {
for n in StreamNotification::from_message(&msg) {
let _ = events.send(VoiceEvent::Stream(n));
}
}
StreamItem::MessageResult(handle, result) => {
if let (Some(request), Err(e)) = (stream_requests.remove(&handle), result) {
let _ =
events.send(VoiceEvent::StreamRequestFailed(request, e.to_string()));
}
}
StreamItem::DisconnectedTemporarily(reason) => {
warn!(?reason, "voice connection interrupted, reconnecting");
}
_ => {}
},
Input::Cmd(None) | Input::Cmd(Some(VoiceCmd::Disconnect)) => break,
Input::Cmd(Some(VoiceCmd::Stream(request))) => {
let handle = request.to_command().send_with_result(&mut con)?;
stream_requests.insert(handle, request);
}
Input::Cmd(Some(cmd)) => handle_command(&mut con, cmd)?,
Input::Tick => {
talking.retain(|client, last| {
@@ -336,6 +367,9 @@ fn handle_command(con: &mut Connection, cmd: VoiceCmd) -> anyhow::Result<()> {
VoiceCmd::Audio(packet) => {
con.send_audio(packet)?;
}
VoiceCmd::Stream(request) => {
request.to_command().send(con)?;
}
VoiceCmd::Disconnect => {}
}
Ok(())
+224
View File
@@ -0,0 +1,224 @@
//! Streams through the engine against the development servers
//! (dev/docker-compose.yml): one session streams synthetic frames, another
//! watches. Runs only with `TSC_LIVE=1`.
use std::time::{Duration, Instant};
use tokio::sync::broadcast::Receiver;
use tokio::time::timeout;
use tsc_core::stream::{
EndReason, FrameSource, LeaveReason, MediaKind, PeerConfig, StreamSetup, SyntheticSource,
ViewerState,
};
use tsc_core::{Command, Engine, Event, StreamState, VoiceOptions, VoiceState, WatchState};
fn live() -> bool {
std::env::var("TSC_LIVE").is_ok_and(|v| v == "1")
}
/// Wait for an event matching `f`, failing after 20 s.
async fn wait_for<T>(
rx: &mut Receiver<Event>,
what: &str,
mut f: impl FnMut(&Event) -> Option<T>,
) -> T {
timeout(Duration::from_secs(20), async {
loop {
match rx.recv().await {
Ok(e) => {
if let Some(t) = f(&e) {
return t;
}
if let Event::Error { session, message } = e {
eprintln!("engine error (session {session}): {message}");
}
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
Err(e) => panic!("event bus closed: {e}"),
}
}
})
.await
.unwrap_or_else(|_| panic!("timed out waiting for {what}"))
}
async fn connect(
engine: &Engine,
events: &mut Receiver<Event>,
session: u64,
addr: &str,
nick: &str,
) {
let mut options = VoiceOptions::new(addr, nick);
options.stream_peer = PeerConfig::loopback();
engine.send(Command::ConnectVoice { session, options: Box::new(options) });
wait_for(events, "voice connected", |e| match e {
Event::State { session: s, state }
if *s == session
&& state.voice == VoiceState::Connected
&& state.own_channel.is_some() =>
{
Some(())
}
_ => None,
})
.await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_stream_between_sessions() {
if !live() {
eprintln!("skipped: set TSC_LIVE=1 with the dev servers running");
return;
}
let engine = Engine::start();
let mut events = engine.subscribe();
let mut frames = engine.subscribe_frames();
let tag = std::process::id() % 10_000;
connect(&engine, &mut events, 1, "127.0.0.1:9988", &format!("e-streamer-{tag}")).await;
connect(&engine, &mut events, 2, "127.0.0.1:9988", &format!("e-viewer-{tag}")).await;
// Stream, asking for each viewer.
let setup = StreamSetup { name: format!("engine {tag}"), ..Default::default() };
engine.send(Command::StartStream { session: 1, setup, auto_accept: false });
let (id, sink) = wait_for(&mut events, "stream live", |e| match e {
Event::StreamState { session: 1, state: StreamState::Live { id, sink } } => {
Some((id.clone(), sink.clone()))
}
Event::StreamState { session: 1, state: StreamState::Ended(reason) } => {
panic!("stream ended: {reason:?}")
}
_ => None,
})
.await;
wait_for(&mut events, "stream in the viewer's list", |e| match e {
Event::StreamsChanged { session: 2, streams } if streams.iter().any(|s| s.id == id) => {
Some(())
}
_ => None,
})
.await;
// Synthetic frames through the sink, as an encoder would send them.
let feeder = tokio::spawn({
let sink = sink.clone();
async move {
let mut source = SyntheticSource::new(30, 3000, true);
let mut out = Vec::new();
while sink.is_live() {
source.poll_frames(Instant::now(), &mut out);
for frame in out.drain(..) {
sink.send(frame);
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
});
engine.send(Command::WatchStream { session: 2, stream_id: id.clone() });
let viewer = wait_for(&mut events, "viewer request", |e| match e {
Event::StreamViewerRequest { session: 1, viewer, .. } => Some(*viewer),
_ => None,
})
.await;
engine.send(Command::AcceptViewer { session: 1, viewer, accept: true });
wait_for(&mut events, "watching", |e| match e {
Event::WatchState { session: 2, stream_id, state: WatchState::Connected }
if *stream_id == id =>
{
Some(())
}
Event::WatchState { session: 2, state: WatchState::Ended(reason), .. } => {
panic!("watching ended: {reason:?}")
}
_ => None,
})
.await;
wait_for(&mut events, "viewer connected", |e| match e {
Event::StreamViewers { session: 1, viewers }
if viewers
.iter()
.any(|v| v.client.0 == viewer && v.state == ViewerState::Connected) =>
{
Some(())
}
_ => None,
})
.await;
assert!(sink.take_keyframe_request(), "a new viewer asks for a keyframe");
let (mut video, mut audio) = (0, 0);
let _ = timeout(Duration::from_secs(10), async {
while video < 60 || audio < 60 {
match frames.recv().await {
Ok(f) if f.session == 2 && f.stream_id == id => match f.frame.kind {
MediaKind::Video => video += 1,
MediaKind::Audio => audio += 1,
},
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
Err(_) => break,
}
}
})
.await;
assert!(video >= 60 && audio >= 60, "viewer got {video} video / {audio} audio frames");
// The streamer removes the viewer, then ends the stream.
engine.send(Command::KickViewer { session: 1, viewer });
wait_for(&mut events, "kicked", |e| match e {
Event::WatchState {
session: 2,
state: WatchState::Ended(EndReason::Removed(Some(LeaveReason::Kicked))),
..
} => Some(()),
_ => None,
})
.await;
engine.send(Command::StopStream { session: 1 });
wait_for(&mut events, "stream ended", |e| match e {
Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Local) } => Some(()),
_ => None,
})
.await;
wait_for(&mut events, "stream gone from the viewer's list", |e| match e {
Event::StreamsChanged { session: 2, streams } if streams.iter().all(|s| s.id != id) => {
Some(())
}
_ => None,
})
.await;
assert!(!sink.send(tsc_core::stream::EncodedFrame {
kind: MediaKind::Audio,
time: tsc_core::stream::MediaTime::from_90khz(0),
data: vec![0].into(),
}));
feeder.await.unwrap();
engine.send(Command::CloseSession { session: 1 });
engine.send(Command::CloseSession { session: 2 });
tokio::time::sleep(Duration::from_millis(500)).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_has_no_streams() {
if !live() {
return;
}
let engine = Engine::start();
let mut events = engine.subscribe();
let nick = format!("e-nostream-{}", std::process::id() % 10_000);
connect(&engine, &mut events, 1, "127.0.0.1:9987", &nick).await;
engine.send(Command::StartStream {
session: 1,
setup: StreamSetup::default(),
auto_accept: true,
});
let message = wait_for(&mut events, "error", |e| match e {
Event::Error { session: 1, message } => Some(message.clone()),
_ => None,
})
.await;
assert!(message.contains("TeamSpeak 6"), "{message}");
engine.send(Command::CloseSession { session: 1 });
tokio::time::sleep(Duration::from_millis(500)).await;
}
+1 -1
View File
@@ -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]
+11
View File
@@ -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};
+145 -22
View File
@@ -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};
@@ -32,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<Self> {
match c {
Codec::Vp8 => Some(Self::Vp8),
@@ -41,6 +44,20 @@ impl VideoCodec {
_ => None,
}
}
/// From an SDP encoding name (`a=rtpmap:<pt> VP8/90000`).
pub fn from_sdp_name(name: &str) -> Option<Self> {
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)]
@@ -49,8 +66,12 @@ pub struct PeerConfig {
pub hosts: Vec<IpAddr>,
/// STUN servers (`host:port`) for a server-reflexive candidate.
pub stun_servers: Vec<String>,
/// 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<VideoCodec>,
/// 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<VideoCodec>,
pub video: bool,
pub audio: bool,
}
@@ -60,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,
}
@@ -100,8 +122,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<String> },
/// A received frame (depacketized).
Media(MediaFrame),
/// The viewer asks for a keyframe.
@@ -140,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());
@@ -161,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()))
@@ -225,6 +258,11 @@ impl Peer {
pub fn try_next_event(&mut self) -> Option<PeerEvent> {
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<Option<PeerEvent>> {
self.events.poll_recv(cx)
}
}
impl Drop for Peer {
@@ -233,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<VideoCodec> {
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<IpAddr> {
let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?;
@@ -420,9 +500,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}"),
@@ -583,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}");
}
}
File diff suppressed because it is too large. Load diff
+129
View File
@@ -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<EncodedFrame>);
/// 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<u8> {
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<EncodedFrame>) {
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);
}
}
+320
View File
@@ -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<BufReader<ChildStdout>>,
}
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;
}
+280
View File
@@ -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<String, ClientId>,
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<SyntheticSource>,
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());
}
+19 -2
View File
@@ -66,8 +66,8 @@ fuzz/ cargo-fuzz targets
| `tsc-gateway-proto`, `tsc-gateway` (`tsgw`) | Companion service for server admins: identity-challenge auth, permission-mirroring authorization, presence stream, chat relay, SQLite history, WebSocket + JSON (`tsgw.v1+json`) | done |
| `tsc-store` | Identities, bookmarks, settings, chat cache, secrets (keyring / Android Keystore) | done |
| `tsc-audio` | Capture/playback, Opus, echo cancellation, resampling, jitter buffer, mixer, VAD/push-to-talk | v0 (no AEC yet) |
| `tsc-stream` | TS6 stream commands, JSON signalling, str0m peer connections, host/STUN candidates | signalling + transport |
| `tsc-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API | done (no streams yet) |
| `tsc-stream` | TS6 stream commands, JSON signalling, str0m peer connections, host/STUN candidates, streamer/viewer sessions, frame-source seam | sessions + transport |
| `tsc-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API, streams on TS6 | done (streams with synthetic frames) |
| `tsc-ui` | Slint UI and the desktop binary | done (no streams yet) |
| `tsc-media` | Screen and system-audio capture backends (PipeWire portal, X11, Windows Graphics Capture, Android MediaProjection), video codecs | planned |
| `tsc-platform` | Global hotkeys, notifications, paths | planned |
@@ -82,6 +82,23 @@ the native command only when voice-connected *and* in that channel, otherwise th
gateway, otherwise a local query relay. UI states: `Offline`,
`Observing (Gateway|Query)` (invisible), `Connecting`, `Connected`.
## Streams
`tsc-stream::Streams` holds the stream state of one TS6 connection without
doing connection IO: it is fed stream notifications (and failed commands) and
the app's decisions, owns the str0m peers, and queues requests to send plus
events. Inside it, `StreamerSession` runs our stream (one peer per viewer, our
offer in `respondjoinstreamrequest`), `ViewerSession` one watched stream
(answer through `streamsignaling`), and `StreamDirectory` the streams of our
channel. Its tests drive two instances through a fake relay server.
In `tsc-core` a stream task per voice connection runs `Streams`; the voice task
forwards `MessageEvent`s and sends the requests. Encoders push frames through
the `StreamSink` of `StreamState::Live`; received frames of watched streams go
to `Engine::subscribe_frames`, not the event bus. `tsc-stream::FrameSource` is
the seam for capture and encoders (`tsc-media`); `SyntheticSource` stands in
for tests and `tsctl stream start --synthetic`.
## Milestones
| | Scope | Exit criteria |
+42 -2
View File
@@ -167,6 +167,44 @@ property for the planned SFU mode.
Errors: `setupstream` refused with error 2568 ("insufficient client
permissions") has been seen; no stream permission names are documented.
More text commands and notifications named in the server binary (not probed
yet): `requeststreaminfo` (its protobuf request only has `stream_id`, so it
cannot discover the ids of unknown streams), `updatestream` (`stream_id`,
`stream_name`, `max_width`, `max_height`, `max_framerate`, `properties`),
`notifystreamupdated`, `notifystreamattendees` (`return_code`, `client_id`).
### Streams that started before we joined (open)
`initserver` and `notifycliententerview` carry `client_is_streaming`, but no
stream id. Whether the server sends `notifystreamstarted` for running streams
to a client that connects or enters the channel later is not confirmed yet.
`tsctl stream list` shows such streamers as "id not announced"; `tsctl stream
watch --id <uuid>` can still join when the streamer is known (`--streamer-nick`,
or the only other client streaming). The smoke test starts the viewer first.
### WebRTC interop with Chromium (confirmed, Chromium 141, 2026-09-26)
`crates/tsc-stream/tests/browser_interop.rs` (`TSC_INTEROP=1`, see
`tests/interop/README.md`) runs our str0m peers against headless Chromium's
libwebrtc, the stack the official client is built on:
- Our streamer offer (VP8 + Opus, BUNDLE, `setup:actpass`, host candidates in
the SDP) is accepted; Chromium answers `setup:active` and decodes the
synthetic 1x1 VP8 keyframes. Opus packets arrive.
- Chromium's offers (canvas video + oscillator audio) with VP8, VP9 or AV1
preferred are answered by our viewer, which receives frames of that codec
and Opus; a PLI from us yields a VP8 keyframe. Playwright's Chromium cannot
send H.264.
- Trickled candidates must carry the real `sdpMid`: str0m's mids are random
strings (e.g. `fhs`), not `0`. Our `iceCandidate` signals use the peer's
first mid and `sdpMLineIndex` 0; Chromium's `addIceCandidate` accepts them.
- Without camera/microphone permission Chromium hides host candidates behind
mDNS names (`<uuid>.local`), which str0m cannot resolve. The test disables
that; the official client may send mDNS candidates, which would then need a
resolver (or its server-reflexive candidates) on our side.
- str0m answers in its own codec order and the offerer sends the answer's
first codec, so `Peer::answer` orders the viewer's codecs like the offer.
## Open questions
- [x] Viewer side: `joinstreamrequest id clid msg is_remove` (see above).
@@ -174,9 +212,11 @@ permissions") has been seen; no stream permission names are documented.
- [x] Parameters of `stopstream` and `removeclientfromstream` (`reason` is required).
- [ ] Which permission gates `setupstream` (error 2568).
- [x] Contents of `notifystreamstarted` (see probe results).
- [ ] Contents of `notifystreaminfo` (`requeststreaminfo`).
- [ ] Contents of `notifystreaminfo` (`requeststreaminfo id=<uuid>`).
- [ ] Whether a client that joins later is told about running streams (see above).
- [ ] Interop with the official TS6 client (its offer/answer details, codecs it
actually picks, whether it trickles candidates).
actually picks, whether it trickles candidates, mDNS host candidates).
Chromium's WebRTC stack interoperates (see above).
- [ ] Whether stream audio can be sent without video.
- [ ] The WebRTC/protobuf transport some TS6 clients use on UDP 9987
(`client_protocol_format=proto`, reported in community reverse engineering).
+26 -1
View File
@@ -11,6 +11,7 @@
# 6. relay chat: a query relay reads channel chat and posts into the channel
# 7. gateway (tsgw): login with a TeamSpeak identity, presence, channel chat
# both ways, refusal of an identity the server does not know
# 8. stream (TeamSpeak 6 only): a viewer watches a synthetic VP8 + Opus stream
#
# Usage: scripts/it-smoke.sh [ts3|ts6]... (default: both)
# Env: TSCTL=path/to/tsctl (default: builds target/debug/tsctl)
@@ -108,6 +109,27 @@ voice_roundtrip() {
grep "tone ratio" "$out"
}
# TeamSpeak 6: a viewer waits for a stream, a streamer sends synthetic frames.
stream_check() {
local addr=$1 out="$STATE_DIR/stream-watch.log" streamer_out="$STATE_DIR/stream-start.log"
# Unique nicknames: other clients may stream on the same server.
local streamer="streamer-$$-$RANDOM"
"$TSCTL" connect "$addr" --nick "viewer-$$" stream --loopback watch --streamer-nick "$streamer" \
--expect-frames 60 --timeout 30 >"$out" 2>&1 &
local viewer=$!
sleep 2
if ! "$TSCTL" connect "$addr" --nick "$streamer" stream --loopback start --synthetic \
--auto-accept --seconds 10 >"$streamer_out" 2>&1; then
cat "$streamer_out" "$out"
fail "streamer failed"
fi
if ! wait "$viewer"; then
cat "$out" "$streamer_out"
fail "stream frames not received"
fi
grep -E "first video frame|received" "$out"
}
# An observer over ServerQuery must see a voice client join.
presence_check() {
local addr=$1 query=$2 out="$STATE_DIR/observe.log"
@@ -213,10 +235,13 @@ for svc in "${SERVERS[@]}"; do
presence_check "$addr" "${QUERY[$svc]}"
relay_check "$addr" "${QUERY[$svc]}"
gateway_check "$svc" "$addr"
if [[ $svc == ts6 ]]; then
stream_check "$addr"
fi
done
log "engine (tsc-core) against both servers"
TSC_LIVE=1 cargo test --quiet -p tsc-core --test live 2>&1 | grep -E "test result|panicked|timed out" || fail "engine tests failed"
TSC_LIVE=1 cargo test --quiet -p tsc-core --test live --test stream_live 2>&1 | grep -E "test result|panicked|timed out" || fail "engine tests failed"
log "stream (tsc-stream) through the TeamSpeak 6 server"
TSC_LIVE=1 cargo test --quiet -p tsc-stream --test live_ts6 2>&1 | grep -E "test result|panicked|timed out" || fail "stream test failed"
+46
View File
@@ -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 (`<uuid>.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.
+198
View File
@@ -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 <video> element
// quit
'use strict';
const readline = require('node:readline');
const { chromium } = require('playwright');
// Runs in the page.
const PAGE_SCRIPT = `
function gathered(pc, ms) {
return new Promise((resolve) => {
if (pc.iceGatheringState === 'complete') return resolve();
pc.addEventListener('icegatheringstatechange', () => {
if (pc.iceGatheringState === 'complete') resolve();
});
setTimeout(resolve, ms);
});
}
window.peer = {
pc: null,
timers: [],
shownFrames: 0,
localCandidates: [],
reset() {
if (this.pc) this.pc.close();
this.timers.forEach(clearInterval);
this.timers = [];
this.shownFrames = 0;
this.localCandidates = [];
this.pc = new RTCPeerConnection();
this.pc.addEventListener('icecandidate', (e) => {
if (e.candidate && e.candidate.candidate) this.localCandidates.push(e.candidate.toJSON());
});
this.pc.addEventListener('connectionstatechange', () => {
console.log('connection ' + this.pc.connectionState);
});
return this.pc;
},
// Count frames a <video> element actually presents (needs decodable video).
show(track) {
const video = document.createElement('video');
video.muted = true;
video.autoplay = true;
video.srcObject = new MediaStream([track]);
document.body.appendChild(video);
const count = () => {
this.shownFrames++;
video.requestVideoFrameCallback(count);
};
video.requestVideoFrameCallback(count);
video.play().catch((e) => console.log('play: ' + e));
},
async answer({ sdp }) {
const pc = this.reset();
pc.addEventListener('track', (e) => {
if (e.track.kind === 'video') this.show(e.track);
});
await pc.setRemoteDescription({ type: 'offer', sdp });
await pc.setLocalDescription(await pc.createAnswer());
await gathered(pc, 3000);
return { sdp: pc.localDescription.sdp };
},
async offer({ codec, trickle }) {
const pc = this.reset();
const canvas = document.createElement('canvas');
canvas.width = 320;
canvas.height = 240;
const ctx = canvas.getContext('2d');
let n = 0;
this.timers.push(setInterval(() => {
n++;
ctx.fillStyle = 'hsl(' + ((n * 7) % 360) + ',60%,50%)';
ctx.fillRect(0, 0, 320, 240);
ctx.fillStyle = '#fff';
ctx.fillText(String(n), 10 + (n % 200), 20 + (n % 150));
}, 33));
const video = canvas.captureStream(30).getVideoTracks()[0];
const audioCtx = new AudioContext();
const osc = audioCtx.createOscillator();
const dest = audioCtx.createMediaStreamDestination();
osc.connect(dest);
osc.start();
const audio = dest.stream.getAudioTracks()[0];
const stream = new MediaStream([video, audio]);
const transceiver = pc.addTransceiver(video, { direction: 'sendonly', streams: [stream] });
pc.addTransceiver(audio, { direction: 'sendonly', streams: [stream] });
if (codec) {
const all = RTCRtpSender.getCapabilities('video').codecs;
const wanted = all.filter((c) => c.mimeType.toLowerCase() === 'video/' + codec.toLowerCase());
if (wanted.length === 0) return { unsupported: codec };
transceiver.setCodecPreferences([...wanted, ...all.filter((c) => !wanted.includes(c))]);
}
await pc.setLocalDescription(await pc.createOffer());
if (!trickle) await gathered(pc, 3000);
const sdp = trickle ? pc.localDescription.sdp.split('\\r\\n').filter((l) => !l.startsWith('a=candidate')).join('\\r\\n') : pc.localDescription.sdp;
return { sdp };
},
async candidates() {
await gathered(this.pc, 3000);
return { candidates: this.localCandidates };
},
async accept({ sdp }) {
await this.pc.setRemoteDescription({ type: 'answer', sdp });
return { ok: true };
},
async candidate({ candidate, sdpMid, sdpMLineIndex }) {
await this.pc.addIceCandidate({ candidate, sdpMid, sdpMLineIndex });
return { ok: true };
},
async stats() {
const report = await this.pc.getStats();
const codecs = {};
const inbound = {};
const outbound = {};
report.forEach((s) => {
if (s.type === 'codec') codecs[s.id] = s.mimeType;
if (s.type === 'inbound-rtp') inbound[s.kind] = s;
if (s.type === 'outbound-rtp') outbound[s.kind] = s;
});
const pick = (s, keys) => {
const o = { codec: codecs[s.codecId] };
keys.forEach((k) => (o[k] = s[k]));
return o;
};
const out = { connectionState: this.pc.connectionState, shownFrames: this.shownFrames, inbound: {}, outbound: {} };
for (const k in inbound) {
out.inbound[k] = pick(inbound[k], ['packetsReceived', 'bytesReceived', 'packetsLost', 'framesReceived', 'framesDecoded', 'keyFramesDecoded', 'pliCount', 'totalSamplesReceived']);
}
for (const k in outbound) {
out.outbound[k] = pick(outbound[k], ['packetsSent', 'bytesSent', 'framesEncoded', 'keyFramesEncoded', 'pliCount']);
}
return out;
},
async quit() {
if (this.pc) this.pc.close();
return { ok: true };
},
};
`;
async function main() {
const browser = await chromium.launch({
headless: true,
args: [
// Real host candidates instead of mDNS names (no getUserMedia permission here).
'--disable-features=WebRtcHideLocalIpsWithMdns',
'--autoplay-policy=no-user-gesture-required',
],
});
const page = await browser.newPage();
page.on('console', (m) => process.stderr.write('[page] ' + m.text() + '\n'));
await page.setContent('<!doctype html><html><body></body></html>');
await page.addScriptTag({ content: PAGE_SCRIPT });
process.stdout.write(JSON.stringify({ ready: true, userAgent: await page.evaluate(() => navigator.userAgent) }) + '\n');
const lines = readline.createInterface({ input: process.stdin });
for await (const line of lines) {
if (!line.trim()) continue;
const cmd = JSON.parse(line);
let reply;
try {
reply = await page.evaluate(([op, arg]) => window.peer[op](arg), [cmd.op, cmd]);
} catch (e) {
reply = { error: String(e) };
}
process.stdout.write(JSON.stringify(reply) + '\n');
if (cmd.op === 'quit') break;
}
await browser.close();
}
main().catch((e) => {
process.stderr.write(String(e && e.stack ? e.stack : e) + '\n');
process.exit(1);
});
+1
View File
@@ -24,6 +24,7 @@ tsc-model = { path = "../../crates/tsc-model" }
tsc-query = { path = "../../crates/tsc-query" }
tsc-observer = { path = "../../crates/tsc-observer" }
tsc-audio = { path = "../../crates/tsc-audio", default-features = false }
tsc-stream = { path = "../../crates/tsc-stream" }
tokio-tungstenite = "0.30"
futures-util = "0.3.34"
tsc-gateway-proto = { path = "../../crates/tsc-gateway-proto" }
+3
View File
@@ -5,6 +5,7 @@ mod identity;
mod observe;
mod query;
mod session;
mod stream;
mod tree;
mod versions;
mod voice;
@@ -133,6 +134,8 @@ pub enum Action {
#[command(subcommand)]
command: VoiceCommand,
},
/// TeamSpeak 6 streams (screen sharing): start, list or watch.
Stream(stream::StreamArgs),
/// Interactive session. Type `/help` for commands.
Repl,
}
+1
View File
@@ -58,6 +58,7 @@ pub async fn run(args: ConnectArgs) -> Result<()> {
send_and_wait(&mut con, cmd, "command").await.map(|()| println!("ok"))
}
Action::Voice { command } => crate::voice::run(&mut con, command).await,
Action::Stream(stream) => crate::stream::run(&mut con, stream).await,
Action::Repl => repl(&mut con).await,
};
+528
View File
@@ -0,0 +1,528 @@
//! `tsctl connect ... stream start|list|watch`: TeamSpeak 6 streams.
use std::collections::HashMap;
use std::time::Duration;
use anyhow::{Result, bail};
use clap::{Args, Subcommand};
use futures::prelude::*;
use tokio::io::{AsyncBufReadExt, BufReader, Lines, Stdin};
use tokio::time::{Instant, Interval, sleep_until};
use tsc_model::ServerFlavor;
use tsc_stream::{
EndReason, FrameSource, MediaKind, Output, PeerConfig, Request, StreamEvent, StreamInfo,
StreamNotification, StreamSetup, StreamerEvent, StreamerOptions, Streams, SyntheticSource,
WatchEvent,
};
use tsclientlib::events::{Event, PropertyId};
use tsclientlib::prelude::*;
use tsclientlib::{ClientId, Connection, MessageHandle, StreamItem};
#[derive(Args, Debug, Clone)]
pub struct StreamArgs {
#[command(subcommand)]
command: StreamCommand,
/// Media over 127.0.0.1 only (both ends on this machine), no STUN.
#[arg(long, global = true)]
loopback: bool,
/// STUN server (`host:port`) for a public candidate; repeatable [default: TeamSpeak's].
#[arg(long, global = true)]
stun: Vec<String>,
/// Do not use STUN.
#[arg(long, global = true, conflicts_with = "stun")]
no_stun: bool,
}
#[derive(Subcommand, Debug, Clone)]
pub enum StreamCommand {
/// Stream in our channel. Without `--auto-accept`, answer join requests on
/// stdin: `accept <clid>`, `deny <clid>`, `kick <clid>`, `stop`.
Start {
/// Stream name.
#[arg(long, default_value = "tsctl")]
name: String,
/// Send synthetic frames (tiny VP8 keyframes and silent Opus); needed
/// until capture and encoders exist.
#[arg(long)]
synthetic: bool,
/// Accept every viewer.
#[arg(long)]
auto_accept: bool,
/// Stop after this many seconds [default: until Ctrl-C].
#[arg(long)]
seconds: Option<u64>,
/// Synthetic video frames per second.
#[arg(long, default_value_t = 30)]
fps: u32,
/// Size of each synthetic video frame in bytes.
#[arg(long, default_value_t = 4000)]
frame_size: usize,
/// No audio track.
#[arg(long)]
no_audio: bool,
},
/// List the streams in our channel.
List {
/// How long to collect stream announcements before printing.
#[arg(long, default_value_t = 1500)]
settle_ms: u64,
},
/// Watch a stream (the first one that shows up if neither `--id` nor
/// `--streamer-nick` is given).
Watch {
/// Stream id.
#[arg(long)]
id: Option<String>,
/// Nickname of the streamer.
#[arg(long)]
streamer_nick: Option<String>,
/// Exit successfully once this many video frames arrived.
#[arg(long)]
expect_frames: Option<u64>,
/// Give up after this many seconds; fails if `--expect-frames` was not reached.
#[arg(long)]
timeout: Option<u64>,
},
}
pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> {
let (own, version) = {
let state = con.get_state()?;
(state.own_client, state.server.version.clone())
};
if !ServerFlavor::from_version_string(&version).capabilities().streams {
bail!("streams need a TeamSpeak 6 server (this one is {version})");
}
let mut config = if args.loopback { PeerConfig::loopback() } else { PeerConfig::default() };
if !args.stun.is_empty() {
config.stun_servers = args.stun.clone();
} else if args.no_stun {
config.stun_servers.clear();
}
let mut driver = Driver { streams: Streams::new(own, config), pending: HashMap::new() };
let result = match &args.command {
StreamCommand::Start {
name,
synthetic,
auto_accept,
seconds,
fps,
frame_size,
no_audio,
} => {
let source = frame_source(*synthetic, *fps, *frame_size, !no_audio)?;
let setup = StreamSetup { name: name.clone(), audio: !no_audio, ..Default::default() };
let options = StreamerOptions { setup, auto_accept: *auto_accept };
start(con, &mut driver, options, source, seconds.map(Duration::from_secs)).await
}
StreamCommand::List { settle_ms } => {
list(con, &mut driver, Duration::from_millis(*settle_ms)).await
}
StreamCommand::Watch { id, streamer_nick, expect_frames, timeout } => {
let target = Target { id: id.clone(), streamer_nick: streamer_nick.clone() };
let timeout = timeout.map(Duration::from_secs);
watch(con, &mut driver, &target, *expect_frames, timeout).await
}
};
driver.finish(con).await;
result
}
/// Where a streamer's frames come from. Capture and encoders (`tsc-media`)
/// plug in here.
fn frame_source(
synthetic: bool,
fps: u32,
frame_size: usize,
audio: bool,
) -> Result<Box<dyn FrameSource>> {
if !synthetic {
bail!("only synthetic frames are available yet: pass --synthetic");
}
Ok(Box::new(SyntheticSource::new(fps, frame_size, audio)))
}
/// What woke the driver.
enum Wake {
/// Connection or peer activity; the new events are returned by `flush`.
Stream,
Tick,
Line(Option<String>),
Interrupted,
Deadline,
}
/// Runs the stream sessions on the connection.
struct Driver {
streams: Streams,
/// Stream commands waiting for the server's answer.
pending: HashMap<MessageHandle, Request>,
}
impl Driver {
/// Wait for the next input and handle it.
async fn next(
&mut self,
con: &mut Connection,
deadline: Option<Instant>,
tick: Option<&mut Interval>,
lines: Option<&mut Lines<BufReader<Stdin>>>,
) -> Result<Wake> {
let item = {
let mut events = con.events();
let deadline = async {
match deadline {
Some(d) => sleep_until(d).await,
None => future::pending().await,
}
};
let tick = async {
match tick {
Some(t) => t.tick().await,
None => future::pending().await,
}
};
let line = async {
match lines {
Some(l) => l.next_line().await,
None => future::pending().await,
}
};
tokio::select! {
item = events.next() => item,
() = self.streams.wait_peers() => return Ok(Wake::Stream),
_ = tick => return Ok(Wake::Tick),
line = line => return Ok(Wake::Line(line?)),
_ = tokio::signal::ctrl_c() => return Ok(Wake::Interrupted),
() = deadline => return Ok(Wake::Deadline),
}
};
match item {
None => bail!("disconnected from server"),
Some(item) => self.item(con, item?).await?,
}
Ok(Wake::Stream)
}
async fn item(&mut self, con: &mut Connection, item: StreamItem) -> Result<()> {
match item {
StreamItem::MessageEvent(msg) => {
for n in StreamNotification::from_message(&msg) {
self.streams.handle_notification(n).await;
}
}
StreamItem::MessageResult(handle, result) => {
if let (Some(request), Err(e)) = (self.pending.remove(&handle), result) {
self.streams.request_failed(&request, &e.to_string());
}
}
StreamItem::BookEvents(events) => {
let state = con.get_state()?;
for e in &events {
if let Event::PropertyChanged {
id: PropertyId::ClientIsStreaming(clid), ..
} = e && let Some(streaming) =
state.clients.get(clid).and_then(|c| c.is_streaming)
{
self.streams.set_client_streaming(*clid, streaming);
}
}
self.streams.retain_streamers(|c| state.clients.contains_key(&c));
}
_ => {}
}
Ok(())
}
/// Send the sessions' requests; returns their events.
fn flush(&mut self, con: &mut Connection) -> Result<Vec<StreamEvent>> {
let mut events = Vec::new();
while let Some(output) = self.streams.poll_output() {
match output {
Output::Request(request) => {
let handle = request.to_command().send_with_result(con)?;
self.pending.insert(handle, request);
}
Output::Event(e) => events.push(e),
}
}
Ok(events)
}
/// Stop streaming and watching; wait briefly for the server's answers.
async fn finish(&mut self, con: &mut Connection) {
self.streams.close();
if self.flush(con).is_err() {
return;
}
let deadline = Instant::now() + Duration::from_secs(3);
while !self.pending.is_empty() {
match self.next(con, Some(deadline), None, None).await {
Ok(Wake::Stream) => {
if self.flush(con).is_err() {
return;
}
}
_ => return,
}
}
}
}
fn nick(con: &Connection, client: ClientId) -> String {
con.get_state()
.ok()
.and_then(|s| s.clients.get(&client).map(|c| c.name.clone()))
.unwrap_or_else(|| "?".into())
}
fn end_text(reason: &EndReason) -> String {
match reason {
EndReason::Local => "stopped".into(),
EndReason::Denied => "denied by the streamer".into(),
EndReason::Stopped => "the stream was stopped".into(),
EndReason::Removed(reason) => format!("removed by the streamer ({reason:?})"),
EndReason::Failed(e) => format!("failed: {e}"),
}
}
async fn start(
con: &mut Connection,
driver: &mut Driver,
options: StreamerOptions,
mut source: Box<dyn FrameSource>,
length: Option<Duration>,
) -> Result<()> {
let auto_accept = options.auto_accept;
driver.streams.start(options)?;
let deadline = length.map(|l| Instant::now() + l);
let mut tick = tokio::time::interval(source.interval());
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut lines = (!auto_accept).then(|| BufReader::new(tokio::io::stdin()).lines());
let (mut live, mut video, mut audio) = (false, 0u64, 0u64);
let mut frames = Vec::new();
loop {
let wake = driver.next(con, deadline, live.then_some(&mut tick), lines.as_mut()).await?;
match wake {
Wake::Stream => {}
Wake::Tick => {
source.poll_frames(std::time::Instant::now(), &mut frames);
let connected =
driver.streams.streamer().is_some_and(|s| s.has_connected_viewers());
for frame in frames.drain(..) {
if connected {
match frame.kind {
MediaKind::Video => video += 1,
MediaKind::Audio => audio += 1,
}
}
driver.streams.write_frame(&frame);
}
}
Wake::Line(None) => lines = None,
Wake::Line(Some(line)) => {
if let Err(e) = command_line(driver, &line).await {
println!("{e}");
}
}
Wake::Interrupted | Wake::Deadline => {
driver.streams.stop()?;
}
}
for event in driver.flush(con)? {
let StreamEvent::Streamer(event) = event else { continue };
match event {
StreamerEvent::Live { id } => {
live = true;
println!("stream {id} is live");
}
StreamerEvent::Request { viewer, message } => {
println!(
"{} (clid {}) asks to watch: {message:?}; type `accept {}` or `deny {}`",
nick(con, viewer),
viewer.0,
viewer.0,
viewer.0
);
}
StreamerEvent::Viewers(viewers) => {
let list: Vec<String> = viewers
.iter()
.map(|v| {
format!("{} (clid {}, {:?})", nick(con, v.client), v.client.0, v.state)
})
.collect();
println!("viewers: [{}]", list.join(", "));
}
StreamerEvent::KeyframeRequest => source.request_keyframe(),
StreamerEvent::Ended(reason) => {
println!("sent {video} video / {audio} audio frames to connected viewers");
return match reason {
EndReason::Local => Ok(()),
other => bail!("stream ended: {}", end_text(&other)),
};
}
}
}
}
}
/// `accept <clid>`, `deny <clid>`, `kick <clid>`, `stop` while streaming.
async fn command_line(driver: &mut Driver, line: &str) -> Result<()> {
let mut words = line.split_whitespace();
let command = words.next().unwrap_or_default();
let client = words.next().and_then(|w| w.parse().ok()).map(ClientId);
match (command, client) {
("accept", Some(c)) => driver.streams.respond(c, true).await?,
("deny", Some(c)) => driver.streams.respond(c, false).await?,
("kick", Some(c)) => driver.streams.kick(c)?,
("stop" | "quit", _) => driver.streams.stop()?,
("", _) => {}
_ => bail!("commands: accept <clid>, deny <clid>, kick <clid>, stop"),
}
Ok(())
}
async fn list(con: &mut Connection, driver: &mut Driver, settle: Duration) -> Result<()> {
let deadline = Instant::now() + settle;
loop {
match driver.next(con, Some(deadline), None, None).await? {
Wake::Deadline | Wake::Interrupted => break,
_ => {
driver.flush(con)?;
}
}
}
let streams: Vec<&StreamInfo> = driver.streams.directory().iter().collect();
for s in &streams {
println!(
"{} {:?} by {} (clid {}), {} kbit/s{}",
s.id,
s.name,
nick(con, s.streamer),
s.streamer.0,
s.bitrate,
if s.audio { ", audio" } else { "" }
);
}
// Streams that started before we connected are only known by the flag.
let state = con.get_state()?;
let mut unannounced = 0;
for c in state.clients.values() {
if c.is_streaming == Some(true) && !streams.iter().any(|s| s.streamer == c.id) {
println!("? {} (clid {}) is streaming; id not announced to us", c.name, c.id.0);
unannounced += 1;
}
}
if streams.is_empty() && unannounced == 0 {
println!("no streams");
}
Ok(())
}
struct Target {
id: Option<String>,
streamer_nick: Option<String>,
}
impl Target {
/// The stream to watch and its streamer, once known.
fn find(&self, con: &Connection, streams: &Streams) -> Option<(String, ClientId)> {
let state = con.get_state().ok()?;
let streamer = match &self.streamer_nick {
Some(nick) => Some(state.clients.values().find(|c| c.name == *nick)?.id),
None => None,
};
let own = streams.own_client();
let found = streams.directory().iter().find(|s| {
s.streamer != own
&& self.id.as_ref().is_none_or(|id| *id == s.id)
&& streamer.is_none_or(|c| c == s.streamer)
});
if let Some(s) = found {
return Some((s.id.clone(), s.streamer));
}
// A known id of a stream that was not announced to us: its streamer
// is the named client, or the only other client that streams.
let id = self.id.clone()?;
let streamer = streamer.or_else(|| {
let mut streaming = state
.clients
.values()
.filter(|c| c.id != own && c.is_streaming == Some(true))
.map(|c| c.id);
let first = streaming.next()?;
streaming.next().is_none().then_some(first)
})?;
Some((id, streamer))
}
}
async fn watch(
con: &mut Connection,
driver: &mut Driver,
target: &Target,
expect: Option<u64>,
timeout: Option<Duration>,
) -> Result<()> {
let deadline = timeout.map(|t| Instant::now() + t);
let mut watching: Option<String> = None;
let (mut video, mut audio) = (0u64, 0u64);
let mut codec = None;
let mut waiting_told = false;
loop {
if watching.is_none() {
if let Some((id, streamer)) = target.find(con, &driver.streams) {
println!("watching {id} of {} (clid {})", nick(con, streamer), streamer.0);
driver.streams.watch_from(&id, streamer, "")?;
watching = Some(id);
} else if !waiting_told {
println!("waiting for a stream");
waiting_told = true;
}
}
for event in driver.flush(con)? {
let StreamEvent::Watch { id, event } = event else { continue };
if Some(&id) != watching.as_ref() {
continue;
}
match event {
WatchEvent::Accepted => println!("accepted, connecting"),
WatchEvent::Connected => println!("connected"),
WatchEvent::Frame(f) => {
match f.kind {
MediaKind::Video => video += 1,
MediaKind::Audio => audio += 1,
}
if f.kind == MediaKind::Video && codec.replace(f.codec).is_none() {
println!("first video frame ({:?}, {} bytes)", f.codec, f.data.len());
}
if expect.is_some_and(|n| video >= n) {
println!("received {video} video / {audio} audio frames");
return Ok(());
}
}
WatchEvent::Ended(reason) => {
println!("received {video} video / {audio} audio frames");
match expect {
Some(n) => bail!("{} before {n} video frames arrived", end_text(&reason)),
None => {
println!("{}", end_text(&reason));
return Ok(());
}
}
}
}
}
match driver.next(con, deadline, None, None).await? {
Wake::Deadline | Wake::Interrupted => {
println!("received {video} video / {audio} audio frames");
return match expect {
Some(n) => bail!("timed out waiting for {n} video frames"),
None => Ok(()),
};
}
_ => {}
}
}
}