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 37d52bc604
commit f032e4b2d2
14 files changed
+2472 -172

No files matched your search

Generated
+1
View File
@@ -9244,6 +9244,7 @@ name = "voelin-stream"
version = "0.1.0"
dependencies = [
"anyhow",
"dimpl",
"futures",
"serde",
"serde_json",
+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.
+3
View File
@@ -9,6 +9,9 @@ repository.workspace = true
publish.workspace = true
[dependencies]
# DTLS with our SRTP profile order (third_party/dimpl, see its VOELIN-PATCH.md),
# with the features str0m's aws-lc-rs provider uses.
dimpl = { version = "0.7.4", default-features = false, features = ["aws-lc-rs", "rcgen"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
str0m = { version = "0.23.1", default-features = false, features = ["aws-lc-rs"] }
+303
View File
@@ -0,0 +1,303 @@
//! DTLS for our peers: str0m's dimpl DTLS (aws-lc-rs), configured with our
//! order of SRTP protection profiles.
//!
//! str0m takes its DTLS implementation from a [`CryptoProvider`], whose DTLS
//! part builds a dimpl `Config` we cannot change. [`crypto_provider`]
//! returns str0m's aws-lc-rs provider with that part replaced by
//! [`VoelinDtlsProvider`], which passes our profile order to dimpl (vendored
//! with a patch for it, see `third_party/dimpl/VOELIN-PATCH.md`).
//!
//! Its DTLS instances also record the profile the handshake negotiated,
//! which str0m does not expose: [`build_rtc`] returns it as a
//! [`NegotiatedProfile`].
use std::cell::RefCell;
use std::fmt;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Instant;
use str0m::crypto::dtls::{
DtlsCert, DtlsImplError, DtlsInstance, DtlsOutput, DtlsProvider, DtlsVersion, ProtocolVersion,
};
use str0m::crypto::{CryptoError, CryptoProvider};
use str0m::{Rtc, RtcConfig};
/// An SRTP protection profile (RFC 5764, RFC 7714).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SrtpProfile {
/// `AES_CM_128_HMAC_SHA1_80`: what official TeamSpeak clients use.
Aes128CmSha1_80,
/// `AEAD_AES_128_GCM`
AeadAes128Gcm,
/// `AEAD_AES_256_GCM`
AeadAes256Gcm,
}
impl SrtpProfile {
/// All profiles, in our default order of preference.
pub const ALL: [Self; 3] = [Self::Aes128CmSha1_80, Self::AeadAes128Gcm, Self::AeadAes256Gcm];
/// Our default order: AES_CM_128_HMAC_SHA1_80 first, as between official
/// clients, then the GCM profiles for peers that do not offer it.
pub const DEFAULT_ORDER: [Self; 3] = Self::ALL;
/// The profile's name as in RFC 5764/7714 and WebRTC statistics
/// (`srtpCipher`).
pub fn name(self) -> &'static str {
match self {
Self::Aes128CmSha1_80 => "AES_CM_128_HMAC_SHA1_80",
Self::AeadAes128Gcm => "AEAD_AES_128_GCM",
Self::AeadAes256Gcm => "AEAD_AES_256_GCM",
}
}
/// From [`name`](Self::name), or the `SRTP_...` names of RFC 5764's
/// registry and dimpl (`SRTP_AES128_CM_HMAC_SHA1_80`,
/// `SRTP_AES128_CM_SHA1_80`, `SRTP_AEAD_AES_128_GCM`, ...); ASCII case
/// is ignored.
pub fn from_name(name: &str) -> Option<Self> {
let name = name.trim().to_ascii_uppercase();
let name = name.strip_prefix("SRTP_").unwrap_or(&name);
match name {
"AES_CM_128_HMAC_SHA1_80" | "AES128_CM_HMAC_SHA1_80" | "AES128_CM_SHA1_80" => {
Some(Self::Aes128CmSha1_80)
}
"AEAD_AES_128_GCM" => Some(Self::AeadAes128Gcm),
"AEAD_AES_256_GCM" => Some(Self::AeadAes256Gcm),
_ => None,
}
}
fn to_dimpl(self) -> dimpl::SrtpProfile {
match self {
Self::Aes128CmSha1_80 => dimpl::SrtpProfile::AES128_CM_SHA1_80,
Self::AeadAes128Gcm => dimpl::SrtpProfile::AEAD_AES_128_GCM,
Self::AeadAes256Gcm => dimpl::SrtpProfile::AEAD_AES_256_GCM,
}
}
fn from_dimpl(profile: dimpl::SrtpProfile) -> Option<Self> {
Self::ALL.into_iter().find(|p| p.to_dimpl() == profile)
}
fn code(self) -> u8 {
match self {
Self::Aes128CmSha1_80 => 1,
Self::AeadAes128Gcm => 2,
Self::AeadAes256Gcm => 3,
}
}
fn from_code(code: u8) -> Option<Self> {
Self::ALL.into_iter().find(|p| p.code() == code)
}
}
impl fmt::Display for SrtpProfile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
/// The SRTP profile a peer connection's DTLS handshake negotiated; unset
/// until the handshake is done.
#[derive(Clone, Debug, Default)]
pub struct NegotiatedProfile(Arc<AtomicU8>);
impl NegotiatedProfile {
pub fn get(&self) -> Option<SrtpProfile> {
SrtpProfile::from_code(self.0.load(Ordering::Relaxed))
}
fn set(&self, profile: SrtpProfile) {
self.0.store(profile.code(), Ordering::Relaxed);
}
}
/// str0m's DTLS (dimpl with aws-lc-rs) with our SRTP profile order.
#[derive(Debug)]
pub struct VoelinDtlsProvider {
profiles: Vec<dimpl::SrtpProfile>,
}
impl VoelinDtlsProvider {
fn new(order: &[SrtpProfile]) -> Self {
Self { profiles: order.iter().map(|p| p.to_dimpl()).collect() }
}
}
thread_local! {
/// Where the next DTLS instance built on this thread records its
/// profile; set by [`build_rtc`] around `RtcConfig::build`, which
/// creates the instance synchronously.
static NEXT_PROFILE: RefCell<Option<NegotiatedProfile>> = const { RefCell::new(None) };
}
impl DtlsProvider for VoelinDtlsProvider {
fn generate_certificate(&self) -> Option<DtlsCert> {
dimpl::certificate::generate_self_signed_certificate().ok()
}
fn new_dtls(
&self,
cert: &DtlsCert,
now: Instant,
dtls_version: DtlsVersion,
mtu: Option<usize>,
) -> Result<Box<dyn DtlsInstance>, CryptoError> {
// As str0m's own provider: ICE already verified the peer's address,
// so server cookies are redundant.
let mut builder =
dimpl::Config::builder().use_server_cookie(false).srtp_profiles(&self.profiles);
if let Some(mtu) = mtu {
builder = builder.mtu(mtu);
}
let config = Arc::new(
builder.build().map_err(|e| CryptoError::Other(format!("dimpl config: {e}")))?,
);
let cert = cert.clone();
let dtls = match dtls_version {
DtlsVersion::Dtls12 => dimpl::Dtls::new_12(config, cert, now),
DtlsVersion::Dtls13 => dimpl::Dtls::new_13(config, cert, now),
DtlsVersion::Auto => dimpl::Dtls::new_auto(config, cert, now),
other => return Err(CryptoError::Other(format!("unsupported DTLS version {other}"))),
};
let profile = NEXT_PROFILE.with(|next| next.borrow_mut().take()).unwrap_or_default();
Ok(Box::new(Instance { dtls, profile }))
}
}
struct Instance {
dtls: dimpl::Dtls,
profile: NegotiatedProfile,
}
impl fmt::Debug for Instance {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("VoelinDtlsInstance").field("profile", &self.profile.get()).finish()
}
}
impl DtlsInstance for Instance {
fn set_active(&mut self, active: bool) {
self.dtls.set_active(active);
}
fn handle_packet(&mut self, packet: &[u8]) -> Result<(), DtlsImplError> {
self.dtls.handle_packet(packet)
}
fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> DtlsOutput<'a> {
let output = self.dtls.poll_output(buf);
if let DtlsOutput::KeyingMaterial(_, profile) = &output
&& let Some(profile) = SrtpProfile::from_dimpl(*profile)
{
self.profile.set(profile);
}
output
}
fn handle_timeout(&mut self, now: Instant) -> Result<(), DtlsImplError> {
self.dtls.handle_timeout(now)
}
fn send_application_data(&mut self, data: &[u8]) -> Result<(), DtlsImplError> {
self.dtls.send_application_data(data)
}
fn is_active(&self) -> bool {
self.dtls.is_active()
}
fn protocol_version(&self) -> Option<ProtocolVersion> {
self.dtls.protocol_version()
}
fn is_closing(&self) -> bool {
self.dtls.is_closing()
}
fn is_closed(&self) -> bool {
self.dtls.is_closed()
}
fn close(&mut self) -> Result<(), DtlsImplError> {
self.dtls.close()
}
}
/// str0m's aws-lc-rs crypto with [`VoelinDtlsProvider`] for `order` (our
/// default order if empty). One provider per distinct order is created and
/// kept for the process (str0m needs `'static` providers); there are at most
/// 15 distinct orders of the three profiles.
pub fn crypto_provider(order: &[SrtpProfile]) -> Arc<CryptoProvider> {
static PROVIDERS: Mutex<Vec<(Vec<SrtpProfile>, Arc<CryptoProvider>)>> = Mutex::new(Vec::new());
let mut key: Vec<SrtpProfile> = Vec::with_capacity(SrtpProfile::ALL.len());
for p in order {
if !key.contains(p) {
key.push(*p);
}
}
if key.is_empty() {
key.extend(SrtpProfile::DEFAULT_ORDER);
}
let mut providers = PROVIDERS.lock().unwrap_or_else(PoisonError::into_inner);
if let Some((_, provider)) = providers.iter().find(|(k, _)| *k == key) {
return provider.clone();
}
let dtls: &'static VoelinDtlsProvider = Box::leak(Box::new(VoelinDtlsProvider::new(&key)));
let provider =
Arc::new(CryptoProvider { dtls_provider: dtls, ..str0m::crypto::from_feature_flags() });
providers.push((key, provider.clone()));
provider
}
/// Build an RTC with our DTLS for `order`; also returns where its DTLS
/// handshake records the negotiated SRTP profile.
pub fn build_rtc(config: RtcConfig, order: &[SrtpProfile]) -> (Rtc, NegotiatedProfile) {
let profile = NegotiatedProfile::default();
NEXT_PROFILE.with(|next| *next.borrow_mut() = Some(profile.clone()));
let rtc = config.set_crypto_provider(crypto_provider(order)).build(Instant::now());
// Normally taken by `new_dtls` already.
NEXT_PROFILE.with(|next| next.borrow_mut().take());
(rtc, profile)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names() {
for p in SrtpProfile::ALL {
assert_eq!(SrtpProfile::from_name(p.name()), Some(p));
assert_eq!(SrtpProfile::from_dimpl(p.to_dimpl()), Some(p));
assert_eq!(SrtpProfile::from_code(p.code()), Some(p));
}
assert_eq!(
SrtpProfile::from_name("srtp_aes128_cm_sha1_80"),
Some(SrtpProfile::Aes128CmSha1_80)
);
assert_eq!(
SrtpProfile::from_name("SRTP_AES128_CM_HMAC_SHA1_80"),
Some(SrtpProfile::Aes128CmSha1_80)
);
assert_eq!(
SrtpProfile::from_name("SRTP_AEAD_AES_256_GCM"),
Some(SrtpProfile::AeadAes256Gcm)
);
assert_eq!(SrtpProfile::from_name("AES_CM_128_HMAC_SHA1_32"), None);
assert_eq!(SrtpProfile::Aes128CmSha1_80.to_string(), "AES_CM_128_HMAC_SHA1_80");
}
#[test]
fn providers_are_shared_per_order() {
let a = crypto_provider(&[SrtpProfile::AeadAes128Gcm, SrtpProfile::AeadAes128Gcm]);
let b = crypto_provider(&[SrtpProfile::AeadAes128Gcm]);
assert!(Arc::ptr_eq(&a, &b));
let default = crypto_provider(&[]);
assert!(Arc::ptr_eq(&default, &crypto_provider(&SrtpProfile::DEFAULT_ORDER)));
assert!(!Arc::ptr_eq(&a, &default));
}
}
+163
View File
@@ -0,0 +1,163 @@
//! Feedback from the stream sessions to the encoders of our stream's layers:
//! keyframe requests and bitrate targets per [`LayerId`].
//!
//! [`LayerFeedback`] is shared between the stream session (which writes) and
//! encoder threads (which read every frame). Both sides only use atomics;
//! the keyframe requests are a bitmap over all layer ids, the bitrate targets
//! a table whose parts are allocated when a layer list is prepared, so
//! nothing allocates per frame and any `u16` layer id works.
use std::array;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU16, AtomicU64, Ordering};
use crate::layer::{LayerId, LayerSet};
/// Words of the keyframe bitmap: one bit per layer id.
const WORDS: usize = (LayerId::MAX as usize + 1) / 64;
/// Summary words: one bit per bitmap word.
const SUMMARY: usize = WORDS / 64;
/// Layer ids per bitrate chunk.
const CHUNK: usize = 256;
/// Keyframe requests and bitrate targets per layer, see the module docs.
pub struct LayerFeedback {
/// Bit `l % 64` of word `l / 64`: layer `l` needs a keyframe.
words: Box<[AtomicU64]>,
/// Bit `w % 64` of `summary[w / 64]`: word `w` may have bits set.
summary: [AtomicU64; SUMMARY],
/// Bit `s`: `summary[s]` may have bits set.
top: AtomicU16,
/// Bitrate targets (bit/s, 0: none) in chunks of [`CHUNK`] layer ids.
bitrates: Box<[OnceLock<Box<[AtomicU64]>>]>,
}
impl Default for LayerFeedback {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for LayerFeedback {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LayerFeedback").finish_non_exhaustive()
}
}
impl LayerFeedback {
pub fn new() -> Self {
Self {
words: (0..WORDS).map(|_| AtomicU64::new(0)).collect(),
summary: array::from_fn(|_| AtomicU64::new(0)),
top: AtomicU16::new(0),
bitrates: (0..=LayerId::MAX as usize / CHUNK).map(|_| OnceLock::new()).collect(),
}
}
/// Allocate the bitrate slots of `layers`, so setting and reading their
/// targets never allocates.
pub fn prepare(&self, layers: impl IntoIterator<Item = LayerId>) {
for layer in layers {
self.chunk(layer);
}
}
fn chunk(&self, layer: LayerId) -> &[AtomicU64] {
self.bitrates[usize::from(layer) / CHUNK]
.get_or_init(|| (0..CHUNK).map(|_| AtomicU64::new(0)).collect())
}
/// A viewer of `layer` needs a keyframe.
pub fn request_keyframe(&self, layer: LayerId) {
let word = usize::from(layer) / 64;
self.words[word].fetch_or(1 << (layer % 64), Ordering::Release);
self.summary[word / 64].fetch_or(1 << (word % 64), Ordering::Release);
self.top.fetch_or(1 << (word / 64), Ordering::Release);
}
/// Call `f` with every layer a keyframe was requested for since the last
/// call, and forget the requests.
pub fn drain_keyframes(&self, mut f: impl FnMut(LayerId)) {
let mut top = self.top.swap(0, Ordering::AcqRel);
while top != 0 {
let s = top.trailing_zeros() as usize;
top &= top - 1;
let mut summary = self.summary[s].swap(0, Ordering::AcqRel);
while summary != 0 {
let w = s * 64 + summary.trailing_zeros() as usize;
summary &= summary - 1;
let mut bits = self.words[w].swap(0, Ordering::AcqRel);
while bits != 0 {
f((w * 64 + bits.trailing_zeros() as usize) as LayerId);
bits &= bits - 1;
}
}
}
}
/// Add the layers a keyframe was requested for to `layers`.
pub fn take_keyframes(&self, layers: &mut LayerSet) {
self.drain_keyframes(|l| {
layers.insert(l);
});
}
/// Whether a keyframe was requested for any layer; forgets the requests.
pub fn take_any_keyframe(&self) -> bool {
let mut any = false;
self.drain_keyframes(|_| any = true);
any
}
/// Set the bitrate target of `layer`; `None`: no target (no viewer with
/// an estimate).
pub fn set_bitrate(&self, layer: LayerId, bitrate: Option<u64>) {
let slot = &self.chunk(layer)[usize::from(layer) % CHUNK];
slot.store(bitrate.map_or(0, |b| b.max(1)), Ordering::Relaxed);
}
/// The bitrate target of `layer` (bit/s).
pub fn bitrate(&self, layer: LayerId) -> Option<u64> {
let chunk = self.bitrates[usize::from(layer) / CHUNK].get()?;
let bitrate = chunk[usize::from(layer) % CHUNK].load(Ordering::Relaxed);
(bitrate != 0).then_some(bitrate)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keyframes() {
let f = LayerFeedback::new();
assert!(!f.take_any_keyframe());
for l in [0, 1, 63, 64, 4095, 4096, LayerId::MAX, 1] {
f.request_keyframe(l);
}
let mut set = LayerSet::new();
f.take_keyframes(&mut set);
assert_eq!(set.iter().collect::<Vec<_>>(), [0, 1, 63, 64, 4095, 4096, LayerId::MAX]);
set.clear();
f.take_keyframes(&mut set);
assert!(set.is_empty());
f.request_keyframe(7);
assert!(f.take_any_keyframe());
assert!(!f.take_any_keyframe());
}
#[test]
fn bitrates() {
let f = LayerFeedback::new();
assert_eq!(f.bitrate(3), None);
f.prepare([3, 300]);
assert_eq!(f.bitrate(3), None);
f.set_bitrate(3, Some(1_500_000));
f.set_bitrate(LayerId::MAX, Some(u64::MAX));
assert_eq!(f.bitrate(3), Some(1_500_000));
assert_eq!(f.bitrate(LayerId::MAX), Some(u64::MAX));
assert_eq!(f.bitrate(300), None);
f.set_bitrate(3, None);
assert_eq!(f.bitrate(3), None);
}
}
+6 -2
View File
@@ -9,6 +9,8 @@
//! 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 dtls;
pub mod feedback;
pub mod layer;
pub mod peer;
pub mod proto;
@@ -17,8 +19,10 @@ pub mod signal;
pub mod source;
pub mod stun;
pub use dtls::SrtpProfile;
pub use feedback::LayerFeedback;
pub use layer::{LayerId, LayerSet, LayerSpec};
pub use peer::{MediaFrame, Peer, PeerConfig, PeerError, PeerEvent, VideoCodec};
pub use peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerError, PeerEvent, VideoCodec};
pub use proto::{LeaveReason, StreamInfo, StreamKind, StreamNotification, StreamSetup};
pub use session::{
EndReason, Output, Request, SessionError, StreamDirectory, StreamEvent, StreamerEvent,
@@ -27,4 +31,4 @@ pub use session::{
pub use signal::{Signal, SignalError};
pub use source::{EncodedFrame, FrameSource, SyntheticSource};
pub use str0m::format::Codec;
pub use str0m::media::{Frequency, MediaKind, MediaTime};
pub use str0m::media::{Frequency, MediaKind, MediaTime, Rid};
+253 -31
View File
@@ -4,6 +4,12 @@
//! viewer and sends its offer through the server; the viewer answers. Host
//! candidates go into the SDP; server-reflexive candidates found through STUN
//! are reported later as [`PeerEvent::LocalCandidate`] for trickling.
//!
//! DTLS negotiates the SRTP profile in the order of
//! [`PeerConfig::srtp_profiles`] (see [`crate::dtls`]). A streamer's peer
//! estimates the bandwidth to its viewer and paces its packets
//! ([`PeerConfig::bandwidth_estimation`], [`PeerEvent::BitrateEstimate`]),
//! and can offer RID simulcast ([`PeerConfig::simulcast`]).
use std::collections::HashMap;
use std::hash::{BuildHasher, RandomState};
@@ -12,17 +18,27 @@ use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use str0m::bwe::{Bitrate, BweKind};
use str0m::change::{SdpAnswer, SdpOffer, SdpPendingOffer};
use str0m::format::Codec;
use str0m::media::{Direction, KeyframeRequestKind, MediaKind, MediaTime, Mid, Pt};
use str0m::media::{
Direction, KeyframeRequestKind, MediaKind, MediaTime, Mid, Pt, Rid, Rids, Simulcast,
SimulcastLayer,
};
use str0m::net::{Protocol, Receive};
use str0m::{Candidate, Event, IceConnectionState, Input, Output, Rtc, RtcConfig, RtcError};
use tokio::net::UdpSocket;
use tokio::sync::{mpsc, oneshot};
use tracing::{debug, trace, warn};
use crate::dtls::{self, NegotiatedProfile, SrtpProfile};
use crate::layer::LayerSpec;
use crate::stun;
/// Initial bandwidth estimate of a streamer's peer without
/// [`OfferOptions::start_bitrate`].
pub const DEFAULT_START_BITRATE: u64 = 1_000_000;
/// Video codecs a peer can negotiate.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VideoCodec {
@@ -74,6 +90,23 @@ pub struct PeerConfig {
pub accept_video_codecs: Vec<VideoCodec>,
pub video: bool,
pub audio: bool,
/// SRTP protection profiles in order of preference. As DTLS server (our
/// role with official TeamSpeak clients and browsers, both as streamer
/// and as viewer) we pick the first of them the other side offers; as
/// DTLS client we offer them in this order. Empty: the default,
/// [`SrtpProfile::DEFAULT_ORDER`]. Applies to connections created after
/// a change.
pub srtp_profiles: Vec<SrtpProfile>,
/// A streamer's peers estimate the bandwidth to their viewer (transport-cc
/// feedback), report it ([`PeerEvent::BitrateEstimate`]) and pace their
/// packets to it.
pub bandwidth_estimation: bool,
/// A streamer offers RID simulcast (`a=simulcast`, one `a=rid` per layer
/// with a [`LayerSpec::rid`]) when it has at least two such layers. Only
/// for peers that support it (SFUs, WHIP servers): an answer without
/// simulcast leaves the peer unable to send video. Official TeamSpeak
/// viewers get a plain offer and one layer at a time.
pub simulcast: bool,
}
impl Default for PeerConfig {
@@ -85,6 +118,9 @@ impl Default for PeerConfig {
accept_video_codecs: VideoCodec::ALL.to_vec(),
video: true,
audio: true,
srtp_profiles: SrtpProfile::DEFAULT_ORDER.to_vec(),
bandwidth_estimation: true,
simulcast: false,
}
}
}
@@ -116,6 +152,20 @@ pub enum PeerError {
Closed,
}
/// How a streamer's peer starts ([`Peer::offer_with`]).
#[derive(Clone, Debug, Default)]
pub struct OfferOptions<'a> {
/// Initial bandwidth estimate in bit/s (with
/// [`PeerConfig::bandwidth_estimation`]); the pacer starts at twice it.
/// `None`: [`DEFAULT_START_BITRATE`].
pub start_bitrate: Option<u64>,
/// Bitrate the estimation probes up to, see
/// [`Peer::set_desired_bitrate`]. `None`: the start bitrate.
pub desired_bitrate: Option<u64>,
/// The stream's layers, for RID simulcast ([`PeerConfig::simulcast`]).
pub layers: &'a [LayerSpec],
}
/// Something that happened on the connection.
#[derive(Clone, Debug)]
pub enum PeerEvent {
@@ -127,8 +177,19 @@ pub enum PeerEvent {
LocalCandidate { candidate: String, mid: Option<String> },
/// A received frame (depacketized).
Media(MediaFrame),
/// A received frame of a RID simulcast layer.
LayerMedia { rid: Rid, frame: MediaFrame },
/// The viewer asks for a keyframe.
KeyframeRequest,
/// The viewer asks for a keyframe of a RID simulcast layer.
LayerKeyframeRequest(Rid),
/// The bandwidth estimate to the viewer changed (bit/s; streamer side,
/// with [`PeerConfig::bandwidth_estimation`]; from transport-cc
/// feedback, or REMB from a viewer that sends no transport-cc).
BitrateEstimate(u64),
/// The answer accepted RID simulcast: video goes out per layer with
/// these RIDs ([`Peer::write_rid`]).
Simulcast(Vec<Rid>),
/// The connection is gone.
Closed,
}
@@ -148,8 +209,9 @@ pub struct MediaFrame {
enum Cmd {
Answer(String, oneshot::Sender<Result<(), PeerError>>),
RemoteCandidate(String),
Write { kind: MediaKind, time: MediaTime, data: Arc<[u8]> },
Write { kind: MediaKind, time: MediaTime, data: Arc<[u8]>, rid: Option<Rid> },
RequestKeyframe,
DesiredBitrate(u64),
Close,
}
@@ -157,20 +219,38 @@ enum Cmd {
pub struct Peer {
cmd: mpsc::UnboundedSender<Cmd>,
events: mpsc::UnboundedReceiver<PeerEvent>,
srtp_profile: NegotiatedProfile,
}
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, &config.video_codecs);
Self::offer_with(config, stream_id, &OfferOptions::default()).await
}
/// [`offer`](Self::offer) with a start estimate for the bandwidth
/// estimation and the stream's layers (for RID simulcast).
pub async fn offer_with(
config: &PeerConfig,
stream_id: &str,
options: &OfferOptions<'_>,
) -> Result<(Self, String), PeerError> {
let start = options.start_bitrate.unwrap_or(DEFAULT_START_BITRATE).max(1);
let bwe = config.bandwidth_estimation.then_some(start);
let (mut rtc, srtp_profile) = build_rtc(config, &config.video_codecs, bwe);
if bwe.is_some() {
let desired = options.desired_bitrate.unwrap_or(start);
rtc.bwe().set_desired_bitrate(Bitrate::bps(desired));
}
let net = Net::bind(config, &mut rtc).await?;
let mut api = rtc.sdp_api();
let msid = Some(stream_id.to_owned());
let mut mids = Vec::new();
if config.video {
let simulcast = config.simulcast.then(|| simulcast_offer(options.layers)).flatten();
let mid =
api.add_media(MediaKind::Video, Direction::SendOnly, msid.clone(), None, None);
api.add_media(MediaKind::Video, Direction::SendOnly, msid.clone(), None, simulcast);
mids.push((mid, MediaKind::Video));
}
if config.audio {
@@ -179,7 +259,7 @@ impl Peer {
}
let (offer, pending) = api.apply().ok_or(PeerError::Sdp("nothing to offer".into()))?;
let sdp = offer.to_sdp_string();
Ok((Self::spawn(rtc, net, config, Some(pending), mids), sdp))
Ok((Self::spawn(rtc, net, config, Some(pending), mids, srtp_profile), sdp))
}
/// Viewer side: accept the streamer's offer; returns our SDP answer.
@@ -195,10 +275,11 @@ impl Peer {
}
}
let offer = SdpOffer::from_sdp_string(offer).map_err(|e| PeerError::Sdp(e.to_string()))?;
let mut rtc = build_rtc(config, &codecs);
let (mut rtc, srtp_profile) = build_rtc(config, &codecs, None);
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()))
let peer = Self::spawn(rtc, net, config, None, Vec::new(), srtp_profile);
Ok((peer, answer.to_sdp_string()))
}
fn spawn(
@@ -207,6 +288,7 @@ impl Peer {
config: &PeerConfig,
pending: Option<SdpPendingOffer>,
mids: Vec<(Mid, MediaKind)>,
srtp_profile: NegotiatedProfile,
) -> Self {
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, event_rx) = mpsc::unbounded_channel();
@@ -219,9 +301,10 @@ impl Peer {
mids,
writers: HashMap::new(),
stun: Vec::new(),
twcc: false,
};
tokio::spawn(task.run(config.stun_servers.clone()));
Self { cmd: cmd_tx, events: event_rx }
Self { cmd: cmd_tx, events: event_rx, srtp_profile }
}
/// Streamer side: apply the viewer's answer.
@@ -238,7 +321,13 @@ impl Peer {
/// Send one encoded frame (streamer). Dropped until connected.
pub fn write(&self, kind: MediaKind, time: MediaTime, data: impl Into<Arc<[u8]>>) {
let _ = self.cmd.send(Cmd::Write { kind, time, data: data.into() });
let _ = self.cmd.send(Cmd::Write { kind, time, data: data.into(), rid: None });
}
/// Send one video frame of the RID simulcast layer `rid`
/// ([`PeerEvent::Simulcast`]); `None` as [`write`](Self::write).
pub fn write_rid(&self, kind: MediaKind, time: MediaTime, data: Arc<[u8]>, rid: Option<Rid>) {
let _ = self.cmd.send(Cmd::Write { kind, time, data, rid });
}
/// Ask the streamer for a keyframe (viewer).
@@ -246,6 +335,17 @@ impl Peer {
let _ = self.cmd.send(Cmd::RequestKeyframe);
}
/// The bitrate (bit/s) the bandwidth estimation probes up to: what we
/// would send if the path allowed it.
pub fn set_desired_bitrate(&self, bitrate: u64) {
let _ = self.cmd.send(Cmd::DesiredBitrate(bitrate));
}
/// The SRTP profile DTLS negotiated, once it has.
pub fn srtp_profile(&self) -> Option<SrtpProfile> {
self.srtp_profile.get()
}
pub fn close(&self) {
let _ = self.cmd.send(Cmd::Close);
}
@@ -275,12 +375,43 @@ impl Drop for Peer {
/// 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);
/// The send simulcast of an offer: the layers with a RID, if at least two.
fn simulcast_offer(layers: &[LayerSpec]) -> Option<Simulcast> {
let mut simulcast = Simulcast::new();
for layer in layers {
let Some(rid) = layer.rid.as_deref() else { continue };
let id = Rid::from(rid);
if *id != *rid {
warn!(rid, sent = &*id, "RIDs are up to 8 letters, digits or _; the RID was changed");
}
if simulcast.send.iter().any(|l| l.rid == id) {
warn!(rid, "duplicate RID, layer not offered");
continue;
}
let mut builder = SimulcastLayer::new_with_attributes(&id);
if let Some((w, h)) = layer.size {
builder = builder.max_width(w).max_height(h);
}
if let Some(fps) = layer.max_fps {
builder = builder.max_fps(fps);
}
if let Some(max) = layer.max_bitrate {
builder = builder.max_br(u32::try_from(max).unwrap_or(u32::MAX));
}
simulcast.add_send_layer(builder.build());
}
(simulcast.send.len() >= 2).then_some(simulcast)
}
/// An RTC with Opus and `video` codecs, in this order of preference, our
/// DTLS, and bandwidth estimation starting at `bwe` bit/s if given.
fn build_rtc(
config: &PeerConfig,
video: &[VideoCodec],
bwe: Option<u64>,
) -> (Rtc, NegotiatedProfile) {
let mut rtc_config =
RtcConfig::new().clear_codecs().enable_opus(config.audio).enable_bwe(bwe.map(Bitrate::bps));
for codec in video {
rtc_config = match codec {
VideoCodec::Vp8 => rtc_config.enable_vp8(true),
@@ -298,7 +429,7 @@ fn build_rtc(config: &PeerConfig, video: &[VideoCodec]) -> Rtc {
VideoCodec::Av1 => rtc_config.enable_av1(true),
};
}
rtc_config.build(Instant::now())
dtls::build_rtc(rtc_config, &config.srtp_profiles)
}
/// The video codecs of the first video media line of `sdp`, in offered order.
@@ -423,6 +554,8 @@ struct Task {
/// Negotiated (mid, pt) for sending each media kind.
writers: HashMap<MediaKind, (Mid, Pt)>,
stun: Vec<PendingStun>,
/// A transport-cc estimate arrived: REMB is ignored from then on.
twcc: bool,
}
fn transaction_id() -> stun::TransactionId {
@@ -585,17 +718,37 @@ impl Task {
} else {
MediaKind::Video
};
let _ = self.events.send(PeerEvent::Media(MediaFrame {
let frame = MediaFrame {
kind,
codec: d.params.spec().codec,
time: d.time,
network_time: d.network_time,
contiguous: d.contiguous,
data: d.data,
}));
};
let _ = self.events.send(match d.rid {
Some(rid) => PeerEvent::LayerMedia { rid, frame },
None => PeerEvent::Media(frame),
});
}
Event::KeyframeRequest(_) => {
let _ = self.events.send(PeerEvent::KeyframeRequest);
Event::KeyframeRequest(r) => {
let _ = self.events.send(match r.rid {
Some(rid) => PeerEvent::LayerKeyframeRequest(rid),
None => PeerEvent::KeyframeRequest,
});
}
Event::EgressBitrateEstimate(estimate) => {
let bitrate = match estimate {
BweKind::Twcc(b) => {
self.twcc = true;
Some(b)
}
BweKind::Remb(_, b) if !self.twcc => Some(b),
_ => None,
};
if let Some(b) = bitrate {
let _ = self.events.send(PeerEvent::BitrateEstimate(b.as_u64()));
}
}
_ => {}
}
@@ -616,7 +769,7 @@ impl Task {
Err(e) => debug!("ignoring remote candidate {line:?}: {e}"),
}
}
Cmd::Write { kind, time, data } => self.write(kind, time, data)?,
Cmd::Write { kind, time, data, rid } => self.write(kind, time, data, rid),
Cmd::RequestKeyframe => {
for &(mid, _) in &self.mids {
if let Some(mut w) = self.rtc.writer(mid) {
@@ -624,6 +777,9 @@ impl Task {
}
}
}
Cmd::DesiredBitrate(bitrate) => {
self.rtc.bwe().set_desired_bitrate(Bitrate::bps(bitrate));
}
Cmd::Close => return Ok(false),
}
Ok(true)
@@ -633,27 +789,37 @@ impl Task {
let pending = self.pending.take().ok_or(PeerError::NotOffering)?;
let answer = SdpAnswer::from_sdp_string(sdp).map_err(|e| PeerError::Sdp(e.to_string()))?;
self.rtc.sdp_api().accept_answer(pending, answer)?;
// RID simulcast: the answer lists the layers it takes.
for &(mid, kind) in &self.mids {
if kind == MediaKind::Video
&& let Some(Rids::Specific(rids)) = self.rtc.media(mid).map(|m| m.rids_tx())
&& !rids.is_empty()
{
let _ = self.events.send(PeerEvent::Simulcast(rids.clone()));
}
}
Ok(())
}
fn write(
&mut self,
kind: MediaKind,
time: MediaTime,
data: Arc<[u8]>,
) -> Result<(), PeerError> {
/// A frame that cannot be sent (e.g. a RID the answer did not take) is
/// dropped; the connection stays.
fn write(&mut self, kind: MediaKind, time: MediaTime, data: Arc<[u8]>, rid: Option<Rid>) {
if !self.writers.contains_key(&kind) {
let Some((mid, pt)) = self.find_writer(kind) else {
trace!(?kind, "no negotiated media to write to");
return Ok(());
return;
};
self.writers.insert(kind, (mid, pt));
}
let (mid, pt) = self.writers[&kind];
if let Some(writer) = self.rtc.writer(mid) {
writer.write(pt, Instant::now(), time, data)?;
if let Some(mut writer) = self.rtc.writer(mid) {
if let Some(rid) = rid {
writer = writer.rid(rid);
}
if let Err(e) = writer.write(pt, Instant::now(), time, data) {
debug!(?kind, ?rid, "frame not sent: {e}");
}
}
Ok(())
}
fn find_writer(&mut self, kind: MediaKind) -> Option<(Mid, Pt)> {
@@ -705,4 +871,60 @@ mod tests {
let (_peer, answer) = Peer::answer(&vp8_only, &offer).await.unwrap();
assert_eq!(offered_video_codecs(&answer), [VideoCodec::Vp8], "{answer}");
}
/// The SDP lines that make up the media description (not the random ids,
/// ports, credentials and fingerprints).
fn media_lines(sdp: &str) -> Vec<&str> {
const KEPT: [&str; 8] = [
"m=",
"a=setup",
"a=extmap",
"a=rtcp-fb",
"a=rtpmap",
"a=fmtp",
"a=simulcast",
"a=rid",
];
sdp.lines().filter(|l| KEPT.iter().any(|k| l.starts_with(k))).collect()
}
/// Bandwidth estimation changes nothing in the offer official viewers get
/// (str0m always offers transport-cc and abs-send-time).
#[tokio::test]
async fn offer_with_bandwidth_estimation_is_unchanged() {
let without = PeerConfig { bandwidth_estimation: false, ..PeerConfig::loopback() };
let (_a, plain) = Peer::offer(&without, "s").await.unwrap();
let (_b, bwe) = Peer::offer(&PeerConfig::loopback(), "s").await.unwrap();
assert_eq!(media_lines(&plain), media_lines(&bwe));
assert!(bwe.contains("transport-wide-cc") && bwe.contains("transport-cc"), "{bwe}");
assert!(!bwe.contains("a=simulcast"), "{bwe}");
// Layers without the simulcast flag: still the plain offer.
let layers = [
LayerSpec { rid: Some("h".into()), ..LayerSpec::single(2_000_000) },
LayerSpec {
id: 1,
size: Some((640, 360)),
max_fps: Some(15),
max_bitrate: Some(500_000),
rid: Some("l".into()),
..LayerSpec::single(400_000)
},
];
let options = OfferOptions { layers: &layers, ..OfferOptions::default() };
let (_c, layered) = Peer::offer_with(&PeerConfig::loopback(), "s", &options).await.unwrap();
assert_eq!(media_lines(&plain), media_lines(&layered));
// With it: RID simulcast with the layers' limits.
let simulcast = PeerConfig { simulcast: true, ..PeerConfig::loopback() };
let (_d, sdp) = Peer::offer_with(&simulcast, "s", &options).await.unwrap();
assert!(sdp.contains("a=simulcast:send h;l"), "{sdp}");
assert!(sdp.contains("a=rid:h send\r\n"), "{sdp}");
assert!(
sdp.contains("a=rid:l send max-width=640;max-height=360;max-fps=15;max-br=500000"),
"{sdp}"
);
// One layer with a RID is not simulcast.
let options = OfferOptions { layers: &layers[..1], ..OfferOptions::default() };
let (_e, sdp) = Peer::offer_with(&simulcast, "s", &options).await.unwrap();
assert!(!sdp.contains("a=simulcast"), "{sdp}");
}
}
File diff suppressed because it is too large. Load diff
+113 -17
View File
@@ -9,7 +9,7 @@ use std::time::{Duration, Instant};
use str0m::media::{Frequency, MediaKind, MediaTime};
use crate::layer::LayerId;
use crate::layer::{LayerId, LayerSpec};
/// One encoded video or audio frame.
#[derive(Clone, Debug)]
@@ -68,26 +68,67 @@ const OPUS_FRAME: u64 = 960;
/// 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.
///
/// With [layers](Self::with_layers) every video tick has a frame of each
/// layer (at its `max_fps`), with the low byte of the layer id in the byte
/// after the sequence number, sized for the layer's bitrate; all are flagged
/// as keyframes (they are). [`FrameSource::set_layer_bitrate`] resizes a
/// layer's frames, so the source follows the viewers' bandwidth.
pub struct SyntheticSource {
start: Instant,
fps: u32,
video_size: usize,
audio: bool,
video_frames: u64,
audio_frames: u64,
layers: Vec<SyntheticLayer>,
}
struct SyntheticLayer {
id: LayerId,
/// Frame rate (at most the source's).
fps: u32,
/// Bytes per frame.
size: usize,
}
/// The smallest synthetic video frame: the keyframe, the sequence and layer bytes.
const MIN_FRAME: usize = VP8_KEYFRAME_1X1.len() + 2;
impl SyntheticSource {
/// `fps` video frames of `video_size` bytes per second, plus audio if `audio`.
/// `fps` video frames of `video_size` bytes per second (layer 0), 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,
let fps = fps.max(1);
let size = video_size.max(VP8_KEYFRAME_1X1.len() + 1);
let layers = vec![SyntheticLayer { id: 0, fps, size }];
Self { start: Instant::now(), fps, audio, video_frames: 0, audio_frames: 0, layers }
}
/// A frame of each of `layers` per video tick (layer 0 of `video_size`
/// bytes if `layers` is empty); see [`set_layers`](Self::set_layers).
pub fn with_layers(fps: u32, video_size: usize, audio: bool, layers: &[LayerSpec]) -> Self {
let mut source = Self::new(fps, video_size, audio);
source.set_layers(layers);
source
}
/// Produce frames of `layers` from now on: each at its `max_fps` (at most
/// the source's), `bitrate / 8 / fps` bytes per frame.
pub fn set_layers(&mut self, layers: &[LayerSpec]) {
if layers.is_empty() {
return;
}
self.layers = layers
.iter()
.map(|l| {
let fps = l.max_fps.map_or(self.fps, |f| f.clamp(1, self.fps));
SyntheticLayer { id: l.id, fps, size: Self::frame_size(l.bitrate, fps) }
})
.collect();
}
fn frame_size(bitrate: u64, fps: u32) -> usize {
usize::try_from(bitrate / 8 / u64::from(fps.max(1))).unwrap_or(usize::MAX).max(MIN_FRAME)
}
pub fn video_frame(seq: u64, size: usize) -> Vec<u8> {
@@ -96,21 +137,48 @@ impl SyntheticSource {
frame.extend((frame.len()..size).map(|i| (i as u8).wrapping_mul(31) ^ seq as u8));
frame
}
/// A frame of `layer`: [`video_frame`](Self::video_frame) with the low
/// byte of the layer id after the sequence number.
pub fn layer_frame(seq: u64, layer: LayerId, size: usize) -> Vec<u8> {
let mut frame = Self::video_frame(seq, size.max(MIN_FRAME));
frame[VP8_KEYFRAME_1X1.len() + 1] = layer as u8;
frame
}
/// The layer id byte of a frame from [`layer_frame`](Self::layer_frame).
pub fn frame_layer(data: &[u8]) -> Option<u8> {
data.get(VP8_KEYFRAME_1X1.len() + 1).copied()
}
}
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;
let layered = self.layers.len() > 1 || self.layers[0].id != 0;
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(),
layer: 0,
keyframe: true,
});
let time = MediaTime::from_90khz(n * 90_000 / u64::from(self.fps));
for layer in &self.layers {
// This tick starts a frame period of the layer.
let (fps, layer_fps) = (u64::from(self.fps), u64::from(layer.fps));
if n > 0 && n * layer_fps / fps == (n - 1) * layer_fps / fps {
continue;
}
let data = if layered {
Self::layer_frame(n, layer.id, layer.size)
} else {
Self::video_frame(n, layer.size)
};
out.push(EncodedFrame {
kind: MediaKind::Video,
time,
data: data.into(),
layer: layer.id,
keyframe: true,
});
}
self.video_frames += 1;
}
if self.audio {
@@ -130,6 +198,12 @@ impl FrameSource for SyntheticSource {
}
}
}
fn set_layer_bitrate(&mut self, layer: LayerId, bitrate: u64) {
if let Some(l) = self.layers.iter_mut().find(|l| l.id == layer) {
l.size = Self::frame_size(bitrate, l.fps);
}
}
}
#[cfg(test)]
@@ -153,4 +227,26 @@ mod tests {
assert_eq!(video[0].data[..22], VP8_KEYFRAME_1X1);
assert_eq!(video[0].data[22], 1);
}
#[test]
fn layered_frames() {
let full = LayerSpec { id: 3, ..LayerSpec::single(2_400_000) };
let half = LayerSpec { id: 7, max_fps: Some(15), ..LayerSpec::single(600_000) };
let mut source = SyntheticSource::with_layers(30, 1000, false, &[full, half]);
let start = source.start;
let mut out = Vec::new();
source.poll_frames(start + Duration::from_millis(999), &mut out);
let of = |id| out.iter().filter(move |f| f.layer == id);
assert_eq!((of(3).count(), of(7).count()), (30, 15));
assert!(out.iter().all(|f| f.keyframe && f.kind == MediaKind::Video));
let f = of(7).nth(1).unwrap();
assert_eq!(SyntheticSource::frame_layer(&f.data), Some(7));
assert_eq!(f.data.len(), 600_000 / 8 / 15);
assert_eq!(f.time, MediaTime::from_90khz(2 * 3000), "same clock as layer 3");
assert_eq!(of(3).next().unwrap().data.len(), 2_400_000 / 8 / 30);
source.set_layer_bitrate(3, 1);
out.clear();
source.poll_frames(start + Duration::from_millis(1030), &mut out);
assert_eq!(out[0].data.len(), MIN_FRAME);
}
}
+44 -3
View File
@@ -1,9 +1,10 @@
//! Two peers on loopback: offer/answer, then video and audio frames flow.
//! Two peers on loopback: offer/answer, then video and audio frames flow;
//! the SRTP profile DTLS negotiates; bandwidth estimates at the streamer.
use std::time::Duration;
use tokio::time::timeout;
use voelin_stream::{MediaKind, MediaTime, Peer, PeerConfig, PeerEvent};
use voelin_stream::{MediaKind, MediaTime, Peer, PeerConfig, PeerEvent, SrtpProfile};
/// Bytes that look like a VP8 keyframe (frame tag + start code), then filler.
pub fn fake_vp8_keyframe(seq: u8, len: usize) -> Vec<u8> {
@@ -79,7 +80,47 @@ async fn media_flows_over_loopback() {
}
})
.await;
let streamer = sender.await.unwrap();
let mut streamer = sender.await.unwrap();
assert!(video >= 40 && audio >= 80, "received {video} video / {audio} audio frames");
// The viewer's transport-cc feedback gives the streamer bandwidth estimates.
let mut estimates = Vec::new();
while let Some(event) = streamer.try_next_event() {
if let PeerEvent::BitrateEstimate(bitrate) = event {
estimates.push(bitrate);
}
}
assert!(!estimates.is_empty(), "no bandwidth estimate");
assert!(estimates.iter().all(|b| *b > 0), "{estimates:?}");
drop(streamer);
}
/// Connect a streamer and a viewer; the SRTP profile each ended up with.
async fn negotiate(streamer: &PeerConfig, viewer: &PeerConfig) -> [Option<SrtpProfile>; 2] {
let (mut s, offer) = Peer::offer(streamer, "srtp").await.unwrap();
let (mut v, answer) = Peer::answer(viewer, &offer).await.unwrap();
s.accept_answer(&answer).await.unwrap();
tokio::join!(wait_connected(&mut s), wait_connected(&mut v));
[s.srtp_profile(), v.srtp_profile()]
}
#[tokio::test(flavor = "multi_thread")]
async fn srtp_profile_order() {
use SrtpProfile::{AeadAes128Gcm, AeadAes256Gcm, Aes128CmSha1_80};
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
let default = PeerConfig::loopback();
// By default: SRTP_AES128_CM_SHA1_80, as between official TeamSpeak clients.
let profiles = negotiate(&default, &default).await;
assert_eq!(profiles, [Some(Aes128CmSha1_80); 2]);
assert_eq!(profiles[0].unwrap().name(), "AES_CM_128_HMAC_SHA1_80");
// The answering peer is the DTLS server (a=setup:passive); its order wins
// over a client that offers GCM first, as browsers do.
let gcm_first = PeerConfig {
srtp_profiles: vec![AeadAes256Gcm, AeadAes128Gcm, Aes128CmSha1_80],
..PeerConfig::loopback()
};
assert_eq!(negotiate(&gcm_first, &default).await, [Some(Aes128CmSha1_80); 2]);
assert_eq!(negotiate(&default, &gcm_first).await, [Some(AeadAes256Gcm); 2]);
// A peer without AES_CM_128_HMAC_SHA1_80 still connects with GCM.
let gcm_only = PeerConfig { srtp_profiles: vec![AeadAes128Gcm], ..PeerConfig::loopback() };
assert_eq!(negotiate(&gcm_only, &default).await, [Some(AeadAes128Gcm); 2]);
}
+130
View File
@@ -0,0 +1,130 @@
//! RID simulcast over loopback: our stream session offers its layers with
//! RIDs (`PeerConfig::simulcast`), a str0m peer (as an SFU or WHIP server
//! would) takes them, and each layer's frames arrive with their RID.
use std::collections::BTreeMap;
use std::time::{Duration, Instant};
use tokio::time::timeout;
use tsclientlib::ClientId;
use voelin_stream::{
FrameSource, LayerSpec, MediaKind, Output, Peer, PeerConfig, PeerEvent, Request, Signal,
StreamEvent, StreamInfo, StreamKind, StreamNotification, StreamerEvent, StreamerOptions,
Streams, SyntheticSource, ViewerState,
};
const OWN: ClientId = ClientId(10);
const VIEWER: ClientId = ClientId(20);
fn drain(s: &mut Streams) -> (Vec<Request>, Vec<StreamEvent>) {
let (mut requests, mut events) = (Vec::new(), Vec::new());
while let Some(o) = s.poll_output() {
match o {
Output::Request(r) => requests.push(r),
Output::Event(e) => events.push(e),
}
}
(requests, events)
}
#[tokio::test(flavor = "multi_thread")]
async fn rid_simulcast_over_loopback() {
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
let layers = vec![
LayerSpec { id: 0, rid: Some("h".into()), ..LayerSpec::single(1_500_000) },
LayerSpec { id: 1, scale: 0.5, rid: Some("l".into()), ..LayerSpec::single(400_000) },
];
let config = PeerConfig { simulcast: true, ..PeerConfig::loopback() };
let mut s = Streams::new(OWN, config);
let options =
StreamerOptions { auto_accept: true, layers: layers.clone(), ..Default::default() };
s.start(options).unwrap();
let info = StreamInfo {
id: "s-1".into(),
streamer: OWN,
name: "simulcast".into(),
kind: StreamKind::Screen,
bitrate: 1900,
viewer_limit: 0,
audio: true,
};
s.handle_notification(StreamNotification::Started { info, return_code: Some("1".into()) })
.await;
s.handle_notification(StreamNotification::JoinRequest {
id: "s-1".into(),
viewer: VIEWER,
message: String::new(),
remove: false,
})
.await;
let (requests, _) = drain(&mut s);
let offer = requests
.iter()
.find_map(|r| match r {
Request::Respond { offer: Some(sdp), .. } => Some(sdp.clone()),
_ => None,
})
.expect("offer");
assert!(offer.contains("a=simulcast:send h;l"), "{offer}");
// The other side takes both layers.
let (mut viewer, answer) = Peer::answer(&PeerConfig::loopback(), &offer).await.unwrap();
assert!(answer.contains("a=simulcast:recv h;l"), "{answer}");
let json = Signal::Answer { sdp: answer }.to_json();
s.handle_notification(StreamNotification::Signaling { id: "s-1".into(), peer: VIEWER, json })
.await;
timeout(Duration::from_secs(10), async {
loop {
let (_, events) = drain(&mut s);
let connected = events.iter().any(|e| {
matches!(e, StreamEvent::Streamer(StreamerEvent::Viewers(v))
if v.iter().any(|v| v.state == ViewerState::Connected))
});
if connected {
return;
}
s.wait_peers().await;
}
})
.await
.expect("viewer did not connect");
let viewers = s.streamer().unwrap().viewers();
assert_eq!(viewers[0].layer, None, "RID simulcast viewers get every layer");
// Every layer's frames arrive with the layer's RID.
let mut source = SyntheticSource::with_layers(30, 0, true, &layers);
let mut frames = Vec::new();
let mut by_rid: BTreeMap<String, Vec<u8>> = BTreeMap::new();
let mut audio = 0;
timeout(Duration::from_secs(10), async {
while by_rid.len() < 2 || by_rid.values().any(|l| l.len() < 20) || audio < 20 {
source.poll_frames(Instant::now(), &mut frames);
for f in frames.drain(..) {
s.write_frame(&f);
}
let _ = drain(&mut s);
while let Some(event) = viewer.try_next_event() {
match event {
PeerEvent::LayerMedia { rid, frame } => {
assert_eq!(frame.kind, MediaKind::Video);
let layer = SyntheticSource::frame_layer(&frame.data).unwrap();
by_rid.entry(rid.to_string()).or_default().push(layer);
}
PeerEvent::Media(frame) => {
assert_eq!(frame.kind, MediaKind::Audio, "video without a RID");
audio += 1;
}
_ => {}
}
}
tokio::select! {
() = s.wait_peers() => {}
() = tokio::time::sleep(Duration::from_millis(10)) => {}
}
}
})
.await
.unwrap_or_else(|_| panic!("frames per RID: {by_rid:?}, audio {audio}"));
assert!(by_rid["h"].iter().all(|l| *l == 0), "{by_rid:?}");
assert!(by_rid["l"].iter().all(|l| *l == 1), "{by_rid:?}");
}
+259 -40
View File
@@ -22,8 +22,9 @@ use voelin_core::media::{
};
use voelin_model::ServerFlavor;
use voelin_stream::{
EndReason, FrameSource, MediaKind, Output, PeerConfig, Request, StreamEvent, StreamInfo,
StreamNotification, StreamSetup, StreamerEvent, StreamerOptions, Streams, WatchEvent,
EndReason, FrameSource, LayerId, LayerSpec, MediaKind, Output, PeerConfig, Request,
SrtpProfile, StreamEvent, StreamInfo, StreamNotification, StreamSetup, StreamerEvent,
StreamerOptions, Streams, SyntheticSource, VideoCodec, ViewerInfo, WatchEvent,
};
#[derive(Args, Debug, Clone)]
@@ -39,6 +40,11 @@ pub struct StreamArgs {
/// Do not use STUN.
#[arg(long, global = true, conflicts_with = "stun")]
no_stun: bool,
/// SRTP profiles in order of preference, comma separated
/// (`AES_CM_128_HMAC_SHA1_80`, `AEAD_AES_128_GCM`, `AEAD_AES_256_GCM`)
/// [default: in this order].
#[arg(long, global = true, value_delimiter = ',')]
srtp: Vec<String>,
}
#[derive(Subcommand, Debug, Clone)]
@@ -76,6 +82,21 @@ pub enum StreamCommand {
/// No audio track.
#[arg(long)]
no_audio: bool,
/// A simulcast layer, repeatable: `<scale or WxH>:<bitrate>[:<option>...]`
/// with options `min=<bitrate>` (estimate a viewer needs; default half
/// the bitrate), `max=<bitrate>`, `fps=<n>`, `rid=<id>`, `id=<n>`
/// (default: position). Bitrates in bit/s with optional k or M, e.g.
/// `--layer 1.0:6000k --layer 0.5:1500k:min=800k`.
#[arg(long = "layer", value_parser = parse_layer)]
layers: Vec<LayerSpec>,
/// Offer RID simulcast (the layers' `rid`s) to viewers. Only for peers
/// that support it; official TeamSpeak clients do not.
#[arg(long)]
simulcast: bool,
/// Send placeholder frames (tiny VP8 keyframes padded to each layer's
/// bitrate, no encoder) instead of capturing.
#[arg(long, conflicts_with_all = ["source", "synthetic"])]
placeholder: bool,
},
/// List the streams in our channel.
List {
@@ -118,9 +139,22 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> {
} else if args.no_stun {
config.stun_servers.clear();
}
if !args.srtp.is_empty() {
config.srtp_profiles = parse_srtp(&args.srtp)?;
}
if let StreamCommand::Start { simulcast, placeholder, .. } = &args.command {
config.simulcast = *simulcast;
if *placeholder {
// The placeholder frames are VP8.
config.video_codecs = vec![VideoCodec::Vp8];
}
}
// Offer the codec we encode, accept what we decode.
let codecs = Arc::new(Codecs::new());
let config = peer_config(&codecs, config);
let config = match &args.command {
StreamCommand::Start { placeholder: true, .. } => config,
_ => peer_config(&codecs, config),
};
let codec = stream_codec(&codecs, &config);
let mut driver = Driver { streams: Streams::new(own, config), pending: HashMap::new() };
let result = match &args.command {
@@ -134,34 +168,59 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> {
fps,
bitrate,
no_audio,
layers,
simulcast: _,
placeholder,
} => {
let source = if *synthetic { "synthetic" } else { source.as_str() };
let (source, backend) = parse_source(source)?;
let Some(codec) = codec else { bail!("no video encoder in this build") };
let config = StreamerConfig {
source,
backend,
fps: *fps,
bitrate_kbps: *bitrate,
codec,
audio: !no_audio,
synthetic_size: parse_size(size)?,
..StreamerConfig::default()
};
let streamer = Streamer::start(&codecs, config).await.context("capture")?;
println!("capturing with {} ({codec})", streamer.backend());
if let Some(e) = streamer.audio_error() {
println!("no system audio: {e}");
for l in layers {
println!(
"layer {}: {}, {}, needs {}{}",
l.id,
l.size.map_or(format!("scale {}", l.scale), |(w, h)| format!("{w}x{h}")),
rate(l.bitrate),
rate(l.min_bitrate),
l.rid.as_ref().map(|r| format!(", rid {r}")).unwrap_or_default()
);
}
let setup = StreamSetup {
name: name.clone(),
bitrate: *bitrate,
audio: streamer.has_audio(),
let (source, audio) = if *placeholder {
let source = SyntheticSource::with_layers(
*fps,
(u64::from(*bitrate) * 1000 / 8 / u64::from((*fps).max(1))) as usize,
!no_audio,
layers,
);
(Source::Placeholder(source), !no_audio)
} else {
let source = if *synthetic { "synthetic" } else { source.as_str() };
let (source, backend) = parse_source(source)?;
let Some(codec) = codec else { bail!("no video encoder in this build") };
let config = StreamerConfig {
source,
backend,
fps: *fps,
bitrate_kbps: *bitrate,
codec,
audio: !no_audio,
synthetic_size: parse_size(size)?,
layers: layers.clone(),
..StreamerConfig::default()
};
let streamer = Streamer::start(&codecs, config).await.context("capture")?;
println!("capturing with {} ({codec})", streamer.backend());
if let Some(e) = streamer.audio_error() {
println!("no system audio: {e}");
}
let audio = streamer.has_audio();
(Source::Encoded(EncodedSource::new(streamer)), audio)
};
let setup =
StreamSetup { name: name.clone(), bitrate: *bitrate, audio, ..Default::default() };
let options = StreamerOptions {
setup,
auto_accept: *auto_accept,
layers: layers.clone(),
..Default::default()
};
let options =
StreamerOptions { setup, auto_accept: *auto_accept, ..Default::default() };
let source = EncodedSource::new(streamer);
start(con, &mut driver, options, source, seconds.map(Duration::from_secs)).await
}
StreamCommand::List { settle_ms } => {
@@ -205,6 +264,119 @@ fn parse_size(size: &str) -> Result<(u32, u32)> {
parsed.with_context(|| format!("bad size {size:?}, expected e.g. 1280x720"))
}
/// A bitrate in bit/s: `1500000`, `1500k`, `1.5M`.
fn parse_rate(rate: &str) -> Result<u64, String> {
let (number, factor) = match rate.trim().char_indices().last() {
Some((i, 'k' | 'K')) => (&rate[..i], 1e3),
Some((i, 'm' | 'M')) => (&rate[..i], 1e6),
_ => (rate, 1.0),
};
match number.trim().parse::<f64>() {
Ok(n) if n.is_finite() && n >= 0.0 => Ok((n * factor).round() as u64),
_ => Err(format!("bad bitrate {rate:?}, expected e.g. 1500k")),
}
}
/// `--layer <scale or WxH>:<bitrate>[:min=..][:max=..][:fps=..][:rid=..][:id=..]`;
/// the id defaults to the position in the list (fixed up by the caller).
fn parse_layer(spec: &str) -> Result<LayerSpec, String> {
let mut parts = spec.split(':');
let (Some(size), Some(bitrate)) = (parts.next(), parts.next()) else {
return Err(format!("bad layer {spec:?}, expected e.g. 0.5:1500k:min=800k"));
};
let bitrate = parse_rate(bitrate)?;
let mut layer =
LayerSpec { min_bitrate: bitrate / 2, id: LayerId::MAX, ..LayerSpec::single(bitrate) };
match parse_size(size) {
Ok(size) => layer.size = Some(size),
Err(_) => {
layer.scale = size.parse().map_err(|_| format!("bad scale or size {size:?}"))?;
if !(layer.scale > 0.0 && layer.scale.is_finite()) {
return Err(format!("bad scale {size:?}"));
}
}
}
for option in parts {
let (key, value) = option.split_once('=').ok_or(format!("bad layer option {option:?}"))?;
let number = || value.parse().map_err(|_| format!("bad number in {option:?}"));
match key {
"min" => layer.min_bitrate = parse_rate(value)?,
"max" => layer.max_bitrate = Some(parse_rate(value)?),
"fps" => layer.max_fps = Some(number()?),
"rid" => layer.rid = Some(value.to_owned()),
"id" => layer.id = number()? as LayerId,
_ => return Err(format!("unknown layer option {key:?} (min, max, fps, rid, id)")),
}
}
Ok(layer)
}
/// Layer ids not given are the layers' positions.
fn number_layers(layers: &mut [LayerSpec]) {
for (i, layer) in layers.iter_mut().enumerate() {
if layer.id == LayerId::MAX {
layer.id = i as LayerId;
}
}
}
fn parse_srtp(names: &[String]) -> Result<Vec<SrtpProfile>> {
names
.iter()
.map(|n| {
SrtpProfile::from_name(n).with_context(|| {
format!(
"unknown SRTP profile {n:?}: {}",
SrtpProfile::ALL.map(SrtpProfile::name).join(", ")
)
})
})
.collect()
}
/// A bitrate for people.
fn rate(bitrate: u64) -> String {
if bitrate >= 1_000_000 {
format!("{:.2} Mbit/s", bitrate as f64 / 1e6)
} else {
format!("{} kbit/s", bitrate / 1000)
}
}
/// What the streamer sends.
enum Source {
/// Captured and encoded.
Encoded(EncodedSource),
/// Placeholder frames, no encoder.
Placeholder(SyntheticSource),
}
impl Source {
fn frames(&mut self) -> &mut dyn FrameSource {
match self {
Self::Encoded(s) => s,
Self::Placeholder(s) => s,
}
}
}
/// A viewer as the streamer's output lists it.
fn viewer_text(con: &Connection, v: &ViewerInfo) -> String {
let mut text = format!("{} (clid {}, {:?}", nick(con, v.client), v.client.0, v.state);
match v.layer {
Some(layer) => text += &format!(", layer {layer}"),
None if v.state == voelin_stream::ViewerState::Connected => text += ", all layers (RID)",
None => {}
}
if let Some(estimate) = v.estimate {
text += &format!(", estimate {}", rate(estimate));
}
if let Some(profile) = v.srtp_profile {
text += &format!(", {profile}");
}
text + ")"
}
/// What woke the driver.
enum Wake {
/// Connection or peer activity; the new events are returned by `flush`.
@@ -352,14 +524,15 @@ fn end_text(reason: &EndReason) -> String {
async fn start(
con: &mut Connection,
driver: &mut Driver,
options: StreamerOptions,
mut source: EncodedSource,
mut options: StreamerOptions,
mut source: Source,
length: Option<Duration>,
) -> Result<()> {
let auto_accept = options.auto_accept;
number_layers(&mut options.layers);
driver.streams.start(options)?;
let deadline = length.map(|l| Instant::now() + l);
let mut tick = tokio::time::interval(source.interval());
let mut tick = tokio::time::interval(source.frames().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);
@@ -369,7 +542,7 @@ async fn start(
match wake {
Wake::Stream => {}
Wake::Tick => {
source.poll_frames(std::time::Instant::now(), &mut frames);
source.frames().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(..) {
@@ -409,19 +582,21 @@ async fn start(
);
}
StreamerEvent::Viewers(viewers) => {
let list: Vec<String> = viewers
.iter()
.map(|v| {
format!("{} (clid {}, {:?})", nick(con, v.client), v.client.0, v.state)
})
.collect();
let list: Vec<String> = viewers.iter().map(|v| viewer_text(con, v)).collect();
println!("viewers: [{}]", list.join(", "));
}
StreamerEvent::KeyframeRequest => source.request_keyframe(),
StreamerEvent::KeyframeRequest { layer } => {
source.frames().request_layer_keyframe(layer);
}
StreamerEvent::LayerBitrate { layer, bitrate } => {
println!("layer {layer}: target {}", rate(bitrate));
source.frames().set_layer_bitrate(layer, bitrate);
}
StreamerEvent::Ended(reason) => {
println!("sent {video} video / {audio} audio frames to connected viewers");
let stats = source.streamer().stats();
if let Some(e) = &stats.error {
if let Source::Encoded(source) = &source
&& let Some(e) = &source.streamer().stats().error
{
println!("last encoder error: {e}");
}
return match reason {
@@ -657,3 +832,47 @@ async fn watch(
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn layers() {
let mut layers = vec![
parse_layer("1.0:6000k").unwrap(),
parse_layer("0.5:1.5M:min=800k:max=2M:fps=15:rid=h:id=7").unwrap(),
parse_layer("640x360:300000:min=0").unwrap(),
];
number_layers(&mut layers);
let [full, half, small] = &layers[..] else { unreachable!() };
assert_eq!(
(full.id, full.scale, full.bitrate, full.min_bitrate),
(0, 1.0, 6_000_000, 3_000_000)
);
assert_eq!(
(half.id, half.scale, half.bitrate, half.min_bitrate),
(7, 0.5, 1_500_000, 800_000)
);
assert_eq!(
(half.max_bitrate, half.max_fps, half.rid.as_deref()),
(Some(2_000_000), Some(15), Some("h"))
);
assert_eq!((small.id, small.size, small.min_bitrate), (2, Some((640, 360)), 0));
for bad in ["1.0", "x:1k", "0:1k", "1.0:fast", "1.0:1k:min", "1.0:1k:color=red"] {
assert!(parse_layer(bad).is_err(), "{bad}");
}
}
#[test]
fn srtp_names() {
let names = ["aes_cm_128_hmac_sha1_80".to_owned(), "AEAD_AES_256_GCM".to_owned()];
assert_eq!(
parse_srtp(&names).unwrap(),
[SrtpProfile::Aes128CmSha1_80, SrtpProfile::AeadAes256Gcm]
);
assert!(parse_srtp(&["rot13".to_owned()]).is_err());
assert_eq!(rate(1_500_000), "1.50 Mbit/s");
assert_eq!(rate(300_000), "300 kbit/s");
}
}