Give the stream API core-owned types

Command and Event no longer carry voelin-stream's types. voelin-core owns
StreamInfo, ViewerInfo, StreamSetup, StreamKind, ViewerState, EndReason and
LeaveReason (stream_types.rs) with u16 client ids, a viewer's SRTP profile
as its name and its codec as voelin_media::Codec; stream.rs converts at the
boundary. Command::SetSrtpProfiles takes profile names, which the stream
task parses.

EncodedFrame, LayerSpec, LayerId and LayerSet move into voelin-media
(stream::EncodedFrame, layer); voelin-stream depends on it and re-exports
them, so the engine, the stream sessions and voelinctl share one type. The
crate is now a plain dependency of voelin-core (feature media keeps the
module and WHIP), and its str0m feature is gone with str0m always there.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-14 15:01:24 +03:00
1 parent b0f95a384f
commit da372dfe10
28 files changed
+798 -342

No files matched your search

+4 -3
View File
@@ -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).
+10 -9
View File
@@ -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<LayerSpec>,
},
/// 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<SrtpProfile>),
/// 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<String>),
/// 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<Vec<SrtpProfile>> = None;
let mut srtp_profiles: Option<Vec<String>> = None;
let mut mic_test: Option<AudioHandle> = None;
loop {
let input = tokio::select! {
+4 -10
View File
@@ -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<JoinHandle<()>
/// 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
+6 -7
View File
@@ -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<LayerSpec>,
/// The SRTP profile setting (`Command::SetSrtpProfiles`), over the voice
/// options' `stream_peer`.
srtp_profiles: Option<Vec<SrtpProfile>>,
srtp_profiles: Option<Vec<String>>,
frames: broadcast::Sender<StreamFrame>,
/// 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.
+1 -1
View File
@@ -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<T>` of the key's `T`).
type Stored = Arc<dyn Any + Send + Sync>;
+274 -23
View File
@@ -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<SrtpProfile>),
/// SRTP profile order of new connections, by name
/// ([`parse_srtp_profiles`]).
SrtpProfiles(Vec<String>),
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<SrtpProfile> {
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<Mutex<GatewayStreams>>);
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<voelin_stream::StreamKind> for StreamKind {
fn from(kind: voelin_stream::StreamKind) -> Self {
Self::from_u8(kind.to_u8())
}
}
impl From<StreamKind> for voelin_stream::StreamKind {
fn from(kind: StreamKind) -> Self {
Self::from_u8(kind.to_u8())
}
}
impl From<StreamSetup> 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<voelin_stream::StreamInfo> 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<StreamInfo> 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<voelin_stream::ViewerState> 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<voelin_stream::ViewerInfo> 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<voelin_stream::LeaveReason> 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<voelin_stream::EndReason> 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<String> =
["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")]
+155
View File
@@ -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<u32>,
}
/// 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<LayerId>,
/// The latest bandwidth estimate of the connection (bit/s).
pub estimate: Option<u64>,
/// 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<String>,
/// The video codec the viewer's answer chose (it gets video in that
/// codec).
pub codec: Option<Codec>,
}
/// 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<LeaveReason>),
/// A command failed or no connection could be established.
Failed(String),
}
+1 -1
View File
@@ -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(())
}