Merge branch 'claude/gifted-lovelace-1crlx2' into worktree-agent-a5ecbed1e5dd55ddc
# Conflicts: # tools/voelinctl/src/stream.rs
This commit is contained in:
commit
92344651ca
28 files changed
+2454
-299
No files matched your search
@@ -34,6 +34,12 @@ The first release is in preparation.
|
||||
under 1 fps of such a stream; 60 fps now). After a lost frame H.264 and
|
||||
HEVC go on decoding while a keyframe is asked for. Settings:
|
||||
`stream.hardware_decoding`, `stream.decoder_backend`.
|
||||
- Streams connect and play in more cases: H.264 is offered in Constrained
|
||||
High and Constrained Baseline, each viewer getting the profile it takes;
|
||||
a connection that comes up but carries nothing is replaced by one
|
||||
without the SRTP profile or the codec it used; host addresses hidden
|
||||
behind mDNS names (as browsers send them) are resolved; larger socket
|
||||
buffers keep high-bitrate streams from losing packets in bursts.
|
||||
- `tsgw`: companion gateway for server admins (presence, channel chat
|
||||
relay, history).
|
||||
- Chat history: messages are kept on the device and, with a gateway, what
|
||||
|
||||
Generated
+1
@@ -9660,6 +9660,7 @@ dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"socket2",
|
||||
"str0m",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
|
||||
@@ -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 {
|
||||
@@ -295,16 +313,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;
|
||||
}
|
||||
|
||||
@@ -322,16 +340,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 {
|
||||
@@ -1990,6 +2004,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>>,
|
||||
@@ -2002,8 +2018,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
|
||||
@@ -2064,7 +2088,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);
|
||||
@@ -2086,20 +2110,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
|
||||
}
|
||||
}
|
||||
@@ -2110,13 +2141,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;
|
||||
@@ -2138,7 +2170,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);
|
||||
@@ -2151,29 +2183,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;
|
||||
@@ -2183,7 +2227,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.
|
||||
@@ -2630,6 +2678,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
|
||||
@@ -2957,11 +3050,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(_) => {}
|
||||
@@ -3118,6 +3225,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.
|
||||
@@ -3196,11 +3368,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,
|
||||
/// What [`MediaSink::auto_bitrate`] told, in order.
|
||||
auto: Mutex<Vec<(LayerId, u64)>>,
|
||||
@@ -3211,8 +3383,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
|
||||
}
|
||||
|
||||
@@ -3220,7 +3392,7 @@ 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());
|
||||
}
|
||||
|
||||
@@ -3289,6 +3461,25 @@ mod tests {
|
||||
assert_eq!(streamer.bitrate_kbps(), 2000);
|
||||
}
|
||||
|
||||
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.
|
||||
@@ -3305,29 +3496,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");
|
||||
@@ -3337,12 +3514,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.
|
||||
@@ -3351,8 +3527,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
|
||||
@@ -171,6 +171,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>,
|
||||
@@ -186,8 +190,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`.
|
||||
@@ -390,6 +394,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)
|
||||
@@ -426,8 +431,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));
|
||||
}
|
||||
@@ -246,6 +246,44 @@ Transport details of our stream (`voelin-stream`):
|
||||
patch for it (`VOELIN-PATCH.md`). The order is a setting
|
||||
(`Streams::set_srtp_profiles`, `Command::SetSrtpProfiles`) and applies to
|
||||
new connections.
|
||||
- **Media that does not get through**: a connection can come up and carry
|
||||
nothing (an SRTP library that negotiates a profile it cannot use, a
|
||||
streamer without an encoder for the codec the answer took). Each peer
|
||||
checks once per connection: a viewer's reports `PeerEvent::NoVideo`
|
||||
(with whether audio came) when no video arrived within
|
||||
`PeerConfig::stall_timeout` (5 s); a streamer's reports
|
||||
`PeerEvent::NoFeedback` when, after twice that, no receiver report (or
|
||||
REMB) of the viewer mentioned our video. Keyframe requests do not count:
|
||||
a viewer that gets nothing keeps asking. The sessions then ask for a new
|
||||
connection with the next lower set and log the step: without the SRTP
|
||||
profile that was negotiated (both AEAD profiles when it was one of
|
||||
them), or without the video codec when audio came and video did not. A
|
||||
viewer sends `reconnect`; a streamer sends a `reconnectOffer` of its own,
|
||||
for viewers that do not step down (it waits twice as long, so a Voelin
|
||||
viewer goes first). One layer up, the app's `media::Viewer` judges by
|
||||
decoded pictures: video of one codec that keeps coming (10 s, at least
|
||||
60 frames) without a single picture, every decoder of the codec's
|
||||
ladder having failed, makes it send `Command::StreamUndecodable`, and
|
||||
the viewer asks for a connection without that codec
|
||||
(`Streams::video_undecodable`). What was left out stays out for that
|
||||
viewer or watched stream; when nothing is left, that is logged and
|
||||
nothing loops.
|
||||
- **mDNS candidates**: host candidates behind `<uuid>.local` names (how
|
||||
browsers and other libwebrtc builds hide host addresses) are resolved by
|
||||
a multicast DNS query (`voelin_stream::mdns`, from port 5353 shared with
|
||||
the system's responder: Chromium's answers nothing else) and added as
|
||||
plain candidates, from offers, answers and trickled candidates alike.
|
||||
- **Losses**: each peer socket asks for 4 MB of receive and send buffer
|
||||
(`PeerConfig::udp_buffer`; Linux caps it at `net.core.rmem_max`, and
|
||||
what was granted is logged, with a hint when it is less): the default
|
||||
208 KB overflowed under a 1440p keyframe on loopback (118-209 datagrams
|
||||
per 5 s of a 9 Mbit/s stream), the larger buffer dropped none
|
||||
(`tests/loopback.rs` `high_bitrate_bursts`). What is still lost is
|
||||
repaired by NACK and retransmission (RTX), which our answers keep for
|
||||
every video codec; str0m waits up to 30 complete frames for a
|
||||
retransmission before it hands a frame over as non-contiguous
|
||||
(`losses_are_repaired_by_retransmission`: one packet in 25 lost, every
|
||||
frame whole).
|
||||
- **Bandwidth estimation and pacing**: each viewer connection of our stream
|
||||
runs str0m's send-side estimation (transport-cc feedback; REMB if a viewer
|
||||
sends only that) and paces packets to it. Estimates are per viewer
|
||||
@@ -299,6 +337,62 @@ does not answer. Our own stream registers itself in the directory when it
|
||||
goes live (title, kind, channel, client), updates its viewer count, and is
|
||||
removed when it ends.
|
||||
|
||||
## Negotiation: best first, then fall back
|
||||
|
||||
Wherever Voelin agrees on parameters with a peer or a system component, it
|
||||
tries the best choice first and steps down towards the most compatible one
|
||||
when the better one is not accepted. "Not accepted" is either refused in
|
||||
the negotiation itself (SDP, handshake, a backend's start) or found failing
|
||||
at runtime. The second matters: the official client answers H.264 it
|
||||
cannot decode and then shows nothing, so for codecs "accepted" is not
|
||||
"works", and a streamer cannot see a viewer's decoder. Audit of
|
||||
2026-10-03:
|
||||
|
||||
| Point | Ladder (best → most compatible) | Not accepted means | State |
|
||||
|---|---|---|---|
|
||||
| Video codec, streamer offer | stream codec (configured, else the first of the encoder preference every TeamSpeak client decodes) → AV1, VP9, VP8 of hardware encoders and VP8 of libvpx → H.264 of hardware → HEVC | SDP: the answer lists what the viewer takes; our first one it took is sent (`PeerEvent::VideoCodec`), one encoder per format. At runtime undetectable for the official client: without OpenH264 it answers H.264, decodes nothing and reports success (libwebrtc's `NullVideoDecoder`, no PLI) | already so; deliberately not best-first for H.264: codecs every client decodes come before it, because the streamer cannot see that failure |
|
||||
| Video codec, viewer answer | the offer's order, limited to what we decode; each codec's decoders hardware → FFmpeg software → built-in ([media.md](media.md)) | SDP: no codec in common → refused with the reason (`PeerError::NoCommonCodec`); an official streamer that does not encode our pick re-offers on the same connection (`Peer::renegotiate`). Runtime: audio comes, video does not for `stall_timeout` (`PeerEvent::NoVideo { audio: true }`), or video comes and no picture decodes for 10 s and 60 frames, every decoder of the ladder having failed (`media::Viewer`, `Command::StreamUndecodable`) → `reconnect` without that codec | renegotiation already so; both runtime steps **changed now** (`viewer_falls_back_to_another_codec`, `undecodable_video_falls_back_to_another_codec`, `undecodable_video_is_noticed_through_the_pipeline`) |
|
||||
| H.264 profile | Constrained High (PT 112) → Constrained Baseline (PT 108) | SDP: the answer takes only the Baseline entry (headless Chromium 152) → that viewer's frames come from an encoder in Constrained Baseline | **changed now** (`a_baseline_only_viewer_gets_the_fallback_profile`, `an_encoder_per_h264_profile_viewers_chose`, browser: 90 of 90 frames, SPS profile 66). Android's MediaCodec encoder makes High only |
|
||||
| H.264 level, packetization | the level the stream needs (at least 3.1); packetization mode 1 | `level-asymmetry-allowed=1`; a peer without mode 1 does not take H.264 and gets the next codec | level: unchanged, not a ladder. The app offers 3.1 whatever the share's size (its peer configuration is made before the share starts; `voelinctl` sets the level): open issue |
|
||||
| SRTP profile | AES_CM_128_HMAC_SHA1_80 → AEAD_AES_128_GCM → AEAD_AES_256_GCM | handshake: the DTLS server (we are, with official clients and browsers) takes the first of its order the client offers. Runtime: connected, nothing gets through (`NoVideo { audio: false }` at the viewer, `NoFeedback` at the streamer) → a new connection without the negotiated profile (without both AEAD ones if it was AEAD) | runtime ladder **changed now** (`viewer_falls_back_when_srtp_fails`, `streamer_falls_back_when_its_viewer_gets_nothing`, `browser_srtp_failure_is_noticed`). The order stays most-compatible-first, see below |
|
||||
| DTLS version, cipher suite | 1.2 (str0m's default); ECDHE-ECDSA AES-128-GCM, AES-256-GCM (dimpl) | in the handshake: Chromium 152 offers 1.3 and 1.2 and gets 1.2; the server picks the suite from the client's list | already so; 1.3 not turned on, see below |
|
||||
| ICE | host (configured, else the primary IPv4) → server-reflexive (TeamSpeak's STUN, trickled) → peer-reflexive; remote `<uuid>.local` names resolved by mDNS | pairs that fail their checks drop out, the best working pair is used; an mDNS name nobody answers within 3 s is dropped (debug log) | mDNS **changed now** (`browser_mdns_candidates_connect`); the rest already so. No TURN (TeamSpeak runs none), no IPv6 gathering |
|
||||
| Stream connection | renegotiation on the running connection (a new `offer` signal) → a new connection (`reconnect` / `reconnectOffer`), each fallback step one more → the watch ends | a viewer whose connection closes asks again, three times, then the watch ends with `Failed`; fallback steps do not count against those three | renegotiation and reconnect already so, fallback steps **changed now**; no automatic `joinstreamrequest` again: a streamer may have to accept it by hand, so the user decides |
|
||||
| Simulcast | one layer per viewer by its bandwidth estimate (TeamSpeak); RID simulcast only with `PeerConfig::simulcast` (SFU, WHIP) | an answer without `a=simulcast` leaves a RID peer without video | not changed: RID is opt-in and only `voelinctl --simulcast` turns it on; offer it only to peers that take it |
|
||||
| Bandwidth feedback | transport-cc → REMB | a viewer without transport-cc feedback: its REMB estimates are used | already so |
|
||||
| Socket buffers | 4 MB → what the system grants (`rmem_max`) | the kernel caps `SO_RCVBUF`; logged, once with a hint | **changed now** (`high_bitrate_bursts`: 118-209 drops per 5 s before, none after) |
|
||||
| Loss repair | NACK + retransmission → after 30 complete frames, the frame is handed over non-contiguous → keyframe request | the depacketizer gives up waiting | already so, verified now (`losses_are_repaired_by_retransmission`) |
|
||||
| Opus | 48 kHz stereo, 128 kbit/s music mode, 20 ms, in-band FEC on (5 %), DTX off; SDP `minptime=10;useinbandfec=1` | fmtp differences do not refuse a codec (str0m scores the match), and every Opus decoder takes every mode | already so, no ladder needed. Our answers lack `stereo=1`, so libwebrtc streamers send us mono; our playback is mono anyway |
|
||||
| WHIP output | the studio's one codec + Opus; one host candidate | the service refuses → the output fails with its answer | not changed: a second codec would need a second encode; no STUN/TURN yet ([studio.md](studio.md)) |
|
||||
| Gateway protocol | subprotocol `tsgw.v1+json`; features by `capabilities` | a gateway without a feature: the client hides it; unknown fields are ignored, unknown message types answered `unknown_type` | already so; a `v2` would be offered first as a second subprotocol once it exists |
|
||||
| TeamSpeak client version | the configured signed version, else the vendored default (`Windows_3_X_X__1`); the legacy UDP protocol on TS3 and TS6 | a server that refuses the version ends the connection with its error | not done: no server here refuses the default; retrying with the newest signed version (`Versions.csv`, only `voelinctl` reads it) needs that refusal recognised first. TS6's protobuf transport is not implemented |
|
||||
| Capture buffers | DMA-BUF in the sink's tiled modifiers → LINEAR DMA-BUF → shared memory | the compositor fixates the format; a LINEAR mapping slower than 1 ns per pixel over 30 frames renegotiates to shared memory; a failed GPU conversion or an encoder that needs frames in memory declines DMA-BUFs | already so |
|
||||
| Capture backend | Android's provider → the ScreenCast portal (Wayland) → X11 (`DISPLAY`) → Windows Graphics Capture; or the backend set | the backend that cannot start fails the share with its reason; a cancelled portal dialog is not a failure | not changed: falling back from the portal to X11 on Wayland would capture XWayland only (black for Wayland windows); wlroots screencopy is the candidate for compositors without a portal |
|
||||
| Encoder backend | the preference: hardware (VA-API, NVENC, Quick Sync, AMF, VideoToolbox, Media Foundation, MediaCodec) → libvpx VP8 → x264, OpenH264 → libvpx VP9 → SVT-AV1, libaom; a named backend first | at start-up each backend's self-test (one keyframe) leaves out what fails, with the reason; at runtime an encoder that fails logs and tries again with the next frame | start-up already so; switching backends after runtime failures not done |
|
||||
|
||||
Not turned on, with the evidence:
|
||||
|
||||
- **AEAD-first SRTP order.** AES-GCM is the better profile, and the
|
||||
fallback works: when SRTP fails after an AES-GCM handshake, our streamer
|
||||
notices (`NoFeedback`, also with headless Chromium as the viewer) and
|
||||
offers AES_CM_128_HMAC_SHA1_80, and our viewer asks for it. But the
|
||||
streamer's half needs the viewer to answer a `reconnectOffer` it did not
|
||||
ask for, and nothing shows that the official client does; how official
|
||||
clients failed with AES-256-GCM is only reported; and streams between
|
||||
official clients reportedly use AES_CM_128_HMAC_SHA1_80, which suggests
|
||||
they offer nothing else, where the order changes nothing. The gain (a
|
||||
cheaper cipher) does not justify the risk until the official client is
|
||||
tried (steps under the open questions of
|
||||
[protocol-notes/ts6-streaming.md](protocol-notes/ts6-streaming.md#open-questions)).
|
||||
- **DTLS 1.3.** With dimpl allowed to (str0m's `DtlsVersion::Auto`),
|
||||
headless Chromium 152 negotiates DTLS 1.3 (`FEFC`, `TLS_AES_128_GCM_SHA256`)
|
||||
and decodes 90 of 90 frames, and its ClientHello also offers 1.2, which
|
||||
is what our 1.2-only peers get. But a DTLS handshake that fails closes
|
||||
the connection without a version step (a reconnect uses the same
|
||||
settings), the official client's DTLS 1.3 is untried, and all 1.3 would
|
||||
save is one round trip while connecting, nothing for the stream. It
|
||||
stays off.
|
||||
|
||||
## Settings
|
||||
|
||||
`voelin-core::settings::Settings` is the settings service. Keys are typed
|
||||
|
||||
+38
-20
@@ -155,16 +155,20 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder
|
||||
retime, the portal renegotiates the rate with the compositor).
|
||||
- One encoder per codec viewers chose: the offer lists several codecs (see
|
||||
`peer_config` below), the streamer's peer reports the codec each answer
|
||||
chose (`PeerEvent::VideoCodec`), and the session sends a video frame only
|
||||
to viewers of its codec (`StreamerSession::write_frame_in`) and tells the
|
||||
encoders which codecs are wanted (`LayerFeedback::set_codecs`,
|
||||
`MediaSink::video_codecs`). Each layer's encoder thread keeps the stream
|
||||
codec's encoder and makes one more per other wanted codec when a viewer
|
||||
needs it (with the streamer's current `Codecs` and preference), drops it
|
||||
when none does, and skips the stream codec while nobody takes it; frames
|
||||
go out through `MediaSink::send_video(frame, codec)`. Sinks that do not
|
||||
tell codecs apart (`EncodedSource`, a `FrameSource`) get the stream codec
|
||||
only, so their offers must list it alone (`voelinctl stream start` does).
|
||||
chose, H.264 with its profile (`PeerEvent::VideoCodec(VideoFormat)`), and
|
||||
the session sends a video frame only to viewers of its format
|
||||
(`StreamerSession::write_frame_in`) and tells the encoders which formats
|
||||
are wanted (`LayerFeedback::set_codecs`, `MediaSink::video_codecs`).
|
||||
Each layer's encoder thread keeps the stream codec's encoder and makes
|
||||
one more per other wanted format when a viewer needs it (with the
|
||||
streamer's current `Codecs` and preference; for H.264 Constrained
|
||||
Baseline with `EncoderConfig::h264_profile` set), drops it when none
|
||||
does, and skips the stream codec while nobody takes it; frames go out
|
||||
through `MediaSink::send_video(frame, format)`. So an H.264 stream runs a
|
||||
second H.264 encoder only while a viewer took the Baseline entry of the
|
||||
offer. Sinks that do not tell formats apart (`EncodedSource`, a
|
||||
`FrameSource`) get the stream codec only, so their offers must list it
|
||||
alone, H.264 in Constrained High only (`voelinctl stream start` does).
|
||||
A studio's outputs count as viewers too: the stream codec always runs
|
||||
for its recordings and replay buffer, and an output that needs a codec of
|
||||
its own (RTMP: H.264) gets an encoder of the layer it takes
|
||||
@@ -198,13 +202,18 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder
|
||||
decodes H.264 only with an OpenH264 library it downloads at start-up; when
|
||||
that fails it still answers H.264 and shows nothing (see
|
||||
`docs/protocol-notes/ts6-streaming.md`), so H.264 never comes before a
|
||||
codec it always decodes. H.264 is offered as one variant, Constrained High
|
||||
(packetization mode 1) at the level the stream needs
|
||||
(`PeerConfig::set_h264_format(profile, width, height, fps, bitrate)`:
|
||||
macroblocks per second and per frame, and bitrate, per H.264 Table A-1;
|
||||
never below 3.1, the level offered before); str0m's other H.264 variants
|
||||
are only accepted, never offered, so a viewer cannot answer a profile we
|
||||
do not send.
|
||||
codec it always decodes. H.264 is offered in two variants, best first:
|
||||
Constrained High (payload type 112), then Constrained Baseline (108) for
|
||||
peers that list no High profile (headless Chromium 152's libwebrtc lists
|
||||
only Baseline, Constrained Baseline and Main), both packetization mode 1
|
||||
at the level the stream needs (`PeerConfig::h264_profile_level_ids`,
|
||||
`set_h264_format(width, height, fps, bitrate)`: macroblocks per second
|
||||
and per frame, and bitrate, per H.264 Table A-1; never below 3.1, the
|
||||
level offered before). A viewer that takes both answers High (the
|
||||
streamer writes the first of its own order the answer lists); one that
|
||||
takes only Baseline gets frames from an encoder in Constrained Baseline
|
||||
(above). str0m's other H.264 variants are only accepted, never offered,
|
||||
so a viewer cannot answer a profile we do not send.
|
||||
- `VideoPipeline` decodes on its own thread, with the first decoder of the
|
||||
stream codec's ladder that opens (`Codecs::decoders_for`, see
|
||||
[FFmpeg decoders](#ffmpeg-decoders-loaded-at-runtime)). It starts at a
|
||||
@@ -233,8 +242,15 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder
|
||||
which runs in the app, not sent as engine events: the engine never sees
|
||||
the decoded pictures.
|
||||
- `Viewer` feeds a `VideoPipeline` from the engine and sends
|
||||
`RequestStreamKeyframe`; `LocalPreview` runs capture → encoder → decoder
|
||||
without a server (the desktop app's `VOELIN_DEMO_STREAM`).
|
||||
`RequestStreamKeyframe`. When video of one codec keeps coming (10 s, at
|
||||
least 60 frames: time for every decoder of the ladder to fail) and not a
|
||||
single picture decodes, it sends `Command::StreamUndecodable` once: the
|
||||
stream session asks for a new connection without that codec, if the
|
||||
streamer offered another we take (the negotiation ladder in
|
||||
[architecture.md](architecture.md#negotiation-best-first-then-fall-back)).
|
||||
A codec that decoded once is never reported. `LocalPreview` runs capture
|
||||
→ encoder → decoder without a server (the desktop app's
|
||||
`VOELIN_DEMO_STREAM`).
|
||||
- Viewer counts come from the server: `StreamInfo::viewers` in
|
||||
`Event::StreamsChanged` is TeamSpeak 6's own count (`viewer` of
|
||||
`notifystreaminfo`), counted up from `notifystreamclientjoined` and
|
||||
@@ -1258,7 +1274,9 @@ has not run on Windows yet.
|
||||
| AMF never loaded on Linux by default; AMF opens serialised | `ffmpeg::encoder::tests::amf_is_opt_in_on_linux`, `tests/ffmpeg.rs` `probe_reports_every_backend` (no `libamfrt` in `/proc/self/maps`), `amf_encoders_open_in_parallel` (`--ignored`, with `VOELIN_FFMPEG_AMF=1`) | tested: the probe crash (SIGSEGV in `libamfrt64`, 10 of 420 concurrent probes under Xvfb) reproduced, then none in 600 with serialised opens |
|
||||
| Encoder preference (auto, software, named, hardware off), report ranks | `codec::tests::encoder_preference` | tested |
|
||||
| An encoder per codec viewers chose (made, dropped, stream codec skipped, preference change) | `voelin-core` `media::tests::an_encoder_per_codec_viewers_chose` | tested |
|
||||
| Answer's codec reported to the streamer, H.264 level in the offer, HEVC offered | `voelin-stream` `peer::tests::streamer_learns_the_answered_codec`, `h264::tests` | tested (str0m on loopback) |
|
||||
| An encoder per H.264 profile viewers chose: Constrained High and Baseline side by side (SPS `profile_idc` 100 and 66), High dropped when only Baseline viewers are left | `voelin-core` `media::tests::an_encoder_per_h264_profile_viewers_chose` | tested (FFmpeg's H.264 encoders here) |
|
||||
| Answer's codec reported to the streamer, H.264 levels and both profiles in the offer, a Baseline-only viewer answering the fallback entry, HEVC offered | `voelin-stream` `peer::tests::streamer_learns_the_answered_codec`, `a_baseline_only_viewer_gets_the_fallback_profile`, `h264::tests` | tested (str0m on loopback) |
|
||||
| The H.264 ladder against libwebrtc: headless Chromium 152 answers the Constrained Baseline entry and decodes frames from an encoder in that profile | `voelin-core/tests/browser_codecs.rs` `real_encoders_decode_in_browser` (`VOELIN_INTEROP=1`) | tested: `h264_vaapi` (from memory and from DMA-BUFs) and `libx264`, 90 of 90 frames at 1280x720, SPS profile 66 |
|
||||
| x264 / SVT-AV1 / libaom in the streamer pipeline | `voelinctl stream bench --encoder ...` | 720p30: x264 8.7 ms per frame, SVT-AV1 1.3 ms, libaom 37 ms; 1.1 allocations per encoded frame |
|
||||
| Hardware encoders VA-API and AMF (H.264, HEVC, AV1) in the streamer pipeline | `voelinctl stream bench` on a Radeon RX 7900 GRE, 1080p60 / 1440p60 / simulcast | tested: full frame rate, 0.20-0.52 cores against 1.16-2.55 for software, 1.02 allocations per encoded frame, every backend within 2 % of the target bitrate once `av1_vaapi` got a two-second buffer (it overshot by 3.5-8 %; see the tables above) |
|
||||
| Hardware encoders → our decoders: `h264_vaapi` / `h264_amf` → OpenH264, `av1_vaapi` / `av1_amf` → dav1d (PSNR > 28 dB, decoded size, keyframes at start and on request, timestamps, bitrate change) at 320x240 and 1920x1080 | `tests/ffmpeg.rs` `hardware_encoders_roundtrip` (`VOELIN_OPENH264_LIB`, `--features av1`) | tested on the Radeon RX 7900 GRE: it found the AV1 encoder padding 1080 rows to 1082 (and other sizes to 64x16), now cropped (see above). HEVC is decoded by FFmpeg's decoders in `tests/ffmpeg_decoders.rs` |
|
||||
|
||||
@@ -272,9 +272,14 @@ libwebrtc, the stack the official client is built on:
|
||||
strings (e.g. `fhs`), not `0`. Our `iceCandidate` signals use the peer's
|
||||
first mid and `sdpMLineIndex` 0; Chromium's `addIceCandidate` accepts them.
|
||||
- Without camera/microphone permission Chromium hides host candidates behind
|
||||
mDNS names (`<uuid>.local`), which str0m cannot resolve. The test disables
|
||||
that; the official client may send mDNS candidates, which would then need a
|
||||
resolver (or its server-reflexive candidates) on our side.
|
||||
mDNS names (`<uuid>.local`), which str0m cannot use. Our peers resolve them
|
||||
with a multicast DNS query (`voelin_stream::mdns`, 2026-10-03). Chromium
|
||||
152's responder answers queries sent from port 5353 (with multicast
|
||||
answers on every interface) and ignores "legacy" queries from other
|
||||
ports, so the query goes out from 5353, shared with the system's
|
||||
responder. `browser_mdns_candidates_connect` keeps our candidates from the
|
||||
browser, so only a resolved name can connect: it does, both ways. The
|
||||
official client may send such names too.
|
||||
- str0m answers in its own codec order and the offerer sends the answer's
|
||||
first codec, so `Peer::answer` orders the viewer's codecs like the offer.
|
||||
- SRTP profile: libwebrtc answers our `setup:actpass` offer as DTLS client
|
||||
@@ -287,6 +292,18 @@ libwebrtc, the stack the official client is built on:
|
||||
`srtpCipher: AES_CM_128_HMAC_SHA1_80` (DTLS 1.2,
|
||||
`TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`). Whether this was what broke the
|
||||
official client is still to be confirmed with it.
|
||||
- When SRTP fails after the handshake (a relay that lets STUN and DTLS
|
||||
through and drops SRTP once AES-GCM was selected), Chromium 152 decodes
|
||||
nothing and its receiver reports never mention our video; our streamer
|
||||
peer reports that (`PeerEvent::NoFeedback`) and the session offers a new
|
||||
connection without AES-GCM (`browser_srtp_failure_is_noticed`; the
|
||||
AES_CM_128_HMAC_SHA1_80 connection then decodes 90 of 90 frames). A
|
||||
working connection raises no such report.
|
||||
- DTLS: Chromium 152's ClientHello offers 1.3 and 1.2. Our peers use 1.2
|
||||
(str0m's default) and get it; allowed 1.3, dimpl negotiates it with
|
||||
Chromium 152 (`FEFC`, `TLS_AES_128_GCM_SHA256`) and the stream decodes
|
||||
(tried 2026-10-03, not turned on: see "Negotiation" in
|
||||
[architecture.md](../architecture.md)).
|
||||
- With bandwidth estimation on our streamer peer, Chromium's transport-cc
|
||||
feedback gives estimates; the offer is the same as without (str0m always
|
||||
offers transport-cc and abs-send-time).
|
||||
@@ -313,7 +330,11 @@ while it watched a Voelin stream, and the symbols of its binary:
|
||||
- It answers with the first codec of the offer it lists, like Chromium.
|
||||
|
||||
Voelin now offers codecs every client decodes first (`decoded_everywhere`)
|
||||
and H.264 only in the profile it encodes. The real encoders' streams (VA-API
|
||||
and H.264 only in the profiles it encodes: Constrained High, then
|
||||
Constrained Baseline (both packetization mode 1). A client that answers
|
||||
the Baseline entry (headless Chromium 152; the official client's own
|
||||
answer above was a Baseline profile too) gets frames from an encoder in
|
||||
that profile. The real encoders' streams (VA-API
|
||||
H.264 and AV1, from memory and from DMA-BUFs; libvpx VP8 and VP9; x264,
|
||||
SVT-AV1, libaom) decode in Chromium 152's libwebrtc at full size
|
||||
(`crates/voelin-core/tests/browser_codecs.rs`). Watching such a stream with
|
||||
@@ -378,6 +399,18 @@ itself with these decoders is still to be confirmed.
|
||||
- [ ] Interop with the official TS6 client (its offer/answer details, whether
|
||||
it trickles candidates, mDNS host candidates). The codecs it picks and
|
||||
decodes are known (see above); Chromium's WebRTC stack interoperates.
|
||||
- [ ] Whether the official client, as a viewer, answers a `reconnectOffer`
|
||||
it did not ask for (our streamer sends one when the viewer's receiver
|
||||
reports show none of our video), and whether it offers AES-GCM at all.
|
||||
To find out: Voelin streams to it with
|
||||
`voelinctl ... stream start --synthetic --auto-accept --srtp
|
||||
AEAD_AES_128_GCM,AES_CM_128_HMAC_SHA1_80` and `RUST_LOG=voelin_stream=debug`;
|
||||
the viewer list prints the SRTP profile per viewer. AES-GCM selected
|
||||
and a picture: the official client handles it, and AEAD-first could
|
||||
become the default. AES_CM_128_HMAC_SHA1_80 selected: it does not
|
||||
offer AES-GCM, and the order does not matter. No picture: after 10 s
|
||||
the log says "offering a new connection without SRTP"; a picture after
|
||||
that proves it answers our `reconnectOffer`.
|
||||
- [ ] Whether stream audio can be sent without video.
|
||||
- [ ] The WebRTC/protobuf transport some TS6 clients use on UDP 9987
|
||||
(`client_protocol_format=proto`, reported in community reverse engineering).
|
||||
|
||||
+19
-4
@@ -201,11 +201,14 @@ stream_elsewhere_check() {
|
||||
presence_check() {
|
||||
local addr=$1 query=$2 out="$STATE_DIR/observe.log"
|
||||
# shellcheck disable=SC2086
|
||||
# A loaded TeamSpeak 6 dev server takes 4 to 13 s to let a client in, so
|
||||
# the observer waits long (it ends as soon as it sees the client) and the
|
||||
# client stays a while.
|
||||
"$VOELINCTL" observe $query --secret "$QUERY_SECRET" --allowlisted --poll 2 \
|
||||
--seconds 20 --expect-client presence-probe >"$out" 2>&1 &
|
||||
--seconds 45 --expect-client presence-probe >"$out" 2>&1 &
|
||||
local observer=$!
|
||||
sleep 2
|
||||
"$VOELINCTL" connect "$addr" --nick presence-probe listen --timeout 4 >/dev/null 2>&1 || true
|
||||
"$VOELINCTL" connect "$addr" --nick presence-probe listen --timeout 8 >/dev/null 2>&1 || true
|
||||
if ! wait "$observer"; then
|
||||
cat "$out"
|
||||
fail "observer did not see the voice client"
|
||||
@@ -224,7 +227,13 @@ relay_check() {
|
||||
"$VOELINCTL" connect "$addr" --nick relay-listener listen --expect "from-relay-$token" \
|
||||
--timeout 20 >"$heard" 2>&1 &
|
||||
local listener=$!
|
||||
sleep 4
|
||||
# Talk once the relay relays and the listener is in (it prints the
|
||||
# clients it sees): a fixed pause lost the message whenever the dev
|
||||
# server was slow to let clients in.
|
||||
for _ in $(seq 1 120); do
|
||||
grep -q "relaying channel" "$out" 2>/dev/null && [[ -s "$heard" ]] && break
|
||||
sleep 0.25
|
||||
done
|
||||
"$VOELINCTL" connect "$addr" --nick relay-talker chat channel "to-relay-$token"
|
||||
# shellcheck disable=SC2086
|
||||
"$VOELINCTL" relay $query --secret "$QUERY_SECRET" --allowlisted --channel 1 --nick Alice \
|
||||
@@ -268,7 +277,13 @@ gateway_check() {
|
||||
"$VOELINCTL" connect "$addr" --nick gateway-listener listen --expect "from-gateway-$token" \
|
||||
--timeout 20 >"$STATE_DIR/gateway-heard.log" 2>&1 &
|
||||
local listener=$!
|
||||
sleep 4
|
||||
# Talk once the gateway user is logged in and sees the listener (in its
|
||||
# presence or as it joins): a fixed pause lost the message whenever the
|
||||
# dev server was slow to let clients in.
|
||||
for _ in $(seq 1 120); do
|
||||
grep -q "gateway-listener" "$out" 2>/dev/null && break
|
||||
sleep 0.25
|
||||
done
|
||||
"$VOELINCTL" connect "$addr" --nick gateway-talker chat channel "to-gateway-$token"
|
||||
"$VOELINCTL" gateway "$url" --identity "$user" --send "channel:1=from-gateway-$token" --seconds 3 >/dev/null
|
||||
if ! wait "$reader"; then
|
||||
|
||||
+21
-5
@@ -12,11 +12,13 @@ TeamSpeak server is involved.
|
||||
|---|---|
|
||||
| `rust_streams_to_browser` | Our streamer offer (`PeerConfig::loopback()`, VP8 + Opus, with the `a=x-voelin-layers` line a Voelin streamer with several layers adds, which libwebrtc must skip) answered by an `RTCPeerConnection`; `SyntheticSource` media for 3 s; `inbound-rtp` stats: VP8 packets and bytes, decoded frames (the synthetic frames are real 1x1 VP8 keyframes), Opus packets; the `transport` stats' `srtpCipher` is `AES_CM_128_HMAC_SHA1_80` (our SRTP order, we are the DTLS server); our bandwidth estimation gets estimates from Chromium's transport-cc feedback |
|
||||
| `browser_streams_to_rust` | Chromium offers a canvas `captureStream` and an oscillator with VP8, VP9, H264 and AV1 preferred in turn (codecs the browser cannot send are skipped); our viewer `Peer::answer` must receive frames of that codec and Opus, over `AES_CM_128_HMAC_SHA1_80`. VP8 also uses trickled browser candidates and checks that a PLI brings a keyframe |
|
||||
| `real_encoders_decode_in_browser` (voelin-core) | Every encoder this machine has (`Codecs::encoders()`), as a share uses it: the 1280x720 test pattern through the `Streamer`, VA-API encoders also from DMA-BUFs as the ScreenCast portal hands over the screen; our streamer peer offers that codec alone (H.264 as Constrained Baseline, see below); the browser must decode at least 60 frames at 1280x720 in 3 s. Codecs the browser does not answer (HEVC, H.264 in Playwright's Chromium) are skipped |
|
||||
| `real_encoders_decode_in_browser` (voelin-core) | Every encoder this machine has (`Codecs::encoders()`), as a share uses it: the 1280x720 test pattern through the `Streamer`, VA-API encoders also from DMA-BUFs as the ScreenCast portal hands over the screen; our streamer peer offers that codec alone (H.264 as the ladder of the offer, Constrained High then Constrained Baseline), and the `Streamer` encodes the format the browser's answer chose, as for a viewer of a real stream; the browser must decode at least 60 frames at 1280x720 in 3 s, and H.264 must carry the chosen profile in its SPS. Codecs the browser does not answer (HEVC, H.264 in Playwright's Chromium) are skipped |
|
||||
| `share_offer_picks_a_codec_every_client_decodes` (voelin-core) | The offer a share makes on this machine (`preferred_codec`, `peer_config`): the browser, answering with the first codec of the offer it lists as the official client does, must pick one every TeamSpeak client decodes (`decoded_everywhere`), and decode it |
|
||||
| `browser_streams_decode_in_the_pipeline` (voelin-core) | The other way: Chromium sends its canvas (320x240) in AV1, VP9 and H.264 in turn (skipping what it cannot send) to our viewer peer, which accepts what this machine decodes (`peer_config`); the engine's `VideoPipeline` must decode 30 pictures at 320x240 with the first decoder of the codec's ladder (`Codecs::decoders_for`), keyframe requests going to the browser as PLIs |
|
||||
| `browser_renegotiates_with_rust` | Chromium streams VP8, then sends a new offer on the same connection with VP9 first (as the official client re-offers when it does not encode the codec we chose); `Peer::renegotiate` answers on the same peer, in the new offer's codec order; VP9 frames must arrive |
|
||||
| `trickled_candidates_reach_browser` | A server-reflexive candidate (from a fake STUN server) as our sessions trickle it (`iceCandidate` signal with the peer's mid) is accepted by `addIceCandidate` |
|
||||
| `browser_mdns_candidates_connect` | Chromium with its host addresses behind mDNS names (`VOELIN_BROWSER_MDNS=1`, see below) and our candidates kept from it, so only resolving its names can connect: our streamer (names in its answer) and our viewer (names in its offer) connect and the media flows |
|
||||
| `browser_srtp_failure_is_noticed` | The relay of `crates/voelin-stream/tests/relay` between our streamer peer and Chromium drops SRTP once AES-GCM was selected: Chromium decodes nothing, our peer reports `NoFeedback`; the next connection with AES_CM_128_HMAC_SHA1_80 only decodes and reports nothing |
|
||||
|
||||
## Running
|
||||
|
||||
@@ -42,8 +44,12 @@ defaults to `npm root -g` so a global Playwright is found.
|
||||
|
||||
Chromium is started with `--disable-features=WebRtcHideLocalIpsWithMdns`:
|
||||
without camera/microphone permission it would hide host candidates behind
|
||||
mDNS names (`<uuid>.local`), which str0m cannot resolve. The official client
|
||||
may do the same; see `docs/protocol-notes/ts6-streaming.md`.
|
||||
mDNS names (`<uuid>.local`). Our peers resolve those (`voelin_stream::mdns`),
|
||||
which `browser_mdns_candidates_connect` tests with the feature left on
|
||||
(`Browser::start_with_mdns`, `VOELIN_BROWSER_MDNS=1` for the driver). That
|
||||
test needs a network interface with multicast (the browser's responder
|
||||
answers on it) and port 5353 shareable (`SO_REUSEADDR`). The official client
|
||||
may hide its addresses the same way; see `docs/protocol-notes/ts6-streaming.md`.
|
||||
|
||||
## Findings
|
||||
|
||||
@@ -71,11 +77,21 @@ may do the same; see `docs/protocol-notes/ts6-streaming.md`.
|
||||
- Headless Chromium 152 lists H.264 only in the profiles of libwebrtc's
|
||||
software decoder (Baseline, Constrained Baseline, Main, packetization modes
|
||||
0 and 1): it does not answer an offer of Constrained High alone
|
||||
(`640c1f`, what our streamers offer), yet decodes High profile streams
|
||||
when it negotiated another profile (its decoder is FFmpeg's).
|
||||
(`640c1f`), yet decodes High profile streams when it negotiated another
|
||||
profile (its decoder is FFmpeg's). Our offers now list Constrained
|
||||
Baseline (`42e01f`) after Constrained High; Chromium 152 answers that
|
||||
entry and decodes what an encoder in Constrained Baseline makes
|
||||
(`h264_vaapi`, also from DMA-BUFs, and `libx264`: 90 of 90 frames,
|
||||
2026-10-03).
|
||||
- Chromium 152 (Arch Linux build, `VOELIN_CHROMIUM=/usr/bin/chromium`) sends
|
||||
AV1, VP9 and H.264; our pipeline decodes all three on the GPU here (AMD,
|
||||
VA-API: `av1_vaapi`, `vp9_vaapi`, `h264_vaapi`), at the canvas's size.
|
||||
- Chromium 152 offers DTLS 1.3 and 1.2; our peers (1.2) get 1.2. Allowed
|
||||
1.3, dimpl negotiates it with Chromium 152 (`tlsVersion` `FEFC`,
|
||||
`TLS_AES_128_GCM_SHA256`) and the stream decodes; it is not turned on
|
||||
(see "Negotiation" in `docs/architecture.md`).
|
||||
- When SRTP fails after the handshake, Chromium sends no receiver report
|
||||
that mentions our video: what `PeerEvent::NoFeedback` waits for.
|
||||
- With str0m's bandwidth estimation and pacer on our streamer peer, Chromium's
|
||||
transport-cc feedback yields estimates within the first second (about
|
||||
640 kbit/s rising towards the desired bitrate with the 720 kbit/s synthetic
|
||||
|
||||
@@ -190,14 +190,16 @@ window.peer = {
|
||||
`;
|
||||
|
||||
async function main() {
|
||||
const args = ['--autoplay-policy=no-user-gesture-required'];
|
||||
// Real host candidates instead of mDNS names (no getUserMedia permission
|
||||
// here), unless the test is about mDNS names (VOELIN_BROWSER_MDNS=1).
|
||||
if (process.env.VOELIN_BROWSER_MDNS !== '1') {
|
||||
args.push('--disable-features=WebRtcHideLocalIpsWithMdns');
|
||||
}
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
executablePath: process.env.VOELIN_CHROMIUM || undefined,
|
||||
args: [
|
||||
// Real host candidates instead of mDNS names (no getUserMedia permission here).
|
||||
'--disable-features=WebRtcHideLocalIpsWithMdns',
|
||||
'--autoplay-policy=no-user-gesture-required',
|
||||
],
|
||||
args,
|
||||
});
|
||||
const page = await browser.newPage();
|
||||
page.on('console', (m) => process.stderr.write('[page] ' + m.text() + '\n'));
|
||||
|
||||
@@ -25,6 +25,18 @@ pub struct Browser {
|
||||
|
||||
impl Browser {
|
||||
pub async fn start() -> Self {
|
||||
Self::launch(false).await
|
||||
}
|
||||
|
||||
/// A browser that hides its host addresses behind mDNS names
|
||||
/// (`<uuid>.local`), as Chromium does without camera or microphone
|
||||
/// permission.
|
||||
#[allow(dead_code, reason = "not every test uses it")]
|
||||
pub async fn start_with_mdns() -> Self {
|
||||
Self::launch(true).await
|
||||
}
|
||||
|
||||
async fn launch(mdns: bool) -> Self {
|
||||
let script = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../tests/interop/browser-peer.cjs")
|
||||
.canonicalize()
|
||||
@@ -36,6 +48,7 @@ impl Browser {
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.env("VOELIN_BROWSER_MDNS", if mdns { "1" } else { "0" })
|
||||
.kill_on_drop(true);
|
||||
// Playwright is usually installed globally.
|
||||
if std::env::var_os("NODE_PATH").is_none()
|
||||
|
||||
@@ -21,9 +21,9 @@ use voelin_core::media::{
|
||||
};
|
||||
use voelin_model::ServerFlavor;
|
||||
use voelin_stream::{
|
||||
ClientState, EndReason, FrameSource, H264Profile, LayerId, LayerSpec, MediaKind, Output,
|
||||
PeerConfig, Request, SrtpProfile, StreamEvent, StreamInfo, StreamNotification, StreamSetup,
|
||||
StreamerEvent, StreamerOptions, Streams, SyntheticSource, VideoCodec, ViewerInfo, WatchEvent,
|
||||
ClientState, EndReason, FrameSource, LayerId, LayerSpec, MediaKind, Output, PeerConfig,
|
||||
Request, SrtpProfile, StreamEvent, StreamInfo, StreamNotification, StreamSetup, StreamerEvent,
|
||||
StreamerOptions, Streams, SyntheticSource, VideoCodec, ViewerInfo, WatchEvent,
|
||||
};
|
||||
|
||||
#[derive(Args, Debug, Clone)]
|
||||
@@ -197,7 +197,7 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> {
|
||||
if *synthetic {
|
||||
let (w, h) = parse_size(size)?;
|
||||
let bitrate = u64::from(pattern_kbps(size, *fps, *bitrate)?) * 1000;
|
||||
config.set_h264_format(H264Profile::ConstrainedHigh, w, h, *fps, bitrate);
|
||||
config.set_h264_format(w, h, *fps, bitrate);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -209,8 +209,10 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> {
|
||||
};
|
||||
if matches!(args.command, StreamCommand::Start { .. }) {
|
||||
// Frames go out through a `FrameSource`, which does not tell codecs
|
||||
// apart: offer the stream codec alone.
|
||||
// apart: offer the stream codec alone, H.264 in the profile it is
|
||||
// encoded in (Constrained High).
|
||||
config.video_codecs.truncate(1);
|
||||
config.h264_profile_level_ids.truncate(1);
|
||||
}
|
||||
let codec = stream_codec(&codecs, &config);
|
||||
let mut driver = Driver { streams: Streams::new(own, config), pending: HashMap::new() };
|
||||
|
||||
Reference in new issue
Block a user