diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 7bff8eb..7692034 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -40,7 +40,8 @@ use voelin_media::{ AudioBuffer, Codec, Codecs, ContentHint, EncoderConfig, FrameReceiver, VideoEncoder, VideoFrame, }; use voelin_stream::{ - EncodedFrame, FrameSource, Frequency, MediaFrame, MediaKind, MediaTime, PeerConfig, VideoCodec, + EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind, + MediaTime, PeerConfig, VideoCodec, }; use crate::stream::StreamSink; @@ -139,6 +140,21 @@ pub trait MediaSink: Send + Sync { /// Whether a keyframe was asked for since the last call. fn take_keyframe_request(&self) -> bool; + + /// Adds to `layers` the simulcast layers a keyframe was asked for since + /// the last call. Sinks without simulcast report a request as layer 0. + fn take_layer_keyframes(&self, layers: &mut LayerSet) { + if self.take_keyframe_request() { + layers.insert(0); + } + } + + /// Bitrate (bit/s) the bandwidth estimates of `layer`'s viewers allow, + /// once known; the encoder of the layer follows it. + fn layer_bitrate(&self, layer: LayerId) -> Option { + let _ = layer; + None + } } impl MediaSink for StreamSink { @@ -181,6 +197,8 @@ pub struct StreamerConfig { /// Portal restore token from an earlier share: the desktop may skip its /// dialog. The new one is [`Streamer::restore_token`]. pub restore_token: Option, + /// Simulcast layers to encode. Empty: one layer at `bitrate_kbps`. + pub layers: Vec, } impl Default for StreamerConfig { @@ -195,6 +213,7 @@ impl Default for StreamerConfig { cursor: true, synthetic_size: (1280, 720), restore_token: None, + layers: Vec::new(), } } } @@ -438,6 +457,7 @@ fn video_loop( kind: MediaKind::Video, time: MediaTime::from_90khz(f.pts_90khz), data: f.data.into(), + layer: 0, }; if sink.send(frame) { shared.video_frames.fetch_add(1, Ordering::Relaxed); @@ -502,7 +522,7 @@ fn audio_loop(shared: &Shared, mut buffers: FrameReceiver, mut enco pending.drain(..OPUS_FRAME * 2); if let Some(data) = data { let time = MediaTime::new(frames * OPUS_FRAME as u64, Frequency::FORTY_EIGHT_KHZ); - if sink.send(EncodedFrame { kind: MediaKind::Audio, time, data }) { + if sink.send(EncodedFrame { kind: MediaKind::Audio, time, data, layer: 0 }) { shared.audio_frames.fetch_add(1, Ordering::Relaxed); } } diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index 1612953..ba6bf7d 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -204,11 +204,12 @@ impl StreamTask { async fn input(&mut self, input: StreamInput) { let session = self.session; let result = match input { - StreamInput::Start { setup, auto_accept } => { - self.streams.start(StreamerOptions { setup, auto_accept }).map(|()| { + StreamInput::Start { setup, auto_accept } => self + .streams + .start(StreamerOptions { setup, auto_accept, ..Default::default() }) + .map(|()| { self.emit(Event::StreamState { session, state: StreamState::Starting }); - }) - } + }), StreamInput::Stop => self.streams.stop(), StreamInput::Respond { viewer, accept } => { self.streams.respond(ClientId(viewer), accept).await diff --git a/crates/voelin-core/tests/stream_live.rs b/crates/voelin-core/tests/stream_live.rs index 486e876..edd9b24 100644 --- a/crates/voelin-core/tests/stream_live.rs +++ b/crates/voelin-core/tests/stream_live.rs @@ -224,6 +224,7 @@ async fn ts6_stream_between_sessions() { kind: MediaKind::Audio, time: voelin_core::stream::MediaTime::from_90khz(0), data: vec![0].into(), + layer: 0, })); feeder.await.unwrap(); diff --git a/crates/voelin-stream/src/layer.rs b/crates/voelin-stream/src/layer.rs new file mode 100644 index 0000000..f4b538f --- /dev/null +++ b/crates/voelin-stream/src/layer.rs @@ -0,0 +1,206 @@ +//! Simulcast layers: several encodings of one stream, each with its own size, +//! frame rate and bitrate. +//! +//! The streamer encodes every layer of its [`LayerSpec`] list and tags each +//! [`EncodedFrame`](crate::EncodedFrame) with its [`LayerId`]. Each viewer +//! connection gets the layer that fits its bandwidth estimate; peers that +//! negotiate RID simulcast (`a=simulcast`) get all of them. There is no limit +//! on the number of layers. + +use std::fmt; + +/// A simulcast layer. Layer 0 is the one a stream without simulcast has. +pub type LayerId = u16; + +/// One encoding of the stream. Compared bit for bit (`scale` by its bits), +/// so it is `Eq`. +#[derive(Clone, Debug)] +pub struct LayerSpec { + pub id: LayerId, + /// Output size relative to the source (1.0: the source's size). Ignored + /// when [`size`](Self::size) is set. + pub scale: f32, + /// Exact output size in pixels, instead of `scale`. + pub size: Option<(u32, u32)>, + /// Frame rate cap; `None`: the source's frame rate. + pub max_fps: Option, + /// Bitrate the encoder starts with, in bit/s. Bandwidth estimates move it + /// down (and back up to this value, or [`max_bitrate`](Self::max_bitrate)). + pub bitrate: u64, + /// Highest bitrate bandwidth estimates may raise the layer to; `None`: no + /// maximum. + pub max_bitrate: Option, + /// Estimate (bit/s) a viewer needs to receive this layer; below it the + /// viewer moves to the next smaller layer. + pub min_bitrate: u64, + /// RTP stream id for peers that negotiate RID simulcast. + pub rid: Option, +} + +impl PartialEq for LayerSpec { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + && self.scale.to_bits() == other.scale.to_bits() + && self.size == other.size + && self.max_fps == other.max_fps + && self.bitrate == other.bitrate + && self.max_bitrate == other.max_bitrate + && self.min_bitrate == other.min_bitrate + && self.rid == other.rid + } +} + +impl Eq for LayerSpec {} + +impl LayerSpec { + /// A stream without simulcast: layer 0 at the source's size and rate. + pub fn single(bitrate: u64) -> Self { + Self { + id: 0, + scale: 1.0, + size: None, + max_fps: None, + bitrate, + max_bitrate: None, + min_bitrate: 0, + rid: None, + } + } + + /// Output size for a source of `width` x `height`: [`size`](Self::size), + /// or the scaled source size rounded down to even numbers (I420), at least + /// 2x2. + pub fn output_size(&self, width: u32, height: u32) -> (u32, u32) { + let (w, h) = self.size.unwrap_or_else(|| { + let scale = if self.scale.is_finite() && self.scale > 0.0 { self.scale } else { 1.0 }; + ((width as f32 * scale) as u32, (height as f32 * scale) as u32) + }); + ((w & !1).max(2), (h & !1).max(2)) + } +} + +/// A set of layers, e.g. those waiting for a keyframe. Grows as needed. +#[derive(Clone, Default, PartialEq, Eq)] +pub struct LayerSet { + words: Vec, +} + +impl LayerSet { + pub const fn new() -> Self { + Self { words: Vec::new() } + } + + /// Adds `layer`; `true` if it was not in the set. + pub fn insert(&mut self, layer: LayerId) -> bool { + let (word, bit) = Self::position(layer); + if self.words.len() <= word { + self.words.resize(word + 1, 0); + } + let new = self.words[word] & bit == 0; + self.words[word] |= bit; + new + } + + /// Removes `layer`; `true` if it was in the set. + pub fn remove(&mut self, layer: LayerId) -> bool { + let (word, bit) = Self::position(layer); + match self.words.get_mut(word) { + Some(w) if *w & bit != 0 => { + *w &= !bit; + true + } + _ => false, + } + } + + pub fn contains(&self, layer: LayerId) -> bool { + let (word, bit) = Self::position(layer); + self.words.get(word).is_some_and(|w| w & bit != 0) + } + + pub fn is_empty(&self) -> bool { + self.words.iter().all(|w| *w == 0) + } + + pub fn len(&self) -> usize { + self.words.iter().map(|w| w.count_ones() as usize).sum() + } + + /// Empties the set, keeping its memory. + pub fn clear(&mut self) { + self.words.fill(0); + } + + /// Adds every layer of `other`. + pub fn union_with(&mut self, other: &LayerSet) { + if self.words.len() < other.words.len() { + self.words.resize(other.words.len(), 0); + } + for (w, o) in self.words.iter_mut().zip(&other.words) { + *w |= o; + } + } + + /// The layers in ascending order. + pub fn iter(&self) -> impl Iterator + '_ { + self.words.iter().enumerate().flat_map(|(i, &word)| { + (0..64).filter(move |b| word & (1 << b) != 0).map(move |b| (i * 64 + b) as LayerId) + }) + } + + fn position(layer: LayerId) -> (usize, u64) { + (usize::from(layer) / 64, 1 << (layer % 64)) + } +} + +impl FromIterator for LayerSet { + fn from_iter>(iter: I) -> Self { + let mut set = Self::new(); + for layer in iter { + set.insert(layer); + } + set + } +} + +impl fmt::Debug for LayerSet { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_set().entries(self.iter()).finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layer_set() { + let mut set = LayerSet::new(); + assert!(set.is_empty()); + assert!(set.insert(3)); + assert!(!set.insert(3)); + assert!(set.insert(200)); + assert!(set.insert(LayerId::MAX)); + assert_eq!(set.iter().collect::>(), [3, 200, LayerId::MAX]); + assert_eq!(set.len(), 3); + assert!(set.contains(200) && !set.contains(4)); + assert!(set.remove(200) && !set.remove(200)); + let other: LayerSet = [1, 3].into_iter().collect(); + set.union_with(&other); + assert_eq!(format!("{set:?}"), format!("{{1, 3, {}}}", LayerId::MAX)); + set.clear(); + assert!(set.is_empty()); + } + + #[test] + fn output_size() { + let mut layer = LayerSpec::single(1_000_000); + assert_eq!(layer.output_size(1921, 1081), (1920, 1080)); + layer.scale = 0.5; + assert_eq!(layer.output_size(2560, 1440), (1280, 720)); + layer.scale = 0.0001; + assert_eq!(layer.output_size(640, 360), (2, 2)); + layer.size = Some((853, 480)); + assert_eq!(layer.output_size(1920, 1080), (852, 480)); + } +} diff --git a/crates/voelin-stream/src/lib.rs b/crates/voelin-stream/src/lib.rs index d6fef35..9efdcc5 100644 --- a/crates/voelin-stream/src/lib.rs +++ b/crates/voelin-stream/src/lib.rs @@ -9,6 +9,7 @@ //! streams in our channel, our own stream with a peer per viewer, and the //! streams we watch. [`FrameSource`] is where a streamer's encoded frames come from. +pub mod layer; pub mod peer; pub mod proto; pub mod session; @@ -16,6 +17,7 @@ pub mod signal; pub mod source; pub mod stun; +pub use layer::{LayerId, LayerSet, LayerSpec}; pub use peer::{MediaFrame, Peer, PeerConfig, PeerError, PeerEvent, VideoCodec}; pub use proto::{LeaveReason, StreamInfo, StreamKind, StreamNotification, StreamSetup}; pub use session::{ diff --git a/crates/voelin-stream/src/session.rs b/crates/voelin-stream/src/session.rs index 9f2a1e1..378d04a 100644 --- a/crates/voelin-stream/src/session.rs +++ b/crates/voelin-stream/src/session.rs @@ -284,6 +284,8 @@ pub struct StreamerOptions { /// Accept every join request. Otherwise each one is reported as /// [`StreamerEvent::Request`] and answered with [`Streams::respond`]. pub auto_accept: bool, + /// The simulcast layers the source produces. Empty: one layer (0). + pub layers: Vec, } struct ViewerSlot { @@ -1206,7 +1208,7 @@ mod tests { let config = PeerConfig::loopback(); let mut s = Streams::new(OWN, config.clone()); let setup = StreamSetup { name: "t".into(), ..Default::default() }; - s.start(StreamerOptions { setup, auto_accept: false }).unwrap(); + s.start(StreamerOptions { setup, auto_accept: false, ..Default::default() }).unwrap(); assert_eq!(s.start(StreamerOptions::default()), Err(SessionError::AlreadyStreaming)); let (requests, _) = drain(&mut s); assert_eq!( diff --git a/crates/voelin-stream/src/source.rs b/crates/voelin-stream/src/source.rs index 69caa57..6ad43e1 100644 --- a/crates/voelin-stream/src/source.rs +++ b/crates/voelin-stream/src/source.rs @@ -9,6 +9,8 @@ use std::time::{Duration, Instant}; use str0m::media::{Frequency, MediaKind, MediaTime}; +use crate::layer::LayerId; + /// One encoded video or audio frame. #[derive(Clone, Debug)] pub struct EncodedFrame { @@ -16,6 +18,9 @@ pub struct EncodedFrame { /// RTP time: 90 kHz for video, 48 kHz for Opus. pub time: MediaTime, pub data: Arc<[u8]>, + /// The simulcast layer of a video frame (0 without simulcast, and for + /// audio). + pub layer: LayerId, } /// Produces encoded frames in real time. @@ -26,6 +31,17 @@ pub trait FrameSource: Send { /// A viewer needs a keyframe soon. fn request_keyframe(&mut self) {} + /// A viewer of simulcast layer `layer` needs a keyframe soon. + fn request_layer_keyframe(&mut self, layer: LayerId) { + let _ = layer; + self.request_keyframe(); + } + + /// The bandwidth estimates of the viewers of `layer` allow `bitrate` bit/s. + fn set_layer_bitrate(&mut self, layer: LayerId, bitrate: u64) { + let _ = (layer, bitrate); + } + /// How often `poll_frames` should be called. fn interval(&self) -> Duration { Duration::from_millis(10) @@ -89,6 +105,7 @@ impl FrameSource for SyntheticSource { kind: MediaKind::Video, time: MediaTime::from_90khz(n * 90_000 / u64::from(self.fps)), data: Self::video_frame(n, self.video_size).into(), + layer: 0, }); self.video_frames += 1; } @@ -98,7 +115,7 @@ impl FrameSource for SyntheticSource { let time = MediaTime::new(self.audio_frames * OPUS_FRAME, Frequency::FORTY_EIGHT_KHZ); let data = Arc::from(&OPUS_SILENCE[..]); - out.push(EncodedFrame { kind: MediaKind::Audio, time, data }); + out.push(EncodedFrame { kind: MediaKind::Audio, time, data, layer: 0 }); self.audio_frames += 1; } } diff --git a/crates/voelin-stream/tests/sessions.rs b/crates/voelin-stream/tests/sessions.rs index c316695..31d910c 100644 --- a/crates/voelin-stream/tests/sessions.rs +++ b/crates/voelin-stream/tests/sessions.rs @@ -199,7 +199,9 @@ async fn stream_between_sessions() { let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); let mut net = Net::new(); let setup = StreamSetup { name: "fake".into(), kind: StreamKind::Screen, ..Default::default() }; - net.clients[STREAMER].start(StreamerOptions { setup, auto_accept: false }).unwrap(); + net.clients[STREAMER] + .start(StreamerOptions { setup, auto_accept: false, ..Default::default() }) + .unwrap(); net.until("live", |i, e| { i == STREAMER && matches!(e, StreamEvent::Streamer(StreamerEvent::Live { .. })) }) diff --git a/tools/voelinctl/src/stream.rs b/tools/voelinctl/src/stream.rs index 6f4ad04..a931df6 100644 --- a/tools/voelinctl/src/stream.rs +++ b/tools/voelinctl/src/stream.rs @@ -159,7 +159,8 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { audio: streamer.has_audio(), ..Default::default() }; - let options = StreamerOptions { setup, auto_accept: *auto_accept }; + let options = + StreamerOptions { setup, auto_accept: *auto_accept, ..Default::default() }; let source = EncodedSource::new(streamer); start(con, &mut driver, options, source, seconds.map(Duration::from_secs)).await }