tsc-core: streams on TeamSpeak 6 sessions
A stream task per voice connection runs tsc-stream's Streams: the voice
task forwards stream notifications and command failures to it and sends
its requests on the connection. It starts only when the server flavor has
the streams capability; stream commands elsewhere give an Error event.
Commands: StartStream{setup, auto_accept}, StopStream, AcceptViewer,
KickViewer, SendStreamFrame, WatchStream, LeaveStream,
RequestStreamKeyframe.
Events: StreamsChanged, StreamState (Starting / Live{id, sink} /
Ended), StreamViewerRequest, StreamViewers, StreamKeyframeRequest,
WatchState (Requested / Connecting / Connected / Ended).
Encoded frames of our stream go in through the StreamSink handed out
with StreamState::Live (or SendStreamFrame); received frames of watched
streams come on their own bus, Engine::subscribe_frames, to keep the
event bus light. VoiceOptions::stream_peer sets the peer network config.
Tests: two stream tasks through a fake relay server (unit), and a
TSC_LIVE test with two engine sessions streaming synthetic frames on the
TS6 dev server plus the error on TS3.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
1 parent
23fbbf0221
commit
43879fec40
7 files changed
+996
-12
No files matched your search
Generated
+1
@@ -8265,6 +8265,7 @@ dependencies = [
|
|||||||
"tsc-model",
|
"tsc-model",
|
||||||
"tsc-observer",
|
"tsc-observer",
|
||||||
"tsc-query",
|
"tsc-query",
|
||||||
|
"tsc-stream",
|
||||||
"tsclientlib",
|
"tsclientlib",
|
||||||
"tsproto-packets",
|
"tsproto-packets",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ tsc-gateway-proto = { path = "../tsc-gateway-proto" }
|
|||||||
tsc-model = { path = "../tsc-model" }
|
tsc-model = { path = "../tsc-model" }
|
||||||
tsc-observer = { path = "../tsc-observer" }
|
tsc-observer = { path = "../tsc-observer" }
|
||||||
tsc-query = { path = "../tsc-query" }
|
tsc-query = { path = "../tsc-query" }
|
||||||
|
tsc-stream = { path = "../tsc-stream" }
|
||||||
tsclientlib = { path = "../proto/tsclientlib" }
|
tsclientlib = { path = "../proto/tsclientlib" }
|
||||||
tsproto-packets = { path = "../proto/tsproto-packets" }
|
tsproto-packets = { path = "../proto/tsproto-packets" }
|
||||||
|
|
||||||
|
|||||||
+105
-4
@@ -10,12 +10,17 @@
|
|||||||
//! Presence comes from the most authoritative connected source
|
//! Presence comes from the most authoritative connected source
|
||||||
//! (voice > gateway > query). Channel chat goes through the voice connection
|
//! (voice > gateway > query). Channel chat goes through the voice connection
|
||||||
//! when the user is in that channel, otherwise through a relay.
|
//! when the user is in that channel, otherwise through a relay.
|
||||||
|
//!
|
||||||
|
//! On TeamSpeak 6 servers the voice connection also carries streams (screen
|
||||||
|
//! sharing): see the `*Stream*` commands and events, and
|
||||||
|
//! [`Engine::subscribe_frames`] for the frames of watched streams.
|
||||||
|
|
||||||
mod audio;
|
mod audio;
|
||||||
mod gateway;
|
mod gateway;
|
||||||
mod query;
|
mod query;
|
||||||
mod route;
|
mod route;
|
||||||
mod session;
|
mod session;
|
||||||
|
pub mod stream;
|
||||||
mod voice;
|
mod voice;
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -25,6 +30,8 @@ use tokio::sync::{broadcast, mpsc};
|
|||||||
use tsc_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
|
use tsc_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
|
||||||
|
|
||||||
pub use route::{ChatRoute, Dedup, route_chat};
|
pub use route::{ChatRoute, Dedup, route_chat};
|
||||||
|
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
|
||||||
|
use tsc_stream::{EncodedFrame, StreamInfo, StreamSetup, ViewerInfo};
|
||||||
pub use voice::VoiceOptions;
|
pub use voice::VoiceOptions;
|
||||||
|
|
||||||
pub type SessionId = u64;
|
pub type SessionId = u64;
|
||||||
@@ -84,6 +91,49 @@ pub enum Command {
|
|||||||
session: SessionId,
|
session: SessionId,
|
||||||
on: bool,
|
on: bool,
|
||||||
},
|
},
|
||||||
|
/// Start streaming in our channel (TeamSpeak 6 only). Progress comes as
|
||||||
|
/// [`Event::StreamState`]; frames go in through the sink of
|
||||||
|
/// [`StreamState::Live`] or [`Command::SendStreamFrame`].
|
||||||
|
StartStream {
|
||||||
|
session: SessionId,
|
||||||
|
setup: StreamSetup,
|
||||||
|
/// Accept every viewer instead of asking with [`Event::StreamViewerRequest`].
|
||||||
|
auto_accept: bool,
|
||||||
|
},
|
||||||
|
StopStream {
|
||||||
|
session: SessionId,
|
||||||
|
},
|
||||||
|
/// Answer an [`Event::StreamViewerRequest`].
|
||||||
|
AcceptViewer {
|
||||||
|
session: SessionId,
|
||||||
|
viewer: u16,
|
||||||
|
accept: bool,
|
||||||
|
},
|
||||||
|
/// Remove a viewer from our stream.
|
||||||
|
KickViewer {
|
||||||
|
session: SessionId,
|
||||||
|
viewer: u16,
|
||||||
|
},
|
||||||
|
/// An encoded frame for our stream.
|
||||||
|
SendStreamFrame {
|
||||||
|
session: SessionId,
|
||||||
|
frame: EncodedFrame,
|
||||||
|
},
|
||||||
|
/// Watch a stream from [`Event::StreamsChanged`]. Frames arrive through
|
||||||
|
/// [`Engine::subscribe_frames`].
|
||||||
|
WatchStream {
|
||||||
|
session: SessionId,
|
||||||
|
stream_id: String,
|
||||||
|
},
|
||||||
|
LeaveStream {
|
||||||
|
session: SessionId,
|
||||||
|
stream_id: String,
|
||||||
|
},
|
||||||
|
/// Ask the streamer of a watched stream for a keyframe.
|
||||||
|
RequestStreamKeyframe {
|
||||||
|
session: SessionId,
|
||||||
|
stream_id: String,
|
||||||
|
},
|
||||||
/// Close everything of a session.
|
/// Close everything of a session.
|
||||||
CloseSession {
|
CloseSession {
|
||||||
session: SessionId,
|
session: SessionId,
|
||||||
@@ -159,6 +209,37 @@ pub enum Event {
|
|||||||
session: SessionId,
|
session: SessionId,
|
||||||
message: String,
|
message: String,
|
||||||
},
|
},
|
||||||
|
/// The streams in our channel (TeamSpeak 6), full list.
|
||||||
|
StreamsChanged {
|
||||||
|
session: SessionId,
|
||||||
|
streams: Vec<StreamInfo>,
|
||||||
|
},
|
||||||
|
/// Our own stream.
|
||||||
|
StreamState {
|
||||||
|
session: SessionId,
|
||||||
|
state: StreamState,
|
||||||
|
},
|
||||||
|
/// Someone asks to watch our stream; answer with [`Command::AcceptViewer`].
|
||||||
|
StreamViewerRequest {
|
||||||
|
session: SessionId,
|
||||||
|
viewer: u16,
|
||||||
|
message: String,
|
||||||
|
},
|
||||||
|
/// The viewers of our stream and their state, full list.
|
||||||
|
StreamViewers {
|
||||||
|
session: SessionId,
|
||||||
|
viewers: Vec<ViewerInfo>,
|
||||||
|
},
|
||||||
|
/// A viewer needs a keyframe (also flagged on the [`StreamSink`]).
|
||||||
|
StreamKeyframeRequest {
|
||||||
|
session: SessionId,
|
||||||
|
},
|
||||||
|
/// A stream we watch.
|
||||||
|
WatchState {
|
||||||
|
session: SessionId,
|
||||||
|
stream_id: String,
|
||||||
|
state: WatchState,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle to the engine. Cheap to clone; all methods are non-blocking.
|
/// Handle to the engine. Cheap to clone; all methods are non-blocking.
|
||||||
@@ -166,6 +247,7 @@ pub enum Event {
|
|||||||
pub struct Engine {
|
pub struct Engine {
|
||||||
commands: mpsc::UnboundedSender<Command>,
|
commands: mpsc::UnboundedSender<Command>,
|
||||||
events: broadcast::Sender<Event>,
|
events: broadcast::Sender<Event>,
|
||||||
|
frames: broadcast::Sender<StreamFrame>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Engine {
|
impl Engine {
|
||||||
@@ -173,8 +255,10 @@ impl Engine {
|
|||||||
pub fn start() -> Self {
|
pub fn start() -> Self {
|
||||||
let (commands, rx) = mpsc::unbounded_channel();
|
let (commands, rx) = mpsc::unbounded_channel();
|
||||||
let (events, _) = broadcast::channel(4096);
|
let (events, _) = broadcast::channel(4096);
|
||||||
tokio::spawn(run(rx, events.clone()));
|
// About a minute of one watched stream.
|
||||||
Self { commands, events }
|
let (frames, _) = broadcast::channel(4096);
|
||||||
|
tokio::spawn(run(rx, events.clone(), frames.clone()));
|
||||||
|
Self { commands, events, frames }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn send(&self, command: Command) {
|
pub fn send(&self, command: Command) {
|
||||||
@@ -184,9 +268,18 @@ impl Engine {
|
|||||||
pub fn subscribe(&self) -> broadcast::Receiver<Event> {
|
pub fn subscribe(&self) -> broadcast::Receiver<Event> {
|
||||||
self.events.subscribe()
|
self.events.subscribe()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Encoded frames of the streams we watch (kept off the event bus).
|
||||||
|
pub fn subscribe_frames(&self) -> broadcast::Receiver<StreamFrame> {
|
||||||
|
self.frames.subscribe()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn run(mut commands: mpsc::UnboundedReceiver<Command>, events: broadcast::Sender<Event>) {
|
async fn run(
|
||||||
|
mut commands: mpsc::UnboundedReceiver<Command>,
|
||||||
|
events: broadcast::Sender<Event>,
|
||||||
|
frames: broadcast::Sender<StreamFrame>,
|
||||||
|
) {
|
||||||
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
|
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
|
||||||
while let Some(command) = commands.recv().await {
|
while let Some(command) = commands.recv().await {
|
||||||
let id = command_session(&command);
|
let id = command_session(&command);
|
||||||
@@ -198,7 +291,7 @@ async fn run(mut commands: mpsc::UnboundedReceiver<Command>, events: broadcast::
|
|||||||
}
|
}
|
||||||
sessions
|
sessions
|
||||||
.entry(id)
|
.entry(id)
|
||||||
.or_insert_with(|| session::SessionHandle::spawn(id, events.clone()))
|
.or_insert_with(|| session::SessionHandle::spawn(id, events.clone(), frames.clone()))
|
||||||
.send(command);
|
.send(command);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -217,6 +310,14 @@ fn command_session(command: &Command) -> SessionId {
|
|||||||
| Command::SetInputMuted { session, .. }
|
| Command::SetInputMuted { session, .. }
|
||||||
| Command::SetOutputMuted { session, .. }
|
| Command::SetOutputMuted { session, .. }
|
||||||
| Command::SetTransmitting { session, .. }
|
| Command::SetTransmitting { session, .. }
|
||||||
|
| Command::StartStream { session, .. }
|
||||||
|
| Command::StopStream { session }
|
||||||
|
| Command::AcceptViewer { session, .. }
|
||||||
|
| Command::KickViewer { session, .. }
|
||||||
|
| Command::SendStreamFrame { session, .. }
|
||||||
|
| Command::WatchStream { session, .. }
|
||||||
|
| Command::LeaveStream { session, .. }
|
||||||
|
| Command::RequestStreamKeyframe { session, .. }
|
||||||
| Command::CloseSession { session } => *session,
|
| Command::CloseSession { session } => *session,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
//! One server session: merges its sources and routes commands.
|
//! One server session: merges its sources and routes commands.
|
||||||
|
|
||||||
use std::collections::HashSet;
|
use std::collections::{BTreeMap, HashSet};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use tokio::sync::{broadcast, mpsc};
|
use tokio::sync::{broadcast, mpsc};
|
||||||
@@ -11,6 +11,7 @@ use crate::audio::{self, AudioHandle, AudioIn};
|
|||||||
use crate::gateway::{self, GatewayCmd, GatewayEvent};
|
use crate::gateway::{self, GatewayCmd, GatewayEvent};
|
||||||
use crate::query::{self, QueryCmd, QueryEvent};
|
use crate::query::{self, QueryCmd, QueryEvent};
|
||||||
use crate::route::{ChatRoute, Dedup, route_chat};
|
use crate::route::{ChatRoute, Dedup, route_chat};
|
||||||
|
use crate::stream::{PeerConfig, StreamFrame, StreamHandle, StreamInput};
|
||||||
use crate::voice::{self, VoiceCmd, VoiceEvent};
|
use crate::voice::{self, VoiceCmd, VoiceEvent};
|
||||||
use crate::{Command, Event, ObserveState, SessionId, SessionState, Source, VoiceState};
|
use crate::{Command, Event, ObserveState, SessionId, SessionState, Source, VoiceState};
|
||||||
|
|
||||||
@@ -19,9 +20,13 @@ pub(crate) struct SessionHandle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl SessionHandle {
|
impl SessionHandle {
|
||||||
pub fn spawn(id: SessionId, events: broadcast::Sender<Event>) -> Self {
|
pub fn spawn(
|
||||||
|
id: SessionId,
|
||||||
|
events: broadcast::Sender<Event>,
|
||||||
|
frames: broadcast::Sender<StreamFrame>,
|
||||||
|
) -> Self {
|
||||||
let (tx, rx) = mpsc::unbounded_channel();
|
let (tx, rx) = mpsc::unbounded_channel();
|
||||||
tokio::spawn(Session::new(id, events).run(rx));
|
tokio::spawn(Session::new(id, events, frames).run(rx));
|
||||||
Self { tx }
|
Self { tx }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,6 +58,12 @@ struct Session {
|
|||||||
query: Option<(u64, mpsc::UnboundedSender<QueryCmd>)>,
|
query: Option<(u64, mpsc::UnboundedSender<QueryCmd>)>,
|
||||||
query_presence: Option<Presence>,
|
query_presence: Option<Presence>,
|
||||||
audio: Option<AudioHandle>,
|
audio: Option<AudioHandle>,
|
||||||
|
/// Streams of the voice connection (TeamSpeak 6 only).
|
||||||
|
streams: Option<StreamHandle>,
|
||||||
|
stream_peer: PeerConfig,
|
||||||
|
frames: broadcast::Sender<StreamFrame>,
|
||||||
|
/// `client_is_streaming` of the voice presence, as last told to the streams.
|
||||||
|
streaming_clients: BTreeMap<u16, Option<bool>>,
|
||||||
open_chats: HashSet<ChatTarget>,
|
open_chats: HashSet<ChatTarget>,
|
||||||
dedup: Dedup,
|
dedup: Dedup,
|
||||||
sources_tx: mpsc::UnboundedSender<SourceEvent>,
|
sources_tx: mpsc::UnboundedSender<SourceEvent>,
|
||||||
@@ -60,7 +71,11 @@ struct Session {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Session {
|
impl Session {
|
||||||
fn new(id: SessionId, events: broadcast::Sender<Event>) -> Self {
|
fn new(
|
||||||
|
id: SessionId,
|
||||||
|
events: broadcast::Sender<Event>,
|
||||||
|
frames: broadcast::Sender<StreamFrame>,
|
||||||
|
) -> Self {
|
||||||
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
|
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
|
||||||
Self {
|
Self {
|
||||||
id,
|
id,
|
||||||
@@ -75,6 +90,10 @@ impl Session {
|
|||||||
query: None,
|
query: None,
|
||||||
query_presence: None,
|
query_presence: None,
|
||||||
audio: None,
|
audio: None,
|
||||||
|
streams: None,
|
||||||
|
stream_peer: PeerConfig::default(),
|
||||||
|
frames,
|
||||||
|
streaming_clients: BTreeMap::new(),
|
||||||
open_chats: HashSet::new(),
|
open_chats: HashSet::new(),
|
||||||
dedup: Dedup::default(),
|
dedup: Dedup::default(),
|
||||||
sources_tx,
|
sources_tx,
|
||||||
@@ -135,8 +154,10 @@ impl Session {
|
|||||||
if let Some((_, tx)) = self.voice.take() {
|
if let Some((_, tx)) = self.voice.take() {
|
||||||
let _ = tx.send(VoiceCmd::Disconnect);
|
let _ = tx.send(VoiceCmd::Disconnect);
|
||||||
}
|
}
|
||||||
|
self.stop_streams("voice reconnecting");
|
||||||
let generation = self.next_generation();
|
let generation = self.next_generation();
|
||||||
self.nickname = options.nickname.clone();
|
self.nickname = options.nickname.clone();
|
||||||
|
self.stream_peer = options.stream_peer.clone();
|
||||||
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
|
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
|
||||||
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
|
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
|
||||||
if options.audio {
|
if options.audio {
|
||||||
@@ -243,10 +264,50 @@ impl Session {
|
|||||||
}
|
}
|
||||||
self.emit_state();
|
self.emit_state();
|
||||||
}
|
}
|
||||||
|
Command::StartStream { setup, auto_accept, .. } => {
|
||||||
|
self.stream_input(StreamInput::Start { setup, auto_accept });
|
||||||
|
}
|
||||||
|
Command::StopStream { .. } => self.stream_input(StreamInput::Stop),
|
||||||
|
Command::AcceptViewer { viewer, accept, .. } => {
|
||||||
|
self.stream_input(StreamInput::Respond { viewer, accept });
|
||||||
|
}
|
||||||
|
Command::KickViewer { viewer, .. } => self.stream_input(StreamInput::Kick { viewer }),
|
||||||
|
Command::SendStreamFrame { frame, .. } => {
|
||||||
|
// Frames without a stream are dropped silently.
|
||||||
|
if let Some(s) = &self.streams {
|
||||||
|
s.send(StreamInput::Frame(frame));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::WatchStream { stream_id, .. } => {
|
||||||
|
self.stream_input(StreamInput::Watch { stream_id });
|
||||||
|
}
|
||||||
|
Command::LeaveStream { stream_id, .. } => {
|
||||||
|
self.stream_input(StreamInput::Leave { stream_id });
|
||||||
|
}
|
||||||
|
Command::RequestStreamKeyframe { stream_id, .. } => {
|
||||||
|
self.stream_input(StreamInput::RequestKeyframe { stream_id });
|
||||||
|
}
|
||||||
Command::CloseSession { .. } => {}
|
Command::CloseSession { .. } => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn stream_input(&self, input: StreamInput) {
|
||||||
|
match &self.streams {
|
||||||
|
Some(s) => s.send(input),
|
||||||
|
None if self.state.voice == VoiceState::Connected => {
|
||||||
|
self.error("streams need a TeamSpeak 6 server");
|
||||||
|
}
|
||||||
|
None => self.error("not connected with voice"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stop_streams(&mut self, reason: &str) {
|
||||||
|
if let Some(s) = self.streams.take() {
|
||||||
|
s.send(StreamInput::Shutdown(reason.into()));
|
||||||
|
}
|
||||||
|
self.streaming_clients.clear();
|
||||||
|
}
|
||||||
|
|
||||||
fn voice_cmd(&self, cmd: VoiceCmd) {
|
fn voice_cmd(&self, cmd: VoiceCmd) {
|
||||||
match &self.voice {
|
match &self.voice {
|
||||||
Some((_, tx)) => {
|
Some((_, tx)) => {
|
||||||
@@ -299,6 +360,7 @@ impl Session {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn stop_all(&mut self) {
|
fn stop_all(&mut self) {
|
||||||
|
self.stop_streams("session closed");
|
||||||
if let Some((_, tx)) = self.voice.take() {
|
if let Some((_, tx)) = self.voice.take() {
|
||||||
let _ = tx.send(VoiceCmd::Disconnect);
|
let _ = tx.send(VoiceCmd::Disconnect);
|
||||||
}
|
}
|
||||||
@@ -334,17 +396,47 @@ impl Session {
|
|||||||
|
|
||||||
fn voice_event(&mut self, e: VoiceEvent) {
|
fn voice_event(&mut self, e: VoiceEvent) {
|
||||||
match e {
|
match e {
|
||||||
VoiceEvent::Connected { name, flavor } => {
|
VoiceEvent::Connected { name, flavor, own_client } => {
|
||||||
self.state.voice = VoiceState::Connected;
|
self.state.voice = VoiceState::Connected;
|
||||||
self.emit_state();
|
self.emit_state();
|
||||||
let capabilities = flavor.capabilities();
|
let capabilities = flavor.capabilities();
|
||||||
|
if capabilities.streams
|
||||||
|
&& let Some((_, voice)) = &self.voice
|
||||||
|
{
|
||||||
|
self.streams = Some(StreamHandle::spawn(
|
||||||
|
self.id,
|
||||||
|
own_client,
|
||||||
|
self.stream_peer.clone(),
|
||||||
|
voice.clone(),
|
||||||
|
self.events.clone(),
|
||||||
|
self.frames.clone(),
|
||||||
|
));
|
||||||
|
}
|
||||||
self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities });
|
self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities });
|
||||||
self.reopen_relayed_chats();
|
self.reopen_relayed_chats();
|
||||||
}
|
}
|
||||||
VoiceEvent::Presence(p) => {
|
VoiceEvent::Presence(p) => {
|
||||||
|
if let Some(s) = &self.streams {
|
||||||
|
let clients: BTreeMap<_, _> =
|
||||||
|
p.clients.values().map(|c| (c.id, c.streaming)).collect();
|
||||||
|
if clients != self.streaming_clients {
|
||||||
|
self.streaming_clients = clients.clone();
|
||||||
|
s.send(StreamInput::Clients(clients));
|
||||||
|
}
|
||||||
|
}
|
||||||
self.voice_presence = Some(p);
|
self.voice_presence = Some(p);
|
||||||
self.publish_presence();
|
self.publish_presence();
|
||||||
}
|
}
|
||||||
|
VoiceEvent::Stream(n) => {
|
||||||
|
if let Some(s) = &self.streams {
|
||||||
|
s.send(StreamInput::Notification(n));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
VoiceEvent::StreamRequestFailed(request, error) => {
|
||||||
|
if let Some(s) = &self.streams {
|
||||||
|
s.send(StreamInput::RequestFailed(request, error));
|
||||||
|
}
|
||||||
|
}
|
||||||
VoiceEvent::OwnChannel(cid) => {
|
VoiceEvent::OwnChannel(cid) => {
|
||||||
if self.state.own_channel != Some(cid) {
|
if self.state.own_channel != Some(cid) {
|
||||||
self.state.own_channel = Some(cid);
|
self.state.own_channel = Some(cid);
|
||||||
@@ -361,6 +453,7 @@ impl Session {
|
|||||||
self.emit(Event::Talking { session: self.id, client, talking });
|
self.emit(Event::Talking { session: self.id, client, talking });
|
||||||
}
|
}
|
||||||
VoiceEvent::Disconnected(reason) => {
|
VoiceEvent::Disconnected(reason) => {
|
||||||
|
self.stop_streams("voice disconnected");
|
||||||
self.voice = None;
|
self.voice = None;
|
||||||
self.voice_presence = None;
|
self.voice_presence = None;
|
||||||
self.audio = None;
|
self.audio = None;
|
||||||
|
|||||||
@@ -0,0 +1,530 @@
|
|||||||
|
//! TeamSpeak 6 streams of a session: a task that runs the stream sessions
|
||||||
|
//! ([`tsc_stream::Streams`]) of the voice connection.
|
||||||
|
//!
|
||||||
|
//! The voice task forwards stream notifications here and sends the resulting
|
||||||
|
//! commands. Only started for TeamSpeak 6 servers.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::fmt;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
|
||||||
|
use tokio::sync::{broadcast, mpsc};
|
||||||
|
use tracing::debug;
|
||||||
|
pub use tsc_stream::{
|
||||||
|
Codec, EncodedFrame, EndReason, FrameSource, Frequency, LeaveReason, MediaFrame, MediaKind,
|
||||||
|
MediaTime, PeerConfig, StreamInfo, StreamKind, StreamSetup, SyntheticSource, VideoCodec,
|
||||||
|
ViewerInfo, ViewerState,
|
||||||
|
};
|
||||||
|
use tsc_stream::{
|
||||||
|
Output, Request, StreamEvent, StreamNotification, StreamerEvent, StreamerOptions, Streams,
|
||||||
|
WatchEvent,
|
||||||
|
};
|
||||||
|
use tsclientlib::ClientId;
|
||||||
|
|
||||||
|
use crate::voice::VoiceCmd;
|
||||||
|
use crate::{Event, SessionId};
|
||||||
|
|
||||||
|
/// Our own stream.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum StreamState {
|
||||||
|
/// `setupstream` sent.
|
||||||
|
Starting,
|
||||||
|
/// Live: frames given to `sink` (or [`crate::Command::SendStreamFrame`])
|
||||||
|
/// reach every connected viewer.
|
||||||
|
Live {
|
||||||
|
id: String,
|
||||||
|
sink: StreamSink,
|
||||||
|
},
|
||||||
|
Ended(EndReason),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A stream we watch.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum WatchState {
|
||||||
|
/// Join request sent; waiting for the streamer.
|
||||||
|
Requested,
|
||||||
|
/// Accepted; connecting to the streamer.
|
||||||
|
Connecting,
|
||||||
|
/// Frames arrive through [`crate::Engine::subscribe_frames`].
|
||||||
|
Connected,
|
||||||
|
Ended(EndReason),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A received frame of a watched stream.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct StreamFrame {
|
||||||
|
pub session: SessionId,
|
||||||
|
pub stream_id: String,
|
||||||
|
pub frame: MediaFrame,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hands encoded frames of our stream to the engine, e.g. from an encoder thread.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct StreamSink {
|
||||||
|
tx: mpsc::UnboundedSender<StreamInput>,
|
||||||
|
live: Arc<AtomicBool>,
|
||||||
|
keyframe: Arc<AtomicBool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StreamSink {
|
||||||
|
/// Send one frame; `false` once the stream has ended.
|
||||||
|
pub fn send(&self, frame: EncodedFrame) -> bool {
|
||||||
|
self.live.load(Ordering::Relaxed) && self.tx.send(StreamInput::Frame(frame)).is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a viewer asked for a keyframe since the last call.
|
||||||
|
pub fn take_keyframe_request(&self) -> bool {
|
||||||
|
self.keyframe.swap(false, Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_live(&self) -> bool {
|
||||||
|
self.live.load(Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for StreamSink {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("StreamSink").field("live", &self.is_live()).finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for StreamSink {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
Arc::ptr_eq(&self.live, &other.live)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) enum StreamInput {
|
||||||
|
Start {
|
||||||
|
setup: StreamSetup,
|
||||||
|
auto_accept: bool,
|
||||||
|
},
|
||||||
|
Stop,
|
||||||
|
Respond {
|
||||||
|
viewer: u16,
|
||||||
|
accept: bool,
|
||||||
|
},
|
||||||
|
Kick {
|
||||||
|
viewer: u16,
|
||||||
|
},
|
||||||
|
Watch {
|
||||||
|
stream_id: String,
|
||||||
|
},
|
||||||
|
Leave {
|
||||||
|
stream_id: String,
|
||||||
|
},
|
||||||
|
RequestKeyframe {
|
||||||
|
stream_id: String,
|
||||||
|
},
|
||||||
|
Frame(EncodedFrame),
|
||||||
|
Notification(StreamNotification),
|
||||||
|
RequestFailed(Request, String),
|
||||||
|
/// Clients on the server with their `client_is_streaming`.
|
||||||
|
Clients(BTreeMap<u16, Option<bool>>),
|
||||||
|
/// The voice connection is gone.
|
||||||
|
Shutdown(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct StreamHandle {
|
||||||
|
tx: mpsc::UnboundedSender<StreamInput>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StreamHandle {
|
||||||
|
pub fn spawn(
|
||||||
|
session: SessionId,
|
||||||
|
own_client: u16,
|
||||||
|
config: PeerConfig,
|
||||||
|
voice: mpsc::UnboundedSender<VoiceCmd>,
|
||||||
|
events: broadcast::Sender<Event>,
|
||||||
|
frames: broadcast::Sender<StreamFrame>,
|
||||||
|
) -> Self {
|
||||||
|
let (tx, rx) = mpsc::unbounded_channel();
|
||||||
|
let task = StreamTask {
|
||||||
|
session,
|
||||||
|
streams: Streams::new(ClientId(own_client), config),
|
||||||
|
voice,
|
||||||
|
events,
|
||||||
|
frames,
|
||||||
|
tx: tx.clone(),
|
||||||
|
sink: None,
|
||||||
|
clients: BTreeMap::new(),
|
||||||
|
};
|
||||||
|
tokio::spawn(task.run(rx));
|
||||||
|
Self { tx }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send(&self, input: StreamInput) {
|
||||||
|
let _ = self.tx.send(input);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct StreamTask {
|
||||||
|
session: SessionId,
|
||||||
|
streams: Streams,
|
||||||
|
voice: mpsc::UnboundedSender<VoiceCmd>,
|
||||||
|
events: broadcast::Sender<Event>,
|
||||||
|
frames: broadcast::Sender<StreamFrame>,
|
||||||
|
/// For the sinks handed out.
|
||||||
|
tx: mpsc::UnboundedSender<StreamInput>,
|
||||||
|
/// The sink of our live stream.
|
||||||
|
sink: Option<StreamSink>,
|
||||||
|
/// Clients on the server and their `client_is_streaming`.
|
||||||
|
clients: BTreeMap<u16, Option<bool>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StreamTask {
|
||||||
|
async fn run(mut self, mut rx: mpsc::UnboundedReceiver<StreamInput>) {
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
input = rx.recv() => match input {
|
||||||
|
None => break,
|
||||||
|
Some(StreamInput::Shutdown(reason)) => {
|
||||||
|
self.shutdown(reason);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Some(input) => self.input(input).await,
|
||||||
|
},
|
||||||
|
() = self.streams.wait_peers() => {}
|
||||||
|
}
|
||||||
|
self.flush();
|
||||||
|
}
|
||||||
|
debug!(session = self.session, "stream task ended");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit(&self, event: Event) {
|
||||||
|
let _ = self.events.send(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn input(&mut self, input: StreamInput) {
|
||||||
|
let session = self.session;
|
||||||
|
let result = match input {
|
||||||
|
StreamInput::Start { setup, auto_accept } => {
|
||||||
|
self.streams.start(StreamerOptions { setup, auto_accept }).map(|()| {
|
||||||
|
self.emit(Event::StreamState { session, state: StreamState::Starting });
|
||||||
|
})
|
||||||
|
}
|
||||||
|
StreamInput::Stop => self.streams.stop(),
|
||||||
|
StreamInput::Respond { viewer, accept } => {
|
||||||
|
self.streams.respond(ClientId(viewer), accept).await
|
||||||
|
}
|
||||||
|
StreamInput::Kick { viewer } => self.streams.kick(ClientId(viewer)),
|
||||||
|
StreamInput::Watch { stream_id } => self.streams.watch(&stream_id, "").map(|()| {
|
||||||
|
self.emit(Event::WatchState { session, stream_id, state: WatchState::Requested });
|
||||||
|
}),
|
||||||
|
StreamInput::Leave { stream_id } => self.streams.leave(&stream_id),
|
||||||
|
StreamInput::RequestKeyframe { stream_id } => {
|
||||||
|
self.streams.request_keyframe(&stream_id);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
StreamInput::Frame(frame) => {
|
||||||
|
self.streams.write_frame(&frame);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
StreamInput::Notification(n) => {
|
||||||
|
self.streams.handle_notification(n).await;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
StreamInput::RequestFailed(request, error) => {
|
||||||
|
self.streams.request_failed(&request, &error);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
StreamInput::Clients(clients) => {
|
||||||
|
// Streams of clients that left or stopped streaming are gone.
|
||||||
|
// Only changes count: a snapshot may predate the streaming flag
|
||||||
|
// of a stream that was just announced.
|
||||||
|
for (client, streaming) in &clients {
|
||||||
|
let was = self.clients.get(client).copied().flatten();
|
||||||
|
if let (Some(was), Some(now)) = (was, *streaming)
|
||||||
|
&& was != now
|
||||||
|
{
|
||||||
|
self.streams.set_client_streaming(ClientId(*client), now);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.streams.retain_streamers(|c| clients.contains_key(&c.0));
|
||||||
|
self.clients = clients;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
StreamInput::Shutdown(_) => Ok(()),
|
||||||
|
};
|
||||||
|
if let Err(e) = result {
|
||||||
|
self.emit(Event::Error { session, message: format!("stream: {e}") });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send the requests on the connection and report the events.
|
||||||
|
fn flush(&mut self) {
|
||||||
|
while let Some(output) = self.streams.poll_output() {
|
||||||
|
match output {
|
||||||
|
Output::Request(request) => {
|
||||||
|
let _ = self.voice.send(VoiceCmd::Stream(request));
|
||||||
|
}
|
||||||
|
Output::Event(event) => self.event(event),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn event(&mut self, event: StreamEvent) {
|
||||||
|
let session = self.session;
|
||||||
|
match event {
|
||||||
|
StreamEvent::Streams(streams) => self.emit(Event::StreamsChanged { session, streams }),
|
||||||
|
StreamEvent::Streamer(StreamerEvent::Live { id }) => {
|
||||||
|
let sink = StreamSink {
|
||||||
|
tx: self.tx.clone(),
|
||||||
|
live: Arc::new(AtomicBool::new(true)),
|
||||||
|
keyframe: Arc::new(AtomicBool::new(true)),
|
||||||
|
};
|
||||||
|
self.sink = Some(sink.clone());
|
||||||
|
self.emit(Event::StreamState { session, state: StreamState::Live { id, sink } });
|
||||||
|
}
|
||||||
|
StreamEvent::Streamer(StreamerEvent::Request { viewer, message }) => {
|
||||||
|
self.emit(Event::StreamViewerRequest { session, viewer: viewer.0, message });
|
||||||
|
}
|
||||||
|
StreamEvent::Streamer(StreamerEvent::Viewers(viewers)) => {
|
||||||
|
self.emit(Event::StreamViewers { session, viewers });
|
||||||
|
}
|
||||||
|
StreamEvent::Streamer(StreamerEvent::KeyframeRequest) => {
|
||||||
|
if let Some(sink) = &self.sink {
|
||||||
|
sink.keyframe.store(true, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
self.emit(Event::StreamKeyframeRequest { session });
|
||||||
|
}
|
||||||
|
StreamEvent::Streamer(StreamerEvent::Ended(reason)) => {
|
||||||
|
if let Some(sink) = self.sink.take() {
|
||||||
|
sink.live.store(false, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
self.emit(Event::StreamState { session, state: StreamState::Ended(reason) });
|
||||||
|
}
|
||||||
|
StreamEvent::Watch { id, event } => {
|
||||||
|
let state = match event {
|
||||||
|
WatchEvent::Accepted => WatchState::Connecting,
|
||||||
|
WatchEvent::Connected => WatchState::Connected,
|
||||||
|
WatchEvent::Ended(reason) => WatchState::Ended(reason),
|
||||||
|
WatchEvent::Frame(frame) => {
|
||||||
|
let _ = self.frames.send(StreamFrame { session, stream_id: id, frame });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.emit(Event::WatchState { session, stream_id: id, state });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The connection is gone: report our stream and watched streams as ended.
|
||||||
|
fn shutdown(&mut self, reason: String) {
|
||||||
|
let session = self.session;
|
||||||
|
let ended = || EndReason::Failed(reason.clone());
|
||||||
|
if self.streams.streamer().is_some() {
|
||||||
|
self.emit(Event::StreamState { session, state: StreamState::Ended(ended()) });
|
||||||
|
}
|
||||||
|
if let Some(sink) = self.sink.take() {
|
||||||
|
sink.live.store(false, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
for watched in self.streams.watching() {
|
||||||
|
let stream_id = watched.id().to_owned();
|
||||||
|
self.emit(Event::WatchState { session, stream_id, state: WatchState::Ended(ended()) });
|
||||||
|
}
|
||||||
|
if self.streams.directory().iter().next().is_some() {
|
||||||
|
self.emit(Event::StreamsChanged { session, streams: Vec::new() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use tokio::time::timeout;
|
||||||
|
use tsc_stream::{FrameSource, SyntheticSource};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const CLIENTS: [u16; 2] = [5, 6];
|
||||||
|
|
||||||
|
/// The notifications the server sends for `request` from `from`, per receiver.
|
||||||
|
fn relay(from: u16, request: Request) -> Vec<(u16, StreamNotification)> {
|
||||||
|
let both = |n: StreamNotification| CLIENTS.map(|c| (c, n.clone())).to_vec();
|
||||||
|
match request {
|
||||||
|
Request::Setup(setup) => CLIENTS
|
||||||
|
.map(|c| {
|
||||||
|
let info = StreamInfo {
|
||||||
|
id: "s-1".into(),
|
||||||
|
streamer: ClientId(from),
|
||||||
|
name: setup.name.clone(),
|
||||||
|
kind: setup.kind,
|
||||||
|
bitrate: setup.bitrate,
|
||||||
|
viewer_limit: setup.viewer_limit,
|
||||||
|
audio: setup.audio,
|
||||||
|
};
|
||||||
|
let return_code = (c == from).then(|| "1".to_owned());
|
||||||
|
(c, StreamNotification::Started { info, return_code })
|
||||||
|
})
|
||||||
|
.to_vec(),
|
||||||
|
Request::Stop { id } => {
|
||||||
|
both(StreamNotification::Stopped { id, streamer: None, reason: None })
|
||||||
|
}
|
||||||
|
Request::Join { id, streamer, message } => vec![(
|
||||||
|
streamer.0,
|
||||||
|
StreamNotification::JoinRequest {
|
||||||
|
id,
|
||||||
|
viewer: ClientId(from),
|
||||||
|
message,
|
||||||
|
remove: false,
|
||||||
|
},
|
||||||
|
)],
|
||||||
|
Request::Leave { id, streamer } => vec![(
|
||||||
|
streamer.0,
|
||||||
|
StreamNotification::JoinRequest {
|
||||||
|
id,
|
||||||
|
viewer: ClientId(from),
|
||||||
|
message: String::new(),
|
||||||
|
remove: true,
|
||||||
|
},
|
||||||
|
)],
|
||||||
|
Request::Respond { id, viewer, offer, accept } => vec![(
|
||||||
|
viewer.0,
|
||||||
|
StreamNotification::JoinResponse {
|
||||||
|
id,
|
||||||
|
streamer: Some(ClientId(from)),
|
||||||
|
accepted: accept,
|
||||||
|
offer,
|
||||||
|
message: String::new(),
|
||||||
|
},
|
||||||
|
)],
|
||||||
|
Request::Signal { id, peer, signal } => vec![(
|
||||||
|
peer.0,
|
||||||
|
StreamNotification::Signaling { id, peer: ClientId(from), json: signal.to_json() },
|
||||||
|
)],
|
||||||
|
Request::RemoveViewer { id, viewer, reason } => {
|
||||||
|
both(StreamNotification::ViewerLeft { id, viewer, reason: Some(reason) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn wait<T>(
|
||||||
|
rx: &mut broadcast::Receiver<Event>,
|
||||||
|
mut f: impl FnMut(Event) -> Option<T>,
|
||||||
|
) -> T {
|
||||||
|
timeout(Duration::from_secs(10), async {
|
||||||
|
loop {
|
||||||
|
if let Some(t) = f(rx.recv().await.unwrap()) {
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("timed out")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Two stream tasks (sessions 1 and 2) whose commands go through a fake server.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn stream_tasks_through_fake_server() {
|
||||||
|
let (events, mut rx) = broadcast::channel(4096);
|
||||||
|
let (frames, mut frames_rx) = broadcast::channel(4096);
|
||||||
|
let mut voices = Vec::new();
|
||||||
|
let mut handles = Vec::new();
|
||||||
|
for (i, clid) in CLIENTS.into_iter().enumerate() {
|
||||||
|
let (voice, voice_rx) = mpsc::unbounded_channel();
|
||||||
|
let config = PeerConfig::loopback();
|
||||||
|
let session = i as u64 + 1;
|
||||||
|
handles.push(StreamHandle::spawn(
|
||||||
|
session,
|
||||||
|
clid,
|
||||||
|
config,
|
||||||
|
voice,
|
||||||
|
events.clone(),
|
||||||
|
frames.clone(),
|
||||||
|
));
|
||||||
|
voices.push(voice_rx);
|
||||||
|
}
|
||||||
|
let handles = Arc::new(handles);
|
||||||
|
// The server: relays requests from one task as notifications to the others.
|
||||||
|
for (i, mut voice_rx) in voices.into_iter().enumerate() {
|
||||||
|
let handles = handles.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while let Some(cmd) = voice_rx.recv().await {
|
||||||
|
if let VoiceCmd::Stream(request) = cmd {
|
||||||
|
for (to, n) in relay(CLIENTS[i], request) {
|
||||||
|
let index = CLIENTS.iter().position(|c| *c == to).unwrap();
|
||||||
|
handles[index].send(StreamInput::Notification(n));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let setup = StreamSetup { name: "t".into(), ..Default::default() };
|
||||||
|
handles[0].send(StreamInput::Start { setup, auto_accept: true });
|
||||||
|
// Live for the streamer and listed for the viewer, in either order.
|
||||||
|
let (mut sink, mut listed) = (None, false);
|
||||||
|
wait(&mut rx, |e| {
|
||||||
|
match e {
|
||||||
|
Event::StreamState { session: 1, state: StreamState::Live { sink: s, .. } } => {
|
||||||
|
sink = Some(s);
|
||||||
|
}
|
||||||
|
Event::StreamsChanged { session: 2, streams } => listed = streams.len() == 1,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
(sink.is_some() && listed).then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let sink = sink.unwrap();
|
||||||
|
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;
|
||||||
|
|
||||||
|
// Frames from the sink reach the viewer's frame bus.
|
||||||
|
let feeder = tokio::spawn({
|
||||||
|
let sink = sink.clone();
|
||||||
|
async move {
|
||||||
|
let mut source = SyntheticSource::new(30, 2000, true);
|
||||||
|
let mut out = Vec::new();
|
||||||
|
while sink.is_live() {
|
||||||
|
source.poll_frames(Instant::now(), &mut out);
|
||||||
|
for f in out.drain(..) {
|
||||||
|
sink.send(f);
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let (mut video, mut audio) = (0, 0);
|
||||||
|
timeout(Duration::from_secs(10), async {
|
||||||
|
while video < 10 || audio < 10 {
|
||||||
|
let f = frames_rx.recv().await.unwrap();
|
||||||
|
assert_eq!((f.session, f.stream_id.as_str()), (2, "s-1"));
|
||||||
|
match f.frame.kind {
|
||||||
|
MediaKind::Video => video += 1,
|
||||||
|
MediaKind::Audio => audio += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("no frames");
|
||||||
|
assert!(sink.take_keyframe_request());
|
||||||
|
|
||||||
|
// Stopping ends the sink and tells the viewer.
|
||||||
|
handles[0].send(StreamInput::Stop);
|
||||||
|
wait(&mut rx, |e| match e {
|
||||||
|
Event::WatchState {
|
||||||
|
session: 2, state: WatchState::Ended(EndReason::Stopped), ..
|
||||||
|
} => Some(()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert!(!sink.is_live());
|
||||||
|
feeder.await.unwrap();
|
||||||
|
|
||||||
|
// Errors surface as events.
|
||||||
|
handles[1].send(StreamInput::Leave { stream_id: "s-1".into() });
|
||||||
|
wait(&mut rx, |e| match e {
|
||||||
|
Event::Error { session: 2, message } if message.contains("not watching") => Some(()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
handles[1].send(StreamInput::Shutdown("bye".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
//! The voice source: a normal client connection.
|
//! The voice source: a normal client connection.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use futures::prelude::*;
|
use futures::prelude::*;
|
||||||
@@ -9,12 +10,13 @@ use tracing::{info, warn};
|
|||||||
use tsc_model::{
|
use tsc_model::{
|
||||||
ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerFlavor,
|
ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerFlavor,
|
||||||
};
|
};
|
||||||
|
use tsc_stream::{PeerConfig, Request, StreamNotification};
|
||||||
use tsclientlib::data;
|
use tsclientlib::data;
|
||||||
use tsclientlib::events::Event as BookEvent;
|
use tsclientlib::events::Event as BookEvent;
|
||||||
use tsclientlib::prelude::*;
|
use tsclientlib::prelude::*;
|
||||||
use tsclientlib::{
|
use tsclientlib::{
|
||||||
ClientType, Connection, DisconnectOptions, Identity, MaxClients, MessageTarget, StreamItem,
|
ClientType, Connection, DisconnectOptions, Identity, MaxClients, MessageHandle, MessageTarget,
|
||||||
Version,
|
StreamItem, Version,
|
||||||
};
|
};
|
||||||
use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket};
|
use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket};
|
||||||
|
|
||||||
@@ -30,6 +32,8 @@ pub struct VoiceOptions {
|
|||||||
pub channel: Option<String>,
|
pub channel: Option<String>,
|
||||||
/// Open the audio devices (capture and playback).
|
/// Open the audio devices (capture and playback).
|
||||||
pub audio: bool,
|
pub audio: bool,
|
||||||
|
/// Network settings for stream peer connections (TeamSpeak 6).
|
||||||
|
pub stream_peer: PeerConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl VoiceOptions {
|
impl VoiceOptions {
|
||||||
@@ -42,6 +46,7 @@ impl VoiceOptions {
|
|||||||
server_password: None,
|
server_password: None,
|
||||||
channel: None,
|
channel: None,
|
||||||
audio: false,
|
audio: false,
|
||||||
|
stream_peer: PeerConfig::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -53,6 +58,8 @@ pub(crate) enum VoiceCmd {
|
|||||||
SetOutputMuted(bool),
|
SetOutputMuted(bool),
|
||||||
/// An encoded voice packet from the audio thread.
|
/// An encoded voice packet from the audio thread.
|
||||||
Audio(OutPacket),
|
Audio(OutPacket),
|
||||||
|
/// A stream command; failures come back as [`VoiceEvent::StreamRequestFailed`].
|
||||||
|
Stream(Request),
|
||||||
Disconnect,
|
Disconnect,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,6 +67,7 @@ pub(crate) enum VoiceEvent {
|
|||||||
Connected {
|
Connected {
|
||||||
name: String,
|
name: String,
|
||||||
flavor: ServerFlavor,
|
flavor: ServerFlavor,
|
||||||
|
own_client: u16,
|
||||||
},
|
},
|
||||||
Presence(Presence),
|
Presence(Presence),
|
||||||
OwnChannel(ChannelId),
|
OwnChannel(ChannelId),
|
||||||
@@ -70,6 +78,8 @@ pub(crate) enum VoiceEvent {
|
|||||||
client: u16,
|
client: u16,
|
||||||
talking: bool,
|
talking: bool,
|
||||||
},
|
},
|
||||||
|
Stream(StreamNotification),
|
||||||
|
StreamRequestFailed(Request, String),
|
||||||
Disconnected(Option<String>),
|
Disconnected(Option<String>),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,7 +202,11 @@ async fn run_inner(
|
|||||||
let state = con.get_state()?;
|
let state = con.get_state()?;
|
||||||
let flavor = ServerFlavor::from_version_string(&state.server.version);
|
let flavor = ServerFlavor::from_version_string(&state.server.version);
|
||||||
info!(server = %state.server.name, ?flavor, "voice connected");
|
info!(server = %state.server.name, ?flavor, "voice connected");
|
||||||
let _ = events.send(VoiceEvent::Connected { name: state.server.name.clone(), flavor });
|
let _ = events.send(VoiceEvent::Connected {
|
||||||
|
name: state.server.name.clone(),
|
||||||
|
flavor,
|
||||||
|
own_client: state.own_client.0,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
// Subscribe to all channels to see everyone.
|
// Subscribe to all channels to see everyone.
|
||||||
let cmd = con.get_state()?.server.set_subscribed(true);
|
let cmd = con.get_state()?.server.set_subscribed(true);
|
||||||
@@ -202,6 +216,8 @@ async fn run_inner(
|
|||||||
// Who is talking: last voice packet per client.
|
// Who is talking: last voice packet per client.
|
||||||
let mut talking: std::collections::HashMap<u16, Instant> = Default::default();
|
let mut talking: std::collections::HashMap<u16, Instant> = Default::default();
|
||||||
let mut tick = tokio::time::interval(Duration::from_millis(250));
|
let mut tick = tokio::time::interval(Duration::from_millis(250));
|
||||||
|
// Stream commands waiting for the server's answer.
|
||||||
|
let mut stream_requests: HashMap<MessageHandle, Request> = HashMap::new();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let input = {
|
let input = {
|
||||||
@@ -258,12 +274,27 @@ async fn run_inner(
|
|||||||
}
|
}
|
||||||
let _ = events.send(VoiceEvent::Audio(packet));
|
let _ = events.send(VoiceEvent::Audio(packet));
|
||||||
}
|
}
|
||||||
|
StreamItem::MessageEvent(msg) => {
|
||||||
|
for n in StreamNotification::from_message(&msg) {
|
||||||
|
let _ = events.send(VoiceEvent::Stream(n));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
StreamItem::MessageResult(handle, result) => {
|
||||||
|
if let (Some(request), Err(e)) = (stream_requests.remove(&handle), result) {
|
||||||
|
let _ =
|
||||||
|
events.send(VoiceEvent::StreamRequestFailed(request, e.to_string()));
|
||||||
|
}
|
||||||
|
}
|
||||||
StreamItem::DisconnectedTemporarily(reason) => {
|
StreamItem::DisconnectedTemporarily(reason) => {
|
||||||
warn!(?reason, "voice connection interrupted, reconnecting");
|
warn!(?reason, "voice connection interrupted, reconnecting");
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
},
|
},
|
||||||
Input::Cmd(None) | Input::Cmd(Some(VoiceCmd::Disconnect)) => break,
|
Input::Cmd(None) | Input::Cmd(Some(VoiceCmd::Disconnect)) => break,
|
||||||
|
Input::Cmd(Some(VoiceCmd::Stream(request))) => {
|
||||||
|
let handle = request.to_command().send_with_result(&mut con)?;
|
||||||
|
stream_requests.insert(handle, request);
|
||||||
|
}
|
||||||
Input::Cmd(Some(cmd)) => handle_command(&mut con, cmd)?,
|
Input::Cmd(Some(cmd)) => handle_command(&mut con, cmd)?,
|
||||||
Input::Tick => {
|
Input::Tick => {
|
||||||
talking.retain(|client, last| {
|
talking.retain(|client, last| {
|
||||||
@@ -336,6 +367,9 @@ fn handle_command(con: &mut Connection, cmd: VoiceCmd) -> anyhow::Result<()> {
|
|||||||
VoiceCmd::Audio(packet) => {
|
VoiceCmd::Audio(packet) => {
|
||||||
con.send_audio(packet)?;
|
con.send_audio(packet)?;
|
||||||
}
|
}
|
||||||
|
VoiceCmd::Stream(request) => {
|
||||||
|
request.to_command().send(con)?;
|
||||||
|
}
|
||||||
VoiceCmd::Disconnect => {}
|
VoiceCmd::Disconnect => {}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -0,0 +1,224 @@
|
|||||||
|
//! Streams through the engine against the development servers
|
||||||
|
//! (dev/docker-compose.yml): one session streams synthetic frames, another
|
||||||
|
//! watches. Runs only with `TSC_LIVE=1`.
|
||||||
|
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use tokio::sync::broadcast::Receiver;
|
||||||
|
use tokio::time::timeout;
|
||||||
|
use tsc_core::stream::{
|
||||||
|
EndReason, FrameSource, LeaveReason, MediaKind, PeerConfig, StreamSetup, SyntheticSource,
|
||||||
|
ViewerState,
|
||||||
|
};
|
||||||
|
use tsc_core::{Command, Engine, Event, StreamState, VoiceOptions, VoiceState, WatchState};
|
||||||
|
|
||||||
|
fn live() -> bool {
|
||||||
|
std::env::var("TSC_LIVE").is_ok_and(|v| v == "1")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait for an event matching `f`, failing after 20 s.
|
||||||
|
async fn wait_for<T>(
|
||||||
|
rx: &mut Receiver<Event>,
|
||||||
|
what: &str,
|
||||||
|
mut f: impl FnMut(&Event) -> Option<T>,
|
||||||
|
) -> T {
|
||||||
|
timeout(Duration::from_secs(20), async {
|
||||||
|
loop {
|
||||||
|
match rx.recv().await {
|
||||||
|
Ok(e) => {
|
||||||
|
if let Some(t) = f(&e) {
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
if let Event::Error { session, message } = e {
|
||||||
|
eprintln!("engine error (session {session}): {message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
|
||||||
|
Err(e) => panic!("event bus closed: {e}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|_| panic!("timed out waiting for {what}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn connect(
|
||||||
|
engine: &Engine,
|
||||||
|
events: &mut Receiver<Event>,
|
||||||
|
session: u64,
|
||||||
|
addr: &str,
|
||||||
|
nick: &str,
|
||||||
|
) {
|
||||||
|
let mut options = VoiceOptions::new(addr, nick);
|
||||||
|
options.stream_peer = PeerConfig::loopback();
|
||||||
|
engine.send(Command::ConnectVoice { session, options: Box::new(options) });
|
||||||
|
wait_for(events, "voice connected", |e| match e {
|
||||||
|
Event::State { session: s, state }
|
||||||
|
if *s == session
|
||||||
|
&& state.voice == VoiceState::Connected
|
||||||
|
&& state.own_channel.is_some() =>
|
||||||
|
{
|
||||||
|
Some(())
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn ts6_stream_between_sessions() {
|
||||||
|
if !live() {
|
||||||
|
eprintln!("skipped: set TSC_LIVE=1 with the dev servers running");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let engine = Engine::start();
|
||||||
|
let mut events = engine.subscribe();
|
||||||
|
let mut frames = engine.subscribe_frames();
|
||||||
|
let tag = std::process::id() % 10_000;
|
||||||
|
connect(&engine, &mut events, 1, "127.0.0.1:9988", &format!("e-streamer-{tag}")).await;
|
||||||
|
connect(&engine, &mut events, 2, "127.0.0.1:9988", &format!("e-viewer-{tag}")).await;
|
||||||
|
|
||||||
|
// Stream, asking for each viewer.
|
||||||
|
let setup = StreamSetup { name: format!("engine {tag}"), ..Default::default() };
|
||||||
|
engine.send(Command::StartStream { session: 1, setup, auto_accept: false });
|
||||||
|
let (id, sink) = wait_for(&mut events, "stream live", |e| match e {
|
||||||
|
Event::StreamState { session: 1, state: StreamState::Live { id, sink } } => {
|
||||||
|
Some((id.clone(), sink.clone()))
|
||||||
|
}
|
||||||
|
Event::StreamState { session: 1, state: StreamState::Ended(reason) } => {
|
||||||
|
panic!("stream ended: {reason:?}")
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
wait_for(&mut events, "stream in the viewer's list", |e| match e {
|
||||||
|
Event::StreamsChanged { session: 2, streams } if streams.iter().any(|s| s.id == id) => {
|
||||||
|
Some(())
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// Synthetic frames through the sink, as an encoder would send them.
|
||||||
|
let feeder = tokio::spawn({
|
||||||
|
let sink = sink.clone();
|
||||||
|
async move {
|
||||||
|
let mut source = SyntheticSource::new(30, 3000, true);
|
||||||
|
let mut out = Vec::new();
|
||||||
|
while sink.is_live() {
|
||||||
|
source.poll_frames(Instant::now(), &mut out);
|
||||||
|
for frame in out.drain(..) {
|
||||||
|
sink.send(frame);
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
engine.send(Command::WatchStream { session: 2, stream_id: id.clone() });
|
||||||
|
let viewer = wait_for(&mut events, "viewer request", |e| match e {
|
||||||
|
Event::StreamViewerRequest { session: 1, viewer, .. } => Some(*viewer),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
engine.send(Command::AcceptViewer { session: 1, viewer, accept: true });
|
||||||
|
wait_for(&mut events, "watching", |e| match e {
|
||||||
|
Event::WatchState { session: 2, stream_id, state: WatchState::Connected }
|
||||||
|
if *stream_id == id =>
|
||||||
|
{
|
||||||
|
Some(())
|
||||||
|
}
|
||||||
|
Event::WatchState { session: 2, state: WatchState::Ended(reason), .. } => {
|
||||||
|
panic!("watching ended: {reason:?}")
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
wait_for(&mut events, "viewer connected", |e| match e {
|
||||||
|
Event::StreamViewers { session: 1, viewers }
|
||||||
|
if viewers
|
||||||
|
.iter()
|
||||||
|
.any(|v| v.client.0 == viewer && v.state == ViewerState::Connected) =>
|
||||||
|
{
|
||||||
|
Some(())
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert!(sink.take_keyframe_request(), "a new viewer asks for a keyframe");
|
||||||
|
|
||||||
|
let (mut video, mut audio) = (0, 0);
|
||||||
|
let _ = timeout(Duration::from_secs(10), async {
|
||||||
|
while video < 60 || audio < 60 {
|
||||||
|
match frames.recv().await {
|
||||||
|
Ok(f) if f.session == 2 && f.stream_id == id => match f.frame.kind {
|
||||||
|
MediaKind::Video => video += 1,
|
||||||
|
MediaKind::Audio => audio += 1,
|
||||||
|
},
|
||||||
|
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
|
||||||
|
Err(_) => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert!(video >= 60 && audio >= 60, "viewer got {video} video / {audio} audio frames");
|
||||||
|
|
||||||
|
// The streamer removes the viewer, then ends the stream.
|
||||||
|
engine.send(Command::KickViewer { session: 1, viewer });
|
||||||
|
wait_for(&mut events, "kicked", |e| match e {
|
||||||
|
Event::WatchState {
|
||||||
|
session: 2,
|
||||||
|
state: WatchState::Ended(EndReason::Removed(Some(LeaveReason::Kicked))),
|
||||||
|
..
|
||||||
|
} => Some(()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
engine.send(Command::StopStream { session: 1 });
|
||||||
|
wait_for(&mut events, "stream ended", |e| match e {
|
||||||
|
Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Local) } => Some(()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
wait_for(&mut events, "stream gone from the viewer's list", |e| match e {
|
||||||
|
Event::StreamsChanged { session: 2, streams } if streams.iter().all(|s| s.id != id) => {
|
||||||
|
Some(())
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert!(!sink.send(tsc_core::stream::EncodedFrame {
|
||||||
|
kind: MediaKind::Audio,
|
||||||
|
time: tsc_core::stream::MediaTime::from_90khz(0),
|
||||||
|
data: vec![0].into(),
|
||||||
|
}));
|
||||||
|
feeder.await.unwrap();
|
||||||
|
|
||||||
|
engine.send(Command::CloseSession { session: 1 });
|
||||||
|
engine.send(Command::CloseSession { session: 2 });
|
||||||
|
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn ts3_has_no_streams() {
|
||||||
|
if !live() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let engine = Engine::start();
|
||||||
|
let mut events = engine.subscribe();
|
||||||
|
let nick = format!("e-nostream-{}", std::process::id() % 10_000);
|
||||||
|
connect(&engine, &mut events, 1, "127.0.0.1:9987", &nick).await;
|
||||||
|
engine.send(Command::StartStream {
|
||||||
|
session: 1,
|
||||||
|
setup: StreamSetup::default(),
|
||||||
|
auto_accept: true,
|
||||||
|
});
|
||||||
|
let message = wait_for(&mut events, "error", |e| match e {
|
||||||
|
Event::Error { session: 1, message } => Some(message.clone()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert!(message.contains("TeamSpeak 6"), "{message}");
|
||||||
|
engine.send(Command::CloseSession { session: 1 });
|
||||||
|
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user