tsc-stream: stream sessions and a frame-source seam

Streams drives one connection's TS6 streams without doing connection IO:
it takes stream notifications and app decisions, owns the str0m peers and
queues requests (to send as commands) and events.

- StreamerSession: setupstream, join requests (auto-accept or ask the
  app), one peer per viewer with the offer in respondjoinstreamrequest,
  answers and trickled candidates, withdrawal, reconnect (new offer as
  reconnectOffer), kick, stop (also before the stream went live),
  merged keyframe requests, frame fan-out to connected viewers
- ViewerSession: joinstreamrequest, answer the offer from the response or
  an offer/reconnectOffer signal, candidates, denial, stop, removal,
  leave, reconnect after a lost connection (up to three times)
- StreamDirectory: streams in the channel from notifications and
  client_is_streaming
- FrameSource + SyntheticSource: decodable 1x1 VP8 keyframes (padded)
  and Opus silence in real time, for tests and tsctl
- Peer: poll_event for driving many peers from one task; trickled local
  candidates carry the bundle mid

Transcript unit tests and an end-to-end test through a fake relay server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-25 19:48:06 +00:00
1 parent 0b1aa5664e
commit 8d8a8c5eab
5 files changed
+1971 -4

No files matched your search

+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};
+12 -4
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};
@@ -100,8 +101,9 @@ pub enum PeerEvent {
/// ICE and DTLS are up; media can flow.
Connected,
/// A candidate found after the SDP was sent (server reflexive), as an SDP
/// `candidate:` line for [`crate::Signal::IceCandidate`].
LocalCandidate(String),
/// `candidate:` line for [`crate::Signal::IceCandidate`], with the mid of
/// the first (bundled) media line.
LocalCandidate { candidate: String, mid: Option<String> },
/// A received frame (depacketized).
Media(MediaFrame),
/// The viewer asks for a keyframe.
@@ -225,6 +227,11 @@ impl Peer {
pub fn try_next_event(&mut self) -> Option<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 {
@@ -420,9 +427,10 @@ impl Task {
}
match Candidate::server_reflexive(mapped, pending.base, "udp") {
Ok(c) => {
let line = c.to_sdp_string();
let candidate = c.to_sdp_string();
let mid = self.mids.first().map(|(mid, _)| mid.to_string());
if self.rtc.add_local_candidate(c).is_some() {
let _ = self.events.send(PeerEvent::LocalCandidate(line));
let _ = self.events.send(PeerEvent::LocalCandidate { candidate, mid });
}
}
Err(e) => debug!("bad reflexive candidate {mapped}: {e}"),
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);
}
}
+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());
}