Merge the audio mixer (86db9c5) into the FFmpeg encoders branch
Both add to StreamerConfig, the reconfigure docs and the imports of core media.rs and the UI's video.rs; kept both sides. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
commit
dd8b628909
49 files changed
+10283
-428
No files matched your search
@@ -3,18 +3,26 @@
|
||||
//!
|
||||
//! The voice task forwards stream notifications here and sends the resulting
|
||||
//! commands. Only started for TeamSpeak 6 servers.
|
||||
//!
|
||||
//! Streams that started before we joined are looked up on the server
|
||||
//! (`requeststreaminfo`) and in the session's gateway directory: its
|
||||
//! registered entries (stream id and streamer) are handed to the stream
|
||||
//! sessions ([`voelin_stream::Streams::discovered`]) for streamers in our
|
||||
//! channel, and a [`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.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
use tracing::debug;
|
||||
use tsclientlib::ClientId;
|
||||
use voelin_stream::{
|
||||
ClientState, LayerFeedback, Output, Request, StreamEvent, StreamNotification, StreamerEvent,
|
||||
StreamerOptions, Streams, WatchEvent,
|
||||
ClientState, LayerFeedback, Output, Request, StreamEvent, StreamLookup, StreamNotification,
|
||||
StreamerEvent, StreamerOptions, Streams, WatchEvent,
|
||||
};
|
||||
pub use voelin_stream::{
|
||||
Codec, EncodedFrame, EndReason, FrameSource, Frequency, LayerId, LayerSet, LayerSpec,
|
||||
@@ -159,10 +167,72 @@ pub(crate) enum StreamInput {
|
||||
RequestFailed(Request, String),
|
||||
/// Clients on the server: channel and `client_is_streaming`.
|
||||
Clients(BTreeMap<u16, ClientState>),
|
||||
/// The registered streams of the gateway's directory (full list).
|
||||
Directory(Vec<StreamInfo>),
|
||||
/// The voice connection is gone.
|
||||
Shutdown(String),
|
||||
}
|
||||
|
||||
/// Our own stream, for the session (the gateway directory).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum OwnStreamEvent {
|
||||
Live {
|
||||
id: String,
|
||||
title: String,
|
||||
kind: StreamKind,
|
||||
},
|
||||
/// Connected viewers.
|
||||
Viewers(u32),
|
||||
Ended {
|
||||
id: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// The kind of a stream as the gateway directory names it.
|
||||
pub(crate) fn kind_name(kind: StreamKind) -> String {
|
||||
match kind {
|
||||
StreamKind::Camera => "camera".into(),
|
||||
StreamKind::Screen => "screen".into(),
|
||||
StreamKind::Window => "window".into(),
|
||||
StreamKind::Other(v) => format!("other:{v}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`kind_name`] back; unknown names are screens.
|
||||
pub(crate) fn parse_kind(name: &str) -> StreamKind {
|
||||
match name {
|
||||
"camera" => StreamKind::Camera,
|
||||
"window" => StreamKind::Window,
|
||||
other => match other.strip_prefix("other:").and_then(|v| v.parse().ok()) {
|
||||
Some(v) => StreamKind::from_u8(v),
|
||||
None => StreamKind::Screen,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The gateway directory as the stream task sees it.
|
||||
#[derive(Default)]
|
||||
struct GatewayStreams {
|
||||
entries: Vec<StreamInfo>,
|
||||
/// Streamers the [`GatewayLookup`] was asked about.
|
||||
wanted: Vec<ClientId>,
|
||||
}
|
||||
|
||||
/// Looks unannounced streams up in the gateway's directory (after the
|
||||
/// server, see [`voelin_stream::discovery`]).
|
||||
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);
|
||||
if known {
|
||||
dir.wanted.push(streamer);
|
||||
}
|
||||
known
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct StreamHandle {
|
||||
tx: mpsc::UnboundedSender<StreamInput>,
|
||||
}
|
||||
@@ -178,11 +248,15 @@ impl StreamHandle {
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
audio: Option<AudioHandle>,
|
||||
settings: SharedSettings,
|
||||
own: mpsc::UnboundedSender<OwnStreamEvent>,
|
||||
) -> Self {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let mut streams = Streams::new(ClientId(own_client), config);
|
||||
let gateway = Arc::new(Mutex::new(GatewayStreams::default()));
|
||||
streams.add_lookup(Box::new(GatewayLookup(gateway.clone())));
|
||||
let task = StreamTask {
|
||||
session,
|
||||
streams: Streams::new(ClientId(own_client), config),
|
||||
streams,
|
||||
voice,
|
||||
events,
|
||||
frames,
|
||||
@@ -191,6 +265,12 @@ impl StreamHandle {
|
||||
sink: None,
|
||||
layers: Vec::new(),
|
||||
settings,
|
||||
own,
|
||||
setup: None,
|
||||
live: None,
|
||||
viewers: 0,
|
||||
clients: BTreeMap::new(),
|
||||
gateway,
|
||||
};
|
||||
tokio::spawn(task.run(rx));
|
||||
Self { tx }
|
||||
@@ -217,6 +297,17 @@ struct StreamTask {
|
||||
layers: Vec<LayerSpec>,
|
||||
/// `stream.permissions` decides join requests.
|
||||
settings: SharedSettings,
|
||||
/// Our stream's life, for the session.
|
||||
own: mpsc::UnboundedSender<OwnStreamEvent>,
|
||||
/// The setup of our stream since `Start`.
|
||||
setup: Option<StreamSetup>,
|
||||
/// Our live stream's id.
|
||||
live: Option<String>,
|
||||
/// Connected viewers of our stream, as last told.
|
||||
viewers: u32,
|
||||
/// The clients as of the last update.
|
||||
clients: BTreeMap<u16, ClientState>,
|
||||
gateway: Arc<Mutex<GatewayStreams>>,
|
||||
}
|
||||
|
||||
impl StreamTask {
|
||||
@@ -246,6 +337,7 @@ impl StreamTask {
|
||||
let session = self.session;
|
||||
let result = match input {
|
||||
StreamInput::Start { setup, auto_accept } => {
|
||||
self.setup = Some(setup.clone());
|
||||
let layers = self.layers.clone();
|
||||
let options = StreamerOptions { setup, auto_accept, layers, ..Default::default() };
|
||||
self.streams.start(options).map(|()| {
|
||||
@@ -297,7 +389,14 @@ impl StreamTask {
|
||||
StreamInput::Clients(clients) => {
|
||||
// Streams of clients that left, stopped streaming or are not
|
||||
// in our channel are gone; unannounced ones are looked up.
|
||||
self.clients = clients.clone();
|
||||
self.streams.update_clients(clients);
|
||||
self.add_directory_streams();
|
||||
Ok(())
|
||||
}
|
||||
StreamInput::Directory(entries) => {
|
||||
self.gateway.lock().unwrap_or_else(PoisonError::into_inner).entries = entries;
|
||||
self.add_directory_streams();
|
||||
Ok(())
|
||||
}
|
||||
StreamInput::Shutdown(_) => Ok(()),
|
||||
@@ -307,6 +406,30 @@ impl StreamTask {
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams of the gateway directory we were not told about: streamers in
|
||||
/// our channel that still stream (the sessions check the channel).
|
||||
fn add_directory_streams(&mut self) {
|
||||
let entries = {
|
||||
let mut dir = self.gateway.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
dir.wanted.clear();
|
||||
dir.entries.clone()
|
||||
};
|
||||
let own = self.streams.own_client();
|
||||
for info in entries {
|
||||
let stopped =
|
||||
self.clients.get(&info.streamer.0).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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn own_stream(&self, event: OwnStreamEvent) {
|
||||
let _ = self.own.send(event);
|
||||
}
|
||||
|
||||
/// Send the requests on the connection and report the events.
|
||||
fn flush(&mut self) {
|
||||
while let Some(output) = self.streams.poll_output() {
|
||||
@@ -334,6 +457,14 @@ impl StreamTask {
|
||||
feedback,
|
||||
};
|
||||
self.sink = Some(sink.clone());
|
||||
let setup = self.setup.clone().unwrap_or_default();
|
||||
self.live = Some(id.clone());
|
||||
self.viewers = 0;
|
||||
self.own_stream(OwnStreamEvent::Live {
|
||||
id: id.clone(),
|
||||
title: setup.name,
|
||||
kind: setup.kind,
|
||||
});
|
||||
self.emit(Event::StreamState { session, state: StreamState::Live { id, sink } });
|
||||
}
|
||||
StreamEvent::Streamer(StreamerEvent::Request { viewer, message }) => {
|
||||
@@ -356,6 +487,12 @@ impl StreamTask {
|
||||
}
|
||||
}
|
||||
StreamEvent::Streamer(StreamerEvent::Viewers(viewers)) => {
|
||||
let connected =
|
||||
viewers.iter().filter(|v| v.state == ViewerState::Connected).count() as u32;
|
||||
if connected != self.viewers && self.live.is_some() {
|
||||
self.viewers = connected;
|
||||
self.own_stream(OwnStreamEvent::Viewers(connected));
|
||||
}
|
||||
self.emit(Event::StreamViewers { session, viewers });
|
||||
}
|
||||
// The sink already has it (layer feedback).
|
||||
@@ -369,6 +506,9 @@ impl StreamTask {
|
||||
if let Some(sink) = self.sink.take() {
|
||||
sink.live.store(false, Ordering::Relaxed);
|
||||
}
|
||||
if let Some(id) = self.live.take() {
|
||||
self.own_stream(OwnStreamEvent::Ended { id });
|
||||
}
|
||||
self.emit(Event::StreamState { session, state: StreamState::Ended(reason) });
|
||||
}
|
||||
StreamEvent::Watch { id, event } => {
|
||||
@@ -423,6 +563,9 @@ impl StreamTask {
|
||||
if let Some(sink) = self.sink.take() {
|
||||
sink.live.store(false, Ordering::Relaxed);
|
||||
}
|
||||
if let Some(id) = self.live.take() {
|
||||
self.own_stream(OwnStreamEvent::Ended { id });
|
||||
}
|
||||
for watched in self.streams.watching() {
|
||||
let stream_id = watched.id().to_owned();
|
||||
if let Some(audio) = &self.audio {
|
||||
@@ -539,6 +682,25 @@ mod tests {
|
||||
audio: Option<AudioHandle>,
|
||||
settings: &Settings,
|
||||
) -> (Handles, broadcast::Receiver<Event>, broadcast::Receiver<StreamFrame>) {
|
||||
let (handles, rx, frames, _) = pair_full(audio, settings, false);
|
||||
(handles, rx, frames)
|
||||
}
|
||||
|
||||
/// [`pair_with`]; with `late`, the server does not tell the viewer
|
||||
/// (session 2) about streams, as for a client that joined after the
|
||||
/// stream started, and does not answer lookups. Also returns what the
|
||||
/// streamer (session 1) reports about its own stream.
|
||||
fn pair_full(
|
||||
audio: Option<AudioHandle>,
|
||||
settings: &Settings,
|
||||
late: bool,
|
||||
) -> (
|
||||
Handles,
|
||||
broadcast::Receiver<Event>,
|
||||
broadcast::Receiver<StreamFrame>,
|
||||
mpsc::UnboundedReceiver<OwnStreamEvent>,
|
||||
) {
|
||||
let (own_tx, own_rx) = mpsc::unbounded_channel();
|
||||
let (events, rx) = broadcast::channel(4096);
|
||||
let (frames, frames_rx) = broadcast::channel(4096);
|
||||
let mut voices = Vec::new();
|
||||
@@ -557,6 +719,7 @@ mod tests {
|
||||
frames.clone(),
|
||||
if session == 2 { audio.take() } else { None },
|
||||
SharedSettings::new(settings.clone()),
|
||||
if session == 1 { own_tx.clone() } else { mpsc::unbounded_channel().0 },
|
||||
));
|
||||
voices.push(voice_rx);
|
||||
}
|
||||
@@ -568,6 +731,10 @@ mod tests {
|
||||
while let Some(cmd) = voice_rx.recv().await {
|
||||
if let VoiceCmd::Stream(request) = cmd {
|
||||
for (to, n) in relay(CLIENTS[i], request) {
|
||||
let announcement = matches!(n, StreamNotification::Started { .. });
|
||||
if late && to == CLIENTS[1] && announcement {
|
||||
continue;
|
||||
}
|
||||
let index = CLIENTS.iter().position(|c| *c == to).unwrap();
|
||||
handles[index].send(StreamInput::Notification(n));
|
||||
}
|
||||
@@ -575,7 +742,7 @@ mod tests {
|
||||
}
|
||||
});
|
||||
}
|
||||
(handles, rx, frames_rx)
|
||||
(handles, rx, frames_rx, own_rx)
|
||||
}
|
||||
|
||||
/// Session 1 streams (auto-accepting), session 2 watches; returns the sink
|
||||
@@ -754,6 +921,92 @@ mod tests {
|
||||
feeder.await.unwrap();
|
||||
}
|
||||
|
||||
/// A viewer that was not told about a running stream, and whose server
|
||||
/// lookup goes unanswered, finds it in the gateway directory and
|
||||
/// watches it; the streamer reports its stream's life for the directory.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn late_viewer_finds_the_stream_in_the_gateway_directory() {
|
||||
let (handles, mut rx, _frames, mut own) = pair_full(None, &Settings::in_memory(), true);
|
||||
let setup = StreamSetup {
|
||||
name: "directory test".into(),
|
||||
kind: StreamKind::Window,
|
||||
..Default::default()
|
||||
};
|
||||
handles[0].send(StreamInput::Start { setup, auto_accept: true });
|
||||
wait(&mut rx, |e| match e {
|
||||
Event::StreamState { session: 1, state: StreamState::Live { .. } } => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
let live = timeout(Duration::from_secs(5), own.recv()).await.unwrap().unwrap();
|
||||
assert_eq!(
|
||||
live,
|
||||
OwnStreamEvent::Live {
|
||||
id: "s-1".into(),
|
||||
title: "directory test".into(),
|
||||
kind: StreamKind::Window
|
||||
}
|
||||
);
|
||||
// Both in channel 1, the streamer streaming: the viewer asks the
|
||||
// server, which does not answer.
|
||||
let clients = BTreeMap::from([
|
||||
(CLIENTS[0], ClientState { channel: 1, streaming: Some(true) }),
|
||||
(CLIENTS[1], ClientState { channel: 1, streaming: Some(false) }),
|
||||
]);
|
||||
handles[1].send(StreamInput::Clients(clients));
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
// The gateway's directory has it.
|
||||
let entry = StreamInfo {
|
||||
id: "s-1".into(),
|
||||
streamer: ClientId(CLIENTS[0]),
|
||||
name: "directory test".into(),
|
||||
kind: parse_kind(&kind_name(StreamKind::Window)),
|
||||
bitrate: 0,
|
||||
viewer_limit: 0,
|
||||
audio: true,
|
||||
};
|
||||
handles[1].send(StreamInput::Directory(vec![entry]));
|
||||
wait(&mut rx, |e| match e {
|
||||
Event::StreamsChanged { session: 2, streams }
|
||||
if streams.iter().any(|s| s.id == "s-1") =>
|
||||
{
|
||||
Some(())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
handles[1].send(StreamInput::Watch { stream_id: "s-1".into() });
|
||||
wait(&mut rx, |e| match e {
|
||||
Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
// One connected viewer, then the end.
|
||||
let viewers = timeout(Duration::from_secs(5), own.recv()).await.unwrap().unwrap();
|
||||
assert_eq!(viewers, OwnStreamEvent::Viewers(1));
|
||||
handles[0].send(StreamInput::Stop);
|
||||
loop {
|
||||
match timeout(Duration::from_secs(5), own.recv()).await.unwrap().unwrap() {
|
||||
OwnStreamEvent::Ended { id } => break assert_eq!(id, "s-1"),
|
||||
OwnStreamEvent::Viewers(_) => {}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
for h in handles.iter() {
|
||||
h.send(StreamInput::Shutdown("done".into()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kind_names_round_trip() {
|
||||
for kind in
|
||||
[StreamKind::Camera, StreamKind::Screen, StreamKind::Window, StreamKind::Other(9)]
|
||||
{
|
||||
assert_eq!(parse_kind(&kind_name(kind)), kind);
|
||||
}
|
||||
assert_eq!(parse_kind("game"), StreamKind::Screen);
|
||||
}
|
||||
|
||||
/// `stream.permissions` answers join requests unless it is `friends`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn permissions_answer_join_requests() {
|
||||
|
||||
Reference in new issue
Block a user