Streams: SRTP profile order, bandwidth estimation, simulcast layers

Official TeamSpeak 6 clients use AES_CM_128_HMAC_SHA1_80, while our peers
negotiated AES-256-GCM. PeerConfig::srtp_profiles now sets the order (default
AES_CM_128_HMAC_SHA1_80, then the GCM profiles for peers without it); a
DTLS provider wrapping str0m's dimpl DTLS applies it and records the
negotiated profile. It can be changed at runtime (Streams::set_srtp_profiles,
Command::SetSrtpProfiles) for new connections.

Streamer peers now run str0m's bandwidth estimation and pacer. Each viewer
gets the simulcast layer its estimate allows (down at once, up after 2 s
above the next layer's minimum plus 20%), switching at a keyframe of the new
layer, which is requested. Keyframe requests and bitrate targets (lowest
estimate of a layer's viewers) are per layer and reach the encoders
lock-free through LayerFeedback (StreamSink::take_layer_keyframes,
layer_bitrate). Peers that negotiate RID simulcast (PeerConfig::simulcast,
for SFUs/WHIP) get every layer with its RID. Layers can change while live.

voelinctl stream start takes --layer, --simulcast, --srtp and --placeholder
(layered synthetic frames without an encoder) and prints each viewer's
layer, estimate and SRTP profile.

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-27 03:56:35 +00:00
1 parent 8bb060167b
commit ede9c3941c
14 files changed
+2472 -172

No files matched your search

+49 -4
View File
@@ -39,7 +39,9 @@ use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, S
use crate::audio::{AudioEvent, AudioHandle, AudioIn};
pub use route::{ChatRoute, Dedup, route_chat};
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
use voelin_stream::{EncodedFrame, StreamInfo, StreamSetup, ViewerInfo};
use voelin_stream::{
EncodedFrame, LayerId, LayerSpec, SrtpProfile, StreamInfo, StreamSetup, ViewerInfo,
};
pub use voice::VoiceOptions;
pub type SessionId = u64;
@@ -149,6 +151,20 @@ pub enum Command {
session: SessionId,
frame: EncodedFrame,
},
/// The simulcast layers of our stream (empty: one layer at the setup's
/// bitrate). Applies to the live stream at once (viewers move to the
/// layers their bandwidth allows, keyframes are requested) and to streams
/// started later; the encoder must produce the same layers
/// (`media::StreamerConfig::layers`).
SetStreamLayers {
session: SessionId,
layers: Vec<LayerSpec>,
},
/// SRTP protection profiles for stream connections, in order of
/// preference (a user setting; empty: the default,
/// `SrtpProfile::DEFAULT_ORDER`). Applies to connections made from now
/// on, in all sessions and those started later.
SetSrtpProfiles(Vec<SrtpProfile>),
/// Watch a stream from [`Event::StreamsChanged`]. Frames arrive through
/// [`Engine::subscribe_frames`].
WatchStream {
@@ -283,9 +299,18 @@ pub enum Event {
session: SessionId,
viewers: Vec<ViewerInfo>,
},
/// A viewer needs a keyframe (also flagged on the [`StreamSink`]).
/// A viewer of simulcast layer `layer` (0 without simulcast) needs a
/// keyframe (also flagged on the [`StreamSink`]).
StreamKeyframeRequest {
session: SessionId,
layer: LayerId,
},
/// The bitrate target of a layer of our stream changed: the lowest
/// bandwidth estimate of its viewers (bit/s; also on the [`StreamSink`]).
StreamLayerBitrate {
session: SessionId,
layer: LayerId,
bitrate: u64,
},
/// A stream we watch.
WatchState {
@@ -342,6 +367,7 @@ async fn run(
) {
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
let mut settings = AudioSettings::default();
let mut srtp_profiles: Option<Vec<SrtpProfile>> = None;
let mut mic_test: Option<AudioHandle> = None;
while let Some(command) = commands.recv().await {
let id = match command {
@@ -359,6 +385,13 @@ async fn run(
mic_test = on.then(|| test_microphone(&settings, &events));
continue;
}
Command::SetSrtpProfiles(profiles) => {
for s in sessions.values() {
s.send(Command::SetSrtpProfiles(profiles.clone()));
}
srtp_profiles = Some(profiles);
continue;
}
ref command => command_session(command),
};
if matches!(command, Command::CloseSession { .. }) {
@@ -370,7 +403,16 @@ async fn run(
sessions
.entry(id)
.or_insert_with(|| {
session::SessionHandle::spawn(id, events.clone(), frames.clone(), settings.clone())
let s = session::SessionHandle::spawn(
id,
events.clone(),
frames.clone(),
settings.clone(),
);
if let Some(profiles) = &srtp_profiles {
s.send(Command::SetSrtpProfiles(profiles.clone()));
}
s
})
.send(command);
}
@@ -415,6 +457,7 @@ fn command_session(command: &Command) -> SessionId {
| Command::AcceptViewer { session, .. }
| Command::KickViewer { session, .. }
| Command::SendStreamFrame { session, .. }
| Command::SetStreamLayers { session, .. }
| Command::WatchStream { session, .. }
| Command::LeaveStream { session, .. }
| Command::RequestStreamKeyframe { session, .. }
@@ -422,7 +465,9 @@ fn command_session(command: &Command) -> SessionId {
| Command::SetClientVolume { session, .. }
| Command::SetClientMuted { session, .. }
| Command::CloseSession { session } => *session,
Command::SetAudioSettings(_) | Command::TestMicrophone { .. } => {
Command::SetAudioSettings(_)
| Command::SetSrtpProfiles(_)
| Command::TestMicrophone { .. } => {
unreachable!("engine-wide commands have no session")
}
}
+31 -3
View File
@@ -13,7 +13,7 @@ use crate::audio::{self, AudioEvent, 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::stream::{LayerSpec, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInput};
use crate::voice::{self, VoiceCmd, VoiceEvent};
use crate::{Command, Event, ObserveState, SessionId, SessionState, Source, VoiceState};
@@ -65,6 +65,11 @@ struct Session {
/// Streams of the voice connection (TeamSpeak 6 only).
streams: Option<StreamHandle>,
stream_peer: PeerConfig,
/// Simulcast layers of our stream, for the stream task.
stream_layers: Vec<LayerSpec>,
/// The SRTP profile setting (`Command::SetSrtpProfiles`), over the voice
/// options' `stream_peer`.
srtp_profiles: Option<Vec<SrtpProfile>>,
frames: broadcast::Sender<StreamFrame>,
/// `client_is_streaming` of the voice presence, as last told to the streams.
streaming_clients: BTreeMap<u16, Option<bool>>,
@@ -98,6 +103,8 @@ impl Session {
audio_settings,
streams: None,
stream_peer: PeerConfig::default(),
stream_layers: Vec::new(),
srtp_profiles: None,
frames,
streaming_clients: BTreeMap::new(),
open_chats: HashSet::new(),
@@ -164,6 +171,9 @@ impl Session {
let generation = self.next_generation();
self.nickname = options.nickname.clone();
self.stream_peer = options.stream_peer.clone();
if let Some(profiles) = &self.srtp_profiles {
self.stream_peer.srtp_profiles = profiles.clone();
}
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
self.audio = None;
@@ -317,6 +327,20 @@ impl Session {
Command::RequestStreamKeyframe { stream_id, .. } => {
self.stream_input(StreamInput::RequestKeyframe { stream_id });
}
// Kept for streams started later, also without a connection.
Command::SetStreamLayers { layers, .. } => {
self.stream_layers = layers.clone();
if let Some(s) = &self.streams {
s.send(StreamInput::Layers(layers));
}
}
Command::SetSrtpProfiles(profiles) => {
self.stream_peer.srtp_profiles = profiles.clone();
self.srtp_profiles = Some(profiles.clone());
if let Some(s) = &self.streams {
s.send(StreamInput::SrtpProfiles(profiles));
}
}
Command::CloseSession { .. } | Command::TestMicrophone { .. } => {}
}
}
@@ -439,7 +463,7 @@ impl Session {
if capabilities.streams
&& let Some((_, voice)) = &self.voice
{
self.streams = Some(StreamHandle::spawn(
let streams = StreamHandle::spawn(
self.id,
own_client,
self.stream_peer.clone(),
@@ -447,7 +471,11 @@ impl Session {
self.events.clone(),
self.frames.clone(),
self.audio.clone(),
));
);
if !self.stream_layers.is_empty() {
streams.send(StreamInput::Layers(self.stream_layers.clone()));
}
self.streams = Some(streams);
}
self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities });
self.reopen_relayed_chats();
+131 -29
View File
@@ -13,13 +13,13 @@ use tokio::sync::{broadcast, mpsc};
use tracing::debug;
use tsclientlib::ClientId;
pub use voelin_stream::{
Codec, EncodedFrame, EndReason, FrameSource, Frequency, LeaveReason, MediaFrame, MediaKind,
MediaTime, PeerConfig, StreamInfo, StreamKind, StreamSetup, SyntheticSource, VideoCodec,
ViewerInfo, ViewerState,
Codec, EncodedFrame, EndReason, FrameSource, Frequency, LayerId, LayerSet, LayerSpec,
LeaveReason, MediaFrame, MediaKind, MediaTime, PeerConfig, SrtpProfile, StreamInfo, StreamKind,
StreamSetup, SyntheticSource, VideoCodec, ViewerInfo, ViewerState,
};
use voelin_stream::{
Output, Request, StreamEvent, StreamNotification, StreamerEvent, StreamerOptions, Streams,
WatchEvent,
LayerFeedback, Output, Request, StreamEvent, StreamNotification, StreamerEvent,
StreamerOptions, Streams, WatchEvent,
};
use crate::audio::{AudioHandle, AudioIn};
@@ -60,12 +60,14 @@ pub struct StreamFrame {
pub frame: MediaFrame,
}
/// Hands encoded frames of our stream to the engine, e.g. from an encoder thread.
/// Hands encoded frames of our stream to the engine, e.g. from an encoder
/// thread, and tells the encoders what the viewers need per simulcast layer:
/// keyframes and bitrates. Those are read lock-free from the stream session.
#[derive(Clone)]
pub struct StreamSink {
tx: mpsc::UnboundedSender<StreamInput>,
live: Arc<AtomicBool>,
keyframe: Arc<AtomicBool>,
feedback: Arc<LayerFeedback>,
}
impl StreamSink {
@@ -74,23 +76,24 @@ impl StreamSink {
self.live.load(Ordering::Relaxed) && self.tx.send(StreamInput::Frame(frame)).is_ok()
}
/// Whether a viewer asked for a keyframe since the last call.
/// Whether a viewer asked for a keyframe of any layer since the last
/// call (or [`take_layer_keyframes`](Self::take_layer_keyframes)).
pub fn take_keyframe_request(&self) -> bool {
self.keyframe.swap(false, Ordering::Relaxed)
self.feedback.take_any_keyframe()
}
/// Adds to `layers` the simulcast layers viewers asked a keyframe for
/// since the last call.
pub fn take_layer_keyframes(&self, layers: &mut voelin_stream::LayerSet) {
if self.take_keyframe_request() {
layers.insert(0);
}
/// since the last call. Every layer is asked for when the stream goes live.
pub fn take_layer_keyframes(&self, layers: &mut LayerSet) {
self.feedback.take_keyframes(layers);
}
/// Bitrate (bit/s) the bandwidth estimates of `layer`'s viewers allow.
pub fn layer_bitrate(&self, layer: voelin_stream::LayerId) -> Option<u64> {
let _ = layer;
None
/// Bitrate (bit/s) the bandwidth estimates of `layer`'s viewers allow:
/// the lowest estimate of its viewers, at least
/// [`voelin_stream::session::MIN_VIDEO_BITRATE`], at most the layer's
/// `max_bitrate`. `None` while no viewer of the layer has an estimate.
pub fn layer_bitrate(&self, layer: LayerId) -> Option<u64> {
self.feedback.bitrate(layer)
}
pub fn is_live(&self) -> bool {
@@ -132,6 +135,10 @@ pub(crate) enum StreamInput {
RequestKeyframe {
stream_id: String,
},
/// Simulcast layers of our stream (now and for streams started later).
Layers(Vec<LayerSpec>),
/// SRTP profile order of new connections.
SrtpProfiles(Vec<SrtpProfile>),
Frame(EncodedFrame),
Notification(StreamNotification),
RequestFailed(Request, String),
@@ -166,6 +173,7 @@ impl StreamHandle {
tx: tx.clone(),
sink: None,
clients: BTreeMap::new(),
layers: Vec::new(),
};
tokio::spawn(task.run(rx));
Self { tx }
@@ -190,6 +198,8 @@ struct StreamTask {
sink: Option<StreamSink>,
/// Clients on the server and their `client_is_streaming`.
clients: BTreeMap<u16, Option<bool>>,
/// Simulcast layers of our stream (empty: one layer).
layers: Vec<LayerSpec>,
}
impl StreamTask {
@@ -218,12 +228,13 @@ impl StreamTask {
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, ..Default::default() })
.map(|()| {
StreamInput::Start { setup, auto_accept } => {
let layers = self.layers.clone();
let options = StreamerOptions { setup, auto_accept, layers, ..Default::default() };
self.streams.start(options).map(|()| {
self.emit(Event::StreamState { session, state: StreamState::Starting });
}),
})
}
StreamInput::Stop => self.streams.stop(),
StreamInput::Respond { viewer, accept } => {
self.streams.respond(ClientId(viewer), accept).await
@@ -237,6 +248,19 @@ impl StreamTask {
self.streams.request_keyframe(&stream_id);
Ok(())
}
StreamInput::Layers(layers) => {
self.layers = layers.clone();
// Without a stream they are used for the next one.
if self.streams.streamer().is_some() {
self.streams.set_layers(layers)
} else {
Ok(())
}
}
StreamInput::SrtpProfiles(profiles) => {
self.streams.set_srtp_profiles(profiles);
Ok(())
}
StreamInput::Frame(frame) => {
self.streams.write_frame(&frame);
Ok(())
@@ -289,10 +313,14 @@ impl StreamTask {
match event {
StreamEvent::Streams(streams) => self.emit(Event::StreamsChanged { session, streams }),
StreamEvent::Streamer(StreamerEvent::Live { id }) => {
let feedback = match self.streams.streamer() {
Some(s) => s.layer_feedback().clone(),
None => Arc::new(LayerFeedback::new()),
};
let sink = StreamSink {
tx: self.tx.clone(),
live: Arc::new(AtomicBool::new(true)),
keyframe: Arc::new(AtomicBool::new(true)),
feedback,
};
self.sink = Some(sink.clone());
self.emit(Event::StreamState { session, state: StreamState::Live { id, sink } });
@@ -303,11 +331,12 @@ impl StreamTask {
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 });
// The sink already has it (layer feedback).
StreamEvent::Streamer(StreamerEvent::KeyframeRequest { layer }) => {
self.emit(Event::StreamKeyframeRequest { session, layer });
}
StreamEvent::Streamer(StreamerEvent::LayerBitrate { layer, bitrate }) => {
self.emit(Event::StreamLayerBitrate { session, layer, bitrate });
}
StreamEvent::Streamer(StreamerEvent::Ended(reason)) => {
if let Some(sink) = self.sink.take() {
@@ -599,6 +628,79 @@ mod tests {
handles[1].send(StreamInput::Shutdown("bye".into()));
}
/// Simulcast layers and the SRTP setting through the stream tasks: the
/// viewer gets the top layer only, the sink carries keyframe requests and
/// the bitrate target per layer.
#[tokio::test(flavor = "multi_thread")]
async fn layers_through_stream_tasks() {
let (handles, mut rx, mut frames_rx) = pair(None);
let layers = vec![
LayerSpec { id: 0, min_bitrate: 800_000, ..LayerSpec::single(2_000_000) },
LayerSpec { id: 1, scale: 0.5, ..LayerSpec::single(500_000) },
];
// Set before the stream starts: kept for it.
handles[0].send(StreamInput::Layers(layers.clone()));
// The viewer is the DTLS server: its order decides.
handles[1].send(StreamInput::SrtpProfiles(vec![SrtpProfile::AeadAes128Gcm]));
let sink = live_and_watching(&handles, &mut rx).await;
let mut keyframes = LayerSet::new();
sink.take_layer_keyframes(&mut keyframes);
assert!(keyframes.contains(0), "{keyframes:?}");
let feeder = tokio::spawn({
let sink = sink.clone();
async move {
let mut source = SyntheticSource::with_layers(30, 0, true, &layers);
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 = 0;
timeout(Duration::from_secs(10), async {
while video < 20 {
let f = frames_rx.recv().await.unwrap();
if f.frame.kind == MediaKind::Video {
assert_eq!(SyntheticSource::frame_layer(&f.frame.data), Some(0));
video += 1;
}
}
})
.await
.expect("no frames");
// Bandwidth estimates reach the viewer list and the layer's target.
let (mut info, mut bitrate) = (None, None);
wait(&mut rx, |e| {
match e {
Event::StreamViewers { session: 1, viewers } if viewers[0].estimate.is_some() => {
info = Some(viewers[0].clone());
}
Event::StreamLayerBitrate { session: 1, layer: 0, bitrate: b } => bitrate = Some(b),
_ => {}
}
(info.is_some() && bitrate.is_some()).then_some(())
})
.await;
let info = info.unwrap();
assert_eq!(info.layer, Some(0));
assert_eq!(info.srtp_profile, Some(SrtpProfile::AeadAes128Gcm));
assert!(sink.layer_bitrate(0).is_some_and(|b| b > 0));
assert_eq!(sink.layer_bitrate(1), None, "no viewer on layer 1");
handles[0].send(StreamInput::Stop);
wait(&mut rx, |e| match e {
Event::WatchState { session: 2, state: WatchState::Ended(_), .. } => Some(()),
_ => None,
})
.await;
feeder.await.unwrap();
}
/// The whole path: test pattern → VP8 → stream task → str0m peers on
/// loopback → the viewer's frame bus → decoder. The pictures show the
/// moving rectangle.