diff --git a/Cargo.lock b/Cargo.lock index 1d6a101..dff23d9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9449,7 +9449,6 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", - "tsclientlib", "voelin-core", "voelin-media", "voelin-model", @@ -9683,6 +9682,7 @@ dependencies = [ "tracing-subscriber", "tsclientlib", "tsproto-packets", + "voelin-media", ] [[package]] diff --git a/crates/voelin-android/Cargo.toml b/crates/voelin-android/Cargo.toml index 284ad3e..9b267aa 100644 --- a/crates/voelin-android/Cargo.toml +++ b/crates/voelin-android/Cargo.toml @@ -32,9 +32,5 @@ voelin-platform = { path = "../voelin-platform", default-features = false } voelin-store = { path = "../voelin-store" } voelin-ui = { path = "../voelin-ui" } -[dev-dependencies] -# Client ids of stream viewers in the tests. -tsclientlib = { path = "../proto/tsclientlib" } - [lints] workspace = true diff --git a/crates/voelin-android/src/foreground.rs b/crates/voelin-android/src/foreground.rs index c909189..9b1b807 100644 --- a/crates/voelin-android/src/foreground.rs +++ b/crates/voelin-android/src/foreground.rs @@ -316,7 +316,7 @@ mod tests { }; assert_eq!(fg.screen(), screen("Live in Chill Zone", "a server").flatten()); let viewer = |client, state| ViewerInfo { - client: tsclientlib::ClientId(client), + client, state, message: String::new(), layer: None, diff --git a/crates/voelin-core/Cargo.toml b/crates/voelin-core/Cargo.toml index f99d859..ab77a67 100644 --- a/crates/voelin-core/Cargo.toml +++ b/crates/voelin-core/Cargo.toml @@ -14,8 +14,9 @@ default = ["audio-device"] audio-device = ["voelin-audio/device"] # The `media` module: capture and video codecs for streams, with whatever # voelin-media backends are enabled (e.g. MediaCodec and a registered capture -# source on Android). -media = ["dep:voelin-media"] +# source on Android), and the studio's WHIP output. The crate itself is always +# there: the stream types in the API (`EncodedFrame`, `LayerSpec`) are its. +media = ["voelin-media/whip"] # `media` with voelin-media's desktop backends: libvpx, dav1d, OpenH264 and # FFmpeg loaded at runtime, X11 and PipeWire on Linux. Not for Android # (libvpx does not cross-compile there). @@ -49,7 +50,7 @@ toml = "1.1.6" tracing = "0.1" voelin-audio = { path = "../voelin-audio", default-features = false } voelin-gateway-proto = { path = "../voelin-gateway-proto", features = ["client"] } -voelin-media = { path = "../voelin-media", default-features = false, features = ["str0m", "whip"], optional = true } +voelin-media = { path = "../voelin-media", default-features = false } voelin-model = { path = "../voelin-model" } voelin-observer = { path = "../voelin-observer" } # Paths only (the cache directory). diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index 2cfe066..446333b 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -61,6 +61,7 @@ mod route; mod session; pub mod settings; pub mod stream; +mod stream_types; #[cfg(feature = "media")] pub mod studio; pub mod versions; @@ -90,10 +91,8 @@ pub use history::{History, HistoryMessage, HistorySource}; pub use offline::{OfflineMessage, OfflineMessageInfo}; pub use route::{ChatRoute, Dedup, route_chat}; use settings::{SettingChange, Settings, SharedSettings}; +use stream::{EncodedFrame, LayerId, LayerSpec, StreamInfo, StreamSetup, ViewerInfo}; pub use stream::{StreamFrame, StreamSink, StreamState, WatchState}; -use voelin_stream::{ - EncodedFrame, LayerId, LayerSpec, SrtpProfile, StreamInfo, StreamSetup, ViewerInfo, -}; pub use voice::VoiceOptions; /// Banners are downloaded and shown by the same rule. pub use web::is_svg; @@ -247,11 +246,13 @@ pub enum Command { session: SessionId, layers: Vec, }, - /// SRTP protection profiles for stream connections, in order of - /// preference (a user setting; empty: the default, - /// `SrtpProfile::DEFAULT_ORDER`). Applies to connections made from now - /// on, in all sessions and those started later. - SetSrtpProfiles(Vec), + /// SRTP protection profiles for stream connections by name (RFC 5764 and + /// RFC 7714: `AEAD_AES_128_GCM`, `AES128_CM_SHA1_80`, ...; names the stream + /// transport does not know are left out), in order of preference (the + /// `stream.srtp_profiles` setting). Empty: the transport's default order. + /// Applies to connections made from now on, in all sessions and those + /// started later. + SetSrtpProfiles(Vec), /// Watch a stream from [`Event::StreamsChanged`]. Frames arrive through /// [`Engine::subscribe_frames`]. WatchStream { @@ -894,7 +895,7 @@ async fn run( let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600)); let mut changes = current.subscribe(); let mut settings = AudioSettings::default(); - let mut srtp_profiles: Option> = None; + let mut srtp_profiles: Option> = None; let mut mic_test: Option = None; loop { let input = tokio::select! { diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 3c21b85..b6c3655 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -56,16 +56,16 @@ use voelin_media::mix::{ }; pub use voelin_media::mix::{Level, SourceState}; use voelin_media::scale::Pyramid; +use voelin_media::stream::EncodedFrame; use voelin_media::studio::Studio; use voelin_media::studio::output::{Packet, Track}; use voelin_media::{ Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, H264Profile, - VideoEncoder, VideoFrame, + LayerId, LayerSet, LayerSpec, VideoEncoder, VideoFrame, }; pub use voelin_media::{DecoderBackend, DecoderPreference, EncoderBackend, EncoderPreference}; use voelin_stream::{ - EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind, - MediaTime, PeerConfig, VideoCodec, VideoFormat, + FrameSource, Frequency, MediaFrame, MediaKind, MediaTime, PeerConfig, VideoCodec, VideoFormat, }; use crate::settings::{AudioSourceKindSetting, AudioSourceSetting}; @@ -127,13 +127,7 @@ fn spawn(name: &str, f: impl FnOnce() + Send + 'static) -> Result /// The `voelin_media` codec of a negotiated video codec. pub fn media_codec(codec: VideoCodec) -> Codec { - match codec { - VideoCodec::Vp8 => Codec::Vp8, - VideoCodec::Vp9 => Codec::Vp9, - VideoCodec::H264 => Codec::H264, - VideoCodec::Av1 => Codec::Av1, - VideoCodec::H265 => Codec::H265, - } + crate::stream::media_codec(codec) } /// The H.264 profile an encoder of `format` makes (Constrained High for diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 00ea155..c6f782d 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -16,7 +16,6 @@ use tokio::time::Instant; use tokio::sync::{broadcast, mpsc, watch}; use tracing::{debug, info, warn}; -use tsclientlib::ClientId; use voelin_audio::{AudioSettings, EncodedVoice, TalkerId}; use voelin_gateway_proto::{ErrorCode, HistoryEntry, StreamEntry, StreamSpec, feature}; use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails, badges}; @@ -38,8 +37,8 @@ use crate::settings::{ PRIVACY_PRIVATE_MESSAGES, SharedSettings, }; use crate::stream::{ - LayerSpec, OwnStreamEvent, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInfo, - StreamInput, StreamKind, kind_name, parse_kind, + LayerSpec, OwnStreamEvent, PeerConfig, StreamFrame, StreamHandle, StreamInfo, StreamInput, + StreamKind, kind_name, parse_kind, parse_srtp_profiles, }; use crate::voice::{self, Remote, VoiceCmd, VoiceEvent, VoiceLink}; use crate::web; @@ -325,7 +324,7 @@ struct Session { stream_layers: Vec, /// The SRTP profile setting (`Command::SetSrtpProfiles`), over the voice /// options' `stream_peer`. - srtp_profiles: Option>, + srtp_profiles: Option>, frames: broadcast::Sender, /// Channel and `client_is_streaming` of the voice presence, as last told /// to the streams. @@ -519,7 +518,7 @@ impl Session { self.nickname = options.nickname.clone(); self.stream_peer = options.stream_peer.clone(); if let Some(profiles) = &self.srtp_profiles { - self.stream_peer.srtp_profiles = profiles.clone(); + self.stream_peer.srtp_profiles = parse_srtp_profiles(profiles); } self.known_server(format!("voice:{}", options.address)); let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); @@ -742,7 +741,7 @@ impl Session { } } Command::SetSrtpProfiles(profiles) => { - self.stream_peer.srtp_profiles = profiles.clone(); + self.stream_peer.srtp_profiles = parse_srtp_profiles(&profiles); self.srtp_profiles = Some(profiles.clone()); if let Some(s) = &self.streams { s.send(StreamInput::SrtpProfiles(profiles)); @@ -1717,7 +1716,7 @@ impl Session { .filter_map(|e| { Some(StreamInfo { id: e.stream_id.clone()?, - streamer: ClientId(e.client_id?), + streamer: e.client_id?, name: e.title.clone(), kind: parse_kind(&e.kind), // Not in the directory; the stream's offer tells. diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index 10996bb..f7390d4 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -50,8 +50,8 @@ use serde_json::{Value, json}; use tokio::sync::{broadcast, watch}; use tracing::{debug, warn}; use voelin_audio::AudioSettings; +use voelin_media::{LayerId, LayerSpec}; use voelin_store::Store; -use voelin_stream::{LayerId, LayerSpec}; /// A value of any key, typed (`Arc` of the key's `T`). type Stored = Arc; diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index c2ea6c4..efbe37e 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -14,6 +14,11 @@ //! [`StreamLookup`] answers for the gateway when the server cannot. Our own //! stream's life (live, viewers, ended) goes back to the session //! ([`OwnStreamEvent`]), which keeps its directory entry. +//! +//! The stream types of the API ([`StreamInfo`], [`ViewerInfo`], [`StreamSetup`], +//! why a stream ended) are the core's own (`stream_types.rs`); this is where +//! they are converted to and from the stream crate's, so that nothing of it +//! shows in the events and commands. use std::collections::{BTreeMap, BTreeSet}; use std::fmt; @@ -23,18 +28,22 @@ use std::sync::{Arc, Mutex, PoisonError}; use tokio::sync::{broadcast, mpsc}; use tracing::debug; use tsclientlib::ClientId; +pub use voelin_media::stream::EncodedFrame; +pub use voelin_media::{LayerId, LayerSet, LayerSpec}; use voelin_stream::{ - ClientState, LayerFeedback, Output, Request, StreamEvent, StreamLookup, StreamNotification, - StreamerEvent, StreamerOptions, Streams, WatchEvent, + ClientState, LayerFeedback, Output, Request, SrtpProfile, StreamEvent, StreamLookup, + StreamNotification, StreamerEvent, StreamerOptions, Streams, WatchEvent, }; pub use voelin_stream::{ - Codec, EncodedFrame, EndReason, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, - LeaveReason, MediaFrame, MediaKind, MediaTime, PeerConfig, SrtpProfile, StreamInfo, StreamKind, - StreamSetup, SyntheticSource, VideoCodec, VideoFormat, ViewerInfo, ViewerState, + Codec, FrameSource, Frequency, MediaFrame, MediaKind, MediaTime, PeerConfig, SyntheticSource, + VideoCodec, VideoFormat, }; use crate::audio::{AudioHandle, AudioIn}; use crate::settings::{STREAM_PERMISSIONS, SharedSettings, StreamPermissions}; +pub use crate::stream_types::{ + EndReason, LeaveReason, StreamInfo, StreamKind, StreamSetup, ViewerInfo, ViewerState, +}; use crate::voice::VoiceCmd; use crate::{Event, SessionId}; @@ -200,8 +209,9 @@ pub(crate) enum StreamInput { layer: LayerId, format: LayerFormat, }, - /// SRTP profile order of new connections. - SrtpProfiles(Vec), + /// SRTP profile order of new connections, by name + /// ([`parse_srtp_profiles`]). + SrtpProfiles(Vec), Frame(EncodedFrame), /// A video frame for the viewers that chose its codec and H.264 profile. VideoFrame(EncodedFrame, VideoFormat), @@ -254,6 +264,13 @@ pub(crate) fn parse_kind(name: &str) -> StreamKind { } } +/// The SRTP profiles a list of names (the `stream.srtp_profiles` setting, +/// [`crate::Command::SetSrtpProfiles`]) stands for, in that order. Names no +/// profile has are left out; none left: the stream crate's default order. +pub(crate) fn parse_srtp_profiles(names: &[String]) -> Vec { + names.iter().filter_map(|name| SrtpProfile::from_name(name)).collect() +} + /// The gateway directory as the stream task sees it. #[derive(Default)] struct GatewayStreams { @@ -269,7 +286,7 @@ struct GatewayLookup(Arc>); impl StreamLookup for GatewayLookup { fn lookup(&mut self, streamer: ClientId, _out: &mut voelin_stream::session::Outbox) -> bool { let mut dir = self.0.lock().unwrap_or_else(PoisonError::into_inner); - let known = dir.entries.iter().any(|e| e.streamer == streamer); + let known = dir.entries.iter().any(|e| e.streamer == streamer.0); if known { dir.wanted.push(streamer); } @@ -442,6 +459,7 @@ impl StreamTask { self.setup = Some(setup.clone()); self.formats.clear(); let layers = self.layers.clone(); + let setup = setup.into(); let options = StreamerOptions { setup, auto_accept, layers, ..Default::default() }; self.streams.start(options).map(|()| { self.emit(Event::StreamState { session, state: StreamState::Starting }); @@ -475,8 +493,8 @@ impl StreamTask { } } StreamInput::LayerFormat { layer, format } => self.layer_format(layer, format), - StreamInput::SrtpProfiles(profiles) => { - self.streams.set_srtp_profiles(profiles); + StreamInput::SrtpProfiles(names) => { + self.streams.set_srtp_profiles(parse_srtp_profiles(&names)); Ok(()) } StreamInput::Frame(frame) => { @@ -527,14 +545,14 @@ impl StreamTask { dir.wanted.clear(); dir.entries.clone() }; - let own = self.streams.own_client(); + let own = self.streams.own_client().0; for info in entries { let stopped = - self.clients.get(&info.streamer.0).is_some_and(|c| c.streaming == Some(false)); + self.clients.get(&info.streamer).is_some_and(|c| c.streaming == Some(false)); if info.streamer != own && !stopped && self.streams.directory().get(&info.id).is_none() { - debug!(stream = %info.id, streamer = info.streamer.0, "stream from the gateway directory"); - self.streams.discovered(info); + debug!(stream = %info.id, streamer = info.streamer, "stream from the gateway directory"); + self.streams.discovered(info.into()); } } } @@ -558,7 +576,10 @@ impl StreamTask { fn event(&mut self, event: StreamEvent) { let session = self.session; match event { - StreamEvent::Streams(streams) => self.emit(Event::StreamsChanged { session, streams }), + StreamEvent::Streams(streams) => { + let streams = streams.into_iter().map(StreamInfo::from).collect(); + self.emit(Event::StreamsChanged { session, streams }); + } StreamEvent::Streamer(StreamerEvent::Live { id }) => { let feedback = match self.streams.streamer() { Some(s) => s.layer_feedback().clone(), @@ -600,12 +621,15 @@ impl StreamTask { } } StreamEvent::Streamer(StreamerEvent::Viewers(viewers)) => { - let connected = - viewers.iter().filter(|v| v.state == ViewerState::Connected).count() as u32; + let connected = viewers + .iter() + .filter(|v| v.state == voelin_stream::ViewerState::Connected) + .count() as u32; if connected != self.viewers && self.live.is_some() { self.viewers = connected; self.own_stream(OwnStreamEvent::Viewers(connected)); } + let viewers = viewers.into_iter().map(ViewerInfo::from).collect(); self.emit(Event::StreamViewers { session, viewers }); } // The sink already has it (layer feedback). @@ -622,7 +646,8 @@ impl StreamTask { if let Some(id) = self.live.take() { self.own_stream(OwnStreamEvent::Ended { id }); } - self.emit(Event::StreamState { session, state: StreamState::Ended(reason) }); + let state = StreamState::Ended(reason.into()); + self.emit(Event::StreamState { session, state }); } StreamEvent::Watch { id, event } => { let state = match event { @@ -632,7 +657,7 @@ impl StreamTask { if let Some(audio) = &self.audio { audio.send(AudioIn::StreamEnded(id.clone())); } - WatchState::Ended(reason) + WatchState::Ended(reason.into()) } WatchEvent::Layers(_) => return self.watch_layers(&id), WatchEvent::Frame(frame) => { @@ -705,6 +730,126 @@ impl StreamTask { } } +// The core-owned stream types and the stream crate's: what the stream task +// reports is converted to the first, what the UI asks for to the second. + +impl From for StreamKind { + fn from(kind: voelin_stream::StreamKind) -> Self { + Self::from_u8(kind.to_u8()) + } +} + +impl From for voelin_stream::StreamKind { + fn from(kind: StreamKind) -> Self { + Self::from_u8(kind.to_u8()) + } +} + +impl From for voelin_stream::StreamSetup { + fn from(setup: StreamSetup) -> Self { + Self { + name: setup.name, + kind: setup.kind.into(), + bitrate: setup.bitrate, + accessibility: setup.accessibility, + mode: setup.mode, + viewer_limit: setup.viewer_limit, + audio: setup.audio, + } + } +} + +impl From for StreamInfo { + fn from(info: voelin_stream::StreamInfo) -> Self { + Self { + id: info.id, + streamer: info.streamer.0, + name: info.name, + kind: info.kind.into(), + bitrate: info.bitrate, + viewer_limit: info.viewer_limit, + audio: info.audio, + viewers: info.viewers, + } + } +} + +impl From for voelin_stream::StreamInfo { + fn from(info: StreamInfo) -> Self { + Self { + id: info.id, + streamer: ClientId(info.streamer), + name: info.name, + kind: info.kind.into(), + bitrate: info.bitrate, + viewer_limit: info.viewer_limit, + audio: info.audio, + viewers: info.viewers, + } + } +} + +impl From for ViewerState { + fn from(state: voelin_stream::ViewerState) -> Self { + match state { + voelin_stream::ViewerState::Requested => Self::Requested, + voelin_stream::ViewerState::Connecting => Self::Connecting, + voelin_stream::ViewerState::Connected => Self::Connected, + } + } +} + +/// The `voelin_media` codec of a negotiated video codec. +pub(crate) fn media_codec(codec: VideoCodec) -> voelin_media::Codec { + match codec { + VideoCodec::Vp8 => voelin_media::Codec::Vp8, + VideoCodec::Vp9 => voelin_media::Codec::Vp9, + VideoCodec::H264 => voelin_media::Codec::H264, + VideoCodec::Av1 => voelin_media::Codec::Av1, + VideoCodec::H265 => voelin_media::Codec::H265, + } +} + +impl From for ViewerInfo { + fn from(viewer: voelin_stream::ViewerInfo) -> Self { + Self { + client: viewer.client.0, + state: viewer.state.into(), + message: viewer.message, + layer: viewer.layer, + estimate: viewer.estimate, + srtp_profile: viewer.srtp_profile.map(|profile| profile.name().to_owned()), + codec: viewer.codec.map(media_codec), + } + } +} + +impl From for LeaveReason { + fn from(reason: voelin_stream::LeaveReason) -> Self { + match reason { + voelin_stream::LeaveReason::None => Self::None, + voelin_stream::LeaveReason::Left => Self::Left, + voelin_stream::LeaveReason::Denied => Self::Denied, + voelin_stream::LeaveReason::Failed => Self::Failed, + voelin_stream::LeaveReason::Kicked => Self::Kicked, + voelin_stream::LeaveReason::Banned => Self::Banned, + voelin_stream::LeaveReason::Other(v) => Self::Other(v), + } + } +} + +impl From for EndReason { + fn from(reason: voelin_stream::EndReason) -> Self { + match reason { + voelin_stream::EndReason::Local => Self::Local, + voelin_stream::EndReason::Denied => Self::Denied, + voelin_stream::EndReason::Stopped => Self::Stopped, + voelin_stream::EndReason::Removed(reason) => Self::Removed(reason.map(Into::into)), + voelin_stream::EndReason::Failed(message) => Self::Failed(message), + } + } +} + #[cfg(test)] mod tests { use std::time::{Duration, Instant}; @@ -732,7 +877,7 @@ mod tests { match request { Request::Setup(setup) => CLIENTS .map(|c| { - let info = StreamInfo { + let info = voelin_stream::StreamInfo { id: "s-1".into(), streamer: ClientId(from), name: setup.name.clone(), @@ -998,7 +1143,7 @@ mod tests { // Set before the stream starts: kept for it. handles[0].send(StreamInput::Layers(layers.clone())); // The viewer is the DTLS server: its order decides. - handles[1].send(StreamInput::SrtpProfiles(vec![SrtpProfile::AeadAes128Gcm])); + handles[1].send(StreamInput::SrtpProfiles(vec!["AEAD_AES_128_GCM".into()])); let sink = live_and_watching(&handles, &mut rx).await; let mut keyframes = LayerSet::new(); sink.take_layer_keyframes(&mut keyframes); @@ -1045,7 +1190,7 @@ mod tests { .await; let info = info.unwrap(); assert_eq!(info.layer, Some(0)); - assert_eq!(info.srtp_profile, Some(SrtpProfile::AeadAes128Gcm)); + assert_eq!(info.srtp_profile.as_deref(), Some("AEAD_AES_128_GCM")); assert!(sink.layer_bitrate(0).is_some_and(|b| b > 0)); assert_eq!(sink.layer_bitrate(1), None, "no viewer on layer 1"); @@ -1184,7 +1329,7 @@ mod tests { // The gateway's directory has it. let entry = StreamInfo { id: "s-1".into(), - streamer: ClientId(CLIENTS[0]), + streamer: CLIENTS[0], name: "directory test".into(), kind: parse_kind(&kind_name(StreamKind::Window)), bitrate: 0, @@ -1234,6 +1379,112 @@ mod tests { assert_eq!(parse_kind("game"), StreamKind::Screen); } + /// The core-owned types convert to and from the stream crate's without + /// losing a field. + #[test] + fn api_types_convert_at_the_boundary() { + use voelin_stream as wire; + + let setup = StreamSetup { + name: "n".into(), + kind: StreamKind::Other(9), + bitrate: 1234, + accessibility: 2, + mode: 3, + viewer_limit: 4, + audio: false, + }; + let sent: wire::StreamSetup = setup.clone().into(); + assert_eq!( + sent, + wire::StreamSetup { + name: "n".into(), + kind: wire::StreamKind::Other(9), + bitrate: 1234, + accessibility: 2, + mode: 3, + viewer_limit: 4, + audio: false, + } + ); + // The defaults agree. + assert_eq!(wire::StreamSetup::from(StreamSetup::default()), wire::StreamSetup::default()); + + let info = StreamInfo { + id: "s-7".into(), + streamer: 7, + name: "x".into(), + kind: StreamKind::Camera, + bitrate: 5, + viewer_limit: 6, + audio: true, + viewers: Some(2), + }; + let announced: wire::StreamInfo = info.clone().into(); + assert_eq!((announced.streamer, announced.kind), (ClientId(7), wire::StreamKind::Camera)); + assert_eq!(StreamInfo::from(announced), info); + + let viewer = wire::ViewerInfo { + client: ClientId(5), + state: wire::ViewerState::Connecting, + message: "hi".into(), + layer: Some(1), + estimate: Some(9), + srtp_profile: Some(SrtpProfile::AeadAes256Gcm), + codec: Some(VideoCodec::H264), + }; + assert_eq!( + ViewerInfo::from(viewer), + ViewerInfo { + client: 5, + state: ViewerState::Connecting, + message: "hi".into(), + layer: Some(1), + estimate: Some(9), + srtp_profile: Some("AEAD_AES_256_GCM".into()), + codec: Some(voelin_media::Codec::H264), + } + ); + for codec in VideoCodec::ALL { + assert!(media_codec(codec).name().eq_ignore_ascii_case(codec.sdp_name())); + } + + for (reason, expected) in [ + (wire::EndReason::Local, EndReason::Local), + (wire::EndReason::Denied, EndReason::Denied), + (wire::EndReason::Stopped, EndReason::Stopped), + (wire::EndReason::Removed(None), EndReason::Removed(None)), + ( + wire::EndReason::Removed(Some(wire::LeaveReason::Kicked)), + EndReason::Removed(Some(LeaveReason::Kicked)), + ), + ( + wire::EndReason::Removed(Some(wire::LeaveReason::Other(42))), + EndReason::Removed(Some(LeaveReason::Other(42))), + ), + (wire::EndReason::Failed("x".into()), EndReason::Failed("x".into())), + ] { + assert_eq!(EndReason::from(reason), expected); + } + } + + /// Profile names of the setting become profiles in order, names no profile + /// has are left out. + #[test] + fn srtp_profiles_are_parsed_from_names() { + let names: Vec = + ["AEAD_AES_128_GCM", "nonsense", "AES128_CM_SHA1_80"].map(String::from).to_vec(); + assert_eq!( + parse_srtp_profiles(&names), + [SrtpProfile::AeadAes128Gcm, SrtpProfile::Aes128CmSha1_80] + ); + assert!(parse_srtp_profiles(&[]).is_empty()); + // Every name the setting offers is a profile. + for name in crate::settings::SRTP_PROFILES { + assert!(SrtpProfile::from_name(name).is_some(), "{name}"); + } + } + /// `stream.permissions` answers join requests (`friends` and `channel`: /// those are let in, others are asked). #[tokio::test(flavor = "multi_thread")] diff --git a/crates/voelin-core/src/stream_types.rs b/crates/voelin-core/src/stream_types.rs new file mode 100644 index 0000000..65f51f7 --- /dev/null +++ b/crates/voelin-core/src/stream_types.rs @@ -0,0 +1,155 @@ +//! The stream types of the engine's API, owned by the core: what the UI is +//! told about streams ([`StreamInfo`], [`ViewerInfo`], why a stream +//! [ended](EndReason)) and what it asks for ([`StreamSetup`]). +//! +//! They carry plain fields only: client ids are `u16`, an SRTP profile is its +//! name, a video codec is `voelin_media`'s. What a server link speaks (the +//! TeamSpeak 6 stream crate today) is converted to and from them at the +//! boundary in [`crate::stream`], so the UI does not depend on the link's +//! types. The frame and simulcast layer types (`EncodedFrame`, `LayerSpec`, +//! `LayerId`) are `voelin-media`'s. + +use voelin_media::{Codec, LayerId}; + +/// What a stream shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StreamKind { + Camera, + Screen, + Window, + /// A kind this client does not know, by its number on the server. + Other(u8), +} + +impl StreamKind { + /// From the number servers use: 2 camera, 3 screen, 4 window. + pub fn from_u8(v: u8) -> Self { + match v { + 2 => Self::Camera, + 3 => Self::Screen, + 4 => Self::Window, + v => Self::Other(v), + } + } + + /// [`from_u8`](Self::from_u8) back. + pub fn to_u8(self) -> u8 { + match self { + Self::Camera => 2, + Self::Screen => 3, + Self::Window => 4, + Self::Other(v) => v, + } + } +} + +/// What we announce when we start a stream ([`crate::Command::StartStream`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StreamSetup { + pub name: String, + pub kind: StreamKind, + /// The stream's video bitrate in kbit/s (the single layer's without + /// simulcast). TeamSpeak 6 servers keep it in 16 bits, so it is + /// announced as at most 65535; the stream sends its real rate whatever + /// the announcement says. + pub bitrate: u32, + /// `accessibility`: the official client sends 1. + pub accessibility: u8, + /// `mode`: 1 (none) is what clients send today; 2 is P2P, 3 SFU. + pub mode: u8, + /// 0 = unlimited. + pub viewer_limit: u32, + pub audio: bool, +} + +impl Default for StreamSetup { + fn default() -> Self { + Self { + name: String::new(), + kind: StreamKind::Screen, + bitrate: 4608, + accessibility: 1, + mode: 1, + viewer_limit: 0, + audio: true, + } + } +} + +/// A stream on the server ([`crate::Event::StreamsChanged`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StreamInfo { + pub id: String, + /// The client id of the streamer. + pub streamer: u16, + pub name: String, + pub kind: StreamKind, + pub bitrate: u32, + pub viewer_limit: u32, + pub audio: bool, + /// How many watch it; `None` where nothing told (e.g. a gateway's + /// directory entry). + pub viewers: Option, +} + +/// A viewer of our stream, as we see it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ViewerState { + /// Asked to watch, waiting for our decision. + Requested, + /// Offer sent; waiting for the answer and the connection. + Connecting, + Connected, +} + +/// A viewer of our stream ([`crate::Event::StreamViewers`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ViewerInfo { + /// The client id of the viewer. + pub client: u16, + pub state: ViewerState, + /// The message of the join request. + pub message: String, + /// The simulcast layer the viewer receives (it moves at a keyframe of the + /// new layer); `None` before we offered, and with RID simulcast (all + /// layers). + pub layer: Option, + /// The latest bandwidth estimate of the connection (bit/s). + pub estimate: Option, + /// The SRTP profile of the connection by its name (as in RFC 5764 and + /// WebRTC statistics, e.g. `AEAD_AES_128_GCM`), once the key exchange is + /// done. + pub srtp_profile: Option, + /// The video codec the viewer's answer chose (it gets video in that + /// codec). + pub codec: Option, +} + +/// Why a viewer left a stream. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LeaveReason { + None, + Left, + Denied, + Failed, + Kicked, + Banned, + /// A reason this client does not know, by its number on the server. + Other(u8), +} + +/// Why a stream ended for us ([`crate::StreamState::Ended`], +/// [`crate::WatchState::Ended`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EndReason { + /// We stopped streaming or watching. + Local, + /// The streamer denied our join request. + Denied, + /// The stream was stopped (or its streamer disconnected). + Stopped, + /// The streamer or the server ended our viewing session. + Removed(Option), + /// A command failed or no connection could be established. + Failed(String), +} diff --git a/crates/voelin-core/tests/stream_live.rs b/crates/voelin-core/tests/stream_live.rs index 4d1222c..2dd9cbd 100644 --- a/crates/voelin-core/tests/stream_live.rs +++ b/crates/voelin-core/tests/stream_live.rs @@ -167,7 +167,7 @@ async fn ts6_stream_between_sessions() { Event::StreamViewers { session: 1, viewers } if viewers .iter() - .any(|v| v.client.0 == viewer && v.state == ViewerState::Connected) => + .any(|v| v.client == viewer && v.state == ViewerState::Connected) => { Some(()) } diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index 318fcae..07ed387 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -40,11 +40,9 @@ wlroots = ["dep:wayland-client", "dep:wayland-protocols", "dep:wayland-protocols # model (PP-HumanSeg, ONNX, bundled in `models/`) run on the CPU by tract. # Without it the background is cut around a centred oval. segment = ["dep:tract-onnx"] -# Conversion between `Codec` and `str0m::format::Codec`. -str0m = ["dep:str0m"] # The studio's WHIP output: a WebRTC session (str0m) set up over HTTP. Needs # str0m's crypto provider, the same one voelin-stream uses. -whip = ["str0m", "str0m/aws-lc-rs", "dep:reqwest"] +whip = ["str0m/aws-lc-rs", "dep:reqwest"] [dependencies] bzip2 = { version = "0.6.1", optional = true } @@ -61,7 +59,9 @@ serde = { version = "1", features = ["derive"] } ab_glyph = "0.2.32" image = { version = "0.25.10", default-features = false, features = ["jpeg", "png"] } sha2 = { version = "0.10.9", optional = true } -str0m = { version = "0.23.1", default-features = false, optional = true } +# Its media types (`MediaKind`, `MediaTime`) are in `stream::EncodedFrame`, and +# `Codec` converts to and from its codec type. +str0m = { version = "0.23.1", default-features = false } thiserror = "2.0.21" tract-onnx = { version = "0.23.8", optional = true } tokio = { version = "1", features = ["sync"] } @@ -97,8 +97,10 @@ criterion = "0.8" opus2 = "0.4" serde_json = "1" # The H.264 `profile-level-id` the signalling offers, to check it against the -# SPS the encoders really emit (`tests/ffmpeg.rs`). No cycle: voelin-stream -# does not depend on this crate. +# SPS the encoders really emit (`tests/ffmpeg.rs`). A cycle through a +# dev-dependency, which cargo allows: voelin-stream depends on this crate for +# the frame and layer types, so this crate's unit tests see itself twice, and +# only primitives and voelin-stream's own types cross between the copies. voelin-stream = { path = "../voelin-stream" } # Logs of integration tests (`RUST_LOG`). tracing-subscriber = { version = "0.3", features = ["env-filter"] } diff --git a/crates/voelin-media/src/codec/mod.rs b/crates/voelin-media/src/codec/mod.rs index 458115a..a505abd 100644 --- a/crates/voelin-media/src/codec/mod.rs +++ b/crates/voelin-media/src/codec/mod.rs @@ -95,7 +95,6 @@ impl FromStr for Codec { } } -#[cfg(feature = "str0m")] impl From for str0m::format::Codec { fn from(c: Codec) -> Self { match c { @@ -108,7 +107,6 @@ impl From for str0m::format::Codec { } } -#[cfg(feature = "str0m")] impl TryFrom for Codec { type Error = Error; @@ -226,7 +224,9 @@ pub struct EncodedChunk<'a> { pub pts_90khz: u64, } -/// One encoded frame, ready for `voelin_stream::Peer::write`. +/// One frame as an encoder makes it. A stream takes it as a +/// [`stream::EncodedFrame`](crate::stream::EncodedFrame), which adds the kind +/// of media, the RTP time and the layer. #[derive(Clone, Debug, PartialEq, Eq)] pub struct EncodedFrame { pub data: Vec, @@ -1039,7 +1039,6 @@ mod tests { assert_eq!(Codec::Av1.to_string(), "AV1"); } - #[cfg(feature = "str0m")] #[test] fn str0m_mapping() { for c in Codec::ALL { diff --git a/crates/voelin-media/src/layer.rs b/crates/voelin-media/src/layer.rs new file mode 100644 index 0000000..0d293ce --- /dev/null +++ b/crates/voelin-media/src/layer.rs @@ -0,0 +1,210 @@ +//! 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::stream::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. +//! +//! The types are the media side's vocabulary; the stream transports (the +//! `voelin-stream` crate, and whatever else carries a stream) and the client +//! engine use them as they are. + +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-media/src/lib.rs b/crates/voelin-media/src/lib.rs index dbe0fc2..932bd7d 100644 --- a/crates/voelin-media/src/lib.rs +++ b/crates/voelin-media/src/lib.rs @@ -5,6 +5,10 @@ //! (interleaved `f32`, 48 kHz) //! - [`convert`]: YUV ↔ RGB conversion (BT.601 limited range, the WebRTC //! default), e.g. RGBA for rendering and I420 for encoding +//! - [`layer`] and [`stream`]: the simulcast layers of a stream +//! ([`LayerSpec`]) and its frames on the way to the viewers +//! ([`stream::EncodedFrame`], the encoder's frame plus kind, RTP time and +//! layer) //! - [`codec`]: [`VideoEncoder`] / [`VideoDecoder`] traits, codec preference //! and the backends: libvpx (VP8/VP9, feature `vpx`), Cisco's OpenH264 //! loaded at runtime (H.264, feature `openh264`), dav1d (AV1 decoding, @@ -24,8 +28,8 @@ //! scaling and the [`scale::Pyramid`] of simulcast sizes), and //! [`convert::Converter`] (borrowed capture buffers straight to I420) //! -//! Encoded frames go to `voelin_stream::Peer::write` with an RTP time of -//! [`EncodedFrame::pts_90khz`] (90 kHz clock); received `MediaFrame`s go to +//! Encoded frames go to a stream as [`stream::EncodedFrame`]s with an RTP time +//! of [`EncodedFrame::pts_90khz`] (90 kHz clock); received `MediaFrame`s go to //! [`VideoDecoder::decode`]. pub mod capture; @@ -35,10 +39,12 @@ pub mod convert; pub mod ffmpeg; pub mod frame; pub mod handoff; +pub mod layer; pub mod mix; pub mod pool; pub mod queue; pub mod scale; +pub mod stream; pub mod studio; pub mod workers; @@ -51,6 +57,7 @@ pub use codec::{ pub use frame::{ AudioBuffer, FrameData, FrameRef, GpuFrame, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame, }; +pub use layer::{LayerId, LayerSet, LayerSpec}; pub use queue::{FrameReceiver, FrameSender, frame_channel}; /// Errors of this crate. diff --git a/crates/voelin-media/src/stream.rs b/crates/voelin-media/src/stream.rs new file mode 100644 index 0000000..1b91fab --- /dev/null +++ b/crates/voelin-media/src/stream.rs @@ -0,0 +1,34 @@ +//! The frames of a stream on their way to its viewers. +//! +//! An [`EncodedFrame`] is what the streamer's encoders and the Opus encoder +//! hand to a stream: the encoder's output ([`codec::EncodedFrame`]) plus what +//! the transport needs, which media it is, its RTP time and its simulcast +//! layer. The engine's stream sink, the stream sessions (`voelin-stream`) and +//! the tools that feed a stream by hand all pass it on unchanged. +//! +//! [`codec::EncodedFrame`]: crate::codec::EncodedFrame + +use std::sync::Arc; + +use str0m::media::{MediaKind, MediaTime}; + +use crate::layer::LayerId; + +/// One encoded video or audio frame of a stream, ready to be sent. +/// +/// Not the encoder's [`codec::EncodedFrame`](crate::codec::EncodedFrame), +/// which has neither a kind nor a layer and counts time on the 90 kHz clock +/// only. +#[derive(Clone, Debug)] +pub struct EncodedFrame { + pub kind: MediaKind, + /// 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, + /// A video keyframe: viewers can start decoding (or switch to this layer) + /// here. + pub keyframe: bool, +} diff --git a/crates/voelin-stream/Cargo.toml b/crates/voelin-stream/Cargo.toml index c83af6b..30e139a 100644 --- a/crates/voelin-stream/Cargo.toml +++ b/crates/voelin-stream/Cargo.toml @@ -22,6 +22,9 @@ tokio = { version = "1", features = ["macros", "net", "rt", "sync", "time"] } tracing = "0.1" tsclientlib = { path = "../proto/tsclientlib" } tsproto-packets = { path = "../proto/tsproto-packets" } +# The frame and simulcast layer types (`EncodedFrame`, `LayerSpec`), which the +# media side owns; re-exported here. +voelin-media = { path = "../voelin-media", default-features = false } [dev-dependencies] anyhow = "1" diff --git a/crates/voelin-stream/src/layer.rs b/crates/voelin-stream/src/layer.rs index a915d7e..aa6e576 100644 --- a/crates/voelin-stream/src/layer.rs +++ b/crates/voelin-stream/src/layer.rs @@ -1,83 +1,13 @@ -//! Simulcast layers: several encodings of one stream, each with its own size, -//! frame rate and bitrate. +//! Simulcast layers of a stream. The types ([`LayerSpec`], [`LayerId`], +//! [`LayerSet`]) are `voelin-media`'s; this module keeps how a streamer's +//! offer lists its layers in the SDP, so that a Voelin viewer can pick one. //! //! 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. +//! negotiate RID simulcast (`a=simulcast`) get all of them. -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)) - } -} +pub use voelin_media::layer::{LayerId, LayerSet, 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`): @@ -129,119 +59,10 @@ pub fn from_sdp(sdp: &str) -> Option> { 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 { - 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 layers_in_the_sdp() { let layers = vec![ @@ -265,16 +86,4 @@ mod tests { [LayerSpec { id: 2, ..LayerSpec::single(700_000) }] ); } - - #[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/source.rs b/crates/voelin-stream/src/source.rs index 8bc1960..2f2cfa4 100644 --- a/crates/voelin-stream/src/source.rs +++ b/crates/voelin-stream/src/source.rs @@ -8,24 +8,10 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use str0m::media::{Frequency, MediaKind, MediaTime}; +pub use voelin_media::stream::EncodedFrame; use crate::layer::{LayerId, LayerSpec}; -/// One encoded video or audio frame. -#[derive(Clone, Debug)] -pub struct EncodedFrame { - pub kind: MediaKind, - /// 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, - /// A video keyframe: viewers can start decoding (or switch to this layer) - /// here. - pub keyframe: bool, -} - /// Produces encoded frames in real time. pub trait FrameSource: Send { /// Append the frames that are due at `now`. diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index 2a3a636..9973194 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -714,7 +714,7 @@ fn demo_ui(app: &mut App) { session, streams: vec![StreamInfo { id: "demo-stream".into(), - streamer: tsclientlib::ClientId(2), + streamer: 2, name: "Exploring the Lands Between".into(), kind: StreamKind::Screen, bitrate: 8000, diff --git a/crates/voelin-ui/src/home.rs b/crates/voelin-ui/src/home.rs index 5686519..eeedd70 100644 --- a/crates/voelin-ui/src/home.rs +++ b/crates/voelin-ui/src/home.rs @@ -63,15 +63,15 @@ impl App { let mut covered: Vec = Vec::new(); if view.streams_available() { for s in &view.streams { - let name = view.nickname(s.streamer.0); + let name = view.nickname(s.streamer); let title = if s.name.is_empty() { format!("{name}'s stream") } else { s.name.clone() }; - let mut room = item(s.id.clone(), title, Some(s.streamer.0), None, name); - room.channel = channel_of(view.channel_of(s.streamer.0)).into(); + let mut room = item(s.id.clone(), title, Some(s.streamer), None, name); + room.channel = channel_of(view.channel_of(s.streamer)).into(); room.viewers = view.stream_viewers.get(&s.id).map_or(0, |v| *v as i32); room.kind = vm::streams::kind_label(&s.kind).into(); - room.watchable = view.state.own_client != Some(s.streamer.0); - covered.push(s.streamer.0); + room.watchable = view.state.own_client != Some(s.streamer); + covered.push(s.streamer); rooms.push(room); } } diff --git a/crates/voelin-ui/src/settings_pages.rs b/crates/voelin-ui/src/settings_pages.rs index 8cef320..8122c3e 100644 --- a/crates/voelin-ui/src/settings_pages.rs +++ b/crates/voelin-ui/src/settings_pages.rs @@ -373,15 +373,11 @@ impl App { } /// The SRTP profiles of the setting, for the engine (it does not read - /// the setting itself). + /// the setting itself; it takes the names and leaves out the ones its + /// stream transport does not know). pub(crate) fn apply_srtp(&self) { - let profiles: Vec<_> = self - .prefs - .get(&STREAM_SRTP_PROFILES) - .iter() - .filter_map(|n| voelin_core::stream::SrtpProfile::from_name(n)) - .collect(); - self.engine.send(Command::SetSrtpProfiles(profiles)); + let profiles = self.prefs.get(&STREAM_SRTP_PROFILES); + self.engine.send(Command::SetSrtpProfiles(profiles.to_vec())); } pub(crate) fn video_changed(&mut self, form: &crate::app::VideoForm) { diff --git a/crates/voelin-ui/src/social.rs b/crates/voelin-ui/src/social.rs index b7493ba..e53deef 100644 --- a/crates/voelin-ui/src/social.rs +++ b/crates/voelin-ui/src/social.rs @@ -317,7 +317,7 @@ impl App { let view = self.sessions.get(&spot.session)?; view.streams .iter() - .find(|s| s.streamer.0 == spot.client) + .find(|s| s.streamer == spot.client) .map(|s| s.name.clone()) .or_else(|| { view.extra.directory.iter().find(|e| e.streamer.uid == uid).map(|e| e.title.clone()) diff --git a/crates/voelin-ui/src/streams.rs b/crates/voelin-ui/src/streams.rs index 46ca1f7..665d8ee 100644 --- a/crates/voelin-ui/src/streams.rs +++ b/crates/voelin-ui/src/streams.rs @@ -61,7 +61,7 @@ fn capture_request( /// The viewers of the sample share (VOELIN_DEMO_UI): two watch, one asks. fn demo_viewers() -> Vec { let viewer = |id, state, message: &str| ViewerInfo { - client: tsclientlib::ClientId(id), + client: id, state, message: message.into(), layer: None, @@ -191,13 +191,13 @@ impl App { && self.current == Some(session as i64); let first = streams .iter() - .find(|s| view.state.own_client != Some(s.streamer.0)) + .find(|s| view.state.own_client != Some(s.streamer)) .map(|s| s.id.clone()); // A client whose stream was asked for while it was looked up. let pending = self .pending_watch .filter(|(s, _)| *s == session as i64) - .and_then(|(_, client)| streams.iter().find(|s| s.streamer.0 == client)) + .and_then(|(_, client)| streams.iter().find(|s| s.streamer == client)) .map(|s| s.id.clone()); view.streams = streams; self.refresh_streams(); @@ -307,7 +307,7 @@ impl App { // ours first. let own_channel = view.state.own_channel; let mut streams: Vec<_> = view.streams.iter().collect(); - streams.sort_by_key(|s| view.channel_of(s.streamer.0) != own_channel); + streams.sort_by_key(|s| view.channel_of(s.streamer) != own_channel); // Our own stream from the studio shows its preview. let studio = current.is_some_and(|c| self.studio_streams_to(c)); for s in streams { @@ -316,12 +316,12 @@ impl App { let watching = self.watch.as_ref().is_some_and(|w| { (w.session == current || w.session.is_none()) && w.stream_id == s.id && !w.ended }); - let own = view.state.own_client == Some(s.streamer.0); + let own = view.state.own_client == Some(s.streamer); items.push(StreamItem { id: s.id.clone().into(), name: s.name.clone().into(), - channel: view.other_channel_name(s.streamer.0).into(), - streamer_id: i32::from(s.streamer.0), + channel: view.other_channel_name(s.streamer).into(), + streamer_id: i32::from(s.streamer), viewers: viewer_count(view, &s.id).unwrap_or(0) as i32, audio: s.audio, watching, @@ -330,8 +330,8 @@ impl App { kind: crate::vm::streams::kind_label(&s.kind).into(), bitrate: bitrate_text(s.bitrate).into(), ..crate::vm::streams::streamer( - &view.nickname(s.streamer.0), - view.avatar(s.streamer.0), + &view.nickname(s.streamer), + view.avatar(s.streamer), ) }); } @@ -340,7 +340,7 @@ impl App { // them up (they arrive in `StreamsChanged` like the others). // Until then only the streaming flag is known. for c in view.presence.clients.values() { - let announced = view.streams.iter().any(|s| s.streamer.0 == c.id); + let announced = view.streams.iter().any(|s| s.streamer == c.id); if c.streaming == Some(true) && !announced && view.state.own_client != Some(c.id) { items.push(StreamItem { name: c.nickname.clone().into(), @@ -381,10 +381,8 @@ impl App { s.viewers .iter() .map(|v| ViewerItem { - client: i32::from(v.client.0), - name: view - .map_or_else(String::new, |view| view.nickname(v.client.0)) - .into(), + client: i32::from(v.client), + name: view.map_or_else(String::new, |view| view.nickname(v.client)).into(), state: match v.state { ViewerState::Requested => "requested", ViewerState::Connecting => "connecting", @@ -393,7 +391,7 @@ impl App { .into(), message: v.message.clone().into(), avatar: crate::vm::avatar::image( - view.and_then(|view| view.avatar(v.client.0)), + view.and_then(|view| view.avatar(v.client)), ), }) .collect() @@ -450,7 +448,7 @@ impl App { .join(" · "); let streamer = view .and_then(|v| v.streams.iter().find(|s| s.id == watch.stream_id)) - .map_or(-1, |s| i32::from(s.streamer.0)); + .map_or(-1, |s| i32::from(s.streamer)); let face = crate::vm::streams::streamer( &watch.streamer, view.zip(u16::try_from(streamer).ok()).and_then(|(v, id)| v.avatar(id)), @@ -798,7 +796,7 @@ impl App { let Some(session) = self.current else { return }; let Some(view) = self.sessions.get(&session) else { return }; let Some(info) = view.streams.iter().find(|s| s.id == stream_id) else { return }; - let streamer = view.nickname(info.streamer.0); + let streamer = view.nickname(info.streamer); let title = if info.name.is_empty() { format!("{streamer}'s stream") } else { info.name.clone() }; // A window of its own stays, for this stream. @@ -845,8 +843,7 @@ impl App { if view.state.own_client == Some(client) { return; } - if let Some(id) = view.streams.iter().find(|s| s.streamer.0 == client).map(|s| s.id.clone()) - { + if let Some(id) = view.streams.iter().find(|s| s.streamer == client).map(|s| s.id.clone()) { self.pending_watch = None; self.watch_stream(id); } else if view.presence.clients.get(&client).is_some_and(|c| c.streaming == Some(true)) { @@ -859,10 +856,7 @@ impl App { /// `VOELIN_OPEN=watch`: watch the first stream of our channel. pub(crate) fn watch_first_stream(&mut self) { let Some(id) = self.view().and_then(|v| { - v.streams - .iter() - .find(|s| v.state.own_client != Some(s.streamer.0)) - .map(|s| s.id.clone()) + v.streams.iter().find(|s| v.state.own_client != Some(s.streamer)).map(|s| s.id.clone()) }) else { return; }; @@ -911,7 +905,7 @@ impl App { /// viewer, dressed as the first stream of our channel. pub(crate) fn demo_watch(&mut self) { let sample = self.view().and_then(|v| { - v.streams.first().map(|s| (s.id.clone(), s.name.clone(), v.nickname(s.streamer.0))) + v.streams.first().map(|s| (s.id.clone(), s.name.clone(), v.nickname(s.streamer))) }); self.start_demo(); if let (Some(watch), Some((id, title, streamer))) = (&mut self.watch, sample) { diff --git a/crates/voelin-ui/src/studio.rs b/crates/voelin-ui/src/studio.rs index 72fa21a..364778b 100644 --- a/crates/voelin-ui/src/studio.rs +++ b/crates/voelin-ui/src/studio.rs @@ -1132,7 +1132,7 @@ impl App { .iter() .filter(|v| v.state == ViewerState::Requested) .map(|v| StudioViewer { - client: i32::from(v.client.0), + client: i32::from(v.client), name: self.studio_viewer_name(v).into(), state: "requested".into(), }) @@ -1149,7 +1149,7 @@ impl App { let session = self.studio.stream.as_ref().map(|s| s.session); session .and_then(|id| self.sessions.get(&id)) - .map_or_else(|| format!("client {}", viewer.client.0), |v| v.nickname(viewer.client.0)) + .map_or_else(|| format!("client {}", viewer.client), |v| v.nickname(viewer.client)) } /// Keep the overlay sources as the switches say (`force`: also when @@ -2024,10 +2024,10 @@ impl App { pub(crate) fn studio_respond_viewer(&mut self, client: u16, accept: bool) { let Some(out) = &mut self.studio.stream else { return }; if self.demo_ui { - for v in out.viewers.iter_mut().filter(|v| v.client.0 == client) { + for v in out.viewers.iter_mut().filter(|v| v.client == client) { v.state = ViewerState::Connected; } - out.viewers.retain(|v| accept || v.client.0 != client); + out.viewers.retain(|v| accept || v.client != client); self.studio_refresh_status(); return; } @@ -2219,7 +2219,7 @@ impl App { /// with sample viewers. fn studio_demo_live(&mut self) { let viewer = |id: u16, state: ViewerState, estimate: u64| ViewerInfo { - client: tsclientlib::ClientId(id), + client: id, state, message: String::new(), layer: Some(0), @@ -2251,7 +2251,7 @@ impl App { if live && let Some(own) = view.state.own_client { view.streams.push(StreamInfo { id: "demo-studio".into(), - streamer: tsclientlib::ClientId(own), + streamer: own, name, kind: StreamKind::Screen, bitrate: 8000, diff --git a/docs/architecture.md b/docs/architecture.md index c1d890b..b2cb0b9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -71,10 +71,10 @@ fuzz/ cargo-fuzz targets | `voelin-gateway-proto`, `voelin-gateway` (`tsgw`) | Companion service for server admins: identity-challenge auth, permission-mirroring authorization, presence stream, chat relay, SQLite history, WebSocket + JSON (`tsgw.v1+json`) | done | | `voelin-store` | Identities, bookmarks, settings, chat history (dedupe, paging, sync cursors, where each chat was read), contacts, secrets (keyring / Android Keystore); versioned schema | done | | `voelin-audio` | Capture/playback, Opus, echo cancellation, resampling, jitter buffer, mixer, VAD/push-to-talk; the voice packet types (`TalkerId`, `VoicePacket`, `EncodedVoice`), so it depends on no voice transport | v0 (no AEC yet) | -| `voelin-stream` | TS6 stream commands, JSON signalling, str0m peer connections, host/STUN candidates, streamer/viewer sessions, frame-source seam | sessions + transport | -| `voelin-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API, chat history, the gateway's features, audio settings and volumes, streams on TS6, files, avatar and icon cache, pokes, offline messages, contacts; `media` module (capture → encoder → stream, stream → decoder) | done | +| `voelin-stream` | TS6 stream commands, JSON signalling, str0m peer connections, host/STUN candidates, streamer/viewer sessions, frame-source seam; its frame and simulcast layer types are `voelin-media`'s | sessions + transport | +| `voelin-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API, chat history, the gateway's features, audio settings and volumes, streams on TS6, files, avatar and icon cache, pokes, offline messages, contacts; `media` module (capture → encoder → stream, stream → decoder); the stream types of its API are its own (`stream_types`, see Streams) | done | | `voelin-ui` | Slint UI and the desktop binary: streams panel, viewer, share dialog, audio / hotkey / codec settings | done (desktop) | -| `voelin-media` | Screen and system-audio capture backends (PipeWire portal, X11, Windows Graphics Capture, Android MediaProjection), video codecs | done (desktop hardware encoders through FFmpeg loaded at runtime, not run on a GPU yet; MediaCodec not run on a device yet) | +| `voelin-media` | Screen and system-audio capture backends (PipeWire portal, X11, Windows Graphics Capture, Android MediaProjection), video codecs; the frame and simulcast layer types of a stream (`stream::EncodedFrame`, `LayerSpec`, `LayerId`, `LayerSet`) | done (desktop hardware encoders through FFmpeg loaded at runtime, not run on a GPU yet; MediaCodec not run on a device yet) | | `voelin-platform` | Global hotkeys, notifications, paths, crash reports, notices | done | | `voelin-android` + `android/` | Android library + Gradle/Kotlin app (foreground services for voice and screen capture); see [android.md](android.md) | builds, not yet run on a device | @@ -265,8 +265,9 @@ Transport details of our stream (`voelin-stream`): browsers, so our order decides. `dtls::VoelinDtlsProvider` wraps str0m's dimpl DTLS with that order; dimpl is vendored in `third_party/dimpl` with a patch for it (`VOELIN-PATCH.md`). The order is a setting - (`Streams::set_srtp_profiles`, `Command::SetSrtpProfiles`) and applies to - new connections. + (`Streams::set_srtp_profiles`, `Command::SetSrtpProfiles`, which takes the + profiles' names; the stream task parses them) 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 @@ -326,6 +327,25 @@ Transport details of our stream (`voelin-stream`): (`Streams::set_layers`, `Command::SetStreamLayers`). Without layers the stream has one layer 0 at the setup's bitrate and every viewer gets it. +The stream types the UI sees are `voelin-core`'s own (`stream_types.rs`, also +under `voelin_core::stream`): `StreamInfo`, `ViewerInfo`, `StreamSetup`, +`StreamKind`, `ViewerState`, and why a stream ended (`EndReason`, +`LeaveReason`). They have plain fields: client ids are `u16`, a viewer's SRTP +profile is its name (`AEAD_AES_128_GCM`), its video codec is +`voelin_media::Codec`. The frame and layer types in the API +(`stream::EncodedFrame`, `LayerSpec`, `LayerId`, `LayerSet`) are +`voelin-media`'s, which `voelin-stream` uses as they are. The conversion to +and from `voelin-stream`'s own types happens in one place, `stream.rs`: the +stream task converts what `Streams` reports, and what the UI asks for +(`StreamSetup`, the profile names) on the way in, so the stream session's +own types (its `StreamInfo`, `ViewerInfo`, `StreamSetup`, `SrtpProfile`, +`EndReason`) no longer show in `Command` and `Event`. Still +`voelin-stream`'s in the engine's API are the peer and media vocabulary: +`PeerConfig` (in `VoiceOptions`), `MediaFrame` (the frames of watched +streams), `VideoFormat` and `VideoCodec` (on the `StreamSink`), +`FrameSource`, `SyntheticSource`; they move out of the core with the stream +task (the decoupling plan's next steps). + In `voelin-core` a stream task per voice connection runs `Streams`; the voice task forwards `MessageEvent`s and sends the requests. Encoders push frames through the `StreamSink` of `StreamState::Live`; received frames of watched streams go diff --git a/docs/media.md b/docs/media.md index 7f11a7f..c9cc6fc 100644 --- a/docs/media.md +++ b/docs/media.md @@ -20,10 +20,12 @@ described in [studio.md](studio.md). | `FrameRef { width, height, timestamp, pixels: PixelsRef }` | the same with borrowed planes (`PlaneRef { data: &[u8], stride }`), e.g. a mapped capture buffer; `VideoFrame::view()`, `FrameRef::to_frame()` | | `AudioBuffer { samples, channels, timestamp }` | interleaved `f32`, 48 kHz | | `convert::to_rgba(&frame, out, stride)`, `to_rgba_vec`, `to_i420`, `psnr` | BT.601 limited range (the WebRTC default). `to_rgba` writes straight into a Slint `SharedPixelBuffer` (`make_mut_bytes()`, stride `width * 4`) | -| `Codec` | `Vp8`, `Vp9`, `H264`, `Av1`; `FromStr` for SDP/MIME names; `From`/`TryFrom` `str0m::format::Codec` with feature `str0m` | +| `Codec` | `Vp8`, `Vp9`, `H264`, `Av1`; `FromStr` for SDP/MIME names; `From`/`TryFrom` `str0m::format::Codec` | | `VideoEncoder` | `encode(&frame, force_keyframe) -> Vec`; `encode_with(&frame, force_keyframe, &mut |EncodedChunk| ..)` hands out the encoder's own buffer (no copy); `set_bitrate(bps)` (libvpx: in place, no keyframe), `set_fps`, `speed()`, `codec()`, `backend()`; `gpu_alignment()` / `encode_gpu(&GpuFrame, ..)` for encoders that take frames in GPU memory (VA-API; MediaCodec's surface path on Android) | | `GpuFrame` | a picture in GPU memory (an NV12 VA-API surface), made by `ffmpeg::GpuConverter` from a captured DMA-BUF; `width`, `height`, `timestamp`, `at(timestamp)` (the same surface at another time). On Android `rendered(width, height, timestamp)`: a screen picture the virtual display renders straight into MediaCodec's input surface, only its size and time travel | -| `EncodedFrame { data, keyframe, pts_90khz }` | one frame for `Peer::write` | +| `EncodedFrame { data, keyframe, pts_90khz }` | one frame as an encoder makes it | +| `stream::EncodedFrame { kind, time, data, layer, keyframe }` | one frame of a stream, ready to send: the encoder's frame with its media kind, RTP time (90 kHz video, 48 kHz Opus) and simulcast layer. What `StreamSink::send` and `Command::SendStreamFrame` take; `voelin-stream` passes the same type on to its peers | +| `LayerSpec`, `LayerId`, `LayerSet` (`layer`) | the simulcast layers of a stream: size or scale, frame-rate cap, start, maximum and minimum bitrate, RID; `LayerSet` is a set of layer ids (e.g. those waiting for a keyframe). Owned here, used as they are by `voelin-stream` and the engine's API | | `VideoDecoder` | `decode(&[u8]) -> Option` (timestamp zero; the caller knows the RTP time); `decode_into(&[u8], &mut VideoFrame) -> bool` reuses the frame's buffers (FFmpeg's decoders: no allocation per picture); `conceals_errors()` (FFmpeg's H.264 and HEVC: frames after a lost one still decode) | | `EncoderConfig { fps, bitrate_bps, keyframe_interval, content, threads, speed }` | resolution follows the frames; a size change restarts with a keyframe; `threads` is a maximum (0: all CPUs but one), still capped at one per 320x240 pixels; `speed: None` adapts libvpx `cpu-used` to the encode time | | `Codecs` | `new()` (probes FFmpeg / MediaCodec once per process), `builtin()` (compiled-in codecs only), `with_openh264(lib)`, `with_preference(EncoderPreference)` / `set_preference`, `decoders()` (viewer order: every codec one decoder here decodes), `decoders_for(codec)` (that codec's decoders, best first: the ladder), `with_decoder_preference(DecoderPreference)` / `set_decoder_preference`, `with_decoder(factory)` (an application's decoder, first), `encoders()` / `encoder_codecs()` (streamer order under the preference), `encoders_for(&pref)`, `new_decoder(codec)` (the first of the ladder that opens), `new_decoder_with(codec, DecoderBackend)`, `new_encoder(codec, config)`, `new_encoder_preferring(codec, config, &pref)`, `new_encoder_with(codec, backend, config)`, `pick_encoder(&accepted)`, `is_hardware(backend)`, `report()`; cheap to clone | @@ -125,7 +127,7 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder portal maps it, and a conversion that fails turns the GPU path off for the capture (`StreamerStats::gpu_error`). Nothing is allocated per frame on this path either (the surfaces' frames are recycled). -- Simulcast: `StreamerConfig::layers` (`voelin_stream::LayerSpec`; empty: +- Simulcast: `StreamerConfig::layers` (`voelin_media::LayerSpec`; empty: one layer 0 at `bitrate_kbps`) are all encoded, each with its own encoder at `output_size()` of the source, its own frame-rate cap (`max_fps`, paced by timestamps) and its share of the CPUs. Frames carry `layer` and diff --git a/tools/voelinctl/src/engine.rs b/tools/voelinctl/src/engine.rs index e3f38d7..6c60008 100644 --- a/tools/voelinctl/src/engine.rs +++ b/tools/voelinctl/src/engine.rs @@ -241,16 +241,13 @@ pub async fn run(args: GatewayArgs) -> Result<()> { } Event::StreamsChanged { session: SESSION, streams } => { for s in &streams { - let nick = nicknames.get(&s.streamer.0).map_or("?", String::as_str); - out.print(format!( - "streams: {} by {nick} ({}) {:?}", - s.id, s.streamer.0, s.name - )); + let nick = nicknames.get(&s.streamer).map_or("?", String::as_str); + out.print(format!("streams: {} by {nick} ({}) {:?}", s.id, s.streamer, s.name)); } if let Some(wanted) = &args.watch_streamer && !watching && let Some(s) = streams .iter() - .find(|s| nicknames.get(&s.streamer.0).is_some_and(|n| n == wanted)) + .find(|s| nicknames.get(&s.streamer).is_some_and(|n| n == wanted)) { watching = true; out.print(format!("watching {}", s.id));