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

+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")]