Merge branch 'claude/gifted-lovelace-1crlx2' into worktree-agent-a5ecbed1e5dd55ddc

# Conflicts:
#	tools/voelinctl/src/stream.rs
This commit is contained in:
selikhov committed 2026-10-04 04:48:34 +03:00
commit 92344651ca
28 files changed
+2454 -299

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 {
+17 -12
View File
@@ -1,6 +1,6 @@
//! Feedback from the stream sessions to the encoders of our stream's layers:
//! keyframe requests and bitrate targets per [`LayerId`], and the video
//! codecs the viewers negotiated.
//! formats (codec and H.264 profile) the viewers negotiated.
//!
//! [`LayerFeedback`] is shared between the stream session (which writes) and
//! encoder threads (which read every frame). Both sides only use atomics;
@@ -13,7 +13,7 @@ use std::sync::OnceLock;
use std::sync::atomic::{AtomicU8, AtomicU16, AtomicU64, Ordering};
use crate::layer::{LayerId, LayerSet};
use crate::peer::VideoCodec;
use crate::peer::VideoFormat;
/// Words of the keyframe bitmap: one bit per layer id.
const WORDS: usize = (LayerId::MAX as usize + 1) / 64;
@@ -32,7 +32,7 @@ pub struct LayerFeedback {
top: AtomicU16,
/// Bitrate targets (bit/s, 0: none) in chunks of [`CHUNK`] layer ids.
bitrates: Box<[OnceLock<Box<[AtomicU64]>>]>,
/// [`VideoCodec::bit`]s of the codecs connected viewers negotiated.
/// [`VideoFormat::bit`]s of the formats connected viewers negotiated.
codecs: AtomicU8,
}
@@ -128,15 +128,15 @@ impl LayerFeedback {
(bitrate != 0).then_some(bitrate)
}
/// The video codecs the viewers negotiated.
pub fn set_codecs(&self, codecs: impl IntoIterator<Item = VideoCodec>) {
let bits = codecs.into_iter().fold(0, |bits, c| bits | c.bit());
/// The video formats the viewers negotiated.
pub fn set_codecs(&self, formats: impl IntoIterator<Item = VideoFormat>) {
let bits = formats.into_iter().fold(0, |bits, f| bits | f.bit());
self.codecs.store(bits, Ordering::Relaxed);
}
/// Whether a viewer negotiated `codec`.
pub fn has_codec(&self, codec: VideoCodec) -> bool {
self.codecs.load(Ordering::Relaxed) & codec.bit() != 0
/// Whether a viewer negotiated `format`.
pub fn has_codec(&self, format: VideoFormat) -> bool {
self.codecs.load(Ordering::Relaxed) & format.bit() != 0
}
/// Whether any viewer negotiated a codec yet.
@@ -184,11 +184,16 @@ mod tests {
#[test]
fn codecs() {
use crate::h264::H264Profile::{ConstrainedBaseline, ConstrainedHigh};
let f = LayerFeedback::new();
assert!(!f.has_codecs());
f.set_codecs([VideoCodec::Vp8, VideoCodec::H265, VideoCodec::Vp8]);
assert!(f.has_codec(VideoCodec::Vp8) && f.has_codec(VideoCodec::H265));
assert!(!f.has_codec(VideoCodec::H264));
f.set_codecs([VideoFormat::Vp8, VideoFormat::H265, VideoFormat::Vp8]);
assert!(f.has_codec(VideoFormat::Vp8) && f.has_codec(VideoFormat::H265));
assert!(!f.has_codec(VideoFormat::H264(ConstrainedHigh)));
// H.264 in each profile is a format of its own.
f.set_codecs([VideoFormat::H264(ConstrainedBaseline)]);
assert!(f.has_codec(VideoFormat::H264(ConstrainedBaseline)));
assert!(!f.has_codec(VideoFormat::H264(ConstrainedHigh)));
f.set_codecs([]);
assert!(!f.has_codecs());
}
+27 -2
View File
@@ -3,16 +3,32 @@
//! H.264 Table A-1), instead of a fixed level.
/// Profile of our H.264 streams.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum H264Profile {
/// Constrained High (`profile_idc` 100, `constraint_set4` and `5`): what
/// TeamSpeak clients decode.
#[default]
ConstrainedHigh,
/// Constrained Baseline (`profile_idc` 66, `constraint_set0` and `1`).
/// Constrained Baseline (`profile_idc` 66, `constraint_set0` and `1`):
/// what every H.264 decoder takes; libwebrtc's software decoder lists
/// no High profile.
ConstrainedBaseline,
}
impl H264Profile {
/// The order an offer lists them in: Constrained High (better pictures
/// for the bitrate), then Constrained Baseline for peers that take only
/// that. The streamer encodes each viewer in the one its answer chose.
pub const LADDER: [Self; 2] = [Self::ConstrainedHigh, Self::ConstrainedBaseline];
/// The profile of a `profile-level-id` (`profile_idc` and `profile-iop`
/// as [`profile_level_id`] writes them; any level); `None` for other
/// profiles.
pub fn from_profile_level_id(id: u32) -> Option<Self> {
Self::LADDER.into_iter().find(|p| profile_level_id(*p, 0) == id & !0xff)
}
}
/// Level limits: `level_idc`, macroblocks per second, macroblocks per frame,
/// bitrate in kbit/s (Baseline; High allows 1.25 times that).
const LEVELS: [(u8, u64, u64, u64); 19] = [
@@ -127,5 +143,14 @@ mod tests {
assert_eq!(profile_level_id(H264Profile::ConstrainedBaseline, 31), 0x42e01f);
assert_eq!(offer_profile_level_id(HIGH, 320, 240, 15, 200_000), 0x640c1f);
assert_eq!(offer_profile_level_id(HIGH, 1920, 1080, 60, 8_000_000), 0x640c2a);
// Back from the SDP, at any level; other profiles are not ours.
assert_eq!(H264Profile::from_profile_level_id(0x640c2a), Some(HIGH));
assert_eq!(
H264Profile::from_profile_level_id(0x42e01f),
Some(H264Profile::ConstrainedBaseline)
);
for other in [0x42001f, 0x4d001f, 0x64001f] {
assert_eq!(H264Profile::from_profile_level_id(other), None);
}
}
}
+4 -1
View File
@@ -14,6 +14,7 @@ pub mod dtls;
pub mod feedback;
pub mod h264;
pub mod layer;
pub mod mdns;
pub mod peer;
pub mod proto;
pub mod session;
@@ -26,7 +27,9 @@ pub use dtls::SrtpProfile;
pub use feedback::LayerFeedback;
pub use h264::H264Profile;
pub use layer::{LayerId, LayerSet, LayerSpec};
pub use peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerError, PeerEvent, VideoCodec};
pub use peer::{
MediaFrame, OfferOptions, Peer, PeerConfig, PeerError, PeerEvent, VideoCodec, VideoFormat,
};
pub use proto::{LeaveReason, StreamInfo, StreamKind, StreamNotification, StreamSetup};
pub use session::{
EndReason, Output, Request, SessionError, StreamDirectory, StreamEvent, StreamerEvent,
+172
View File
@@ -0,0 +1,172 @@
//! Host candidates behind mDNS names (`<uuid>.local`): browsers and other
//! libwebrtc builds hide their host addresses this way, and str0m takes
//! only IP addresses. [`resolve`] asks with a multicast DNS query
//! (RFC 6762) for the name's IPv4 address.
//!
//! The query goes out from port 5353, shared with the system's responder
//! (`SO_REUSEADDR`), and the answer is read from the multicast group:
//! Chromium's responder answers only such queries, not "legacy" ones from
//! another port (checked against Chromium 152). Where 5353 cannot be
//! shared, the query goes out from a port of our own, which responders
//! that follow RFC 6762 answer directly.
use std::net::{Ipv4Addr, SocketAddr};
use std::time::Duration;
use socket2::{Domain, Protocol, Socket, Type};
use tokio::net::UdpSocket;
use tokio::time::Instant;
const GROUP: Ipv4Addr = Ipv4Addr::new(224, 0, 0, 251);
const PORT: u16 = 5353;
/// The mDNS name of a candidate line (`candidate:...`, `a=` prefix
/// optional), if its address is one.
pub fn candidate_name(line: &str) -> Option<&str> {
let line = line.trim();
if !line.trim_start_matches("a=").starts_with("candidate:") {
return None;
}
let address = line.split_whitespace().nth(4)?;
address.to_ascii_lowercase().ends_with(".local").then_some(address)
}
/// The IPv4 address of `name` (`<uuid>.local`), asked on the local network
/// for up to `timeout`; `None` if nobody answered.
pub async fn resolve(name: &str, timeout: Duration) -> Option<Ipv4Addr> {
let query = query(name)?;
let socket = multicast_socket(PORT).or_else(|_| multicast_socket(0)).ok()?;
let deadline = Instant::now() + timeout;
let mut buf = vec![0; 1500];
// Asked again after 0.5 s and 1.5 s: a first query may go unanswered.
let mut again = [Duration::from_millis(500), Duration::from_secs(1)].into_iter();
loop {
socket.send_to(&query, (GROUP, PORT)).await.ok()?;
let wait = again.next().map_or(deadline, |d| (Instant::now() + d).min(deadline));
while let Ok(received) = tokio::time::timeout_at(wait, socket.recv_from(&mut buf)).await {
let (n, _) = received.ok()?;
if let Some(ip) = answer(&buf[..n], name) {
return Some(ip);
}
}
if Instant::now() >= deadline {
return None;
}
}
}
/// A UDP socket on `port` (shared) that receives the mDNS group.
fn multicast_socket(port: u16) -> std::io::Result<UdpSocket> {
let socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?;
socket.set_reuse_address(true)?;
socket.set_nonblocking(true)?;
socket.bind(&SocketAddr::from((Ipv4Addr::UNSPECIFIED, port)).into())?;
socket.join_multicast_v4(&GROUP, &Ipv4Addr::UNSPECIFIED)?;
socket.set_multicast_ttl_v4(255)?;
UdpSocket::from_std(socket.into())
}
/// A query for the A record of `name`; `None` for a name DNS cannot carry.
fn query(name: &str) -> Option<Vec<u8>> {
// Id 0, no flags, one question.
let mut packet = vec![0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0];
for label in name.trim_end_matches('.').split('.') {
let len = u8::try_from(label.len()).ok().filter(|l| (1..64).contains(l))?;
packet.push(len);
packet.extend_from_slice(label.as_bytes());
}
// Root, type A, class IN.
packet.extend_from_slice(&[0, 0, 1, 0, 1]);
Some(packet)
}
/// The address an mDNS response gives `name` (an A record in any
/// section), if it does.
fn answer(packet: &[u8], name: &str) -> Option<Ipv4Addr> {
let u16_at = |at: usize| Some(u16::from_be_bytes([*packet.get(at)?, *packet.get(at + 1)?]));
// A response.
if packet.get(2)? & 0x80 == 0 {
return None;
}
let questions = u16_at(4)?;
let records = u16_at(6)? as usize + u16_at(8)? as usize + u16_at(10)? as usize;
let mut at = 12;
for _ in 0..questions {
at = read_name(packet, at)?.1 + 4;
}
for _ in 0..records {
let (owner, end) = read_name(packet, at)?;
let (kind, len) = (u16_at(end)?, usize::from(u16_at(end + 8)?));
let data = packet.get(end + 10..end + 10 + len)?;
if kind == 1 && len == 4 && owner.eq_ignore_ascii_case(name.trim_end_matches('.')) {
return Some(Ipv4Addr::new(data[0], data[1], data[2], data[3]));
}
at = end + 10 + len;
}
None
}
/// The (dotted) name at `at`, following compression pointers, and where
/// the record goes on after it.
fn read_name(packet: &[u8], mut at: usize) -> Option<(String, usize)> {
let mut name = String::new();
let mut end = None;
// Pointers only go back, but a crafted packet could loop.
for _ in 0..64 {
let len = *packet.get(at)?;
match len {
0 => return Some((name, end.unwrap_or(at + 1))),
_ if len & 0xc0 == 0xc0 => {
end.get_or_insert(at + 2);
at = usize::from(u16::from_be_bytes([len & 0x3f, *packet.get(at + 1)?]));
}
_ => {
let label = packet.get(at + 1..at + 1 + usize::from(len))?;
if !name.is_empty() {
name.push('.');
}
name.push_str(&String::from_utf8_lossy(label));
at += 1 + usize::from(len);
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_in_candidates() {
let line = "a=candidate:2387469048 1 udp 2113937151 6e2d1f23-173c-492f-bfef-16577595fc11.local \
39386 typ host generation 0";
assert_eq!(candidate_name(line), Some("6e2d1f23-173c-492f-bfef-16577595fc11.local"));
assert_eq!(candidate_name("candidate:1 1 udp 2130706431 10.0.0.2 50000 typ host"), None);
assert_eq!(candidate_name("a=mid:0"), None);
}
#[test]
fn query_and_answer() {
let name = "abc-1.local";
let q = query(name).unwrap();
assert_eq!(&q[12..], b"\x05abc-1\x05local\x00\x00\x01\x00\x01");
assert_eq!(query(&"x".repeat(64)), None);
// A response as Chromium sends it: the question repeated, the A
// record with the cache-flush class, its owner a pointer to the
// question's name; another record first.
let mut r = vec![0, 0, 0x84, 0, 0, 1, 0, 2, 0, 0, 0, 0];
r.extend_from_slice(&q[12..]);
r.extend_from_slice(b"\xc0\x0c\x00\x10\x80\x01\x00\x00\x00\x78\x00\x02\x01x");
r.extend_from_slice(b"\xc0\x0c\x00\x01\x80\x01\x00\x00\x00\x78\x00\x04\xc0\xa8\x01\x07");
assert_eq!(answer(&r, "ABC-1.local."), Some(Ipv4Addr::new(192, 168, 1, 7)));
assert_eq!(answer(&r, "other.local"), None);
// A query is not an answer; truncated or looping packets are none.
assert_eq!(answer(&q, name), None);
assert_eq!(answer(&r[..r.len() - 2], name), None);
let mut looped = r.clone();
looped[12] = 0xc0;
looped[13] = 12;
assert_eq!(answer(&looped, name), None);
}
}
+434 -73
View File
@@ -34,12 +34,23 @@ use tracing::{debug, trace, warn};
use crate::dtls::{self, NegotiatedProfile, SrtpProfile};
use crate::h264::{self, H264Profile};
use crate::layer::LayerSpec;
use crate::stun;
use crate::{mdns, stun};
/// Initial bandwidth estimate of a streamer's peer without
/// [`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;
/// How long an mDNS candidate's name is asked for.
const MDNS_TIMEOUT: Duration = Duration::from_secs(3);
/// 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 {
@@ -92,6 +103,73 @@ impl std::fmt::Display for VideoCodec {
}
}
/// A video codec as an answer chose it, with the H.264 profile: the
/// streamer encodes each format with an encoder of its own and sends a
/// viewer only frames of its format.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VideoFormat {
Vp8,
Vp9,
H264(H264Profile),
Av1,
H265,
}
impl VideoFormat {
pub const ALL: [Self; 6] = [
Self::Vp8,
Self::Vp9,
Self::H264(H264Profile::ConstrainedHigh),
Self::H264(H264Profile::ConstrainedBaseline),
Self::Av1,
Self::H265,
];
pub fn codec(self) -> VideoCodec {
match self {
Self::Vp8 => VideoCodec::Vp8,
Self::Vp9 => VideoCodec::Vp9,
Self::H264(_) => VideoCodec::H264,
Self::Av1 => VideoCodec::Av1,
Self::H265 => VideoCodec::H265,
}
}
/// Bit of this format in a set of formats ([`crate::LayerFeedback`]):
/// the codec's, and one more for H.264 Constrained Baseline.
pub fn bit(self) -> u8 {
match self {
Self::H264(H264Profile::ConstrainedBaseline) => 1 << VideoCodec::ALL.len(),
other => other.codec().bit(),
}
}
}
/// H.264 in Constrained High, what our encoders make unless told otherwise.
impl From<VideoCodec> for VideoFormat {
fn from(codec: VideoCodec) -> Self {
match codec {
VideoCodec::Vp8 => Self::Vp8,
VideoCodec::Vp9 => Self::Vp9,
VideoCodec::H264 => Self::H264(H264Profile::ConstrainedHigh),
VideoCodec::Av1 => Self::Av1,
VideoCodec::H265 => Self::H265,
}
}
}
impl std::fmt::Display for VideoFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::H264(H264Profile::ConstrainedHigh) => f.write_str("H264 Constrained High"),
Self::H264(H264Profile::ConstrainedBaseline) => {
f.write_str("H264 Constrained Baseline")
}
other => other.codec().fmt(f),
}
}
}
#[derive(Clone, Debug)]
pub struct PeerConfig {
/// Local addresses for host candidates. Empty: the primary IPv4 address.
@@ -123,10 +201,25 @@ pub struct PeerConfig {
/// simulcast leaves the peer unable to send video. Official TeamSpeak
/// viewers get a plain offer and one layer at a time.
pub simulcast: bool,
/// H.264 `profile-level-id` of the offer: Constrained High at the level
/// the stream needs ([`set_h264_format`](Self::set_h264_format)); level
/// 3.1 by default.
pub h264_profile_level_id: u32,
/// H.264 `profile-level-id`s of the offer, best first: Constrained High,
/// then Constrained Baseline for peers that take only that (headless
/// Chromium and other libwebrtc builds without a High decoder), each at
/// the level the stream needs ([`set_h264_format`](Self::set_h264_format));
/// 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,
/// 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 {
@@ -141,7 +234,12 @@ impl Default for PeerConfig {
srtp_profiles: SrtpProfile::DEFAULT_ORDER.to_vec(),
bandwidth_estimation: true,
simulcast: false,
h264_profile_level_id: H264_CONSTRAINED_HIGH,
h264_profile_level_ids: H264Profile::LADDER
.iter()
.map(|p| h264::profile_level_id(*p, h264::MIN_OFFER_LEVEL))
.collect(),
udp_buffer: DEFAULT_UDP_BUFFER,
stall_timeout: DEFAULT_STALL_TIMEOUT,
}
}
}
@@ -156,19 +254,14 @@ impl PeerConfig {
}
}
/// Offer H.264 in `profile` at the level a `width` x `height` stream at
/// `fps` and `bitrate` bit/s needs (at least 3.1, see
/// [`crate::h264::offer_profile_level_id`]).
pub fn set_h264_format(
&mut self,
profile: H264Profile,
width: u32,
height: u32,
fps: u32,
bitrate: u64,
) {
self.h264_profile_level_id =
h264::offer_profile_level_id(profile, width, height, fps, bitrate);
/// Offer H.264 in both profiles ([`H264Profile::LADDER`]) at the levels
/// a `width` x `height` stream at `fps` and `bitrate` bit/s needs (at
/// least 3.1, see [`crate::h264::offer_profile_level_id`]).
pub fn set_h264_format(&mut self, width: u32, height: u32, fps: u32, bitrate: u64) {
self.h264_profile_level_ids = H264Profile::LADDER
.iter()
.map(|p| h264::offer_profile_level_id(*p, width, height, fps, bitrate))
.collect();
}
}
@@ -231,9 +324,20 @@ pub enum PeerEvent {
/// The answer accepted RID simulcast: video goes out per layer with
/// these RIDs ([`Peer::write_rid`]).
Simulcast(Vec<Rid>),
/// The video codec the answer chose (streamer side): the viewer's first
/// one. Video written to this peer must be in it.
VideoCodec(VideoCodec),
/// The video codec the answer chose (streamer side), with the H.264
/// 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,
}
@@ -280,6 +384,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);
@@ -288,7 +402,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();
@@ -333,14 +447,37 @@ impl Peer {
codecs.push(*c);
}
}
let offer = SdpOffer::from_sdp_string(offer).map_err(|e| PeerError::Sdp(e.to_string()))?;
let parsed = 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 answer = rtc.sdp_api().accept_offer(offer)?;
let net = Net::bind(config, &mut rtc)?;
let answer = rtc.sdp_api().accept_offer(parsed)?;
let peer = Self::spawn(rtc, net, config, None, Vec::new(), srtp_profile);
peer.resolve_mdns(offer);
Ok((peer, answer.to_sdp_string()))
}
/// Resolve the mDNS names of the candidates in `sdp` (a whole SDP or one
/// candidate line) in the background and add them as plain candidates:
/// peers that hide their host addresses (browsers, other libwebrtc
/// builds) can then still connect on a LAN. ICE takes whichever pair
/// works, these or the others.
fn resolve_mdns(&self, sdp: &str) {
for line in sdp.lines() {
let Some(name) = mdns::candidate_name(line) else { continue };
let (name, line, cmd) = (name.to_owned(), line.to_owned(), self.cmd.clone());
tokio::spawn(async move {
match mdns::resolve(&name, MDNS_TIMEOUT).await {
Some(ip) => {
debug!(name, %ip, "mDNS candidate resolved");
let _ =
cmd.send(Cmd::RemoteCandidate(line.replace(&name, &ip.to_string())));
}
None => debug!(name, "mDNS candidate not resolved"),
}
});
}
}
fn spawn(
rtc: Rtc,
net: Net,
@@ -354,6 +491,7 @@ impl Peer {
let task = Task {
rtc,
net,
offerer: pending.is_some(),
pending,
cmd: cmd_rx,
events: event_tx,
@@ -361,6 +499,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 }
@@ -370,7 +509,9 @@ impl Peer {
pub async fn accept_answer(&self, sdp: &str) -> Result<(), PeerError> {
let (tx, rx) = oneshot::channel();
self.cmd.send(Cmd::Answer(sdp.to_owned(), tx)).map_err(|_| PeerError::Closed)?;
rx.await.map_err(|_| PeerError::Closed)?
rx.await.map_err(|_| PeerError::Closed)??;
self.resolve_mdns(sdp);
Ok(())
}
/// Viewer side: answer a new offer of the streamer on this connection
@@ -380,12 +521,19 @@ impl Peer {
pub async fn renegotiate(&self, offer: &str) -> Result<String, PeerError> {
let (tx, rx) = oneshot::channel();
self.cmd.send(Cmd::Offer(offer.to_owned(), tx)).map_err(|_| PeerError::Closed)?;
rx.await.map_err(|_| PeerError::Closed)?
let answer = rx.await.map_err(|_| PeerError::Closed)??;
self.resolve_mdns(offer);
Ok(answer)
}
/// Add a trickled remote candidate (`candidate:...`, `a=` prefix optional).
/// Add a trickled remote candidate (`candidate:...`, `a=` prefix
/// optional); one with an mDNS name once it is resolved.
pub fn add_remote_candidate(&self, candidate: &str) {
let _ = self.cmd.send(Cmd::RemoteCandidate(candidate.to_owned()));
if mdns::candidate_name(candidate).is_some() {
self.resolve_mdns(candidate);
} else {
let _ = self.cmd.send(Cmd::RemoteCandidate(candidate.to_owned()));
}
}
/// Send one encoded frame (streamer). Dropped until connected.
@@ -440,9 +588,11 @@ impl Drop for Peer {
}
}
/// H.264 Constrained High, level 3.1: reportedly the only H.264 profile the
/// TeamSpeak client decodes; str0m's defaults lack it.
const H264_CONSTRAINED_HIGH: u32 = 0x640c1f;
/// Payload types (and their RTX) of the H.264 profiles an offer lists, in
/// the order of [`PeerConfig::h264_profile_level_ids`]: 112 as before for
/// Constrained High, which str0m's defaults lack, and 108, str0m's own for
/// Constrained Baseline.
const H264_PTS: [(u8, u8); 2] = [(112, 113), (108, 109)];
/// The send simulcast of an offer: the layers with a RID, if at least two.
fn simulcast_offer(layers: &[LayerSpec]) -> Option<Simulcast> {
@@ -474,10 +624,11 @@ fn simulcast_offer(layers: &[LayerSpec]) -> Option<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. An
/// offer lists H.264 only as our encoders produce it (`profile-level-id`
/// [`PeerConfig::h264_profile_level_id`], packetization mode 1): with
/// str0m's other variants offered too, a viewer may answer a profile we
/// never send. An answer takes every variant the offer has.
/// offer lists H.264 only as our encoders produce it (the
/// [`PeerConfig::h264_profile_level_ids`], packetization mode 1, best
/// first): with str0m's other variants offered too, a viewer may answer a
/// profile we never send. An answer takes str0m's variants and Constrained
/// High, which they lack.
fn build_rtc(
config: &PeerConfig,
video: &[VideoCodec],
@@ -486,18 +637,24 @@ 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),
VideoCodec::Vp9 => rtc_config.enable_vp9(true),
VideoCodec::H264 => {
let mut c = if offer { rtc_config } else { rtc_config.enable_h264(true) };
c.codec_config().add_h264(
112.into(),
Some(113.into()),
true,
config.h264_profile_level_id,
);
let ids = config.h264_profile_level_ids.iter().copied().filter(|id| {
offer
|| H264Profile::from_profile_level_id(*id)
== Some(H264Profile::ConstrainedHigh)
});
for (id, (pt, rtx)) in ids.zip(H264_PTS) {
c.codec_config().add_h264(pt.into(), Some(rtx.into()), true, id);
}
c
}
VideoCodec::Av1 => rtc_config.enable_av1(true),
@@ -542,7 +699,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;
@@ -593,7 +750,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 {
@@ -602,7 +759,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) => {
@@ -646,6 +803,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,
@@ -665,6 +854,53 @@ 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)
}
/// A renegotiated connection waits from `now` again, if it is connected.
fn restart(&mut self, now: Instant) {
if self.connected.is_some() {
*self = Self { timeout: self.timeout, connected: Some(now), ..Self::default() };
}
}
/// 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 {
@@ -758,7 +994,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(());
@@ -779,6 +1021,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() => {
@@ -813,6 +1056,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,
@@ -823,8 +1067,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 {
@@ -847,18 +1093,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
@@ -876,6 +1133,10 @@ impl Task {
.map_err(|e| PeerError::Sdp(e.to_string()))
.and_then(|offer| Ok(self.rtc.sdp_api().accept_offer(offer)?.to_sdp_string()))
.map(|answer| order_like_offer(&answer, &sdp));
if result.is_ok() {
// Another codec, maybe: it gets the whole wait anew.
self.stall.restart(Instant::now());
}
let _ = reply.send(result);
}
Cmd::RemoteCandidate(line) => {
@@ -917,13 +1178,21 @@ impl Task {
// The codec video is written in (see `find_writer`).
if let Some((mid, pt)) = self.find_writer(MediaKind::Video) {
self.writers.insert(MediaKind::Video, (mid, pt));
let codec = self.rtc.writer(mid).and_then(|w| {
let params = w.payload_params().find(|p| p.pt() == pt)?;
VideoCodec::from_codec(params.spec().codec)
let format = self.rtc.writer(mid).and_then(|w| {
let spec = w.payload_params().find(|p| p.pt() == pt)?.spec();
Some(match VideoCodec::from_codec(spec.codec)? {
VideoCodec::H264 => VideoFormat::H264(
spec.format
.profile_level_id
.and_then(H264Profile::from_profile_level_id)
.unwrap_or_default(),
),
codec => codec.into(),
})
});
if let Some(codec) = codec {
debug!(%codec, "the answer chose");
let _ = self.events.send(PeerEvent::VideoCodec(codec));
if let Some(format) = format {
debug!(%format, "the answer chose");
let _ = self.events.send(PeerEvent::VideoCodec(format));
}
}
Ok(())
@@ -944,8 +1213,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}"),
}
}
}
@@ -991,10 +1261,24 @@ mod tests {
..PeerConfig::loopback()
};
let (_peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
assert!(offer.contains("profile-level-id=640c1f"), "{offer}");
// Only the profile we encode: a viewer must not answer another.
let h264 = offer.lines().filter(|l| l.contains(" H264/90000")).count();
assert_eq!(h264, 1, "{offer}");
// Only the profiles we encode, best first: a viewer must not answer
// another.
let h264: Vec<&str> = offer
.lines()
.filter(|l| l.starts_with("a=fmtp:") && l.contains("profile-level-id"))
.collect();
assert_eq!(h264.len(), 2, "{offer}");
assert!(h264[0].contains("profile-level-id=640c1f"), "{offer}");
assert!(h264[1].contains("profile-level-id=42e01f"), "{offer}");
let pts: Vec<&str> = offer
.lines()
.find_map(|l| l.strip_prefix("m=video "))
.unwrap()
.split(' ')
.skip(2)
.collect();
let at = |pt: &str| pts.iter().position(|p| *p == pt).unwrap();
assert!(at("112") < at("108") && at("108") < at("96"), "{pts:?}");
let (_peer, answer) = Peer::answer(&PeerConfig::loopback(), &offer).await.unwrap();
assert_eq!(offered_video_codecs(&answer)[0], VideoCodec::H264, "{answer}");
let vp8_only =
@@ -1067,41 +1351,118 @@ mod tests {
);
}
/// The format the answer chose, as the streamer's peer reports it.
async fn answered_format(peer: &mut Peer) -> VideoFormat {
loop {
match peer.next_event().await.unwrap() {
PeerEvent::VideoCodec(format) => return format,
PeerEvent::Closed => panic!("closed"),
_ => {}
}
}
}
/// Several codecs offered: the streamer learns which one each viewer's
/// answer chose; H.264 carries the level the stream needs.
/// answer chose; H.264 carries the level the stream needs, in both
/// profiles.
#[tokio::test]
async fn streamer_learns_the_answered_codec() {
let mut streamer = PeerConfig {
video_codecs: vec![VideoCodec::Vp8, VideoCodec::H264, VideoCodec::H265],
..PeerConfig::loopback()
};
streamer.set_h264_format(H264Profile::ConstrainedHigh, 1920, 1080, 60, 8_000_000);
streamer.set_h264_format(1920, 1080, 60, 8_000_000);
let (mut peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
assert!(offer.contains("profile-level-id=640c2a"), "{offer}");
assert!(offer.contains("profile-level-id=42e02a"), "{offer}");
assert!(offer.contains("H265/90000"), "{offer}");
let high = VideoFormat::H264(H264Profile::ConstrainedHigh);
let viewers = [
(vec![VideoCodec::Vp8, VideoCodec::H264], VideoCodec::Vp8),
(vec![VideoCodec::H264], VideoCodec::H264),
(vec![VideoCodec::H265], VideoCodec::H265),
(vec![VideoCodec::Vp8, VideoCodec::H264], VideoFormat::Vp8),
// Our viewers take both H.264 profiles: the better one.
(vec![VideoCodec::H264], high),
(vec![VideoCodec::H265], VideoFormat::H265),
];
for (accept, expected) in viewers {
let (mut streamer_peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
let config = PeerConfig { accept_video_codecs: accept, ..PeerConfig::loopback() };
let (_viewer, answer) = Peer::answer(&config, &offer).await.unwrap();
streamer_peer.accept_answer(&answer).await.unwrap();
let codec = loop {
match streamer_peer.next_event().await.unwrap() {
PeerEvent::VideoCodec(codec) => break codec,
PeerEvent::Closed => panic!("closed"),
_ => {}
}
};
assert_eq!(codec, expected);
assert_eq!(answered_format(&mut streamer_peer).await, expected);
}
peer.close();
while peer.next_event().await.is_some() {}
}
/// A viewer whose H.264 is Constrained Baseline only (headless
/// Chromium's libwebrtc lists no High profile) answers the fallback
/// payload type of our H.264 ladder, and the streamer learns the profile.
#[tokio::test]
async fn a_baseline_only_viewer_gets_the_fallback_profile() {
let streamer =
PeerConfig { video_codecs: vec![VideoCodec::H264], ..PeerConfig::loopback() };
let (mut streamer_peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
let mut viewer = RtcConfig::new().clear_codecs().enable_opus(true);
viewer.codec_config().add_h264(102.into(), Some(103.into()), true, 0x42e01f);
let mut viewer = viewer.build(Instant::now());
let offer = SdpOffer::from_sdp_string(&offer).unwrap();
let answer = viewer.sdp_api().accept_offer(offer).unwrap().to_sdp_string();
assert!(answer.contains("profile-level-id=42e01f"), "{answer}");
assert!(!answer.contains("profile-level-id=640c"), "{answer}");
streamer_peer.accept_answer(&answer).await.unwrap();
assert_eq!(
answered_format(&mut streamer_peer).await,
VideoFormat::H264(H264Profile::ConstrainedBaseline)
);
}
#[test]
fn format_bits_are_distinct() {
let bits = VideoFormat::ALL.iter().fold(0u8, |bits, f| {
assert_eq!(bits & f.bit(), 0, "{f}");
bits | f.bit()
});
assert_eq!(bits.count_ones(), 6);
assert_eq!(VideoFormat::from(VideoCodec::H264).bit(), VideoCodec::H264.bit());
}
/// Once per connection, after the timeout (twice it for a streamer),
/// anew after a renegotiation; never with `Duration::MAX`.
#[test]
fn stall_checks() {
let t0 = Instant::now();
let second = Duration::from_secs(1);
let mut viewer = Stall { timeout: second, ..Stall::default() };
assert!(viewer.check(t0 + 10 * second, false, true).is_none(), "not connected");
viewer.connected = Some(t0);
viewer.audio_in = true;
assert!(viewer.check(t0 + second / 2, false, true).is_none());
let event = viewer.check(t0 + second, false, true);
assert!(matches!(event, Some(PeerEvent::NoVideo { audio: true })), "{event:?}");
assert!(viewer.check(t0 + 2 * second, false, true).is_none(), "once");
// A new offer on the connection: the new codec gets its own wait.
viewer.restart(t0 + 2 * second);
viewer.video_in = true;
assert!(viewer.check(t0 + 4 * second, false, true).is_none(), "video came");
assert_eq!(viewer.due(false), None);
let mut streamer = Stall { timeout: second, connected: Some(t0), ..Stall::default() };
streamer.video_out = true;
assert!(streamer.check(t0 + second, true, true).is_none(), "a streamer waits longer");
assert!(matches!(streamer.check(t0 + 2 * second, true, true), Some(PeerEvent::NoFeedback)));
let mut working = Stall {
timeout: second,
connected: Some(t0),
video_out: true,
acknowledged: true,
..Stall::default()
};
assert!(working.check(t0 + 2 * second, true, true).is_none(), "the viewer reported");
let off = Stall { timeout: Duration::MAX, connected: Some(t0), ..Stall::default() };
assert_eq!(off.due(false), None);
}
/// The SDP lines that make up the media description (not the random ids,
/// ports, credentials and fingerprints).
fn media_lines(sdp: &str) -> Vec<&str> {
+206 -25
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};
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,
@@ -567,11 +638,13 @@ struct ViewerSlot {
/// The latest bandwidth estimate of the connection (bit/s).
estimate: Option<u64>,
srtp_profile: Option<SrtpProfile>,
/// The video codec its answer chose.
codec: Option<VideoCodec>,
/// The video codec (and H.264 profile) its answer chose.
codec: Option<VideoFormat>,
/// 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(),
}
}
@@ -680,7 +754,7 @@ impl StreamerSession {
layer: (v.peer.is_some() && v.rids.is_none()).then_some(v.choice.layer),
estimate: v.estimate,
srtp_profile: v.srtp_profile,
codec: v.codec,
codec: v.codec.map(VideoFormat::codec),
})
.collect()
}
@@ -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 });
@@ -1001,13 +1080,13 @@ impl StreamerSession {
self.write_frame_in(frame, None, out);
}
/// [`write_frame`](Self::write_frame) for video encoded in `codec`
/// [`write_frame`](Self::write_frame) for video encoded in `format`
/// (`None`: whatever the viewers negotiated): only viewers whose answer
/// chose that codec get it.
/// chose that codec and H.264 profile get it.
pub fn write_frame_in(
&mut self,
frame: &EncodedFrame,
codec: Option<VideoCodec>,
format: Option<VideoFormat>,
out: &mut Outbox,
) {
let (kind, time, layer) = (frame.kind, frame.time, frame.layer);
@@ -1024,8 +1103,8 @@ impl StreamerSession {
peer.write(kind, time, frame.data.clone());
continue;
}
if let (Some(codec), Some(negotiated)) = (codec, slot.codec)
&& codec != negotiated
if let (Some(format), Some(negotiated)) = (format, slot.codec)
&& format != negotiated
{
continue;
}
@@ -1147,12 +1226,36 @@ impl StreamerSession {
slot.rids = Some(rids);
}
}
PeerEvent::VideoCodec(codec) => {
debug!(viewer = viewer.0, %codec, "viewer's video codec");
slot.codec = Some(codec);
PeerEvent::VideoCodec(format) => {
debug!(viewer = viewer.0, %format, "viewer's video codec");
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,52 @@ impl ViewerSession {
Ok(())
}
/// The media of this connection does not get through (`why`): ask for a
/// new connection with the next lower set ([`Fallback`]): without the
/// SRTP profile this one negotiated when `srtp` (nothing came at all),
/// else (or when no other profile is left) without its video codec.
fn fall_back(&mut self, srtp: bool, why: &str, 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 srtp && 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, "{why}; nothing left to fall back to");
return;
};
warn!(stream = self.id, "{why}; asking for a new connection {step}");
self.peer = None;
self.state = WatchState::Connecting;
self.signal(Signal::Reconnect, out);
}
/// Video arrives, but none of it decodes here (the app's decoders told
/// [`Streams::video_undecodable`]): a new connection without its codec,
/// if the streamer offered another we take.
pub fn video_undecodable(&mut self, out: &mut Outbox) {
if self.state == WatchState::Connected {
self.fall_back(false, "video arrives, but none of it decodes", 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 +1722,18 @@ impl ViewerSession {
self.event(WatchEvent::Frame(frame), out);
}
}
PeerEvent::NoVideo { audio: false } => {
self.fall_back(true, "connected, but nothing arrives", out);
}
PeerEvent::NoVideo { audio: true } => {
self.fall_back(false, "connected, but no video arrives (audio does)", out);
}
PeerEvent::KeyframeRequest
| PeerEvent::LayerKeyframeRequest(_)
| PeerEvent::BitrateEstimate(_)
| PeerEvent::Simulcast(_)
| PeerEvent::VideoCodec(_) => {}
| PeerEvent::VideoCodec(_)
| PeerEvent::NoFeedback => {}
PeerEvent::Closed => {
if self.peer.take().is_none() {
return;
@@ -1683,12 +1854,12 @@ impl Streams {
self.write_frame_in(frame, None);
}
/// [`write_frame`](Self::write_frame) of video encoded in `codec`: to
/// [`write_frame`](Self::write_frame) of video encoded in `format`: to
/// the viewers that negotiated it (see
/// [`StreamerSession::write_frame_in`]).
pub fn write_frame_in(&mut self, frame: &EncodedFrame, codec: Option<VideoCodec>) {
pub fn write_frame_in(&mut self, frame: &EncodedFrame, format: Option<VideoFormat>) {
if let Some(s) = self.streamer.as_mut().filter(|s| !s.is_ended()) {
s.write_frame_in(frame, codec, &mut self.out);
s.write_frame_in(frame, format, &mut self.out);
}
}
@@ -1784,6 +1955,16 @@ impl Streams {
viewer.set_layer(layer, &mut self.out)
}
/// The video of a watched stream arrives, but none of it decodes: watch
/// it in another codec the streamer offered, if there is one (see
/// [`ViewerSession::video_undecodable`]).
pub fn video_undecodable(&mut self, id: &str) -> Result<(), SessionError> {
let viewer =
self.viewers.get_mut(id).ok_or_else(|| SessionError::NotWatching(id.into()))?;
viewer.video_undecodable(&mut self.out);
Ok(())
}
/// Reconnect to a watched stream: the streamer sends a new offer.
pub fn reconnect(&mut self, id: &str) -> Result<(), SessionError> {
let viewer =