Give the stream sockets room for high-bitrate bursts

Watching an official client's 1440p60 H.264 stream (6-9 Mbit/s) showed a
very bad frame rate. The peer sockets used the system's default buffers
(208 KB on Linux, about 90 full-size packets once the kernel's per-packet
overhead is counted), so a keyframe of hundreds of packets that arrives
while the peer task is busy overflows them, and every packet the kernel
drops costs the viewer a retransmission or a keyframe.

Each peer socket now asks for 4 MB of receive and send buffer
(PeerConfig::udp_buffer; the kernel caps it at rmem_max/wmem_max). What
the system granted is logged, and once per process with a sysctl hint
when it is less than asked.

Measured on loopback, 9 Mbit/s of noise at 60 fps with a 400 KB keyframe
every second, unpaced (high_bitrate_bursts, --ignored): with the default
buffers the kernel dropped 118-209 datagrams per 5 s and 3 of 300 frames
arrived after a gap; asking for 212992 bytes (what a default rmem_max
allows, doubled by Linux) or for 4 MB, nothing was dropped and every
frame arrived whole.

Also checked: our answer to a real libwebrtc offer (headless Chromium
152, H.264 first, stored as a fixture) keeps nack, nack pli,
transport-cc and an RTX payload type for every H.264 variant, and a relay
that loses one media packet in 25 shows str0m's NACK and retransmissions
repairing every loss before its depacketizer gives up (30 frames). The
relay (tests/relay) also serves the fallback tests that follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-03 22:56:14 +03:00
1 parent e568e96ada
commit 52c3dbf34f
6 files changed
+625 -3

No files matched your search

Generated
+1
View File
@@ -9652,6 +9652,7 @@ dependencies = [
"futures",
"serde",
"serde_json",
"socket2",
"str0m",
"thiserror 2.0.21",
"tokio",
+2
View File
@@ -14,6 +14,8 @@ publish.workspace = true
dimpl = { version = "0.7.4", default-features = false, features = ["aws-lc-rs", "rcgen"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# Socket options std lacks: UDP buffer sizes.
socket2 = "0.6"
str0m = { version = "0.23.1", default-features = false, features = ["aws-lc-rs"] }
thiserror = "2"
tokio = { version = "1", features = ["macros", "net", "rt", "sync", "time"] }
+44 -1
View File
@@ -40,6 +40,9 @@ use crate::stun;
/// [`OfferOptions::start_bitrate`].
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;
/// Video codecs a peer can negotiate.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VideoCodec {
@@ -197,6 +200,13 @@ pub struct PeerConfig {
/// level 3.1 by default. A viewer gets frames of the profile its answer
/// chose ([`PeerEvent::VideoCodec`]). At most two are offered.
pub h264_profile_level_ids: Vec<u32>,
/// Receive and send buffer (bytes) each peer socket asks the system for
/// (`SO_RCVBUF`, `SO_SNDBUF`; Linux caps them at `net.core.rmem_max` and
/// `wmem_max`); 0 keeps the system's default. Linux's default, 208 KB,
/// holds about 90 full-size packets: a 1440p keyframe arriving while
/// the peer task is busy overflows it, and every lost packet costs the
/// viewer a retransmission or a keyframe.
pub udp_buffer: usize,
}
impl Default for PeerConfig {
@@ -215,6 +225,7 @@ impl Default for PeerConfig {
.iter()
.map(|p| h264::profile_level_id(*p, h264::MIN_OFFER_LEVEL))
.collect(),
udp_buffer: DEFAULT_UDP_BUFFER,
}
}
}
@@ -676,7 +687,7 @@ impl Net {
let (tx, incoming) = mpsc::channel(256);
let mut sockets = Vec::new();
for ip in hosts {
let socket = Arc::new(UdpSocket::bind(SocketAddr::new(ip, 0)).await?);
let socket = Arc::new(udp_socket(SocketAddr::new(ip, 0), config.udp_buffer)?);
let local = socket.local_addr()?;
match Candidate::host(local, "udp") {
Ok(c) => {
@@ -720,6 +731,38 @@ impl Net {
}
}
/// A UDP socket on `addr` asking for `buffer` bytes of receive and send
/// buffer (0: the system's default), see [`PeerConfig::udp_buffer`]. What
/// the system granted is logged; once per process with a hint when it is
/// less than asked.
fn udp_socket(addr: SocketAddr, buffer: usize) -> std::io::Result<UdpSocket> {
use socket2::{Domain, Protocol, Socket, Type};
static CAPPED: std::sync::Once = std::sync::Once::new();
let socket = Socket::new(Domain::for_address(addr), Type::DGRAM, Some(Protocol::UDP))?;
if buffer > 0 {
// Best effort: the system caps what it grants, and a smaller
// buffer only costs packets under load.
let _ = socket.set_recv_buffer_size(buffer);
let _ = socket.set_send_buffer_size(buffer);
}
socket.set_nonblocking(true)?;
socket.bind(&addr.into())?;
let (receive, send) =
(socket.recv_buffer_size().unwrap_or(0), socket.send_buffer_size().unwrap_or(0));
debug!(%addr, asked = buffer, receive, send, "UDP socket buffers");
if receive < buffer {
CAPPED.call_once(|| {
warn!(
asked = buffer,
granted = receive,
"the system grants less UDP receive buffer than asked; high-bitrate streams \
may lose packets in bursts (Linux: sysctl net.core.rmem_max)"
);
});
}
UdpSocket::from_std(socket.into())
}
struct PendingStun {
id: stun::TransactionId,
server: SocketAddr,
@@ -0,0 +1,192 @@
v=0
o=- 9203238114082164645 2 IN IP4 127.0.0.1
s=-
t=0 0
a=group:BUNDLE 0 1
a=extmap-allow-mixed
a=msid-semantic: WMS
m=video 9 UDP/TLS/RTP/SAVPF 102 103 104 107 108 109 114 115 116 117 39 40 96 97 45 46 98 99 100 101 118 119 120
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-ufrag:DFXJ
a=ice-pwd:lU2jJo7vdAba3Jc3gl5jJTsP
a=ice-options:trickle
a=fingerprint:sha-256 04:9C:62:DF:8B:89:2E:CD:3F:61:FF:45:7F:3D:35:5C:DD:7C:A1:4C:CE:59:A8:89:DE:80:79:41:EA:84:41:7F
a=setup:actpass
a=mid:0
a=extmap:1 urn:ietf:params:rtp-hdrext:toffset
a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
a=extmap:3 urn:3gpp:video-orientation
a=extmap:4 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
a=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay
a=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/video-content-type
a=extmap:7 http://www.webrtc.org/experiments/rtp-hdrext/video-timing
a=extmap:8 http://www.webrtc.org/experiments/rtp-hdrext/color-space
a=extmap:9 urn:ietf:params:rtp-hdrext:sdes:mid
a=extmap:10 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id
a=extmap:11 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id
a=sendonly
a=msid:- 94762b0c-48a6-4384-90af-71e6ea13d9b6
a=rtcp-mux
a=rtcp-rsize
a=rtcp-xr:rcvr-rtt=all
a=rtcp-fb:102 rrtr
a=rtcp-fb:103 rrtr
a=rtcp-fb:104 rrtr
a=rtcp-fb:107 rrtr
a=rtcp-fb:108 rrtr
a=rtcp-fb:109 rrtr
a=rtcp-fb:114 rrtr
a=rtcp-fb:115 rrtr
a=rtcp-fb:116 rrtr
a=rtcp-fb:117 rrtr
a=rtcp-fb:39 rrtr
a=rtcp-fb:40 rrtr
a=rtcp-fb:96 rrtr
a=rtcp-fb:97 rrtr
a=rtcp-fb:45 rrtr
a=rtcp-fb:46 rrtr
a=rtcp-fb:98 rrtr
a=rtcp-fb:99 rrtr
a=rtcp-fb:100 rrtr
a=rtcp-fb:101 rrtr
a=rtcp-fb:118 rrtr
a=rtcp-fb:119 rrtr
a=rtcp-fb:120 rrtr
a=rtpmap:102 H264/90000
a=rtcp-fb:102 goog-remb
a=rtcp-fb:102 transport-cc
a=rtcp-fb:102 ccm fir
a=rtcp-fb:102 nack
a=rtcp-fb:102 nack pli
a=fmtp:102 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f
a=rtpmap:103 rtx/90000
a=fmtp:103 apt=102
a=rtpmap:104 H264/90000
a=rtcp-fb:104 goog-remb
a=rtcp-fb:104 transport-cc
a=rtcp-fb:104 ccm fir
a=rtcp-fb:104 nack
a=rtcp-fb:104 nack pli
a=fmtp:104 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42001f
a=rtpmap:107 rtx/90000
a=fmtp:107 apt=104
a=rtpmap:108 H264/90000
a=rtcp-fb:108 goog-remb
a=rtcp-fb:108 transport-cc
a=rtcp-fb:108 ccm fir
a=rtcp-fb:108 nack
a=rtcp-fb:108 nack pli
a=fmtp:108 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f
a=rtpmap:109 rtx/90000
a=fmtp:109 apt=108
a=rtpmap:114 H264/90000
a=rtcp-fb:114 goog-remb
a=rtcp-fb:114 transport-cc
a=rtcp-fb:114 ccm fir
a=rtcp-fb:114 nack
a=rtcp-fb:114 nack pli
a=fmtp:114 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f
a=rtpmap:115 rtx/90000
a=fmtp:115 apt=114
a=rtpmap:116 H264/90000
a=rtcp-fb:116 goog-remb
a=rtcp-fb:116 transport-cc
a=rtcp-fb:116 ccm fir
a=rtcp-fb:116 nack
a=rtcp-fb:116 nack pli
a=fmtp:116 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d001f
a=rtpmap:117 rtx/90000
a=fmtp:117 apt=116
a=rtpmap:39 H264/90000
a=rtcp-fb:39 goog-remb
a=rtcp-fb:39 transport-cc
a=rtcp-fb:39 ccm fir
a=rtcp-fb:39 nack
a=rtcp-fb:39 nack pli
a=fmtp:39 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=4d001f
a=rtpmap:40 rtx/90000
a=fmtp:40 apt=39
a=rtpmap:96 VP8/90000
a=rtcp-fb:96 goog-remb
a=rtcp-fb:96 transport-cc
a=rtcp-fb:96 ccm fir
a=rtcp-fb:96 nack
a=rtcp-fb:96 nack pli
a=rtpmap:97 rtx/90000
a=fmtp:97 apt=96
a=rtpmap:45 AV1/90000
a=rtcp-fb:45 goog-remb
a=rtcp-fb:45 transport-cc
a=rtcp-fb:45 ccm fir
a=rtcp-fb:45 nack
a=rtcp-fb:45 nack pli
a=fmtp:45 level-idx=5;profile=0;tier=0
a=rtpmap:46 rtx/90000
a=fmtp:46 apt=45
a=rtpmap:98 VP9/90000
a=rtcp-fb:98 goog-remb
a=rtcp-fb:98 transport-cc
a=rtcp-fb:98 ccm fir
a=rtcp-fb:98 nack
a=rtcp-fb:98 nack pli
a=fmtp:98 profile-id=0
a=rtpmap:99 rtx/90000
a=fmtp:99 apt=98
a=rtpmap:100 VP9/90000
a=rtcp-fb:100 goog-remb
a=rtcp-fb:100 transport-cc
a=rtcp-fb:100 ccm fir
a=rtcp-fb:100 nack
a=rtcp-fb:100 nack pli
a=fmtp:100 profile-id=2
a=rtpmap:101 rtx/90000
a=fmtp:101 apt=100
a=rtpmap:118 red/90000
a=rtpmap:119 rtx/90000
a=fmtp:119 apt=118
a=rtpmap:120 ulpfec/90000
a=ssrc-group:FID 3176611392 128448062
a=ssrc:3176611392 cname:l3Nm9fNJE6+G+Rx2
a=ssrc:3176611392 msid:- 94762b0c-48a6-4384-90af-71e6ea13d9b6
a=ssrc:128448062 cname:l3Nm9fNJE6+G+Rx2
a=ssrc:128448062 msid:- 94762b0c-48a6-4384-90af-71e6ea13d9b6
m=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-ufrag:DFXJ
a=ice-pwd:lU2jJo7vdAba3Jc3gl5jJTsP
a=ice-options:trickle
a=fingerprint:sha-256 04:9C:62:DF:8B:89:2E:CD:3F:61:FF:45:7F:3D:35:5C:DD:7C:A1:4C:CE:59:A8:89:DE:80:79:41:EA:84:41:7F
a=setup:actpass
a=mid:1
a=extmap:14 urn:ietf:params:rtp-hdrext:ssrc-audio-level
a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
a=extmap:4 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
a=extmap:9 urn:ietf:params:rtp-hdrext:sdes:mid
a=sendonly
a=msid:- 68074a2b-7d1a-4909-a331-99c02e2b666e
a=rtcp-mux
a=rtcp-rsize
a=rtcp-xr:rcvr-rtt=all
a=rtcp-fb:111 rrtr
a=rtcp-fb:63 rrtr
a=rtcp-fb:9 rrtr
a=rtcp-fb:0 rrtr
a=rtcp-fb:8 rrtr
a=rtcp-fb:13 rrtr
a=rtcp-fb:110 rrtr
a=rtcp-fb:126 rrtr
a=rtpmap:111 opus/48000/2
a=rtcp-fb:111 transport-cc
a=fmtp:111 minptime=10;useinbandfec=1
a=rtpmap:63 red/48000/2
a=fmtp:63 111/111
a=rtpmap:9 G722/8000
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
a=rtpmap:13 CN/8000
a=rtpmap:110 telephone-event/48000
a=rtpmap:126 telephone-event/8000
a=ssrc:4046889866 cname:l3Nm9fNJE6+G+Rx2
a=ssrc:4046889866 msid:- 68074a2b-7d1a-4909-a331-99c02e2b666e
+163 -2
View File
@@ -1,11 +1,15 @@
//! Two peers on loopback: offer/answer, then video and audio frames flow;
//! the SRTP profile DTLS negotiates; bandwidth estimates at the streamer.
//! the SRTP profile DTLS negotiates; bandwidth estimates at the streamer;
//! losses repaired by retransmission; bursts of a high-bitrate stream.
use std::time::Duration;
use std::time::{Duration, Instant};
use tokio::time::timeout;
use voelin_stream::{MediaKind, MediaTime, Peer, PeerConfig, PeerEvent, SrtpProfile};
mod relay;
use relay::{Relay, Rule};
/// Bytes that look like a VP8 keyframe (frame tag + start code), then filler.
pub fn fake_vp8_keyframe(seq: u8, len: usize) -> Vec<u8> {
let mut f = vec![0x10, 0x02, 0x00, 0x9d, 0x01, 0x2a, 0x80, 0x02, 0xe0, 0x01];
@@ -124,3 +128,160 @@ async fn srtp_profile_order() {
let gcm_only = PeerConfig { srtp_profiles: vec![AeadAes128Gcm], ..PeerConfig::loopback() };
assert_eq!(negotiate(&gcm_only, &default).await, [Some(AeadAes128Gcm); 2]);
}
/// The payload types of the first video section of `sdp` with `name`.
fn video_pts<'a>(sdp: &'a str, name: &str) -> Vec<&'a str> {
let video = sdp.split("m=").find(|s| s.starts_with("video")).unwrap();
video
.lines()
.filter_map(|l| l.strip_prefix("a=rtpmap:"))
.filter(|l| l.contains(&format!(" {name}/")))
.filter_map(|l| l.split(' ').next())
.collect()
}
/// Our answer to a libwebrtc offer (headless Chromium 152, H.264 first, as
/// the official client streams) keeps what repairs losses and paces the
/// sender: NACK with retransmissions (RTX), PLI, transport-cc.
#[tokio::test]
async fn answers_keep_loss_repair_and_feedback() {
let offer = include_str!("data/chromium-152-h264-offer.sdp");
let (_viewer, answer) = Peer::answer(&PeerConfig::loopback(), offer).await.unwrap();
let h264 = video_pts(&answer, "H264");
assert!(!h264.is_empty(), "{answer}");
for pt in h264 {
for fb in ["nack", "nack pli", "transport-cc"] {
let line = format!("a=rtcp-fb:{pt} {fb}\r\n");
assert!(answer.contains(&line), "no {line:?} in\n{answer}");
}
assert!(answer.contains(&format!(" apt={pt}")), "no retransmissions for {pt}:\n{answer}");
}
assert!(answer.contains("transport-wide-cc"), "{answer}");
}
/// Video frames of `size` bytes that look like VP8 to the depacketizer
/// (keyframe tag on `keyframe`), the rest pseudo-random: nothing on the
/// path compresses or repeats.
fn noise_frame(seq: u64, size: usize, keyframe: bool) -> Vec<u8> {
let mut state = seq.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1;
let mut frame = fake_vp8_keyframe(seq as u8, 0);
frame[0] |= u8::from(!keyframe);
frame.extend((0..size).map(|_| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state as u8
}));
frame
}
/// Connect `streamer` and `viewer` configurations, through `relay` if given.
async fn connect(
streamer: &PeerConfig,
viewer: &PeerConfig,
relay: Option<&Relay>,
) -> (Peer, Peer) {
let (mut s, offer) = Peer::offer(streamer, "loss").await.unwrap();
let offer = relay.map_or(offer.clone(), |r| r.offer(&offer));
let (mut v, answer) = Peer::answer(viewer, &offer).await.unwrap();
let answer = relay.map_or(answer.clone(), |r| r.answer(&answer));
s.accept_answer(&answer).await.unwrap();
tokio::join!(wait_connected(&mut s), wait_connected(&mut v));
(s, v)
}
/// What the viewer got of a stream: frames, and those after a gap.
#[derive(Debug, Default)]
struct Received {
frames: u64,
gaps: u64,
}
/// Send `frames` video frames at `fps` (a keyframe of `keyframe_size`
/// every `keyframe_every`, else `size`); count what the viewer receives
/// until a second of silence.
async fn stream_noise(
streamer: Peer,
viewer: &mut Peer,
(frames, fps, size): (u64, u64, usize),
(keyframe_every, keyframe_size): (u64, usize),
) -> Received {
let sender = tokio::spawn(async move {
let start = Instant::now();
for i in 0..frames {
let keyframe = i % keyframe_every == 0;
let data = noise_frame(i, if keyframe { keyframe_size } else { size }, keyframe);
streamer.write(MediaKind::Video, MediaTime::from_90khz(i * 90_000 / fps), data);
let next = start + Duration::from_micros((i + 1) * 1_000_000 / fps);
tokio::time::sleep_until(next.into()).await;
}
streamer
});
let mut received = Received::default();
while let Ok(Some(event)) = timeout(Duration::from_secs(1), viewer.next_event()).await {
if let PeerEvent::Media(f) = event
&& f.kind == MediaKind::Video
{
received.frames += 1;
received.gaps += u64::from(!f.contiguous);
}
}
drop(sender.await.unwrap());
received
}
/// One media packet in 25 lost on the way to the viewer: the viewer asks
/// again (NACK) and the streamer retransmits (RTX) before the depacketizer
/// gives up, so every frame arrives whole and in order.
#[tokio::test(flavor = "multi_thread")]
async fn losses_are_repaired_by_retransmission() {
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
let relay = Relay::new(Rule::LoseEvery(25)).await;
let config = PeerConfig { bandwidth_estimation: false, ..PeerConfig::loopback() };
let (streamer, mut viewer) = connect(&config, &config, Some(&relay)).await;
// 3 s at 30 fps, 12 KB frames (about 10 packets each), keyframes of 60 KB.
let received = stream_noise(streamer, &mut viewer, (90, 30, 12_000), (30, 60_000)).await;
let (media, lost) = relay.media();
eprintln!("{received:?}; relay: {lost} of {media} media packets lost");
assert!(lost >= 30, "the relay lost too little: {lost} of {media}");
assert_eq!(received.frames, 90, "{received:?}");
assert_eq!(received.gaps, 0, "a loss reached the viewer: {received:?}");
}
/// UDP receive errors of this host so far (`RcvbufErrors` in
/// `/proc/net/snmp`: datagrams dropped because a socket's buffer was full).
fn receive_buffer_errors() -> Option<u64> {
let snmp = std::fs::read_to_string("/proc/net/snmp").ok()?;
let mut udp = snmp.lines().filter(|l| l.starts_with("Udp: "));
let (names, values) = (udp.next()?, udp.next()?);
let column = names.split_whitespace().position(|n| n == "RcvbufErrors")?;
values.split_whitespace().nth(column)?.parse().ok()
}
/// A 9 Mbit/s stream at 60 fps with a 400 KB keyframe every second, sent
/// without pacing (the worst case of a 1440p stream), over loopback with
/// the system's socket buffers, with what Linux's default `rmem_max`
/// (212992) lets us ask for, and with ours: datagrams the kernel dropped
/// (host-wide counter), frames that arrived, and those after a gap. A
/// measurement, not a check: `-- --ignored --nocapture`.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "a measurement (about 20 s)"]
async fn high_bitrate_bursts() {
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
for buffer in [0, 212_992, voelin_stream::peer::DEFAULT_UDP_BUFFER] {
let config = PeerConfig {
bandwidth_estimation: false,
udp_buffer: buffer,
..PeerConfig::loopback()
};
let (streamer, mut viewer) = connect(&config, &config, None).await;
let before = receive_buffer_errors();
let received = stream_noise(streamer, &mut viewer, (300, 60, 18_750), (60, 400_000)).await;
let dropped = before.zip(receive_buffer_errors()).map(|(a, b)| b - a);
eprintln!(
"socket buffers asked: {buffer} bytes; datagrams dropped by the kernel: \
{dropped:?}; frames received: {} of 300, after a gap: {}",
received.frames, received.gaps
);
}
}
+223
View File
@@ -0,0 +1,223 @@
//! A UDP relay between a streamer's and a viewer's peer on loopback that
//! loses packets on purpose: every n-th media packet towards the viewer
//! (losses that NACK and retransmissions must repair), or everything but
//! STUN and DTLS once the handshake picked certain SRTP profiles (a peer
//! whose SRTP fails after a successful handshake).
//!
//! Put it between the peers by rewriting their host candidates:
//! [`Relay::offer`] on the streamer's offer, [`Relay::answer`] on the
//! viewer's answer. Packets are told apart as RFC 7983 does.
#![allow(dead_code, reason = "each test file uses part of it")]
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use tokio::net::UdpSocket;
/// What the relay lets through.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Rule {
Pass,
/// Every n-th RTP packet towards the viewer is lost (retransmissions
/// included).
LoseEvery(u64),
/// Once a DTLS 1.2 ServerHello selects one of these SRTP profiles
/// (RFC 5764 ids: 1 AES_CM_128_HMAC_SHA1_80, 7 AEAD_AES_128_GCM, 8
/// AEAD_AES_256_GCM), no RTP or RTCP gets through either way.
FailSrtp(&'static [u16]),
}
/// One end of the relay.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Towards {
Viewer,
Streamer,
}
struct State {
rule: Mutex<Rule>,
streamer: OnceLock<SocketAddr>,
viewer: OnceLock<SocketAddr>,
/// A ServerHello picked a failing profile.
failing: AtomicBool,
/// The SRTP profile the handshake selected (0 before).
profile: AtomicU64,
/// RTP packets towards the viewer, and how many were lost on purpose.
media: AtomicU64,
lost: AtomicU64,
}
pub struct Relay {
/// Where the streamer reaches the viewer.
a: SocketAddr,
/// Where the viewer reaches the streamer.
b: SocketAddr,
state: Arc<State>,
tasks: Vec<tokio::task::JoinHandle<()>>,
}
impl Drop for Relay {
fn drop(&mut self) {
for task in &self.tasks {
task.abort();
}
}
}
/// The first host candidate's address in `sdp`.
pub fn host_candidate(sdp: &str) -> Option<SocketAddr> {
sdp.lines().find_map(|l| {
let parts: Vec<&str> = l.trim().split(' ').collect();
let typ = parts.iter().position(|p| *p == "typ")?;
if !parts[0].contains("candidate:") || parts.get(typ + 1) != Some(&"host") || typ < 2 {
return None;
}
format!("{}:{}", parts[typ - 2], parts[typ - 1]).parse().ok()
})
}
/// `sdp` with the candidate address `from` replaced by `to`.
fn replace(sdp: &str, from: SocketAddr, to: SocketAddr) -> String {
sdp.replace(
&format!(" {} {} typ ", from.ip(), from.port()),
&format!(" {} {} typ ", to.ip(), to.port()),
)
}
/// The SRTP profile a DTLS 1.2 ServerHello in `data` selects.
fn server_hello_profile(data: &[u8]) -> Option<u16> {
// Handshake record; its first message a ServerHello.
if data.first() != Some(&22) || data.get(13) != Some(&2) {
return None;
}
// use_srtp: type 14, length 5, one profile, no MKI.
data.windows(9).find_map(|w| {
(w[..6] == [0, 14, 0, 5, 0, 2] && w[8] == 0).then(|| u16::from_be_bytes([w[6], w[7]]))
})
}
/// RTP or RTCP (RFC 7983), and RTCP among them (RFC 5761).
fn is_media(data: &[u8]) -> bool {
data.first().is_some_and(|b| (128..=191).contains(b))
}
fn is_rtcp(data: &[u8]) -> bool {
is_media(data) && data.get(1).is_some_and(|b| (192..=223).contains(b))
}
impl State {
/// Whether `data`, on its way `to`, gets through.
fn passes(&self, to: Towards, data: &[u8]) -> bool {
let rule = *self.rule.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(profile) = server_hello_profile(data) {
self.profile.store(u64::from(profile), Ordering::Relaxed);
let fails = matches!(rule, Rule::FailSrtp(set) if set.contains(&profile));
self.failing.store(fails, Ordering::Relaxed);
}
if !is_media(data) {
return true;
}
if self.failing.load(Ordering::Relaxed) {
return false;
}
if to == Towards::Viewer && !is_rtcp(data) {
let n = self.media.fetch_add(1, Ordering::Relaxed) + 1;
if let Rule::LoseEvery(every) = rule
&& n.is_multiple_of(every)
{
self.lost.fetch_add(1, Ordering::Relaxed);
return false;
}
}
true
}
}
impl Relay {
pub async fn new(rule: Rule) -> Self {
let a = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
let b = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
let state = Arc::new(State {
rule: Mutex::new(rule),
streamer: OnceLock::new(),
viewer: OnceLock::new(),
failing: AtomicBool::new(false),
profile: AtomicU64::new(0),
media: AtomicU64::new(0),
lost: AtomicU64::new(0),
});
let (addr_a, addr_b) = (a.local_addr().unwrap(), b.local_addr().unwrap());
// From the streamer on a, to the viewer from b; and back.
let forward = |from: Arc<UdpSocket>, to: Arc<UdpSocket>, towards: Towards| {
let state = state.clone();
tokio::spawn(async move {
let mut buf = vec![0; 2048];
loop {
let Ok((n, _)) = from.recv_from(&mut buf).await else { continue };
let target = match towards {
Towards::Viewer => state.viewer.get(),
Towards::Streamer => state.streamer.get(),
};
if let Some(target) = target
&& state.passes(towards, &buf[..n])
{
let _ = to.send_to(&buf[..n], target).await;
}
}
})
};
let tasks =
vec![forward(a.clone(), b.clone(), Towards::Viewer), forward(b, a, Towards::Streamer)];
Self { a: addr_a, b: addr_b, state, tasks }
}
/// The streamer's offer as the viewer gets it: the relay in place of
/// the streamer.
pub fn offer(&self, sdp: &str) -> String {
let streamer = host_candidate(sdp).expect("a host candidate in the offer");
let _ = self.state.streamer.set(streamer);
replace(sdp, streamer, self.b)
}
/// The viewer's answer as the streamer gets it: the relay in place of
/// the viewer.
pub fn answer(&self, sdp: &str) -> String {
let viewer = host_candidate(sdp).expect("a host candidate in the answer");
let _ = self.state.viewer.set(viewer);
replace(sdp, viewer, self.a)
}
pub fn set_rule(&self, rule: Rule) {
*self.state.rule.lock().unwrap_or_else(PoisonError::into_inner) = rule;
}
/// The SRTP profile id the handshake selected, if it was seen.
pub fn profile(&self) -> Option<u16> {
let profile = self.state.profile.load(Ordering::Relaxed);
(profile != 0).then_some(profile as u16)
}
/// RTP packets towards the viewer, and how many of them were lost.
pub fn media(&self) -> (u64, u64) {
(self.state.media.load(Ordering::Relaxed), self.state.lost.load(Ordering::Relaxed))
}
}
#[test]
fn packets_are_told_apart() {
let mut hello = vec![22, 0xfe, 0xfd, 0, 0, 0, 0, 0, 0, 0, 0, 0, 80, 2];
hello.extend([0; 40]);
hello.extend([0, 14, 0, 5, 0, 2, 0, 7, 0]);
assert_eq!(server_hello_profile(&hello), Some(7));
hello[13] = 1;
assert_eq!(server_hello_profile(&hello), None, "a ClientHello");
assert!(is_media(&[0x80, 96]) && !is_rtcp(&[0x80, 96]));
assert!(is_rtcp(&[0x81, 201]) && !is_media(&[0, 1]));
let sdp = "a=candidate:1 1 udp 2130706431 127.0.0.1 50000 typ host\r\n";
let addr = host_candidate(sdp).unwrap();
assert_eq!(addr, "127.0.0.1:50000".parse().unwrap());
let to = "127.0.0.1:1".parse().unwrap();
assert_eq!(replace(sdp, addr, to), "a=candidate:1 1 udp 2130706431 127.0.0.1 1 typ host\r\n");
}