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:
14 files changed
+2472
-172
No files matched your search
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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};
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user