Merge the negotiation work: best first, then fall back, everywhere
The user's rule for every negotiation: try the best option first and step down for compatibility when it is not accepted. - H.264 is offered in Constrained High, then Constrained Baseline; the streamer encodes each viewer in the profile its answer took (headless Chromium, which answers Baseline only, now decodes our H.264 streams). - A connection that connects but carries nothing steps down at runtime: the viewer reconnects without the failing SRTP profile, or without the codec when audio came; the streamer offers a new connection when its viewer reports nothing; video of one codec that never decodes makes the viewer ask for another codec. Proven with a UDP relay that breaks SRTP and against Chromium. - mDNS host candidates (`<uuid>.local`) are resolved, so peers that hide their addresses still connect on a LAN. - Peer sockets get 4 MB send and receive buffers: bursts at 9 Mbit/s no longer drop datagrams in the kernel; NACK and retransmission repair losses before frames reach the pipeline. - docs/architecture.md, "Negotiation: best first, then fall back": every negotiation point, its ladder, what counts as refused, and why AES_CM stays first for SRTP and DTLS stays at 1.2 until the official client is shown to take the alternatives. Checked on the merged tree (with the decoders and servers work): fmt, clippy, the tests of stream, media, core, ui, voelinctl, gateway and tsclientlib, the browser interop tests (7 and 3) and scripts/it-smoke.sh. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
8fb1c475df
27 files changed
+2435
-295
No files matched your search
@@ -244,6 +244,13 @@ pub enum Command {
|
||||
session: SessionId,
|
||||
stream_id: String,
|
||||
},
|
||||
/// The video of a watched stream arrives, but none of it decodes: watch
|
||||
/// it in another codec the streamer offered, if there is one (a new
|
||||
/// connection without this one). [`media::Viewer`] sends it.
|
||||
StreamUndecodable {
|
||||
session: SessionId,
|
||||
stream_id: String,
|
||||
},
|
||||
/// Watch simulcast layer `layer` of a stream (`None`: as the bandwidth
|
||||
/// allows). Only for a stream whose [`Event::WatchLayers`] listed
|
||||
/// layers; otherwise an [`Event::Error`].
|
||||
@@ -962,6 +969,7 @@ fn command_session(command: &Command) -> SessionId {
|
||||
| Command::WatchStream { session, .. }
|
||||
| Command::LeaveStream { session, .. }
|
||||
| Command::RequestStreamKeyframe { session, .. }
|
||||
| Command::StreamUndecodable { session, .. }
|
||||
| Command::SetWatchLayer { session, .. }
|
||||
| Command::SetStreamVolume { session, .. }
|
||||
| Command::SetClientVolume { session, .. }
|
||||
|
||||
+298
-76
@@ -59,13 +59,13 @@ use voelin_media::scale::Pyramid;
|
||||
use voelin_media::studio::Studio;
|
||||
use voelin_media::studio::output::{Packet, Track};
|
||||
use voelin_media::{
|
||||
Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, VideoEncoder,
|
||||
VideoFrame,
|
||||
Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, H264Profile,
|
||||
VideoEncoder, VideoFrame,
|
||||
};
|
||||
pub use voelin_media::{DecoderBackend, DecoderPreference, EncoderBackend, EncoderPreference};
|
||||
use voelin_stream::{
|
||||
EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind,
|
||||
MediaTime, PeerConfig, VideoCodec,
|
||||
MediaTime, PeerConfig, VideoCodec, VideoFormat,
|
||||
};
|
||||
|
||||
use crate::settings::{AudioSourceKindSetting, AudioSourceSetting};
|
||||
@@ -95,6 +95,13 @@ const FRAMES_WITHOUT_PICTURE: u32 = 10;
|
||||
const PICTURE_POOL: usize = 4;
|
||||
/// The decoding rates of [`DecodeStats`] cover at least this long.
|
||||
const RATE_WINDOW: Duration = Duration::from_millis(500);
|
||||
/// A watched stream's video of one codec counts as undecodable here once it
|
||||
/// came this long, and at least [`UNDECODABLE_FRAMES`] frames of it, without
|
||||
/// a single picture: time for the pipeline to try every decoder of the
|
||||
/// codec's ladder ([`DECODER_FAILURES`] failures of up to
|
||||
/// [`FRAMES_WITHOUT_PICTURE`] frames each).
|
||||
const UNDECODABLE_AFTER: Duration = Duration::from_secs(10);
|
||||
const UNDECODABLE_FRAMES: u64 = 60;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum MediaError {
|
||||
@@ -128,6 +135,17 @@ pub fn media_codec(codec: VideoCodec) -> Codec {
|
||||
}
|
||||
}
|
||||
|
||||
/// The H.264 profile an encoder of `format` makes (Constrained High for
|
||||
/// every other codec, where it means nothing).
|
||||
fn h264_profile(format: VideoFormat) -> H264Profile {
|
||||
match format {
|
||||
VideoFormat::H264(voelin_stream::H264Profile::ConstrainedBaseline) => {
|
||||
H264Profile::ConstrainedBaseline
|
||||
}
|
||||
_ => H264Profile::ConstrainedHigh,
|
||||
}
|
||||
}
|
||||
|
||||
/// The negotiable video codec of a `voelin_media` codec.
|
||||
pub fn video_codec(codec: Codec) -> VideoCodec {
|
||||
match codec {
|
||||
@@ -279,16 +297,16 @@ pub trait MediaSink: Send + Sync {
|
||||
None
|
||||
}
|
||||
|
||||
/// Send one video frame encoded in `codec`: it goes to the viewers whose
|
||||
/// answer chose `codec`.
|
||||
fn send_video(&self, frame: EncodedFrame, codec: Codec) -> bool {
|
||||
let _ = codec;
|
||||
/// Send one video frame encoded in `format`: it goes to the viewers
|
||||
/// whose answer chose that codec (and H.264 profile).
|
||||
fn send_video(&self, frame: EncodedFrame, format: VideoFormat) -> bool {
|
||||
let _ = format;
|
||||
self.send(frame)
|
||||
}
|
||||
|
||||
/// Adds to `out` the video codecs the viewers chose; none (the default)
|
||||
/// means only the stream codec is sent.
|
||||
fn video_codecs(&self, out: &mut Vec<Codec>) {
|
||||
/// Adds to `out` the video codecs (with the H.264 profile) the viewers
|
||||
/// chose; none (the default) means only the stream codec is sent.
|
||||
fn video_codecs(&self, out: &mut Vec<VideoFormat>) {
|
||||
let _ = out;
|
||||
}
|
||||
}
|
||||
@@ -298,16 +316,12 @@ impl MediaSink for StreamSink {
|
||||
StreamSink::send(self, frame)
|
||||
}
|
||||
|
||||
fn send_video(&self, frame: EncodedFrame, codec: Codec) -> bool {
|
||||
StreamSink::send_video(self, frame, video_codec(codec))
|
||||
fn send_video(&self, frame: EncodedFrame, format: VideoFormat) -> bool {
|
||||
StreamSink::send_video(self, frame, format)
|
||||
}
|
||||
|
||||
fn video_codecs(&self, out: &mut Vec<Codec>) {
|
||||
for codec in VideoCodec::ALL {
|
||||
if self.has_video_codec(codec) {
|
||||
out.push(media_codec(codec));
|
||||
}
|
||||
}
|
||||
fn video_codecs(&self, out: &mut Vec<VideoFormat>) {
|
||||
out.extend(VideoFormat::ALL.into_iter().filter(|f| self.has_video_codec(*f)));
|
||||
}
|
||||
|
||||
fn take_keyframe_request(&self) -> bool {
|
||||
@@ -1934,6 +1948,8 @@ enum ToStudio<'a> {
|
||||
|
||||
/// One encoder of a layer: its keyframe and bitrate state.
|
||||
struct LayerEncoder {
|
||||
/// What viewers get from it: the codec, and H.264 in one profile.
|
||||
format: VideoFormat,
|
||||
codec: Codec,
|
||||
/// `None`: creating it failed (not retried until it is needed anew).
|
||||
encoder: Option<Box<dyn VideoEncoder>>,
|
||||
@@ -1946,8 +1962,16 @@ struct LayerEncoder {
|
||||
}
|
||||
|
||||
impl LayerEncoder {
|
||||
fn new(encoder: Box<dyn VideoEncoder>, fps: u32) -> Self {
|
||||
Self { codec: encoder.codec(), encoder: Some(encoder), keyframe_due: true, bitrate: 0, fps }
|
||||
fn new(encoder: Box<dyn VideoEncoder>, format: VideoFormat, fps: u32) -> Self {
|
||||
let codec = encoder.codec();
|
||||
Self { format, codec, encoder: Some(encoder), keyframe_due: true, bitrate: 0, fps }
|
||||
}
|
||||
|
||||
/// The stream codec's encoder: H.264 in Constrained High, as
|
||||
/// [`new_encoder`] makes it.
|
||||
fn primary(encoder: Box<dyn VideoEncoder>, fps: u32) -> Self {
|
||||
let format = video_codec(encoder.codec()).into();
|
||||
Self::new(encoder, format, fps)
|
||||
}
|
||||
|
||||
/// Encode `picture` and hand the frames to `sink` (and `studio`'s
|
||||
@@ -2008,7 +2032,7 @@ impl LayerEncoder {
|
||||
layer: layer.id,
|
||||
keyframe: chunk.keyframe,
|
||||
};
|
||||
if sink.send_video(encoded, codec) {
|
||||
if sink.send_video(encoded, self.format) {
|
||||
layer.frames.fetch_add(1, Ordering::Relaxed);
|
||||
layer.keyframes.fetch_add(u64::from(chunk.keyframe), Ordering::Relaxed);
|
||||
layer.bytes.fetch_add(chunk.data.len() as u64, Ordering::Relaxed);
|
||||
@@ -2030,20 +2054,27 @@ impl LayerEncoder {
|
||||
}
|
||||
}
|
||||
|
||||
/// An encoder of `codec` for `layer` (a codec a viewer chose), with the
|
||||
/// streamer's current codecs and preference.
|
||||
fn extra_encoder(shared: &Shared, layer: &Layer, codec: Codec) -> Option<Box<dyn VideoEncoder>> {
|
||||
/// An encoder of `format` for `layer` (a codec and H.264 profile a viewer
|
||||
/// chose), with the streamer's current codecs and preference.
|
||||
fn extra_encoder(
|
||||
shared: &Shared,
|
||||
layer: &Layer,
|
||||
format: VideoFormat,
|
||||
) -> Option<Box<dyn VideoEncoder>> {
|
||||
let guard = lock(&shared.encoders);
|
||||
let (codecs, preference) = guard.as_ref()?;
|
||||
let spec = lock(&layer.spec).clone();
|
||||
let config = encoder_config(&spec, layer.fps.load(Ordering::Relaxed), layer.threads);
|
||||
match codecs.new_encoder_preferring(codec, config, preference) {
|
||||
let config = EncoderConfig {
|
||||
h264_profile: h264_profile(format),
|
||||
..encoder_config(&spec, layer.fps.load(Ordering::Relaxed), layer.threads)
|
||||
};
|
||||
match codecs.new_encoder_preferring(media_codec(format.codec()), config, preference) {
|
||||
Ok(encoder) => {
|
||||
debug!(layer = layer.id, %codec, backend = %encoder.backend(), "encoder for viewers");
|
||||
debug!(layer = layer.id, %format, backend = %encoder.backend(), "encoder for viewers");
|
||||
Some(encoder)
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(layer = layer.id, %codec, "no encoder for viewers of this codec: {e}");
|
||||
warn!(layer = layer.id, %format, "no encoder for viewers of this codec: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -2054,13 +2085,14 @@ fn extra_encoder(shared: &Shared, layer: &Layer, codec: Codec) -> Option<Box<dyn
|
||||
/// dropped when none does).
|
||||
fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
|
||||
let fps = layer.fps.load(Ordering::Relaxed);
|
||||
let mut primary = LayerEncoder::new(encoder, fps);
|
||||
let mut primary = LayerEncoder::primary(encoder, fps);
|
||||
// The first frame is a keyframe anyway; no need to insist.
|
||||
primary.keyframe_due = false;
|
||||
primary.bitrate = layer.bitrate.load(Ordering::Relaxed);
|
||||
*lock(&layer.backend) = primary.encoder.as_ref().map(|e| e.backend());
|
||||
let mut extra: Vec<LayerEncoder> = Vec::new();
|
||||
let mut wanted: Vec<Codec> = Vec::new();
|
||||
let mut wanted: Vec<VideoFormat> = Vec::new();
|
||||
let mut studio_codecs: Vec<Codec> = Vec::new();
|
||||
let mut generation = shared.encoders_generation.load(Ordering::Relaxed);
|
||||
// Whether the stream codec was encoded for the last frame.
|
||||
let mut primary_on = true;
|
||||
@@ -2080,7 +2112,7 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
|
||||
if let Some(next) = lock(&layer.next_encoder).take() {
|
||||
// Another codec: its first frame is a keyframe anyway.
|
||||
*lock(&layer.backend) = Some(next.backend());
|
||||
primary = LayerEncoder::new(next, primary.fps);
|
||||
primary = LayerEncoder::primary(next, primary.fps);
|
||||
}
|
||||
let Some(sink) = shared.sink() else { continue };
|
||||
shared.poll_keyframes(&*sink);
|
||||
@@ -2093,29 +2125,41 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
|
||||
// With a studio, the stream codec for its recordings and replay
|
||||
// buffer, and the codecs its outputs of this layer need (RTMP: H.264).
|
||||
if let Some(studio) = &shared.studio {
|
||||
if !wanted.contains(&primary.codec) {
|
||||
wanted.insert(0, primary.codec);
|
||||
if !wanted.contains(&primary.format) {
|
||||
wanted.insert(0, primary.format);
|
||||
}
|
||||
studio_codecs.clear();
|
||||
studio.output_codecs(u32::from(layer.id), &mut studio_codecs);
|
||||
for &codec in &studio_codecs {
|
||||
let format = video_codec(codec).into();
|
||||
if !wanted.contains(&format) {
|
||||
wanted.push(format);
|
||||
}
|
||||
}
|
||||
studio.output_codecs(u32::from(layer.id), &mut wanted);
|
||||
}
|
||||
let now = shared.encoders_generation.load(Ordering::Relaxed);
|
||||
if now != generation {
|
||||
generation = now;
|
||||
extra.clear();
|
||||
}
|
||||
extra.retain(|e| wanted.contains(&e.codec));
|
||||
for &codec in &wanted {
|
||||
if codec != primary.codec && !extra.iter().any(|e| e.codec == codec) {
|
||||
extra.retain(|e| wanted.contains(&e.format));
|
||||
for &format in &wanted {
|
||||
if format != primary.format && !extra.iter().any(|e| e.format == format) {
|
||||
let fps = layer.fps.load(Ordering::Relaxed);
|
||||
extra.push(match extra_encoder(shared, layer, codec) {
|
||||
Some(encoder) => LayerEncoder::new(encoder, fps),
|
||||
None => {
|
||||
LayerEncoder { codec, encoder: None, keyframe_due: false, bitrate: 0, fps }
|
||||
}
|
||||
extra.push(match extra_encoder(shared, layer, format) {
|
||||
Some(encoder) => LayerEncoder::new(encoder, format, fps),
|
||||
None => LayerEncoder {
|
||||
format,
|
||||
codec: media_codec(format.codec()),
|
||||
encoder: None,
|
||||
keyframe_due: false,
|
||||
bitrate: 0,
|
||||
fps,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
let primary_wanted = wanted.is_empty() || wanted.contains(&primary.codec);
|
||||
let primary_wanted = wanted.is_empty() || wanted.contains(&primary.format);
|
||||
if primary_wanted && !primary_on {
|
||||
// Frames were skipped: the next one must stand alone.
|
||||
primary.keyframe_due = true;
|
||||
@@ -2125,7 +2169,11 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
|
||||
let mut codecs = lock(&layer.codecs);
|
||||
codecs.clear();
|
||||
codecs.extend(primary_on.then_some(primary.codec));
|
||||
codecs.extend(extra.iter().filter(|e| e.encoder.is_some()).map(|e| e.codec));
|
||||
for e in extra.iter().filter(|e| e.encoder.is_some()) {
|
||||
if !codecs.contains(&e.codec) {
|
||||
codecs.push(e.codec);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The stream codec's encoder counts even while nobody takes it, so
|
||||
// the capture does not switch paths as viewers come and go.
|
||||
@@ -2560,6 +2608,51 @@ impl FrameInput {
|
||||
pub fn lost(&self) {
|
||||
lock(&self.queue.state).lost = true;
|
||||
}
|
||||
|
||||
/// Pictures decoded so far (without touching the rates of
|
||||
/// [`VideoPipeline::stats`]).
|
||||
fn decoded(&self) -> u64 {
|
||||
lock(&self.queue.stats).decoded
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the video of a watched stream decodes at all: video of one codec
|
||||
/// that keeps coming ([`UNDECODABLE_AFTER`], [`UNDECODABLE_FRAMES`]) without a
|
||||
/// single picture is reported once, so the stream can be watched in another
|
||||
/// codec ([`Command::StreamUndecodable`]). A codec that decoded once is
|
||||
/// fine (losses later are the pipeline's to repair); another codec starts
|
||||
/// over.
|
||||
struct DecodeWatch {
|
||||
after: Duration,
|
||||
frames: u64,
|
||||
/// The codec, when its first frame came, pictures decoded by then, its
|
||||
/// frames so far, and whether it is settled (decoded, or reported).
|
||||
current: Option<(MediaCodec, Instant, u64, u64, bool)>,
|
||||
}
|
||||
|
||||
type MediaCodec = voelin_stream::Codec;
|
||||
|
||||
impl DecodeWatch {
|
||||
fn new(after: Duration, frames: u64) -> Self {
|
||||
Self { after, frames, current: None }
|
||||
}
|
||||
|
||||
/// A video frame of `codec` arrived at `now`, with `decoded` pictures so
|
||||
/// far; `true` when the codec turned out undecodable.
|
||||
fn frame(&mut self, codec: MediaCodec, decoded: u64, now: Instant) -> bool {
|
||||
let current = match &mut self.current {
|
||||
Some(current) if current.0 == codec => current,
|
||||
_ => self.current.insert((codec, now, decoded, 0, false)),
|
||||
};
|
||||
let (_, since, start, frames, settled) = current;
|
||||
*frames += 1;
|
||||
if *settled || decoded > *start {
|
||||
*settled = true;
|
||||
return false;
|
||||
}
|
||||
*settled = *frames >= self.frames && now.saturating_duration_since(*since) >= self.after;
|
||||
*settled
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes the video frames of one stream on its own thread. See the
|
||||
@@ -2887,11 +2980,25 @@ impl Viewer {
|
||||
let input = pipeline.input();
|
||||
let mut frames = engine.subscribe_frames();
|
||||
let stream_id = stream_id.to_owned();
|
||||
let forward = engine.runtime().spawn(async move {
|
||||
let runtime = engine.runtime().clone();
|
||||
let engine = engine.clone();
|
||||
let forward = runtime.spawn(async move {
|
||||
use tokio::sync::broadcast::error::RecvError;
|
||||
let mut watch = DecodeWatch::new(UNDECODABLE_AFTER, UNDECODABLE_FRAMES);
|
||||
loop {
|
||||
match frames.recv().await {
|
||||
Ok(f) if f.session == session && f.stream_id == stream_id => {
|
||||
if f.frame.kind == MediaKind::Video
|
||||
&& watch.frame(f.frame.codec, input.decoded(), Instant::now())
|
||||
{
|
||||
warn!(
|
||||
stream = stream_id,
|
||||
codec = ?f.frame.codec,
|
||||
"the stream's video does not decode here; asking for another codec"
|
||||
);
|
||||
let stream_id = stream_id.clone();
|
||||
engine.send(Command::StreamUndecodable { session, stream_id });
|
||||
}
|
||||
input.push(f.frame)
|
||||
}
|
||||
Ok(_) => {}
|
||||
@@ -3048,6 +3155,71 @@ pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Reported once, only after both the time and the frames, never for a
|
||||
/// codec that decoded; another codec starts over.
|
||||
#[test]
|
||||
fn decode_watch_reports_a_codec_that_never_decodes() {
|
||||
let (t0, second) = (Instant::now(), Duration::from_secs(1));
|
||||
let mut watch = DecodeWatch::new(2 * second, 3);
|
||||
let vp9 = MediaCodec::Vp9;
|
||||
assert!(!watch.frame(vp9, 5, t0));
|
||||
assert!(!watch.frame(vp9, 5, t0 + 3 * second), "two frames are not enough");
|
||||
assert!(watch.frame(vp9, 5, t0 + 3 * second), "three frames, three seconds, no picture");
|
||||
assert!(!watch.frame(vp9, 5, t0 + 9 * second), "once");
|
||||
// Another codec starts over, and once it decodes it is fine.
|
||||
let vp8 = MediaCodec::Vp8;
|
||||
assert!(!watch.frame(vp8, 5, t0 + 10 * second));
|
||||
assert!(!watch.frame(vp8, 6, t0 + 11 * second));
|
||||
for _ in 0..10 {
|
||||
assert!(!watch.frame(vp8, 6, t0 + 20 * second));
|
||||
}
|
||||
// Many frames quickly are not enough without the time.
|
||||
let av1 = MediaCodec::Av1;
|
||||
for _ in 0..100 {
|
||||
assert!(!watch.frame(av1, 6, t0 + 20 * second));
|
||||
}
|
||||
assert!(watch.frame(av1, 6, t0 + 22 * second));
|
||||
}
|
||||
|
||||
/// Frames that no decoder of the codec takes (VP9 that is not VP9)
|
||||
/// through a real pipeline: no picture comes, and the watch reports it;
|
||||
/// real VP8 keyframes decode and are never reported.
|
||||
#[tokio::test]
|
||||
async fn undecodable_video_is_noticed_through_the_pipeline() {
|
||||
let codecs = Arc::new(Codecs::builtin());
|
||||
let run = |codec: MediaCodec, data: Vec<u8>| {
|
||||
let codecs = codecs.clone();
|
||||
async move {
|
||||
let pipeline = VideoPipeline::new(codecs, |_| {}, || {});
|
||||
let input = pipeline.input();
|
||||
let mut watch = DecodeWatch::new(Duration::from_millis(400), 10);
|
||||
let start = Instant::now();
|
||||
let data: Arc<[u8]> = data.into();
|
||||
for n in 0..40u64 {
|
||||
let frame = MediaFrame {
|
||||
kind: MediaKind::Video,
|
||||
codec,
|
||||
time: MediaTime::from_90khz(n * 3000),
|
||||
network_time: Instant::now(),
|
||||
contiguous: true,
|
||||
data: data.clone(),
|
||||
};
|
||||
if watch.frame(codec, input.decoded(), Instant::now()) {
|
||||
return Some(start.elapsed());
|
||||
}
|
||||
input.push(frame);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
None
|
||||
}
|
||||
};
|
||||
let junk = vec![0x82, 0x49, 0x83, 0x42, 0x00, 0x13, 0xf0, 0x0e, 0xf6, 0x00, 1, 2, 3];
|
||||
let reported = run(MediaCodec::Vp9, junk).await;
|
||||
assert!(reported.is_some_and(|after| after >= Duration::from_millis(400)), "{reported:?}");
|
||||
let vp8 = voelin_stream::SyntheticSource::video_frame(0, 64);
|
||||
assert_eq!(run(MediaCodec::Vp8, vp8).await, None, "VP8 decodes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyframe_detection() {
|
||||
// VP8: the 1x1 keyframe of voelin-stream's synthetic source.
|
||||
@@ -3126,11 +3298,11 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A sink whose viewers chose `codecs`; keeps every video frame with its
|
||||
/// codec.
|
||||
/// format.
|
||||
#[derive(Default)]
|
||||
struct CodecSink {
|
||||
codecs: Mutex<Vec<Codec>>,
|
||||
frames: Mutex<Vec<(Codec, EncodedFrame)>>,
|
||||
codecs: Mutex<Vec<VideoFormat>>,
|
||||
frames: Mutex<Vec<(VideoFormat, EncodedFrame)>>,
|
||||
keyframe: AtomicBool,
|
||||
}
|
||||
|
||||
@@ -3139,8 +3311,8 @@ mod tests {
|
||||
true
|
||||
}
|
||||
|
||||
fn send_video(&self, frame: EncodedFrame, codec: Codec) -> bool {
|
||||
lock(&self.frames).push((codec, frame));
|
||||
fn send_video(&self, frame: EncodedFrame, format: VideoFormat) -> bool {
|
||||
lock(&self.frames).push((format, frame));
|
||||
true
|
||||
}
|
||||
|
||||
@@ -3148,11 +3320,30 @@ mod tests {
|
||||
self.keyframe.swap(false, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn video_codecs(&self, out: &mut Vec<Codec>) {
|
||||
fn video_codecs(&self, out: &mut Vec<VideoFormat>) {
|
||||
out.extend(lock(&self.codecs).iter());
|
||||
}
|
||||
}
|
||||
|
||||
impl CodecSink {
|
||||
/// Wait until `count` frames of `format` arrived.
|
||||
async fn wait_for(&self, format: VideoFormat, count: usize) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
let n = lock(&self.frames).iter().filter(|(f, _)| *f == format).count();
|
||||
if n >= count {
|
||||
return;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "no {format} frames");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn count(&self, format: VideoFormat) -> usize {
|
||||
lock(&self.frames).iter().filter(|(f, _)| *f == format).count()
|
||||
}
|
||||
}
|
||||
|
||||
/// Viewers that chose another codec get their own encoder per layer,
|
||||
/// made when they come and dropped when they go; the stream codec is
|
||||
/// skipped while nobody takes it.
|
||||
@@ -3169,29 +3360,15 @@ mod tests {
|
||||
let streamer = Streamer::start(&codecs, config).await.unwrap();
|
||||
let sink = Arc::new(CodecSink::default());
|
||||
streamer.attach(sink.clone());
|
||||
let wait_for = |codec: Codec, count: usize| {
|
||||
let sink = sink.clone();
|
||||
async move {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
let n = lock(&sink.frames).iter().filter(|(c, _)| *c == codec).count();
|
||||
if n >= count {
|
||||
return;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "no {codec} frames");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
};
|
||||
// Nobody chose yet: the stream codec.
|
||||
wait_for(Codec::Vp8, 3).await;
|
||||
sink.wait_for(VideoFormat::Vp8, 3).await;
|
||||
// A VP9 viewer as well.
|
||||
*lock(&sink.codecs) = vec![Codec::Vp8, Codec::Vp9];
|
||||
wait_for(Codec::Vp9, 5).await;
|
||||
*lock(&sink.codecs) = vec![VideoFormat::Vp8, VideoFormat::Vp9];
|
||||
sink.wait_for(VideoFormat::Vp9, 5).await;
|
||||
assert_eq!(streamer.stats().layers[0].codecs, [Codec::Vp8, Codec::Vp9]);
|
||||
let vp9: Vec<EncodedFrame> = lock(&sink.frames)
|
||||
.iter()
|
||||
.filter(|(c, _)| *c == Codec::Vp9)
|
||||
.filter(|(f, _)| *f == VideoFormat::Vp9)
|
||||
.map(|(_, f)| f.clone())
|
||||
.collect();
|
||||
assert!(is_keyframe(Codec::Vp9, &vp9[0].data), "the first VP9 frame is a keyframe");
|
||||
@@ -3201,12 +3378,11 @@ mod tests {
|
||||
assert_eq!((picture.width, picture.height), (160, 120));
|
||||
}
|
||||
// Only VP9 viewers left: VP8 stops.
|
||||
*lock(&sink.codecs) = vec![Codec::Vp9];
|
||||
*lock(&sink.codecs) = vec![VideoFormat::Vp9];
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
let before = lock(&sink.frames).iter().filter(|(c, _)| *c == Codec::Vp8).count();
|
||||
wait_for(Codec::Vp9, vp9.len() + 10).await;
|
||||
let after = lock(&sink.frames).iter().filter(|(c, _)| *c == Codec::Vp8).count();
|
||||
assert_eq!(before, after, "VP8 is not encoded for nobody");
|
||||
let before = sink.count(VideoFormat::Vp8);
|
||||
sink.wait_for(VideoFormat::Vp9, vp9.len() + 10).await;
|
||||
assert_eq!(before, sink.count(VideoFormat::Vp8), "VP8 is not encoded for nobody");
|
||||
assert_eq!(streamer.stats().layers[0].codecs, [Codec::Vp9]);
|
||||
assert_eq!(streamer.stats().layers[0].backend, Some(EncoderBackend::Libvpx));
|
||||
// Another encoder preference: new encoders, the stream goes on.
|
||||
@@ -3215,8 +3391,54 @@ mod tests {
|
||||
..StreamerConfigUpdate::default()
|
||||
};
|
||||
streamer.reconfigure(&codecs, update).unwrap();
|
||||
let count = lock(&sink.frames).iter().filter(|(c, _)| *c == Codec::Vp9).count();
|
||||
wait_for(Codec::Vp9, count + 5).await;
|
||||
sink.wait_for(VideoFormat::Vp9, sink.count(VideoFormat::Vp9) + 5).await;
|
||||
}
|
||||
|
||||
/// `profile_idc` of the first SPS in an H.264 access unit (Annex B).
|
||||
fn sps_profile(data: &[u8]) -> Option<u8> {
|
||||
let at = data.windows(4).position(|w| w[..3] == [0, 0, 1] && w[3] & 0x1f == 7)?;
|
||||
data.get(at + 4).copied()
|
||||
}
|
||||
|
||||
/// H.264 viewers of both profiles of our offer's ladder: each gets an
|
||||
/// encoder of its own, in its profile (High 100, Baseline 66 in the SPS).
|
||||
#[cfg(feature = "media-desktop")]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_encoder_per_h264_profile_viewers_chose() {
|
||||
use voelin_stream::H264Profile::{ConstrainedBaseline, ConstrainedHigh};
|
||||
let codecs = Codecs::new();
|
||||
if !codecs.encoder_codecs().contains(&Codec::H264) {
|
||||
eprintln!("skipped: no H.264 encoder on this machine");
|
||||
return;
|
||||
}
|
||||
let config = StreamerConfig {
|
||||
source: SourceId::Synthetic,
|
||||
synthetic_size: (320, 240),
|
||||
codec: Codec::H264,
|
||||
audio: false,
|
||||
..StreamerConfig::default()
|
||||
};
|
||||
let streamer = Streamer::start(&codecs, config).await.unwrap();
|
||||
let sink = Arc::new(CodecSink::default());
|
||||
let (high, baseline) =
|
||||
(VideoFormat::H264(ConstrainedHigh), VideoFormat::H264(ConstrainedBaseline));
|
||||
*lock(&sink.codecs) = vec![high, baseline];
|
||||
streamer.attach(sink.clone());
|
||||
sink.wait_for(high, 3).await;
|
||||
sink.wait_for(baseline, 3).await;
|
||||
let first = |format| {
|
||||
let frames = lock(&sink.frames);
|
||||
frames.iter().find(|(f, _)| *f == format).map(|(_, frame)| frame.data.clone()).unwrap()
|
||||
};
|
||||
assert_eq!(sps_profile(&first(high)), Some(100));
|
||||
assert_eq!(sps_profile(&first(baseline)), Some(66));
|
||||
assert_eq!(streamer.stats().layers[0].codecs, [Codec::H264], "one codec, two profiles");
|
||||
// The Baseline viewers alone: High is no longer encoded.
|
||||
*lock(&sink.codecs) = vec![baseline];
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
let before = sink.count(high);
|
||||
sink.wait_for(baseline, sink.count(baseline) + 10).await;
|
||||
assert_eq!(before, sink.count(high), "High is not encoded for nobody");
|
||||
}
|
||||
|
||||
/// The test pattern through VP8 and back, without a network: pictures
|
||||
|
||||
@@ -463,6 +463,9 @@ impl Session {
|
||||
Command::RequestStreamKeyframe { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::RequestKeyframe { stream_id });
|
||||
}
|
||||
Command::StreamUndecodable { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::Undecodable { stream_id });
|
||||
}
|
||||
Command::SetWatchLayer { stream_id, layer, .. } => {
|
||||
self.stream_input(StreamInput::WatchLayer { stream_id, layer });
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ use voelin_stream::{
|
||||
pub use voelin_stream::{
|
||||
Codec, EncodedFrame, EndReason, FrameSource, Frequency, LayerId, LayerSet, LayerSpec,
|
||||
LeaveReason, MediaFrame, MediaKind, MediaTime, PeerConfig, SrtpProfile, StreamInfo, StreamKind,
|
||||
StreamSetup, SyntheticSource, VideoCodec, ViewerInfo, ViewerState,
|
||||
StreamSetup, SyntheticSource, VideoCodec, VideoFormat, ViewerInfo, ViewerState,
|
||||
};
|
||||
|
||||
use crate::audio::{AudioHandle, AudioIn};
|
||||
@@ -92,16 +92,16 @@ impl StreamSink {
|
||||
self.live.load(Ordering::Relaxed) && self.tx.send(StreamInput::Frame(frame)).is_ok()
|
||||
}
|
||||
|
||||
/// Send one video frame encoded in `codec`: only viewers whose answer
|
||||
/// chose `codec` get it.
|
||||
pub fn send_video(&self, frame: EncodedFrame, codec: VideoCodec) -> bool {
|
||||
/// Send one video frame encoded in `format`: only viewers whose answer
|
||||
/// chose that codec (and H.264 profile) get it.
|
||||
pub fn send_video(&self, frame: EncodedFrame, format: VideoFormat) -> bool {
|
||||
self.live.load(Ordering::Relaxed)
|
||||
&& self.tx.send(StreamInput::VideoFrame(frame, codec)).is_ok()
|
||||
&& self.tx.send(StreamInput::VideoFrame(frame, format)).is_ok()
|
||||
}
|
||||
|
||||
/// Whether a viewer's answer chose `codec`.
|
||||
pub fn has_video_codec(&self, codec: VideoCodec) -> bool {
|
||||
self.feedback.has_codec(codec)
|
||||
/// Whether a viewer's answer chose `format`.
|
||||
pub fn has_video_codec(&self, format: VideoFormat) -> bool {
|
||||
self.feedback.has_codec(format)
|
||||
}
|
||||
|
||||
/// Whether a viewer asked for a keyframe of any layer since the last
|
||||
@@ -163,6 +163,10 @@ pub(crate) enum StreamInput {
|
||||
RequestKeyframe {
|
||||
stream_id: String,
|
||||
},
|
||||
/// The stream's video arrives but does not decode.
|
||||
Undecodable {
|
||||
stream_id: String,
|
||||
},
|
||||
WatchLayer {
|
||||
stream_id: String,
|
||||
layer: Option<LayerId>,
|
||||
@@ -172,8 +176,8 @@ pub(crate) enum StreamInput {
|
||||
/// SRTP profile order of new connections.
|
||||
SrtpProfiles(Vec<SrtpProfile>),
|
||||
Frame(EncodedFrame),
|
||||
/// A video frame for the viewers that chose its codec.
|
||||
VideoFrame(EncodedFrame, VideoCodec),
|
||||
/// A video frame for the viewers that chose its codec and H.264 profile.
|
||||
VideoFrame(EncodedFrame, VideoFormat),
|
||||
Notification(StreamNotification),
|
||||
RequestFailed(Request, String),
|
||||
/// Clients on the server: channel and `client_is_streaming`.
|
||||
@@ -376,6 +380,7 @@ impl StreamTask {
|
||||
self.streams.request_keyframe(&stream_id);
|
||||
Ok(())
|
||||
}
|
||||
StreamInput::Undecodable { stream_id } => self.streams.video_undecodable(&stream_id),
|
||||
StreamInput::WatchLayer { stream_id, layer } => self
|
||||
.streams
|
||||
.set_watch_layer(&stream_id, layer)
|
||||
@@ -397,8 +402,8 @@ impl StreamTask {
|
||||
self.streams.write_frame(&frame);
|
||||
Ok(())
|
||||
}
|
||||
StreamInput::VideoFrame(frame, codec) => {
|
||||
self.streams.write_frame_in(&frame, Some(codec));
|
||||
StreamInput::VideoFrame(frame, format) => {
|
||||
self.streams.write_frame_in(&frame, Some(format));
|
||||
Ok(())
|
||||
}
|
||||
StreamInput::Notification(n) => {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
//! The stream's real encoders against a browser's WebRTC stack: the test
|
||||
//! pattern, encoded by each encoder this machine has as a share encodes the
|
||||
//! screen, sent by our streamer peer offering just that codec, must decode
|
||||
//! at its size in headless Chromium (libwebrtc, the stack the official
|
||||
//! TeamSpeak 6 client is built on). And the other way: what Chromium sends
|
||||
//! (AV1, VP9, H.264) our viewer accepts and the engine's pipeline decodes.
|
||||
//! screen, sent by our streamer peer offering just that codec (H.264 in both
|
||||
//! profiles of the ladder, encoded in the one the browser chose), must
|
||||
//! decode at its size in headless Chromium (libwebrtc, the stack the
|
||||
//! official TeamSpeak 6 client is built on). And the other way: what
|
||||
//! Chromium sends (AV1, VP9, H.264) our viewer accepts and the engine's
|
||||
//! pipeline decodes.
|
||||
//!
|
||||
//! Runs only with `VOELIN_INTEROP=1` (see `tests/interop/README.md`). Codecs
|
||||
//! the browser does not decode (H.264 in Playwright's Chromium, HEVC) are
|
||||
@@ -12,8 +14,8 @@
|
||||
|
||||
#![cfg(feature = "media-desktop")]
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, mpsc};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -21,11 +23,11 @@ use tokio::time::timeout;
|
||||
use voelin_core::media::voelin_media::capture::SourceId;
|
||||
use voelin_core::media::voelin_media::{Codec, Codecs};
|
||||
use voelin_core::media::{
|
||||
EncodedSource, EncoderPreference, Streamer, StreamerConfig, VideoPipeline, decoded_everywhere,
|
||||
EncoderPreference, MediaSink, Streamer, StreamerConfig, VideoPipeline, decoded_everywhere,
|
||||
media_codec, peer_config, preferred_codec, video_codec,
|
||||
};
|
||||
use voelin_core::stream::{FrameSource, PeerConfig, VideoCodec};
|
||||
use voelin_stream::{Peer, PeerEvent};
|
||||
use voelin_core::stream::{EncodedFrame, PeerConfig, VideoFormat};
|
||||
use voelin_stream::{H264Profile, Peer, PeerEvent};
|
||||
|
||||
#[path = "../../../tests/interop/browser.rs"]
|
||||
mod browser;
|
||||
@@ -33,10 +35,45 @@ use browser::{Browser, enabled};
|
||||
|
||||
const SIZE: (u32, u32) = (1280, 720);
|
||||
|
||||
/// A viewer as the stream task serves it: the frames of the format its
|
||||
/// answer chose (the streamer makes an encoder of that format), keyframe
|
||||
/// requests back.
|
||||
struct ViewerSink {
|
||||
format: VideoFormat,
|
||||
frames: mpsc::Sender<EncodedFrame>,
|
||||
keyframe: AtomicBool,
|
||||
}
|
||||
|
||||
impl MediaSink for ViewerSink {
|
||||
fn send(&self, _: EncodedFrame) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn send_video(&self, frame: EncodedFrame, format: VideoFormat) -> bool {
|
||||
format != self.format || self.frames.send(frame).is_ok()
|
||||
}
|
||||
|
||||
fn video_codecs(&self, out: &mut Vec<VideoFormat>) {
|
||||
out.push(self.format);
|
||||
}
|
||||
|
||||
fn take_keyframe_request(&self) -> bool {
|
||||
self.keyframe.swap(false, Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
/// The streamer, its viewer and the viewer's frames.
|
||||
type Source = (Streamer, Arc<ViewerSink>, mpsc::Receiver<EncodedFrame>);
|
||||
|
||||
/// The test pattern encoded with `codec` by the encoders `preference` picks
|
||||
/// (from DMA-BUFs with `dmabuf`, as the ScreenCast portal hands over the
|
||||
/// screen).
|
||||
async fn test_pattern(preference: EncoderPreference, codec: Codec, dmabuf: bool) -> EncodedSource {
|
||||
/// screen), for a viewer of `format`.
|
||||
async fn test_pattern(
|
||||
preference: EncoderPreference,
|
||||
codec: Codec,
|
||||
dmabuf: bool,
|
||||
format: VideoFormat,
|
||||
) -> Source {
|
||||
let codecs = Codecs::new().with_preference(preference.clone());
|
||||
let config = StreamerConfig {
|
||||
source: SourceId::Synthetic,
|
||||
@@ -49,12 +86,22 @@ async fn test_pattern(preference: EncoderPreference, codec: Codec, dmabuf: bool)
|
||||
encoder: preference,
|
||||
..StreamerConfig::default()
|
||||
};
|
||||
EncodedSource::new(Streamer::start(&codecs, config).await.unwrap())
|
||||
let streamer = Streamer::start(&codecs, config).await.unwrap();
|
||||
let (tx, frames) = mpsc::channel();
|
||||
let sink = Arc::new(ViewerSink { format, frames: tx, keyframe: AtomicBool::new(true) });
|
||||
streamer.attach(sink.clone());
|
||||
(streamer, sink, frames)
|
||||
}
|
||||
|
||||
/// `profile_idc` of the first SPS in an H.264 access unit (Annex B).
|
||||
fn sps_profile(data: &[u8]) -> Option<u8> {
|
||||
let at = data.windows(4).position(|w| w[..3] == [0, 0, 1] && w[3] & 0x1f == 7)?;
|
||||
data.get(at + 4).copied()
|
||||
}
|
||||
|
||||
/// Our streamer peer with `config`'s offer, answered by the browser and
|
||||
/// connected; the codec the answer chose, `None` if it took no video.
|
||||
async fn connect(browser: &mut Browser, config: &PeerConfig) -> Option<(Peer, VideoCodec)> {
|
||||
/// connected; the format the answer chose, `None` if it took no video.
|
||||
async fn connect(browser: &mut Browser, config: &PeerConfig) -> Option<(Peer, VideoFormat)> {
|
||||
let (mut peer, offer) = Peer::offer(config, "interop").await.unwrap();
|
||||
let answer = browser.call(json!({ "op": "answer", "sdp": offer })).await;
|
||||
peer.accept_answer(answer["sdp"].as_str().unwrap()).await.ok()?;
|
||||
@@ -74,27 +121,30 @@ async fn connect(browser: &mut Browser, config: &PeerConfig) -> Option<(Peer, Vi
|
||||
Some((peer, chosen?))
|
||||
}
|
||||
|
||||
/// Three seconds of `source` to `peer`; the browser's `inbound-rtp` video
|
||||
/// stats.
|
||||
async fn send(browser: &mut Browser, peer: &mut Peer, source: &mut EncodedSource) -> Value {
|
||||
source.request_keyframe();
|
||||
let mut frames = Vec::new();
|
||||
/// Three seconds of the streamer's frames for its viewer to `peer`; the
|
||||
/// browser's `inbound-rtp` video stats, and the first frame sent.
|
||||
async fn send(
|
||||
browser: &mut Browser,
|
||||
peer: &mut Peer,
|
||||
(_streamer, sink, frames): Source,
|
||||
) -> (Value, Option<EncodedFrame>) {
|
||||
let mut first = None;
|
||||
let end = Instant::now() + Duration::from_secs(3);
|
||||
while Instant::now() < end {
|
||||
source.poll_frames(Instant::now(), &mut frames);
|
||||
for f in frames.drain(..) {
|
||||
peer.write(f.kind, f.time, f.data);
|
||||
while let Ok(f) = frames.try_recv() {
|
||||
peer.write(f.kind, f.time, f.data.clone());
|
||||
first.get_or_insert(f);
|
||||
}
|
||||
while let Some(event) = peer.try_next_event() {
|
||||
if matches!(event, PeerEvent::KeyframeRequest) {
|
||||
source.request_keyframe();
|
||||
sink.keyframe.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
let stats = browser.call(json!({ "op": "stats" })).await;
|
||||
peer.close();
|
||||
stats["inbound"]["video"].clone()
|
||||
(stats["inbound"]["video"].clone(), first)
|
||||
}
|
||||
|
||||
/// Whether the browser decoded most of three seconds at the stream's size.
|
||||
@@ -110,7 +160,9 @@ fn decoded(video: &Value) -> Result<(), String> {
|
||||
|
||||
/// Every encoder of this machine (hardware ones from memory and from
|
||||
/// DMA-BUFs) decodes in the browser: most frames decoded, at the stream's
|
||||
/// size.
|
||||
/// size. H.264 is offered in both profiles of the ladder; the browser takes
|
||||
/// the one it lists (headless Chromium: Constrained Baseline only) and gets
|
||||
/// it from an encoder of that profile.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn real_encoders_decode_in_browser() {
|
||||
if !enabled() {
|
||||
@@ -129,25 +181,30 @@ async fn real_encoders_decode_in_browser() {
|
||||
let config = PeerConfig {
|
||||
video_codecs: vec![video_codec(codec)],
|
||||
audio: false,
|
||||
// Headless Chromium lists only the H.264 profiles of
|
||||
// libwebrtc's software decoder (Baseline, Constrained
|
||||
// Baseline, Main), not the Constrained High we offer; its
|
||||
// FFmpeg decoder takes our High profile streams all the same.
|
||||
h264_profile_level_id: 0x42e01f,
|
||||
..PeerConfig::loopback()
|
||||
};
|
||||
let Some((mut peer, _)) = connect(&mut browser, &config).await else {
|
||||
let Some((mut peer, format)) = connect(&mut browser, &config).await else {
|
||||
eprintln!("{what}: the browser does not decode it, skipped");
|
||||
continue;
|
||||
};
|
||||
let preference =
|
||||
EncoderPreference { hardware: true, backend: backend.name().parse().unwrap() };
|
||||
let mut source = test_pattern(preference, codec, dmabuf).await;
|
||||
let video = send(&mut browser, &mut peer, &mut source).await;
|
||||
eprintln!("{what}: {video}");
|
||||
let source = test_pattern(preference, codec, dmabuf, format).await;
|
||||
let (video, first) = send(&mut browser, &mut peer, source).await;
|
||||
eprintln!("{what}, the browser chose {format}: {video}");
|
||||
if let Err(e) = decoded(&video) {
|
||||
failed.push(format!("{what}: {e}"));
|
||||
}
|
||||
// H.264 in the profile the answer chose.
|
||||
let expected = match format {
|
||||
VideoFormat::H264(H264Profile::ConstrainedHigh) => Some(100),
|
||||
VideoFormat::H264(H264Profile::ConstrainedBaseline) => Some(66),
|
||||
_ => None,
|
||||
};
|
||||
let sps = first.as_ref().and_then(|f| sps_profile(&f.data));
|
||||
if expected.is_some() && sps != expected {
|
||||
failed.push(format!("{what}: SPS profile {sps:?}, {format} answered"));
|
||||
}
|
||||
}
|
||||
}
|
||||
browser.quit().await;
|
||||
@@ -175,15 +232,15 @@ async fn share_offer_picks_a_codec_every_client_decodes() {
|
||||
};
|
||||
let config = peer_config(&codecs, config);
|
||||
eprintln!("offer: {:?}", config.video_codecs);
|
||||
let (mut peer, chosen) = connect(&mut browser, &config).await.expect("video answered");
|
||||
let chosen = media_codec(chosen);
|
||||
let (mut peer, format) = connect(&mut browser, &config).await.expect("video answered");
|
||||
let chosen = media_codec(format.codec());
|
||||
assert!(
|
||||
decoded_everywhere(chosen),
|
||||
"the browser chose {chosen} from {:?}",
|
||||
config.video_codecs
|
||||
);
|
||||
let mut source = test_pattern(codecs.preference().clone(), chosen, false).await;
|
||||
let video = send(&mut browser, &mut peer, &mut source).await;
|
||||
let source = test_pattern(codecs.preference().clone(), chosen, false, format).await;
|
||||
let (video, _) = send(&mut browser, &mut peer, source).await;
|
||||
eprintln!("{chosen}: {video}");
|
||||
browser.quit().await;
|
||||
decoded(&video).unwrap();
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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> {
|
||||
|
||||
@@ -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 =
|
||||
|
||||
@@ -16,6 +16,8 @@ use voelin_stream::{
|
||||
#[path = "../../../tests/interop/browser.rs"]
|
||||
mod browser;
|
||||
use browser::{Browser, enabled};
|
||||
mod relay;
|
||||
use relay::{Relay, Rule};
|
||||
|
||||
/// The `srtpCipher` of `getStats()` for AES_CM_128_HMAC_SHA1_80, as Chromium
|
||||
/// 141 and 152 name it.
|
||||
@@ -312,3 +314,128 @@ async fn browser_renegotiates_with_rust() {
|
||||
assert_eq!(stats["connectionState"], "connected", "{stats:#}");
|
||||
browser.quit().await;
|
||||
}
|
||||
|
||||
/// Chromium with its host addresses behind mDNS names (`<uuid>.local`, as
|
||||
/// without camera or microphone permission) and no STUN: the names are
|
||||
/// its only candidates. Our candidates are kept from it, so it cannot
|
||||
/// start the checks itself (and learn our address from them): the
|
||||
/// connection comes up only if our peers resolve its names by a multicast
|
||||
/// DNS query and reach it, as streamer (the names in the browser's answer)
|
||||
/// and as viewer (in its offer). Then the media flows.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn browser_mdns_candidates_connect() {
|
||||
if !enabled() {
|
||||
eprintln!("skipped: set VOELIN_INTEROP=1 (needs node, Playwright and Chromium)");
|
||||
return;
|
||||
}
|
||||
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
|
||||
let mut browser = Browser::start_with_mdns().await;
|
||||
let only_mdns = |sdp: &str| {
|
||||
let candidates: Vec<&str> = sdp.lines().filter(|l| l.starts_with("a=candidate:")).collect();
|
||||
!candidates.is_empty() && candidates.iter().all(|l| l.contains(".local "))
|
||||
};
|
||||
let without_candidates = |sdp: &str| -> String {
|
||||
sdp.split_inclusive('\n').filter(|l| !l.starts_with("a=candidate:")).collect()
|
||||
};
|
||||
let config = PeerConfig::loopback();
|
||||
|
||||
// Our streamer, the browser's answer with mDNS names.
|
||||
let (mut peer, offer) = Peer::offer(&config, "mdns").await.unwrap();
|
||||
let offer = without_candidates(&offer);
|
||||
let answer = browser.call(json!({ "op": "answer", "sdp": offer })).await;
|
||||
let answer = answer["sdp"].as_str().unwrap();
|
||||
assert!(only_mdns(answer), "the browser's answer:\n{answer}");
|
||||
peer.accept_answer(answer).await.unwrap();
|
||||
wait_connected(&mut peer).await;
|
||||
let mut source = SyntheticSource::new(30, 3000, false);
|
||||
let mut frames = Vec::new();
|
||||
let end = Instant::now() + Duration::from_secs(2);
|
||||
while Instant::now() < end {
|
||||
source.poll_frames(Instant::now(), &mut frames);
|
||||
for f in frames.drain(..) {
|
||||
peer.write(f.kind, f.time, f.data);
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
let stats = browser.call(json!({ "op": "stats" })).await;
|
||||
assert!(stats["inbound"]["video"]["framesDecoded"].as_u64().unwrap() > 20, "{stats:#}");
|
||||
|
||||
// The browser streams, its offer with mDNS names; our viewer answers.
|
||||
let offer = browser.call(json!({ "op": "offer", "codec": "VP8", "trickle": false })).await;
|
||||
let offer = offer["sdp"].as_str().unwrap();
|
||||
assert!(only_mdns(offer), "the browser's offer:\n{offer}");
|
||||
let (mut peer, answer) = Peer::answer(&config, offer).await.unwrap();
|
||||
browser.call(json!({ "op": "accept", "sdp": without_candidates(&answer) })).await;
|
||||
wait_connected(&mut peer).await;
|
||||
let received = receive(&mut peer, Duration::from_secs(5), 20).await;
|
||||
assert!(received.video.get(Codec::Vp8) >= 20, "{:?}", received.video);
|
||||
browser.quit().await;
|
||||
}
|
||||
|
||||
/// Our streamer peer to Chromium through a relay that passes the handshake
|
||||
/// and drops SRTP once AES-GCM was selected, as an official viewer whose
|
||||
/// SRTP fails after the handshake: synthetic media for `seconds`; whether
|
||||
/// the peer reported `NoFeedback`, the profile selected, Chromium's stats.
|
||||
async fn stream_through_failing_srtp(
|
||||
browser: &mut Browser,
|
||||
srtp_profiles: Vec<SrtpProfile>,
|
||||
seconds: u64,
|
||||
) -> (bool, Option<u16>, serde_json::Value) {
|
||||
let relay = Relay::new(Rule::FailSrtp(&[7, 8])).await;
|
||||
let config = PeerConfig {
|
||||
srtp_profiles,
|
||||
stall_timeout: Duration::from_secs(1),
|
||||
..PeerConfig::loopback()
|
||||
};
|
||||
let (mut peer, offer) = Peer::offer(&config, "interop").await.unwrap();
|
||||
let answer = browser.call(json!({ "op": "answer", "sdp": relay.offer(&offer) })).await;
|
||||
peer.accept_answer(&relay.answer(answer["sdp"].as_str().unwrap())).await.unwrap();
|
||||
wait_connected(&mut peer).await;
|
||||
let mut source = SyntheticSource::new(30, 3000, true);
|
||||
let (mut frames, mut no_feedback) = (Vec::new(), false);
|
||||
let end = Instant::now() + Duration::from_secs(seconds);
|
||||
while Instant::now() < end {
|
||||
source.poll_frames(Instant::now(), &mut frames);
|
||||
for f in frames.drain(..) {
|
||||
peer.write(f.kind, f.time, f.data);
|
||||
}
|
||||
while let Some(event) = peer.try_next_event() {
|
||||
no_feedback |= matches!(event, PeerEvent::NoFeedback);
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
(no_feedback, relay.profile(), browser.call(json!({ "op": "stats" })).await)
|
||||
}
|
||||
|
||||
/// The streamer's fallback against libwebrtc: with AES-GCM first, our peer
|
||||
/// (the DTLS server) selects it; the relay lets no SRTP through, Chromium's
|
||||
/// receiver reports never mention our video, and the peer reports
|
||||
/// `NoFeedback` (the streamer session then offers again without the AEAD
|
||||
/// profiles). The next connection, AES_CM_128_HMAC_SHA1_80 only, works:
|
||||
/// no `NoFeedback`, Chromium decodes.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn browser_srtp_failure_is_noticed() {
|
||||
use SrtpProfile::{AeadAes128Gcm, AeadAes256Gcm, Aes128CmSha1_80};
|
||||
if !enabled() {
|
||||
eprintln!("skipped: set VOELIN_INTEROP=1 (needs node, Playwright and Chromium)");
|
||||
return;
|
||||
}
|
||||
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
|
||||
let mut browser = Browser::start().await;
|
||||
let aead_first = vec![AeadAes128Gcm, AeadAes256Gcm, Aes128CmSha1_80];
|
||||
let (no_feedback, profile, stats) =
|
||||
stream_through_failing_srtp(&mut browser, aead_first, 3).await;
|
||||
eprintln!("AES-GCM failing: NoFeedback {no_feedback}, profile {profile:?}, {stats:#}");
|
||||
assert_eq!(profile, Some(7), "AEAD_AES_128_GCM selected");
|
||||
assert!(no_feedback, "a viewer that gets nothing must be noticed");
|
||||
assert_eq!(stats["inbound"]["video"]["framesDecoded"].as_u64().unwrap_or(0), 0);
|
||||
|
||||
let (no_feedback, profile, stats) =
|
||||
stream_through_failing_srtp(&mut browser, vec![Aes128CmSha1_80], 3).await;
|
||||
eprintln!("AES_CM: NoFeedback {no_feedback}, profile {profile:?}, {stats:#}");
|
||||
assert_eq!(profile, Some(1));
|
||||
assert!(!no_feedback, "a working connection must not be taken for a failing one");
|
||||
assert!(aes_cm_128_sha1_80(&stats["transport"]["srtpCipher"]), "{stats:#}");
|
||||
assert!(stats["inbound"]["video"]["framesDecoded"].as_u64().unwrap() > 30, "{stats:#}");
|
||||
browser.quit().await;
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
//! 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`, and no other
|
||||
/// candidates (a browser lists one per network interface).
|
||||
fn replace(sdp: &str, from: SocketAddr, to: SocketAddr) -> String {
|
||||
let (from, to) = (
|
||||
format!(" {} {} typ ", from.ip(), from.port()),
|
||||
format!(" {} {} typ ", to.ip(), to.port()),
|
||||
);
|
||||
sdp.split_inclusive('\n')
|
||||
.filter(|l| !l.starts_with("a=candidate:") || l.contains(&from))
|
||||
.map(|l| l.replace(&from, &to))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 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");
|
||||
}
|
||||
@@ -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,128 @@ 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));
|
||||
}
|
||||
|
||||
/// Video arrives in the codec our answer took, but our decoders make
|
||||
/// nothing of it (the app's pipeline says so: `video_undecodable`): the
|
||||
/// viewer asks for a new connection without that codec and gets the next
|
||||
/// one the streamer offered. With no other codec left it stays.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn undecodable_video_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, Duration::MAX), None);
|
||||
net.source = Some(SyntheticSource::new(30, 4000, true));
|
||||
let id = net.watching().await;
|
||||
net.frames(10).await;
|
||||
assert_eq!(net.viewer().codec, Some(VideoCodec::Vp9));
|
||||
net.clients[VIEWER].video_undecodable(&id).unwrap();
|
||||
net.until("connected again", |i, e| {
|
||||
i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected))
|
||||
})
|
||||
.await;
|
||||
net.frames(10).await;
|
||||
assert_eq!(net.sent(VIEWER, |s| *s == Signal::Reconnect), 1);
|
||||
assert_eq!(net.viewer().codec, Some(VideoCodec::Vp8));
|
||||
// VP8 does not decode either: nothing is left, the viewer stays.
|
||||
net.clients[VIEWER].video_undecodable(&id).unwrap();
|
||||
net.frames(10).await;
|
||||
assert_eq!(net.sent(VIEWER, |s| *s == Signal::Reconnect), 1);
|
||||
assert_eq!(
|
||||
net.clients[VIEWER].video_undecodable("nope"),
|
||||
Err(SessionError::NotWatching("nope".into()))
|
||||
);
|
||||
}
|
||||
|
||||
/// 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));
|
||||
}
|
||||
Reference in new issue
Block a user