Step down when a connection connects but carries no media

A connection could reach "connected" and still show nothing: an SRTP
library that negotiates a profile it then cannot use (official clients
reportedly failed that way with AES-GCM), or a streamer that has no
encoder for the codec our answer took. Nothing noticed; the viewer
waited forever.

Now each peer checks once per connection whether media gets through:
a viewer's peer reports NoVideo (with whether audio came) when no video
arrived within PeerConfig::stall_timeout (5 s), a streamer's peer
reports NoFeedback when, after twice that, none of the viewer's receiver
reports (or REMB) mentioned our video. Keyframe requests do not count:
a viewer that gets nothing keeps asking. The streamer waits longer so a
Voelin viewer steps down first.

The sessions then ask for a new connection with the next lower set,
logging each step: without the SRTP profile that was negotiated (both
AEAD profiles when it was one of them), or, when audio came but video
did not, without the video codec. A viewer sends `reconnect`; a
streamer sends a `reconnectOffer` itself, for viewers that do not step
down. What was left out stays out for that viewer; when nothing is left
the step is logged and nothing loops.

Proven with two sessions through a relay that passes the handshake and
drops SRTP once AES-GCM was selected (and with a source whose video is
only VP8 while the answer took VP9): each side falls back to
AES_CM_128_HMAC_SHA1_80 (or VP8), the media arrives, and the working
connection does not step again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-03 23:13:22 +03:00
1 parent 675a057153
commit 9d4fcc015f
4 files changed
+463 -35

No files matched your search

+6
View File
@@ -42,6 +42,12 @@ impl SrtpProfile {
/// clients, then the GCM profiles for peers that do not offer it.
pub const DEFAULT_ORDER: [Self; 3] = Self::ALL;
/// An AEAD profile (AES-GCM, RFC 7714): an SRTP library either has both
/// or neither.
pub fn is_aead(self) -> bool {
matches!(self, Self::AeadAes128Gcm | Self::AeadAes256Gcm)
}
/// The profile's name as in RFC 5764/7714 and WebRTC statistics
/// (`srtpCipher`).
pub fn name(self) -> &'static str {
+107 -8
View File
@@ -43,6 +43,11 @@ pub const DEFAULT_START_BITRATE: u64 = 1_000_000;
/// Socket buffers a peer asks for by default ([`PeerConfig::udp_buffer`]).
pub const DEFAULT_UDP_BUFFER: usize = 4 << 20;
/// How long a connected viewer waits for video by default
/// ([`PeerConfig::stall_timeout`]): a streamer sends a keyframe as soon as
/// a viewer connects.
pub const DEFAULT_STALL_TIMEOUT: Duration = Duration::from_secs(5);
/// Video codecs a peer can negotiate.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VideoCodec {
@@ -207,6 +212,11 @@ pub struct PeerConfig {
/// the peer task is busy overflows it, and every lost packet costs the
/// viewer a retransmission or a keyframe.
pub udp_buffer: usize,
/// How long a connected viewer waits for video before its peer reports
/// [`PeerEvent::NoVideo`]; a streamer's peer waits twice as long for
/// the viewer to report any of our video ([`PeerEvent::NoFeedback`]),
/// so a Voelin viewer steps down first. `Duration::MAX` turns both off.
pub stall_timeout: Duration,
}
impl Default for PeerConfig {
@@ -226,6 +236,7 @@ impl Default for PeerConfig {
.map(|p| h264::profile_level_id(*p, h264::MIN_OFFER_LEVEL))
.collect(),
udp_buffer: DEFAULT_UDP_BUFFER,
stall_timeout: DEFAULT_STALL_TIMEOUT,
}
}
}
@@ -314,6 +325,16 @@ pub enum PeerEvent {
/// profile: the first of our offer the viewer took. Video written to
/// this peer must be in it.
VideoCodec(VideoFormat),
/// Viewer side: connected, but no video arrived within
/// [`PeerConfig::stall_timeout`]. `audio`: audio did, so SRTP works
/// and the video codec is the suspect. Once per connection.
NoVideo { audio: bool },
/// Streamer side: connected and sending video for twice
/// [`PeerConfig::stall_timeout`], yet the viewer reported none of it
/// (no receiver report of our video, no REMB): its SRTP fails or
/// nothing reaches it. Keyframe requests do not count: a viewer that
/// gets nothing keeps asking. Once per connection.
NoFeedback,
/// The connection is gone.
Closed,
}
@@ -360,6 +381,16 @@ impl Peer {
config: &PeerConfig,
stream_id: &str,
options: &OfferOptions<'_>,
) -> Result<(Self, String), PeerError> {
Self::offer_now(config, stream_id, options)
}
/// [`offer_with`](Self::offer_with), which never waits: for the stream
/// sessions, which offer again from peer events.
pub(crate) fn offer_now(
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);
@@ -368,7 +399,7 @@ impl Peer {
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 net = Net::bind(config, &mut rtc)?;
let mut api = rtc.sdp_api();
let msid = Some(stream_id.to_owned());
let mut mids = Vec::new();
@@ -415,7 +446,7 @@ impl Peer {
}
let offer = SdpOffer::from_sdp_string(offer).map_err(|e| PeerError::Sdp(e.to_string()))?;
let (mut rtc, srtp_profile) = build_rtc(config, &codecs, false, None);
let net = Net::bind(config, &mut rtc).await?;
let net = Net::bind(config, &mut rtc)?;
let answer = rtc.sdp_api().accept_offer(offer)?;
let peer = Self::spawn(rtc, net, config, None, Vec::new(), srtp_profile);
Ok((peer, answer.to_sdp_string()))
@@ -434,6 +465,7 @@ impl Peer {
let task = Task {
rtc,
net,
offerer: pending.is_some(),
pending,
cmd: cmd_rx,
events: event_tx,
@@ -441,6 +473,7 @@ impl Peer {
writers: HashMap::new(),
stun: Vec::new(),
twcc: false,
stall: Stall { timeout: config.stall_timeout, ..Stall::default() },
};
tokio::spawn(task.run(config.stun_servers.clone()));
Self { cmd: cmd_tx, events: event_rx, srtp_profile }
@@ -569,6 +602,10 @@ fn build_rtc(
) -> (Rtc, NegotiatedProfile) {
let mut rtc_config =
RtcConfig::new().clear_codecs().enable_opus(config.audio).enable_bwe(bwe.map(Bitrate::bps));
if offer {
// The viewer's receiver reports ([`PeerEvent::NoFeedback`]).
rtc_config = rtc_config.set_stats_interval(Some(Duration::from_secs(1)));
}
for codec in video {
rtc_config = match codec {
VideoCodec::Vp8 => rtc_config.enable_vp8(true),
@@ -627,7 +664,7 @@ fn order_like_offer(answer: &str, offer: &str) -> String {
}
/// The video codecs of the first video media line of `sdp`, in offered order.
fn offered_video_codecs(sdp: &str) -> Vec<VideoCodec> {
pub(crate) fn offered_video_codecs(sdp: &str) -> Vec<VideoCodec> {
let mut pts: Vec<&str> = Vec::new();
let mut names: Vec<(&str, VideoCodec)> = Vec::new();
let mut in_video = false;
@@ -678,7 +715,7 @@ struct Net {
}
impl Net {
async fn bind(config: &PeerConfig, rtc: &mut Rtc) -> Result<Self, PeerError> {
fn bind(config: &PeerConfig, rtc: &mut Rtc) -> Result<Self, PeerError> {
let hosts = if config.hosts.is_empty() {
primary_ipv4().into_iter().collect()
} else {
@@ -782,6 +819,46 @@ struct Task {
stun: Vec<PendingStun>,
/// A transport-cc estimate arrived: REMB is ignored from then on.
twcc: bool,
/// Made the offer: the streamer's side.
offerer: bool,
stall: Stall,
}
/// Whether media gets through once connected ([`PeerEvent::NoVideo`],
/// [`PeerEvent::NoFeedback`]).
#[derive(Debug, Default)]
struct Stall {
timeout: Duration,
connected: Option<Instant>,
/// Checked already (once per connection).
checked: bool,
audio_in: bool,
video_in: bool,
video_out: bool,
/// The viewer reported our video (receiver report, REMB).
acknowledged: bool,
}
impl Stall {
/// When the check is due: after the timeout for a viewer, twice it for
/// a streamer.
fn due(&self, offerer: bool) -> Option<Instant> {
let wait = if offerer { self.timeout.saturating_mul(2) } else { self.timeout };
self.connected.filter(|_| !self.checked)?.checked_add(wait)
}
/// The event to report at `now`, once, if media does not get through.
fn check(&mut self, now: Instant, offerer: bool, video: bool) -> Option<PeerEvent> {
if self.due(offerer).is_none_or(|due| now < due) {
return None;
}
self.checked = true;
if offerer {
(self.video_out && !self.acknowledged).then_some(PeerEvent::NoFeedback)
} else {
(video && !self.video_in).then_some(PeerEvent::NoVideo { audio: self.audio_in })
}
}
}
fn transaction_id() -> stun::TransactionId {
@@ -875,7 +952,13 @@ impl Task {
mut stun_servers: mpsc::UnboundedReceiver<SocketAddr>,
) -> Result<(), PeerError> {
loop {
self.rtc.handle_input(Input::Timeout(Instant::now()))?;
let now = Instant::now();
self.rtc.handle_input(Input::Timeout(now))?;
let video = self.mids.iter().any(|(_, kind)| *kind == MediaKind::Video);
if let Some(event) = self.stall.check(now, self.offerer, video) {
debug!(?event, "connected, but the media does not get through");
let _ = self.events.send(event);
}
let deadline = loop {
if !self.rtc.is_alive() {
return Ok(());
@@ -896,6 +979,7 @@ impl Task {
}
}
};
let deadline = self.stall.due(self.offerer).map_or(deadline, |due| due.min(deadline));
let sleep = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline));
tokio::select! {
packet = self.net.incoming.recv() => {
@@ -930,6 +1014,7 @@ impl Task {
fn handle_event(&mut self, event: Event) -> bool {
match event {
Event::Connected => {
self.stall.connected = Some(Instant::now());
let _ = self.events.send(PeerEvent::Connected);
}
Event::IceConnectionStateChange(IceConnectionState::Disconnected) => return false,
@@ -940,8 +1025,10 @@ impl Task {
}
Event::MediaData(d) => {
let kind = if d.params.spec().codec.is_audio() {
self.stall.audio_in = true;
MediaKind::Audio
} else {
self.stall.video_in = true;
MediaKind::Video
};
let frame = MediaFrame {
@@ -964,18 +1051,29 @@ impl Task {
});
}
Event::EgressBitrateEstimate(estimate) => {
// Transport-cc estimates also come from the estimator's own
// timer; a REMB only from the viewer.
let bitrate = match estimate {
BweKind::Twcc(b) => {
self.twcc = true;
Some(b)
}
BweKind::Remb(_, b) if !self.twcc => Some(b),
BweKind::Remb(_, b) => {
self.stall.acknowledged = true;
(!self.twcc).then_some(b)
}
_ => None,
};
if let Some(b) = bitrate {
let _ = self.events.send(PeerEvent::BitrateEstimate(b.as_u64()));
}
}
// A receiver report of our video: the viewer decrypts it.
Event::MediaEgressStats(stats)
if stats.remote.is_some() && self.mids.contains(&(stats.mid, MediaKind::Video)) =>
{
self.stall.acknowledged = true;
}
_ => {}
}
true
@@ -1069,8 +1167,9 @@ impl Task {
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}");
match writer.write(pt, Instant::now(), time, data) {
Ok(()) => self.stall.video_out |= kind == MediaKind::Video,
Err(e) => debug!(?kind, ?rid, "frame not sent: {e}"),
}
}
}
+171 -11
View File
@@ -40,7 +40,10 @@ use crate::discovery::{ClientState, Discovery, StreamLookup};
use crate::dtls::SrtpProfile;
use crate::feedback::LayerFeedback;
use crate::layer::{self, LayerId, LayerSet, LayerSpec};
use crate::peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerEvent, VideoCodec, VideoFormat};
use crate::peer::{
MediaFrame, OfferOptions, Peer, PeerConfig, PeerEvent, VideoCodec, VideoFormat,
offered_video_codecs,
};
use crate::proto::{self, LeaveReason, StreamInfo, StreamNotification, StreamSetup};
use crate::signal::Signal;
use crate::source::EncodedFrame;
@@ -555,6 +558,74 @@ impl LayerChoice {
}
}
/// The ladder of a connection that connects but carries no media: the next
/// one leaves out the SRTP profile it negotiated (every AEAD profile when
/// that was one: an SRTP library has both or neither), or the video codec
/// it carried, as long as another is left. What was left out stays out for
/// the later connections of that viewer or watched stream.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Fallback {
srtp: Vec<SrtpProfile>,
codecs: Vec<VideoCodec>,
}
impl Fallback {
/// `config` without what was left out.
fn apply(&self, config: &PeerConfig) -> PeerConfig {
let mut config = config.clone();
config.srtp_profiles = self.srtp_left(&config);
config.video_codecs.retain(|c| !self.codecs.contains(c));
config.accept_video_codecs.retain(|c| !self.codecs.contains(c));
config
}
/// The profiles of `config`'s order not left out yet.
fn srtp_left(&self, config: &PeerConfig) -> Vec<SrtpProfile> {
let order: &[SrtpProfile] = match &config.srtp_profiles[..] {
[] => &SrtpProfile::DEFAULT_ORDER,
order => order,
};
order.iter().copied().filter(|p| !self.srtp.contains(p)).collect()
}
/// Leave out `failed` (and the other AEAD profile with an AEAD one); the
/// profiles left, `None` (nothing left out) when none would be.
fn without_srtp(
&mut self,
config: &PeerConfig,
failed: SrtpProfile,
) -> Option<Vec<SrtpProfile>> {
let same = |p: &SrtpProfile| *p == failed || (p.is_aead() && failed.is_aead());
let left: Vec<_> = self.srtp_left(config).into_iter().filter(|p| !same(p)).collect();
if left.is_empty() {
return None;
}
self.srtp.extend(SrtpProfile::ALL.into_iter().filter(same));
Some(left)
}
/// Leave out `failed` of `codecs`; those left, `None` (nothing left
/// out) when none would be.
fn without_codec(
&mut self,
codecs: &[VideoCodec],
failed: VideoCodec,
) -> Option<Vec<VideoCodec>> {
let left: Vec<_> =
codecs.iter().copied().filter(|c| *c != failed && !self.codecs.contains(c)).collect();
if left.is_empty() {
return None;
}
self.codecs.push(failed);
Some(left)
}
}
/// `items` for a log line.
fn list<T: std::fmt::Display>(items: &[T]) -> String {
items.iter().map(T::to_string).collect::<Vec<_>>().join(", ")
}
struct ViewerSlot {
state: ViewerState,
message: String,
@@ -572,6 +643,8 @@ struct ViewerSlot {
/// The layer the viewer asked for ([`Signal::Layer`]); `None`: its
/// estimate decides.
pinned: Option<LayerId>,
/// What its connections leave out after one carried nothing.
fallback: Fallback,
}
impl ViewerSlot {
@@ -586,6 +659,7 @@ impl ViewerSlot {
srtp_profile: None,
codec: None,
pinned: None,
fallback: Fallback::default(),
}
}
@@ -716,7 +790,7 @@ impl StreamerSession {
StreamNotification::JoinRequest { viewer, message, remove: false, .. } => {
self.viewers.insert(viewer.0, ViewerSlot::new(message.clone()));
if self.options.auto_accept {
self.offer(*viewer, false, out).await;
self.offer(*viewer, false, out);
} else {
out.event(StreamEvent::Streamer(StreamerEvent::Request {
viewer: *viewer,
@@ -769,7 +843,7 @@ impl StreamerSession {
}
Signal::Reconnect => {
if slot.state != ViewerState::Requested {
self.offer(viewer, true, out).await;
self.offer(viewer, true, out);
}
}
Signal::Layer { layer } => self.pin(viewer, layer, out),
@@ -821,8 +895,9 @@ impl StreamerSession {
}
/// Create a peer for `viewer` and send our offer: in `respondjoinstreamrequest`,
/// or as `reconnectOffer` for a viewer that lost its connection.
async fn offer(&mut self, viewer: ClientId, reconnect: bool, out: &mut Outbox) {
/// or as `reconnectOffer` for a viewer that lost its connection (or
/// whose connection carried nothing, see [`Fallback`]).
fn offer(&mut self, viewer: ClientId, reconnect: bool, out: &mut Outbox) {
let Some(id) = self.id.clone() else { return };
let start = self.start_bitrate();
let layer = self.layers.specs[self.layers.fitting(start)].id;
@@ -841,7 +916,11 @@ impl StreamerSession {
desired_bitrate: Some(desired_bitrate),
layers: &self.layers.specs,
};
match Peer::offer_with(&self.config, &id, &options).await {
let config = match self.viewers.get(&viewer.0) {
Some(slot) => slot.fallback.apply(&self.config),
None => self.config.clone(),
};
match Peer::offer_now(&config, &id, &options) {
Ok((peer, sdp)) => {
// Voelin viewers learn the layers and may pick one (other
// clients skip the attribute); not with RID simulcast, where
@@ -894,7 +973,7 @@ impl StreamerSession {
_ => return Err(SessionError::NoRequest(viewer.0)),
}
if accept {
self.offer(viewer, false, out).await;
self.offer(viewer, false, out);
} else {
self.viewers.remove(&viewer.0);
out.request(Request::Respond { id, viewer, offer: None, accept: false });
@@ -1152,7 +1231,31 @@ impl StreamerSession {
slot.codec = Some(format);
self.emit_viewers(out);
}
PeerEvent::Media(_) | PeerEvent::LayerMedia { .. } => {}
PeerEvent::NoFeedback => {
// Its SRTP fails, or nothing reaches it: offer a new
// connection with the next lower set. A Voelin viewer steps
// down by itself first (it waits half as long).
let profile = slot.peer.as_ref().and_then(Peer::srtp_profile);
let left = profile.and_then(|p| slot.fallback.without_srtp(&self.config, p));
match (profile, left) {
(Some(profile), Some(left)) => {
warn!(
viewer = viewer.0,
"connected, but the viewer reports none of our video; offering a \
new connection without SRTP {profile} (left: {})",
list(&left)
);
self.offer(viewer, true, out);
}
_ => warn!(
viewer = viewer.0,
?profile,
"connected, but the viewer reports none of our video; nothing left to \
fall back to"
),
}
}
PeerEvent::Media(_) | PeerEvent::LayerMedia { .. } | PeerEvent::NoVideo { .. } => {}
PeerEvent::Closed => {
// The viewer may ask for a new offer (`reconnect`); it stays
// until it leaves.
@@ -1306,6 +1409,11 @@ pub struct ViewerSession {
layers: Option<Vec<LayerSpec>>,
/// The layer we asked for; `None`: the streamer's estimate decides.
layer: Option<LayerId>,
/// The streamer's last offer, and the codec our answer took from it.
offer: Option<String>,
codec: Option<VideoCodec>,
/// What our connections leave out after one carried nothing.
fallback: Fallback,
}
impl ViewerSession {
@@ -1330,6 +1438,9 @@ impl ViewerSession {
layer_rid: None,
layers: None,
layer: None,
offer: None,
codec: None,
fallback: Fallback::default(),
}
}
@@ -1382,7 +1493,11 @@ impl ViewerSession {
Ok(Signal::Offer { sdp, reconnect: false }) if self.peer.is_some() => {
let peer = self.peer.as_ref().expect("checked above");
match peer.renegotiate(&sdp).await {
Ok(sdp) => self.signal(Signal::Answer { sdp }, out),
Ok(answer) => {
self.codec = offered_video_codecs(&answer).first().copied();
self.offer = Some(sdp);
self.signal(Signal::Answer { sdp: answer }, out);
}
Err(e) => {
self.fail(format!("cannot answer the streamer's new offer: {e}"), out)
}
@@ -1407,10 +1522,13 @@ impl ViewerSession {
/// Answer an offer (the first one or a `reconnectOffer`) with a new peer.
async fn answer(&mut self, offer: &str, out: &mut Outbox) {
match Peer::answer(&self.config, offer).await {
match Peer::answer(&self.fallback.apply(&self.config), offer).await {
Ok((peer, sdp)) => {
self.peer = Some(peer);
self.state = WatchState::Connecting;
// The streamer sends the first codec of our answer.
self.codec = offered_video_codecs(&sdp).first().copied();
self.offer = Some(offer.to_owned());
self.signal(Signal::Answer { sdp }, out);
let layers = layer::from_sdp(offer).filter(|l| l.len() > 1);
if layers != self.layers {
@@ -1479,6 +1597,46 @@ impl ViewerSession {
Ok(())
}
/// Connected, but no video came ([`PeerEvent::NoVideo`]): ask for a new
/// connection with the next lower set ([`Fallback`]), without the SRTP
/// profile this one negotiated when nothing came at all, without its
/// video codec when audio did (or no other profile is left).
fn fall_back(&mut self, audio: bool, out: &mut Outbox) {
let config = self.fallback.apply(&self.config);
let profile = self.peer.as_ref().and_then(Peer::srtp_profile);
let mut step = None;
if !audio && let Some(profile) = profile {
step = self
.fallback
.without_srtp(&config, profile)
.map(|left| format!("without SRTP {profile} (left: {})", list(&left)));
}
if step.is_none()
&& let Some(codec) = self.codec
{
let offered: Vec<VideoCodec> =
offered_video_codecs(self.offer.as_deref().unwrap_or(""))
.into_iter()
.filter(|c| config.accept_video_codecs.contains(c))
.collect();
step = self
.fallback
.without_codec(&offered, codec)
.map(|left| format!("without {codec} (left: {})", list(&left)));
}
let Some(step) = step else {
warn!(stream = self.id, audio, "connected, but no video; nothing left to fall back to");
return;
};
warn!(
stream = self.id,
audio, "connected, but no video; asking for a new connection {step}"
);
self.peer = None;
self.state = WatchState::Connecting;
self.signal(Signal::Reconnect, out);
}
/// Drop the connection and ask the streamer for a new offer (`reconnect`).
pub fn reconnect(&mut self, out: &mut Outbox) {
if matches!(self.state, WatchState::Connecting | WatchState::Connected) {
@@ -1558,11 +1716,13 @@ impl ViewerSession {
self.event(WatchEvent::Frame(frame), out);
}
}
PeerEvent::NoVideo { audio } => self.fall_back(audio, out),
PeerEvent::KeyframeRequest
| PeerEvent::LayerKeyframeRequest(_)
| PeerEvent::BitrateEstimate(_)
| PeerEvent::Simulcast(_)
| PeerEvent::VideoCodec(_) => {}
| PeerEvent::VideoCodec(_)
| PeerEvent::NoFeedback => {}
PeerEvent::Closed => {
if self.peer.take().is_none() {
return;
+179 -16
View File
@@ -9,10 +9,14 @@ use tokio::time::timeout;
use tsclientlib::ClientId;
use voelin_stream::{
ClientState, EndReason, FrameSource, LayerSpec, LeaveReason, MediaKind, Output, PeerConfig,
Request, SessionError, Signal, StreamEvent, StreamInfo, StreamKind, StreamNotification,
StreamSetup, StreamerEvent, StreamerOptions, Streams, SyntheticSource, ViewerState, WatchEvent,
Request, SessionError, Signal, SrtpProfile, StreamEvent, StreamInfo, StreamKind,
StreamNotification, StreamSetup, StreamerEvent, StreamerOptions, Streams, SyntheticSource,
VideoCodec, VideoFormat, ViewerState, WatchEvent,
};
mod relay;
use relay::{Relay, Rule};
const STREAMER: usize = 0;
const VIEWER: usize = 1;
const IDS: [ClientId; 2] = [ClientId(5), ClientId(6)];
@@ -113,47 +117,87 @@ struct Net {
layer: Option<u8>,
/// Every signal relayed, with the sender's index.
signals: Vec<(usize, Signal)>,
/// Media goes through a relay with this rule, one per connection.
relay: Option<Rule>,
relays: Vec<Relay>,
/// The format the source's video is in (`None`: every viewer gets it).
video_format: Option<VideoFormat>,
}
impl Net {
fn new() -> Self {
let config = PeerConfig::loopback();
Self::with(config.clone(), config, None)
}
/// The streamer's and the viewer's peer configurations, media through a
/// relay with `relay`.
fn with(streamer: PeerConfig, viewer: PeerConfig, relay: Option<Rule>) -> Self {
Self {
server: FakeServer::default(),
clients: IDS.map(|id| Streams::new(id, config.clone())),
clients: [Streams::new(IDS[STREAMER], streamer), Streams::new(IDS[VIEWER], viewer)],
events: Vec::new(),
source: None,
video: 0,
audio: 0,
layer: None,
signals: Vec::new(),
relay,
relays: Vec::new(),
video_format: None,
}
}
/// `request` of client `from` with its SDP pointing at a new relay (an
/// offer) or the last one (an answer).
async fn through_relay(&mut self, from: usize, mut request: Request) -> Request {
let Some(rule) = self.relay else { return request };
match &mut request {
Request::Respond { offer: Some(sdp), .. }
| Request::Signal { signal: Signal::Offer { sdp, .. }, .. }
if from == STREAMER =>
{
let relay = Relay::new(rule).await;
*sdp = relay.offer(sdp);
self.relays.push(relay);
}
Request::Signal { signal: Signal::Answer { sdp }, .. } if from == VIEWER => {
*sdp = self.relays.last().expect("an offer went first").answer(sdp);
}
_ => {}
}
request
}
/// Deliver queued requests until nothing is left.
async fn flush(&mut self) {
loop {
let mut notes = Vec::new();
let mut outputs = Vec::new();
for (i, client) in self.clients.iter_mut().enumerate() {
while let Some(output) = client.poll_output() {
match output {
Output::Request(r) => {
if let Request::Signal { signal, .. } = &r {
self.signals.push((i, signal.clone()));
}
notes.extend(self.server.relay(IDS[i], r));
outputs.push((i, output));
}
}
let mut notes = Vec::new();
for (i, output) in outputs {
match output {
Output::Request(r) => {
let r = self.through_relay(i, r).await;
if let Request::Signal { signal, .. } = &r {
self.signals.push((i, signal.clone()));
}
Output::Event(StreamEvent::Watch {
event: WatchEvent::Frame(f), ..
}) => match f.kind {
notes.extend(self.server.relay(IDS[i], r));
}
Output::Event(StreamEvent::Watch { event: WatchEvent::Frame(f), .. }) => {
match f.kind {
MediaKind::Video => {
self.video += 1;
self.layer = SyntheticSource::frame_layer(&f.data);
}
MediaKind::Audio => self.audio += 1,
},
Output::Event(e) => self.events.push((i, e)),
}
}
Output::Event(e) => self.events.push((i, e)),
}
}
if notes.is_empty() {
@@ -178,7 +222,8 @@ impl Net {
let mut frames = Vec::new();
source.poll_frames(Instant::now(), &mut frames);
for frame in &frames {
self.clients[STREAMER].write_frame(frame);
let format = self.video_format.filter(|_| frame.kind == MediaKind::Video);
self.clients[STREAMER].write_frame_in(frame, format);
}
}
}
@@ -221,6 +266,33 @@ impl Net {
}
}
/// Start a stream that accepts everyone, watch it until connected; its id.
async fn watching(&mut self) -> String {
let options = StreamerOptions { auto_accept: true, ..Default::default() };
self.clients[STREAMER].start(options).unwrap();
self.until("stream in the viewer's list", |i, e| {
i == VIEWER && matches!(e, StreamEvent::Streams(l) if l.len() == 1)
})
.await;
let id = self.clients[VIEWER].directory().by_streamer(IDS[STREAMER]).unwrap().id.clone();
self.clients[VIEWER].watch(&id, "").unwrap();
self.until("viewer connected", |i, e| {
i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected))
})
.await;
id
}
/// The signals `client` sent that `f` accepts.
fn sent(&self, client: usize, f: impl Fn(&Signal) -> bool) -> usize {
self.signals.iter().filter(|(i, s)| *i == client && f(s)).count()
}
/// The first viewer of our stream, as the streamer sees it.
fn viewer(&self) -> voelin_stream::ViewerInfo {
self.clients[STREAMER].streamer().unwrap().viewers().remove(0)
}
/// Run until the viewer received `n` more video and audio frames.
async fn frames(&mut self, n: usize) {
let (video, audio) = (self.video + n, self.audio + n);
@@ -464,3 +536,94 @@ async fn no_layer_request_without_the_offer_listing_layers() {
net.flush().await;
assert!(!net.signals.iter().any(|(_, s)| matches!(s, Signal::Layer { .. })));
}
const AEAD_FIRST: [SrtpProfile; 3] =
[SrtpProfile::AeadAes128Gcm, SrtpProfile::AeadAes256Gcm, SrtpProfile::Aes128CmSha1_80];
/// SRTP that fails after the handshake with these profiles: AES-GCM.
const AEAD: Rule = Rule::FailSrtp(&[7, 8]);
const STALL: Duration = Duration::from_secs(1);
fn config(srtp: &[SrtpProfile], stall_timeout: Duration) -> PeerConfig {
PeerConfig { srtp_profiles: srtp.to_vec(), stall_timeout, ..PeerConfig::loopback() }
}
/// The viewer's connection carries nothing (its SRTP fails after the
/// handshake, with AES-GCM here): the viewer asks for a new one without the
/// AEAD profiles and gets the stream over AES_CM_128_HMAC_SHA1_80; the new
/// connection does not fall back again.
#[tokio::test(flavor = "multi_thread")]
async fn viewer_falls_back_when_srtp_fails() {
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
// The answering viewer is the DTLS server: its order picks AES-GCM. The
// streamer does not step down by itself.
let streamer = config(&SrtpProfile::DEFAULT_ORDER, Duration::MAX);
let mut net = Net::with(streamer, config(&AEAD_FIRST, STALL), Some(AEAD));
net.source = Some(SyntheticSource::new(30, 4000, true));
net.watching().await;
net.frames(10).await;
assert_eq!(net.relays.iter().map(Relay::profile).collect::<Vec<_>>(), [Some(7), Some(1)]);
assert_eq!(net.sent(VIEWER, |s| *s == Signal::Reconnect), 1);
assert_eq!(net.viewer().srtp_profile, Some(SrtpProfile::Aes128CmSha1_80));
// Longer than the stall timeout: the working connection stays.
net.frames(60).await;
assert_eq!(net.sent(VIEWER, |s| *s == Signal::Reconnect), 1);
assert_eq!(net.relays.len(), 2);
}
/// A viewer that gets nothing and does not step down by itself (as the
/// official client may not): its receiver reports never mention our video,
/// so the streamer offers a new connection (`reconnectOffer`) without the
/// profile that failed, and the viewer gets the stream.
#[tokio::test(flavor = "multi_thread")]
async fn streamer_falls_back_when_its_viewer_gets_nothing() {
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
let streamer = config(&AEAD_FIRST, STALL);
let mut net = Net::with(streamer, config(&AEAD_FIRST, Duration::MAX), Some(AEAD));
net.source = Some(SyntheticSource::new(30, 4000, true));
net.watching().await;
net.frames(10).await;
assert_eq!(net.relays.iter().map(Relay::profile).collect::<Vec<_>>(), [Some(7), Some(1)]);
assert_eq!(net.sent(VIEWER, |s| *s == Signal::Reconnect), 0);
assert_eq!(net.sent(STREAMER, |s| matches!(s, Signal::Offer { reconnect: true, .. })), 1);
assert_eq!(net.viewer().srtp_profile, Some(SrtpProfile::Aes128CmSha1_80));
net.frames(90).await;
assert_eq!(net.relays.len(), 2, "the working connection stays");
}
/// Audio comes, video does not (the streamer has no encoder for the codec
/// our answer took): the viewer asks for a new connection without that
/// codec and gets video in the next one.
#[tokio::test(flavor = "multi_thread")]
async fn viewer_falls_back_to_another_codec() {
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
let streamer = PeerConfig {
video_codecs: vec![VideoCodec::Vp9, VideoCodec::Vp8],
..config(&SrtpProfile::DEFAULT_ORDER, Duration::MAX)
};
let mut net = Net::with(streamer, config(&SrtpProfile::DEFAULT_ORDER, STALL), None);
// The source's video is VP8 only.
net.video_format = Some(VideoFormat::Vp8);
net.source = Some(SyntheticSource::new(30, 4000, true));
net.watching().await;
net.frames(10).await;
assert_eq!(net.sent(VIEWER, |s| *s == Signal::Reconnect), 1);
assert_eq!(net.viewer().codec, Some(VideoCodec::Vp8));
}
/// Nothing left to fall back to: SRTP fails with every profile both sides
/// have. The viewer says so and stays; nothing loops.
#[tokio::test(flavor = "multi_thread")]
async fn no_fallback_left() {
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
let only_aead = [SrtpProfile::AeadAes128Gcm];
let streamer = config(&only_aead, Duration::MAX);
let mut net = Net::with(streamer, config(&only_aead, STALL), Some(AEAD));
net.source = Some(SyntheticSource::new(30, 4000, true));
net.watching().await;
let end = Instant::now() + STALL * 3;
while Instant::now() < end {
net.step().await;
}
assert_eq!(net.sent(VIEWER, |s| *s == Signal::Reconnect), 0);
assert_eq!((net.video, net.relays.len()), (0, 1));
}