diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index 6b33338..705179f 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -243,6 +243,14 @@ pub enum Command { 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`]. + SetWatchLayer { + session: SessionId, + stream_id: String, + layer: Option, + }, /// Playback volume of a watched stream's audio, linear (1 = unchanged, /// up to 4). SetStreamVolume { @@ -552,6 +560,15 @@ pub enum Event { stream_id: String, state: WatchState, }, + /// The simulcast layers a watched stream offers (a Voelin streamer with + /// several lists them; empty: none to choose from), and the one we asked + /// for with [`Command::SetWatchLayer`] (`None`: as the bandwidth allows). + WatchLayers { + session: SessionId, + stream_id: String, + layers: Vec, + layer: Option, + }, /// A setting was set or reset (by anyone: a command, the UI through /// [`Engine::settings`], …). Read the new value from the settings. SettingChanged { @@ -944,6 +961,7 @@ fn command_session(command: &Command) -> SessionId { | Command::WatchStream { session, .. } | Command::LeaveStream { session, .. } | Command::RequestStreamKeyframe { session, .. } + | Command::SetWatchLayer { session, .. } | Command::SetStreamVolume { session, .. } | Command::SetClientVolume { session, .. } | Command::SetClientMuted { session, .. } diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 9a862ed..1a4634d 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -463,6 +463,9 @@ impl Session { Command::RequestStreamKeyframe { stream_id, .. } => { self.stream_input(StreamInput::RequestKeyframe { stream_id }); } + Command::SetWatchLayer { stream_id, layer, .. } => { + self.stream_input(StreamInput::WatchLayer { stream_id, layer }); + } // Kept for streams started later, also without a connection. Command::SetStreamLayers { layers, .. } => { self.stream_layers = layers.clone(); diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index 5bcda8b..e1f5ac6 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -160,6 +160,10 @@ pub(crate) enum StreamInput { RequestKeyframe { stream_id: String, }, + WatchLayer { + stream_id: String, + layer: Option, + }, /// Simulcast layers of our stream (now and for streams started later). Layers(Vec), /// SRTP profile order of new connections. @@ -369,6 +373,10 @@ impl StreamTask { self.streams.request_keyframe(&stream_id); Ok(()) } + StreamInput::WatchLayer { stream_id, layer } => self + .streams + .set_watch_layer(&stream_id, layer) + .map(|()| self.watch_layers(&stream_id)), StreamInput::Layers(layers) => { self.layers = layers.clone(); // Without a stream they are used for the next one. @@ -537,6 +545,7 @@ impl StreamTask { } WatchState::Ended(reason) } + WatchEvent::Layers(_) => return self.watch_layers(&id), WatchEvent::Frame(frame) => { if let (MediaKind::Audio, Some(audio)) = (frame.kind, &self.audio) { audio.send(AudioIn::StreamAudio { @@ -554,6 +563,17 @@ impl StreamTask { } } + /// Tell the layers of watched stream `id` and the one we asked for. + fn watch_layers(&self, id: &str) { + let Some(watched) = self.streams.watching().find(|v| v.id() == id) else { return }; + self.emit(Event::WatchLayers { + session: self.session, + stream_id: id.to_owned(), + layers: watched.layers().to_vec(), + layer: watched.layer(), + }); + } + /// The answer `stream.permissions` gives to a join request; `None`: ask. fn join_decision(&self, viewer: ClientId) -> Option { match *self.settings.current().get_arc(&STREAM_PERMISSIONS) { diff --git a/crates/voelin-stream/src/layer.rs b/crates/voelin-stream/src/layer.rs index f4b538f..a915d7e 100644 --- a/crates/voelin-stream/src/layer.rs +++ b/crates/voelin-stream/src/layer.rs @@ -79,6 +79,56 @@ impl LayerSpec { } } +/// The session-level SDP attribute in which a Voelin streamer's offer lists +/// its layers, so that a Voelin viewer can pick one (`Signal::Layer`): +/// `a=x-voelin-layers: ...`, each layer +/// `//[/]`. WebRTC stacks skip session +/// attributes they do not know (libwebrtc, which the official TeamSpeak +/// client is built on, and str0m), so other viewers are unaffected, and a +/// viewer asks for a layer only when the offer had it. +pub const SDP_ATTRIBUTE: &str = "x-voelin-layers"; + +/// `sdp` with the [`SDP_ATTRIBUTE`] line listing `layers` at the end of its +/// session section (before the first `m=` line). +pub fn add_to_sdp(sdp: &str, layers: &[LayerSpec]) -> String { + let list: Vec = layers + .iter() + .map(|l| { + let size = l.size.map_or_else(|| l.scale.to_string(), |(w, h)| format!("{w}x{h}")); + let fps = l.max_fps.map(|f| format!("/{f}")).unwrap_or_default(); + format!("{}/{size}/{}{fps}", l.id, l.bitrate) + }) + .collect(); + let line = format!("a={SDP_ATTRIBUTE}:{}\r\n", list.join(" ")); + let at = sdp.find("\r\nm=").map_or(sdp.len(), |i| i + 2); + let mut out = String::with_capacity(sdp.len() + line.len()); + out.push_str(&sdp[..at]); + out.push_str(&line); + out.push_str(&sdp[at..]); + out +} + +/// The layers an SDP lists in [`SDP_ATTRIBUTE`]; `None` without the +/// attribute. Entries that do not parse are left out. +pub fn from_sdp(sdp: &str) -> Option> { + let prefix = format!("a={SDP_ATTRIBUTE}:"); + let value = sdp.lines().find_map(|l| l.trim_end().strip_prefix(prefix.as_str()))?; + let layer = |entry: &str| { + let mut parts = entry.split('/'); + let id = parts.next()?.parse().ok()?; + let size = parts.next()?; + let bitrate = parts.next()?.parse().ok()?; + let max_fps = parts.next().map(str::parse).transpose().ok()?; + let mut layer = LayerSpec { id, max_fps, ..LayerSpec::single(bitrate) }; + match size.split_once('x') { + Some((w, h)) => layer.size = Some((w.parse().ok()?, h.parse().ok()?)), + None => layer.scale = size.parse().ok()?, + } + Some(layer) + }; + Some(value.split_whitespace().filter_map(layer).collect()) +} + /// A set of layers, e.g. those waiting for a keyframe. Grows as needed. #[derive(Clone, Default, PartialEq, Eq)] pub struct LayerSet { @@ -192,6 +242,30 @@ mod tests { assert!(set.is_empty()); } + #[test] + fn layers_in_the_sdp() { + let layers = vec![ + LayerSpec { id: 0, size: Some((1920, 1080)), ..LayerSpec::single(6_000_000) }, + LayerSpec { id: 3, scale: 0.5, max_fps: Some(15), ..LayerSpec::single(800_000) }, + ]; + let sdp = "v=0\r\no=- 1 2 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\n\ + m=video 9 UDP/TLS/RTP/SAVPF 96\r\na=mid:0\r\n"; + let with = add_to_sdp(sdp, &layers); + assert_eq!( + with, + "v=0\r\no=- 1 2 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\n\ + a=x-voelin-layers:0/1920x1080/6000000 3/0.5/800000/15\r\n\ + m=video 9 UDP/TLS/RTP/SAVPF 96\r\na=mid:0\r\n" + ); + assert_eq!(from_sdp(&with), Some(layers)); + assert_eq!(from_sdp(sdp), None); + // Garbled entries are left out. + assert_eq!( + from_sdp("a=x-voelin-layers:x/1/2 1/0.5 2/1/700000\r\n").unwrap(), + [LayerSpec { id: 2, ..LayerSpec::single(700_000) }] + ); + } + #[test] fn output_size() { let mut layer = LayerSpec::single(1_000_000); diff --git a/crates/voelin-stream/src/session.rs b/crates/voelin-stream/src/session.rs index 28cbed3..ef4d6b6 100644 --- a/crates/voelin-stream/src/session.rs +++ b/crates/voelin-stream/src/session.rs @@ -39,7 +39,7 @@ use tsproto_packets::packets::OutCommand; use crate::discovery::{ClientState, Discovery, StreamLookup}; use crate::dtls::SrtpProfile; use crate::feedback::LayerFeedback; -use crate::layer::{LayerId, LayerSet, LayerSpec}; +use crate::layer::{self, LayerId, LayerSet, LayerSpec}; use crate::peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerEvent, VideoCodec}; use crate::proto::{self, LeaveReason, StreamInfo, StreamNotification, StreamSetup}; use crate::signal::Signal; @@ -189,6 +189,10 @@ pub enum WatchEvent { Connected, /// An encoded video or audio frame. Frame(MediaFrame), + /// The simulcast layers the streamer's offer lists + /// ([`layer::SDP_ATTRIBUTE`]): pick one with [`Streams::set_watch_layer`]. + /// Only Voelin streamers list them, and only with several layers. + Layers(Vec), Ended(EndReason), } @@ -252,6 +256,10 @@ pub enum SessionError { NotWatching(String), #[error("cannot watch our own stream")] OwnStream, + #[error("stream {0} has no layers to choose from")] + NoLayers(String), + #[error("stream {0} has no layer {1}")] + UnknownLayer(String, LayerId), } /// The streams in our channel, from `notifystreamstarted`/`notifystreaminfo`/ @@ -561,6 +569,9 @@ struct ViewerSlot { srtp_profile: Option, /// The video codec its answer chose. codec: Option, + /// The layer the viewer asked for ([`Signal::Layer`]); `None`: its + /// estimate decides. + pinned: Option, } impl ViewerSlot { @@ -574,6 +585,7 @@ impl ViewerSlot { estimate: None, srtp_profile: None, codec: None, + pinned: None, } } @@ -760,10 +772,32 @@ impl StreamerSession { self.offer(viewer, true, out).await; } } + Signal::Layer { layer } => self.pin(viewer, layer, out), other => debug!(viewer = viewer.0, "ignoring signal {other:?}"), } } + /// A viewer asks for `layer` ([`Signal::Layer`]; `None`: its estimate + /// decides again). It moves at the layer's next keyframe, which is + /// requested. An unknown layer counts as `None`; viewers with RID + /// simulcast get every layer anyway. + fn pin(&mut self, viewer: ClientId, layer: Option, out: &mut Outbox) { + let start = self.start_bitrate(); + let Some(slot) = self.viewers.get_mut(&viewer.0).filter(|s| s.rids.is_none()) else { + return; + }; + slot.pinned = layer.filter(|l| self.layers.index(*l).is_some()); + slot.choice.up_since = None; + let fitting = self.layers.fitting(slot.estimate.unwrap_or(start)); + let target = slot.pinned.unwrap_or(self.layers.specs[fitting].id); + debug!(viewer = viewer.0, ?layer, target, "viewer picks a layer"); + if let Some(layer) = slot.choice.switch_to(target) { + self.keyframe_request(layer, out); + } + self.emit_viewers(out); + self.update_targets(out); + } + /// The estimate a new viewer starts with. fn start_bitrate(&self) -> u64 { self.options.start_bitrate.unwrap_or(self.layers.specs[self.layers.top()].bitrate) @@ -809,10 +843,19 @@ impl StreamerSession { }; match Peer::offer_with(&self.config, &id, &options).await { Ok((peer, sdp)) => { + // Voelin viewers learn the layers and may pick one (other + // clients skip the attribute); not with RID simulcast, where + // a viewer gets them all. + let sdp = if self.layers.len() > 1 && !rid_offer { + layer::add_to_sdp(&sdp, &self.layers.specs) + } else { + sdp + }; if let Some(slot) = self.viewers.get_mut(&viewer.0) { slot.peer = Some(peer); slot.state = ViewerState::Connecting; - slot.choice = LayerChoice::new(layer); + // A reconnecting viewer keeps the layer it asked for. + slot.choice = LayerChoice::new(slot.pinned.unwrap_or(layer)); slot.codec = None; slot.rids = None; slot.estimate = None; @@ -916,14 +959,17 @@ impl StreamerSession { let start = self.start_bitrate(); let mut keyframes = LayerSet::new(); for slot in self.viewers.values_mut() { + slot.pinned = slot.pinned.filter(|l| self.layers.index(*l).is_some()); if slot.peer.is_none() { - slot.choice = LayerChoice::new(self.layers.specs[self.layers.fitting(start)].id); + let fitting = self.layers.specs[self.layers.fitting(start)].id; + slot.choice = LayerChoice::new(slot.pinned.unwrap_or(fitting)); continue; } if slot.rids.is_none() { let fitting = self.layers.fitting(slot.estimate.unwrap_or(start)); slot.choice.up_since = None; - if let Some(layer) = slot.choice.switch_to(self.layers.specs[fitting].id) { + let target = slot.pinned.unwrap_or(self.layers.specs[fitting].id); + if let Some(layer) = slot.choice.switch_to(target) { keyframes.insert(layer); } if slot.connected() { @@ -1139,7 +1185,7 @@ impl StreamerSession { let (keyframe, affected) = match &slot.rids { Some(_) => (None, None), None => { - let keyframe = if self.layers.len() > 1 { + let keyframe = if self.layers.len() > 1 && slot.pinned.is_none() { slot.choice.estimate(&self.layers, bitrate, now) } else { None @@ -1182,7 +1228,9 @@ impl StreamerSession { let lowest = self .viewers .values() - .filter(|v| v.connected()) + // A viewer that picked its layer takes it as it is: a slow one + // must not lower the picture of everyone else on that layer. + .filter(|v| v.connected() && v.pinned.is_none()) .filter_map(|v| { let estimate = v.estimate?; match &v.rids { @@ -1253,6 +1301,11 @@ pub struct ViewerSession { reconnects: u32, /// The RID simulcast layer we play, if the streamer sends several. layer_rid: Option, + /// The layers the streamer's offer listed; `None`: it listed none (not + /// a Voelin streamer, or one layer), so we never ask for one. + layers: Option>, + /// The layer we asked for; `None`: the streamer's estimate decides. + layer: Option, } impl ViewerSession { @@ -1275,6 +1328,8 @@ impl ViewerSession { peer: None, reconnects: 0, layer_rid: None, + layers: None, + layer: None, } } @@ -1345,6 +1400,13 @@ impl ViewerSession { self.peer = Some(peer); self.state = WatchState::Connecting; self.signal(Signal::Answer { sdp }, out); + let layers = layer::from_sdp(offer).filter(|l| l.len() > 1); + if layers != self.layers { + self.layer = + self.layer.filter(|id| layers.iter().flatten().any(|l| l.id == *id)); + self.layers = layers; + self.event(WatchEvent::Layers(self.layers.clone().unwrap_or_default()), out); + } } Err(e) => self.fail(format!("cannot answer the streamer's offer: {e}"), out), } @@ -1375,6 +1437,36 @@ impl ViewerSession { } } + /// The layers the streamer offers to choose from (see + /// [`WatchEvent::Layers`]). + pub fn layers(&self) -> &[LayerSpec] { + self.layers.as_deref().unwrap_or_default() + } + + /// The layer we asked for ([`set_layer`](Self::set_layer)). + pub fn layer(&self) -> Option { + self.layer + } + + /// Ask the streamer for simulcast layer `layer` (`None`: let our + /// bandwidth estimate decide again). Only if its offer listed layers: + /// other streamers never get the request. + pub fn set_layer( + &mut self, + layer: Option, + out: &mut Outbox, + ) -> Result<(), SessionError> { + let layers = self.layers.as_ref().ok_or_else(|| SessionError::NoLayers(self.id.clone()))?; + if let Some(id) = layer + && !layers.iter().any(|l| l.id == id) + { + return Err(SessionError::UnknownLayer(self.id.clone(), id)); + } + self.layer = layer; + self.signal(Signal::Layer { layer }, out); + Ok(()) + } + /// 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) { @@ -1668,6 +1760,18 @@ impl Streams { } } + /// Watch simulcast layer `layer` of a stream (`None`: as our bandwidth + /// allows); see [`ViewerSession::set_layer`]. + pub fn set_watch_layer( + &mut self, + id: &str, + layer: Option, + ) -> Result<(), SessionError> { + let viewer = + self.viewers.get_mut(id).ok_or_else(|| SessionError::NotWatching(id.into()))?; + viewer.set_layer(layer, &mut self.out) + } + /// Reconnect to a watched stream: the streamer sends a new offer. pub fn reconnect(&mut self, id: &str) -> Result<(), SessionError> { let viewer = diff --git a/crates/voelin-stream/src/signal.rs b/crates/voelin-stream/src/signal.rs index 923465c..9152f3e 100644 --- a/crates/voelin-stream/src/signal.rs +++ b/crates/voelin-stream/src/signal.rs @@ -7,6 +7,8 @@ use serde_json::{Map, Value, json}; +use crate::layer::LayerId; + /// One signalling message between streamer and viewer. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Signal { @@ -18,6 +20,11 @@ pub enum Signal { IceCandidate { candidate: String, mid: Option, mline_index: Option }, /// The other side asks for a new offer. Reconnect, + /// A Voelin viewer asks for simulcast layer `layer` (`None`: let its + /// bandwidth estimate decide again). Sent only to a streamer whose offer + /// listed its layers ([`crate::layer::SDP_ATTRIBUTE`]): only Voelin + /// streamers do, so other clients never get it. + Layer { layer: Option }, /// A command this client does not know; kept for logging. Unknown { cmd: String, args: Value }, } @@ -63,6 +70,9 @@ impl Signal { .and_then(|v| u32::try_from(v).ok()), }, "reconnect" => Signal::Reconnect, + "x-voelin-layer" => Signal::Layer { + layer: args.get("layer").and_then(Value::as_u64).and_then(|v| v.try_into().ok()), + }, other => Signal::Unknown { cmd: other.to_owned(), args: Value::Object(args.clone()) }, }) } @@ -79,6 +89,9 @@ impl Signal { "args": { "candidate": candidate, "sdpMid": mid, "sdpMLineIndex": mline_index }, }), Signal::Reconnect => json!({ "cmd": "reconnect", "args": {} }), + Signal::Layer { layer } => { + json!({ "cmd": "x-voelin-layer", "args": { "layer": layer } }) + } Signal::Unknown { cmd, args } => json!({ "cmd": cmd, "args": args }), }; value.to_string() @@ -101,6 +114,8 @@ mod tests { mline_index: Some(0), }, Signal::Reconnect, + Signal::Layer { layer: Some(2) }, + Signal::Layer { layer: None }, ]; for s in signals { assert_eq!(Signal::parse(&s.to_json()).unwrap(), s); diff --git a/crates/voelin-stream/tests/browser_interop.rs b/crates/voelin-stream/tests/browser_interop.rs index 538c55c..7ae7424 100644 --- a/crates/voelin-stream/tests/browser_interop.rs +++ b/crates/voelin-stream/tests/browser_interop.rs @@ -9,7 +9,7 @@ use std::time::{Duration, Instant}; use serde_json::json; use tokio::time::timeout; use voelin_stream::{ - Codec, FrameSource, MediaKind, Peer, PeerConfig, PeerEvent, Signal, SrtpProfile, + Codec, FrameSource, LayerSpec, MediaKind, Peer, PeerConfig, PeerEvent, Signal, SrtpProfile, SyntheticSource, }; @@ -50,6 +50,14 @@ async fn rust_streams_to_browser() { let mut browser = Browser::start().await; let config = PeerConfig::loopback(); let (mut peer, offer) = Peer::offer(&config, "interop").await.unwrap(); + // As a Voelin streamer with several layers offers: with the list of its + // layers, which libwebrtc (the official client's stack) must skip. + let layers = [ + LayerSpec::single(4_000_000), + LayerSpec { id: 1, scale: 0.5, ..LayerSpec::single(1_000_000) }, + ]; + let offer = voelin_stream::layer::add_to_sdp(&offer, &layers); + assert!(offer.contains("\r\na=x-voelin-layers:0/1/4000000 1/0.5/1000000\r\n"), "{offer}"); let answer = browser.call(json!({ "op": "answer", "sdp": offer })).await; let answer = answer["sdp"].as_str().unwrap(); eprintln!("browser answer:\n{answer}"); diff --git a/crates/voelin-stream/tests/sessions.rs b/crates/voelin-stream/tests/sessions.rs index f45df5b..7b74139 100644 --- a/crates/voelin-stream/tests/sessions.rs +++ b/crates/voelin-stream/tests/sessions.rs @@ -8,9 +8,9 @@ use std::time::{Duration, Instant}; use tokio::time::timeout; use tsclientlib::ClientId; use voelin_stream::{ - ClientState, EndReason, FrameSource, LeaveReason, MediaKind, Output, PeerConfig, Request, - StreamEvent, StreamInfo, StreamKind, StreamNotification, StreamSetup, StreamerEvent, - StreamerOptions, Streams, SyntheticSource, ViewerState, WatchEvent, + ClientState, EndReason, FrameSource, LayerSpec, LeaveReason, MediaKind, Output, PeerConfig, + Request, SessionError, Signal, StreamEvent, StreamInfo, StreamKind, StreamNotification, + StreamSetup, StreamerEvent, StreamerOptions, Streams, SyntheticSource, ViewerState, WatchEvent, }; const STREAMER: usize = 0; @@ -109,6 +109,10 @@ struct Net { source: Option, video: usize, audio: usize, + /// The layer of the last video frame the viewer got (layered sources). + layer: Option, + /// Every signal relayed, with the sender's index. + signals: Vec<(usize, Signal)>, } impl Net { @@ -121,6 +125,8 @@ impl Net { source: None, video: 0, audio: 0, + layer: None, + signals: Vec::new(), } } @@ -131,11 +137,19 @@ impl Net { for (i, client) in self.clients.iter_mut().enumerate() { while let Some(output) = client.poll_output() { match output { - Output::Request(r) => notes.extend(self.server.relay(IDS[i], r)), + Output::Request(r) => { + if let Request::Signal { signal, .. } = &r { + self.signals.push((i, signal.clone())); + } + notes.extend(self.server.relay(IDS[i], r)); + } Output::Event(StreamEvent::Watch { event: WatchEvent::Frame(f), .. }) => match f.kind { - MediaKind::Video => self.video += 1, + 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)), @@ -185,6 +199,28 @@ impl Net { .unwrap_or_else(|_| panic!("timed out waiting for {what}; events: {:?}", self.events)); } + /// Run until the viewer's video comes from `layer` (and the streamer + /// reports it on that layer). + async fn on_layer(&mut self, layer: u8) { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let streamer = self.clients[STREAMER].streamer().unwrap().viewers(); + let reported = streamer.first().and_then(|v| v.layer) == Some(u16::from(layer)); + let video = self.video; + // Frames of the new layer, after the switch. + if self.layer == Some(layer) && reported { + while self.video < video + 5 { + self.step().await; + } + if self.layer == Some(layer) { + return; + } + } + assert!(Instant::now() < deadline, "video stays on layer {:?}", self.layer); + self.step().await; + } + } + /// 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); @@ -335,3 +371,96 @@ async fn late_viewer_finds_the_stream() { }) .await; } + +/// A Voelin streamer with layers lists them in its offer; the viewer picks +/// one, and "Auto" hands the choice back to its bandwidth estimate. +#[tokio::test(flavor = "multi_thread")] +async fn viewer_picks_a_layer() { + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let mut net = Net::new(); + // Without `min_bitrate`s every estimate fits the top layer. + let layers = vec![ + LayerSpec { id: 0, ..LayerSpec::single(1_500_000) }, + LayerSpec { id: 1, scale: 0.5, max_fps: Some(15), ..LayerSpec::single(400_000) }, + ]; + let options = + StreamerOptions { auto_accept: true, layers: layers.clone(), ..Default::default() }; + net.clients[STREAMER].start(options).unwrap(); + net.until("stream in the viewer's list", |i, e| { + i == VIEWER && matches!(e, StreamEvent::Streams(l) if l.len() == 1) + }) + .await; + let id = net.clients[VIEWER].directory().by_streamer(IDS[STREAMER]).unwrap().id.clone(); + net.clients[VIEWER].watch(&id, "").unwrap(); + net.until("the offer's layers", |i, e| { + i == VIEWER + && watch_event(e, |e| { + matches!(e, WatchEvent::Layers(l) + if l.iter().map(|l| (l.id, l.scale, l.max_fps)).eq([(0, 1.0, None), (1, 0.5, Some(15))])) + }) + }) + .await; + net.until("viewer connected", |i, e| { + i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected)) + }) + .await; + net.source = Some(SyntheticSource::with_layers(30, 0, true, &layers)); + net.on_layer(0).await; + + net.clients[VIEWER].set_watch_layer(&id, Some(1)).unwrap(); + assert_eq!(net.clients[VIEWER].watching().next().unwrap().layer(), Some(1)); + net.on_layer(1).await; + // The estimate does not move it back while it is picked. + net.frames(20).await; + assert_eq!(net.layer, Some(1)); + + net.clients[VIEWER].set_watch_layer(&id, None).unwrap(); + net.on_layer(0).await; + let asked: Vec<_> = net + .signals + .iter() + .filter_map(|(i, s)| match s { + Signal::Layer { layer } => Some((*i, *layer)), + _ => None, + }) + .collect(); + assert_eq!(asked, [(VIEWER, Some(1)), (VIEWER, None)]); + assert_eq!( + net.clients[VIEWER].set_watch_layer(&id, Some(7)), + Err(SessionError::UnknownLayer(id.clone(), 7)) + ); +} + +/// A streamer whose offer lists no layers (one layer here; an official +/// client always) is never asked for one. +#[tokio::test(flavor = "multi_thread")] +async fn no_layer_request_without_the_offer_listing_layers() { + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let mut net = Net::new(); + let options = StreamerOptions { auto_accept: true, ..Default::default() }; + net.clients[STREAMER].start(options).unwrap(); + net.until("stream in the viewer's list", |i, e| { + i == VIEWER && matches!(e, StreamEvent::Streams(l) if l.len() == 1) + }) + .await; + let id = net.clients[VIEWER].directory().by_streamer(IDS[STREAMER]).unwrap().id.clone(); + net.clients[VIEWER].watch(&id, "").unwrap(); + net.until("viewer connected", |i, e| { + i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected)) + }) + .await; + net.source = Some(SyntheticSource::new(30, 4000, true)); + net.frames(10).await; + assert!( + !net.events.iter().any(|(_, e)| watch_event(e, |e| matches!(e, WatchEvent::Layers(_)))), + "{:?}", + net.events + ); + let viewer = &mut net.clients[VIEWER]; + assert!(viewer.watching().next().unwrap().layers().is_empty()); + assert_eq!(viewer.set_watch_layer(&id, Some(0)), Err(SessionError::NoLayers(id.clone()))); + assert_eq!(viewer.set_watch_layer(&id, None), Err(SessionError::NoLayers(id.clone()))); + assert!(viewer.poll_output().is_none(), "nothing sent"); + net.flush().await; + assert!(!net.signals.iter().any(|(_, s)| matches!(s, Signal::Layer { .. }))); +} diff --git a/crates/voelin-ui/src/streams.rs b/crates/voelin-ui/src/streams.rs index 93c80a2..6196755 100644 --- a/crates/voelin-ui/src/streams.rs +++ b/crates/voelin-ui/src/streams.rs @@ -154,6 +154,17 @@ impl App { Event::WatchState { session, stream_id, state } => { self.watch_state(session as i64, &stream_id, state); } + Event::WatchLayers { session, stream_id, layers, layer } => { + if let Some(watch) = self + .watch + .as_mut() + .filter(|w| w.session == Some(session as i64) && w.stream_id == stream_id) + { + watch.layers = layers; + watch.layer = layer; + self.refresh_viewer(); + } + } // Also flagged on the sink, which the encoder reads. Event::StreamKeyframeRequest { .. } => {} _ => {} @@ -369,17 +380,17 @@ impl App { } /// A simulcast layer of the watched stream (0: follow the bandwidth - /// estimate). The streamer picks the layer from each viewer's estimate, - /// so this asks for the picture again; a viewer-side choice needs an - /// engine API that does not exist yet. + /// estimate), asked of the streamer; the engine confirms with + /// `WatchLayers`. pub(crate) fn set_stream_quality(&mut self, index: i32) { let Some(watch) = &mut self.watch else { return }; watch.layer = usize::try_from(index - 1).ok().and_then(|i| watch.layers.get(i)).map(|l| l.id); if let Some(session) = watch.session { - self.engine.send(Command::RequestStreamKeyframe { + self.engine.send(Command::SetWatchLayer { session: session as u64, stream_id: watch.stream_id.clone(), + layer: watch.layer, }); } self.refresh_viewer(); diff --git a/docs/media.md b/docs/media.md index 688405e..9f0d0b5 100644 --- a/docs/media.md +++ b/docs/media.md @@ -197,6 +197,23 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder ([protocol notes](protocol-notes/ts6-streaming.md#viewer-counts-confirmed-600-beta131-2026-10-03)). The app shows it, and the gateway directory's count where the server gave none. +- A viewer picks a simulcast layer (the watch screen's quality picker): a + Voelin streamer with several layers lists them in its offer, in a + session-level SDP attribute (`a=x-voelin-layers:0/1/6000000 + 1/640x360/1500000/15`: id, size or scale, bitrate, frame-rate cap; + `voelin_stream::layer::SDP_ATTRIBUTE`). The viewer reports them + (`WatchEvent::Layers`, `Event::WatchLayers`), and `Command::SetWatchLayer` + sends `{"cmd":"x-voelin-layer","args":{"layer":1}}` through + `streamsignaling` (`Signal::Layer`; `null` is "Auto"). The streamer moves + that viewer to the layer at its next keyframe and keeps it there whatever + its estimate says, and such a viewer no longer lowers its layer's bitrate + for the others; "Auto" hands it back to the estimate. Official clients + never see either: libwebrtc skips session attributes it does not know + (headless Chromium 152 answers such an offer and decodes, see the + browser interop test), and a viewer sends the request only to a streamer + whose offer had the attribute, which only Voelin streamers add. Not with + RID simulcast (that viewer gets every layer), and a streamer that changes + its layers live is seen with its next offer. - The audio of watched streams does not go through this module: the session hands the Opus frames to its audio thread, which plays them through the jitter buffer and mixer under a made-up client id, with its own volume. @@ -1010,6 +1027,8 @@ has not run on Windows yet. | Offer [VP9, VP8], a viewer that decodes only VP8 → its own VP8 encoder, VP9 idle, pictures decoded | `voelin-core/tests/media_live.rs` `ts6_viewer_gets_the_codec_it_chose` (`VOELIN_LIVE=1`) | tested against the TeamSpeak 6 dev server (our client on both ends) | | Several codecs against official TeamSpeak viewers | – | not tested (no official client here) | | Viewer counts: `viewer` of `notifystreaminfo`, counted up and down from the viewers joining and leaving, refreshed one stream at a time | `voelin-stream` `proto::tests::stream_info_answers`, `session::tests::viewer_counts`; `voelinctl stream list` | tested; against the TeamSpeak 6 dev server `stream list` printed "1 watching" while a viewer watched and "0 watching" after | +| A viewer picks a layer: the offer's `a=x-voelin-layers`, `Signal::Layer`, the streamer moving it (and back with "Auto"); no request to a streamer whose offer lists no layers | `voelin-stream` `layer::tests::layers_in_the_sdp`, `tests/sessions.rs` `viewer_picks_a_layer` and `no_layer_request_without_the_offer_listing_layers` (two sessions, peers on loopback); `voelinctl stream watch --layer 1` against `stream start --placeholder --layer 1.0:2000k --layer 0.5:500k` | tested, also through the TeamSpeak 6 dev server (the viewer stayed on layer 1 at a 2.5 Mbit/s estimate that fits layer 0) | +| An offer with `a=x-voelin-layers` against libwebrtc | `tests/browser_interop.rs` `rust_streams_to_browser` (`VOELIN_INTEROP=1`, system Chromium 152 through `playwright-core`) | tested: answered and decoded as before. The official client itself not tried | | Test pattern → VP8 → decoder, rectangle position and colour | `voelin-core` `media::tests::local_preview_decodes_the_pattern` | tested | | Test pattern → two engine stream tasks → str0m peers on loopback → decoder | `voelin-core` `stream::tests::test_pattern_through_stream_tasks` | tested | | Stream audio (RTP time → jitter buffer ids, volume, end) | `voelin-core` `audio::tests::stream_audio_with_volume`, stream task test | tested | diff --git a/docs/protocol-notes/ts6-streaming.md b/docs/protocol-notes/ts6-streaming.md index 70b0d18..d74937c 100644 --- a/docs/protocol-notes/ts6-streaming.md +++ b/docs/protocol-notes/ts6-streaming.md @@ -218,6 +218,19 @@ then for the leaves it is not told about: `StreamInfo::viewers` (`voelin_stream`), kept by `StreamDirectory` and refreshed one stream at a time every 5 s by the engine (`Streams::refresh_viewer_counts`). +### Voelin's own additions (not TeamSpeak's) + +Between Voelin clients only, a viewer can pick the streamer's simulcast +layer: the offer of a Voelin streamer with several layers carries a +session-level `a=x-voelin-layers://[/] ...` +line, and a Voelin viewer that saw it may send +`streamsignaling json={"cmd":"x-voelin-layer","args":{"layer":}}`. +The server relays both unchanged (6.0.0-beta13.1). Official clients are not +affected: libwebrtc skips unknown session attributes (headless Chromium 152 +answers and decodes such an offer), and official streamers never put the +attribute in their offers, so they are never sent the signal. Details in +[media.md](../media.md). + ### WebRTC interop with Chromium (confirmed, Chromium 141, 2026-09-26) `crates/voelin-stream/tests/browser_interop.rs` (`VOELIN_INTEROP=1`, see diff --git a/tests/interop/README.md b/tests/interop/README.md index 638c69a..d75dc72 100644 --- a/tests/interop/README.md +++ b/tests/interop/README.md @@ -10,7 +10,7 @@ TeamSpeak server is involved. | Test | What it checks | |---|---| -| `rust_streams_to_browser` | Our streamer offer (`PeerConfig::loopback()`, VP8 + Opus) 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 | +| `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 | | `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 | diff --git a/tools/voelinctl/src/stream.rs b/tools/voelinctl/src/stream.rs index 0b094a6..6fc1671 100644 --- a/tools/voelinctl/src/stream.rs +++ b/tools/voelinctl/src/stream.rs @@ -132,6 +132,10 @@ pub enum StreamCommand { /// Save the last decoded picture as PNG. #[arg(long)] save_frame: Option, + /// Ask for this simulcast layer (by id) once the streamer's offer + /// lists its layers (Voelin streamers with several do). + #[arg(long)] + layer: Option, }, } @@ -281,8 +285,9 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { StreamCommand::List { settle_ms } => { list(con, &mut driver, Duration::from_millis(*settle_ms)).await } - StreamCommand::Watch { id, streamer_nick, expect_frames, timeout, save_frame } => { - let target = Target { id: id.clone(), streamer_nick: streamer_nick.clone() }; + StreamCommand::Watch { id, streamer_nick, expect_frames, timeout, save_frame, layer } => { + let target = + Target { id: id.clone(), streamer_nick: streamer_nick.clone(), layer: *layer }; let timeout = timeout.map(Duration::from_secs); let expect = *expect_frames; let save = save_frame.as_deref(); @@ -727,6 +732,8 @@ async fn list(con: &mut Connection, driver: &mut Driver, settle: Duration) -> Re struct Target { id: Option, streamer_nick: Option, + /// The simulcast layer to ask for. + layer: Option, } impl Target { @@ -859,6 +866,16 @@ async fn watch( } match event { WatchEvent::Accepted => println!("accepted, connecting"), + WatchEvent::Layers(layers) => { + println!( + "layers offered: {:?}", + layers.iter().map(|l| l.id).collect::>() + ); + if let Some(layer) = target.layer { + driver.streams.set_watch_layer(&id, Some(layer))?; + println!("asked for layer {layer}"); + } + } WatchEvent::Connected => println!("connected"), WatchEvent::Frame(f) => { match f.kind {