stream::tests::layer_formats_reach_the_live_stream asserts that telling the
sink the same layer format twice asks for no second keyframe: it drains the
sink's keyframe requests, changes the format, waits for the request that
follows, tells the same format again and expects none within 200 ms. It failed
once ("nothing changed", stream.rs:1326) in the first of the three final runs of
the CI test step in the runner image of this task, with the machine busy with
another job.
Requests reach the sink from the stream going live, from the streamer's own
view of its viewer connecting (PeerEvent::Connected, a moment after the viewer
sees WatchState::Connected, which is all the test waited for), from the
viewer's picture requests, and from a changed layer. The test drained once,
right after the viewer's side was connected, so a request of one of the first
three that arrives later is taken for the one the changed format asked for, and
the real one then arrives after the "same again" and is counted as a change.
This could not be reproduced here (0 in 400 runs of the single test, 32 at a
time with 48 busy loops, nor in 200 runs of the lib tests); the change closes
those windows as far as they can be named: the test waits for the streamer's
own Connected (StreamViewers) as well, and drains until a moment longer than
the merge interval of requests (250 ms) passes with no request, before the
format is changed. The assertions are those of before.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1746 lines
56 KiB
Rust
1746 lines
56 KiB
Rust
//! TeamSpeak 6 streams of a session: a task that runs the stream sessions
|
|
//! ([`voelin_stream::Streams`]) of the voice connection.
|
|
//!
|
|
//! The voice task forwards stream notifications here and sends the resulting
|
|
//! commands. Only started for TeamSpeak 6 servers.
|
|
//!
|
|
//! The streams of the whole server are listed, in every channel: a stream can
|
|
//! be watched from any channel, as with the official client. Streams that
|
|
//! started before we joined, and streams in other channels (the server
|
|
//! announces a stream only in its channel), are looked up on the server
|
|
//! (`requeststreaminfo`), so no gateway is needed. A gateway's directory is a
|
|
//! second source: its registered entries (stream id and streamer) are handed
|
|
//! to the stream sessions ([`voelin_stream::Streams::discovered`]), 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.
|
|
//!
|
|
//! 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;
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
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, SrtpProfile, StreamEvent, StreamLookup,
|
|
StreamNotification, StreamerEvent, StreamerOptions, Streams, WatchEvent,
|
|
};
|
|
pub use voelin_stream::{
|
|
Codec, FrameSource, Frequency, MediaFrame, MediaKind, MediaTime, PeerConfig, SyntheticSource,
|
|
VideoCodec, VideoFormat,
|
|
};
|
|
|
|
use crate::link::LinkEvent;
|
|
use crate::settings::{STREAM_PERMISSIONS, SharedSettings, StreamPermissions};
|
|
pub use crate::stream_types::{
|
|
EndReason, LeaveReason, StreamInfo, StreamKind, StreamSetup, ViewerInfo, ViewerState,
|
|
};
|
|
use crate::{Event, SessionId};
|
|
|
|
/// How often the viewer count of one stream in our channel is asked for
|
|
/// (round robin, see [`Streams::refresh_viewer_counts`]).
|
|
const VIEWER_COUNTS: std::time::Duration = std::time::Duration::from_secs(5);
|
|
|
|
/// 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,
|
|
}
|
|
|
|
/// What a simulcast layer of our stream is encoded at
|
|
/// ([`StreamSink::layer_format`]).
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub struct LayerFormat {
|
|
pub width: u32,
|
|
pub height: u32,
|
|
pub fps: u32,
|
|
/// Bit/s: the layer's bitrate, or its automatic one.
|
|
pub bitrate: u64,
|
|
/// The bitrate is automatic (from the size and frame rate).
|
|
pub automatic: bool,
|
|
}
|
|
|
|
/// Hands encoded frames of our stream to the engine, e.g. from an encoder
|
|
/// thread, and tells the encoders what the viewers need per simulcast layer:
|
|
/// keyframes and bitrates. Those are read lock-free from the stream session.
|
|
#[derive(Clone)]
|
|
pub struct StreamSink {
|
|
tx: mpsc::UnboundedSender<StreamInput>,
|
|
live: Arc<AtomicBool>,
|
|
feedback: Arc<LayerFeedback>,
|
|
}
|
|
|
|
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(StreamCmd::Frame(frame).into()).is_ok()
|
|
}
|
|
|
|
/// Send one video frame encoded in `format`: only viewers whose answer
|
|
/// chose that codec (and H.264 profile) get it.
|
|
pub fn send_video(&self, frame: EncodedFrame, format: VideoFormat) -> bool {
|
|
self.live.load(Ordering::Relaxed)
|
|
&& self.tx.send(StreamCmd::VideoFrame(frame, format).into()).is_ok()
|
|
}
|
|
|
|
/// Whether a viewer's answer chose `format`.
|
|
pub fn has_video_codec(&self, format: VideoFormat) -> bool {
|
|
self.feedback.has_codec(format)
|
|
}
|
|
|
|
/// Whether a viewer asked for a keyframe of any layer since the last
|
|
/// call (or [`take_layer_keyframes`](Self::take_layer_keyframes)).
|
|
pub fn take_keyframe_request(&self) -> bool {
|
|
self.feedback.take_any_keyframe()
|
|
}
|
|
|
|
/// Adds to `layers` the simulcast layers viewers asked a keyframe for
|
|
/// since the last call. Every layer is asked for when the stream goes live.
|
|
pub fn take_layer_keyframes(&self, layers: &mut LayerSet) {
|
|
self.feedback.take_keyframes(layers);
|
|
}
|
|
|
|
/// Bitrate (bit/s) the bandwidth estimates of `layer`'s viewers allow:
|
|
/// the lowest estimate of its viewers, at least
|
|
/// [`voelin_stream::session::MIN_VIDEO_BITRATE`], at most the layer's
|
|
/// `max_bitrate`. `None` while no viewer of the layer has an estimate.
|
|
pub fn layer_bitrate(&self, layer: LayerId) -> Option<u64> {
|
|
self.feedback.bitrate(layer)
|
|
}
|
|
|
|
/// What the encoder of `layer` makes. An automatic bitrate goes into the
|
|
/// stream's layer, so new connections start at it and every connection
|
|
/// probes for it; the largest layer sets the H.264 level of new offers
|
|
/// (`PeerConfig::set_h264_format`), so the offer declares what the
|
|
/// encoder writes into its SPS, also for 4K, 8K and high frame rates.
|
|
pub fn layer_format(&self, layer: LayerId, format: LayerFormat) {
|
|
let _ = self.tx.send(StreamCmd::LayerFormat { layer, format }.into());
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|
|
|
|
/// What the session asks of the streams of a connection (`LinkCmd::Stream`).
|
|
#[derive(Debug)]
|
|
pub enum StreamCmd {
|
|
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,
|
|
},
|
|
/// The stream's video arrives but does not decode.
|
|
Undecodable {
|
|
stream_id: String,
|
|
},
|
|
WatchLayer {
|
|
stream_id: String,
|
|
layer: Option<LayerId>,
|
|
},
|
|
/// Simulcast layers of our stream (now and for streams started later).
|
|
Layers(Vec<LayerSpec>),
|
|
/// What a layer of our stream is encoded at ([`StreamSink::layer_format`]).
|
|
LayerFormat {
|
|
layer: LayerId,
|
|
format: LayerFormat,
|
|
},
|
|
/// SRTP profile order of new connections, by name
|
|
/// (unknown names are left out).
|
|
SrtpProfiles(Vec<String>),
|
|
Frame(EncodedFrame),
|
|
/// A video frame for the viewers that chose its codec and H.264 profile.
|
|
VideoFrame(EncodedFrame, VideoFormat),
|
|
/// Clients that are friends (contacts), for `stream.permissions`.
|
|
Friends(BTreeSet<u16>),
|
|
/// The registered streams of the gateway's directory (full list).
|
|
Directory(Vec<StreamInfo>),
|
|
/// The voice connection is going: streams end, with this reason.
|
|
Shutdown(String),
|
|
}
|
|
|
|
/// What the stream task takes: the session's [`StreamCmd`]s, and what only the
|
|
/// connection that runs it knows (the server's notifications and the state
|
|
/// of its clients).
|
|
pub(crate) enum StreamInput {
|
|
Cmd(StreamCmd),
|
|
Notification(StreamNotification),
|
|
RequestFailed(Request, String),
|
|
/// Clients on the server: channel and `client_is_streaming`.
|
|
Clients(BTreeMap<u16, ClientState>),
|
|
}
|
|
|
|
impl From<StreamCmd> for StreamInput {
|
|
fn from(cmd: StreamCmd) -> Self {
|
|
Self::Cmd(cmd)
|
|
}
|
|
}
|
|
|
|
/// Our own stream, for the session (the gateway directory).
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub 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 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 {
|
|
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.0);
|
|
if known {
|
|
dir.wanted.push(streamer);
|
|
}
|
|
known
|
|
}
|
|
}
|
|
|
|
/// The stream task of a connection. The connection (a link) owns it: it
|
|
/// feeds it what the server says and sends the requests it makes.
|
|
pub(crate) struct StreamHandle {
|
|
tx: mpsc::UnboundedSender<StreamInput>,
|
|
}
|
|
|
|
impl StreamHandle {
|
|
#[allow(clippy::too_many_arguments)] // the parts of the session the task uses
|
|
pub fn spawn(
|
|
session: SessionId,
|
|
own_client: u16,
|
|
config: PeerConfig,
|
|
requests: mpsc::UnboundedSender<Request>,
|
|
events: broadcast::Sender<Event>,
|
|
frames: broadcast::Sender<StreamFrame>,
|
|
audio: bool,
|
|
settings: SharedSettings,
|
|
link: mpsc::UnboundedSender<LinkEvent>,
|
|
) -> 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,
|
|
requests,
|
|
events,
|
|
frames,
|
|
audio,
|
|
tx: tx.clone(),
|
|
sink: None,
|
|
layers: Vec::new(),
|
|
settings,
|
|
link,
|
|
setup: None,
|
|
formats: BTreeMap::new(),
|
|
live: None,
|
|
viewers: 0,
|
|
clients: BTreeMap::new(),
|
|
friends: BTreeSet::new(),
|
|
gateway,
|
|
};
|
|
tokio::spawn(task.run(rx));
|
|
Self { tx }
|
|
}
|
|
|
|
pub fn send(&self, input: impl Into<StreamInput>) {
|
|
let _ = self.tx.send(input.into());
|
|
}
|
|
}
|
|
|
|
/// What an offer's H.264 level must hold: the largest size, frame rate and
|
|
/// bitrate of the stream's layers that are encoded (`formats`), a layer's
|
|
/// bitrate taken at its `max_bitrate` when that is higher, since bandwidth
|
|
/// estimates may raise the encoder to it. `None` before any is.
|
|
fn offer_format(
|
|
formats: &BTreeMap<LayerId, LayerFormat>,
|
|
layers: &[LayerSpec],
|
|
) -> Option<(u32, u32, u32, u64)> {
|
|
formats.iter().filter(|(id, _)| layers.iter().any(|l| l.id == **id)).fold(
|
|
None,
|
|
|most, (id, f)| {
|
|
let max = layers.iter().find(|l| l.id == *id).and_then(|l| l.max_bitrate);
|
|
let bitrate = f.bitrate.max(max.unwrap_or(0));
|
|
let (w, h, fps, b) = most.unwrap_or((0, 0, 0, 0));
|
|
Some((w.max(f.width), h.max(f.height), fps.max(f.fps), b.max(bitrate)))
|
|
},
|
|
)
|
|
}
|
|
|
|
struct StreamTask {
|
|
session: SessionId,
|
|
streams: Streams,
|
|
/// Where the requests go that the stream sessions make (the connection
|
|
/// sends them to the server).
|
|
requests: mpsc::UnboundedSender<Request>,
|
|
events: broadcast::Sender<Event>,
|
|
frames: broadcast::Sender<StreamFrame>,
|
|
/// The session has audio: the audio of watched streams goes to it
|
|
/// ([`LinkEvent::StreamAudio`]).
|
|
audio: bool,
|
|
/// For the sinks handed out.
|
|
tx: mpsc::UnboundedSender<StreamInput>,
|
|
/// The sink of our live stream.
|
|
sink: Option<StreamSink>,
|
|
/// Simulcast layers of our stream (empty: one layer).
|
|
layers: Vec<LayerSpec>,
|
|
/// `stream.permissions` decides join requests.
|
|
settings: SharedSettings,
|
|
/// The link's events, for the session: our stream's life
|
|
/// ([`LinkEvent::OwnStream`]) and the audio of watched streams.
|
|
link: mpsc::UnboundedSender<LinkEvent>,
|
|
/// The setup of our stream since `Start`.
|
|
setup: Option<StreamSetup>,
|
|
/// What each layer of our stream is encoded at, since `Start`.
|
|
formats: BTreeMap<LayerId, LayerFormat>,
|
|
/// 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>,
|
|
/// Friends' client ids (`stream.permissions = friends`).
|
|
friends: BTreeSet<u16>,
|
|
gateway: Arc<Mutex<GatewayStreams>>,
|
|
}
|
|
|
|
impl StreamTask {
|
|
async fn run(mut self, mut rx: mpsc::UnboundedReceiver<StreamInput>) {
|
|
let mut counts = tokio::time::interval(VIEWER_COUNTS);
|
|
counts.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
|
loop {
|
|
tokio::select! {
|
|
input = rx.recv() => match input {
|
|
None => break,
|
|
Some(StreamInput::Cmd(StreamCmd::Shutdown(reason))) => {
|
|
self.shutdown(reason);
|
|
break;
|
|
}
|
|
Some(input) => self.input(input).await,
|
|
},
|
|
() = self.streams.wait_peers() => {}
|
|
_ = counts.tick() => self.streams.refresh_viewer_counts(),
|
|
}
|
|
self.flush();
|
|
}
|
|
debug!(session = self.session, "stream task ended");
|
|
}
|
|
|
|
fn emit(&self, event: Event) {
|
|
let _ = self.events.send(event);
|
|
}
|
|
|
|
/// A layer of our stream is encoded at `format` (see
|
|
/// [`StreamSink::layer_format`]).
|
|
fn layer_format(
|
|
&mut self,
|
|
layer: LayerId,
|
|
format: LayerFormat,
|
|
) -> Result<(), voelin_stream::SessionError> {
|
|
// The live stream's layers only; the configured ones (for streams
|
|
// started later) keep their automatic bitrate.
|
|
let Some(mut layers) = self.streams.streamer().map(|s| s.layers().to_vec()) else {
|
|
return Ok(());
|
|
};
|
|
self.formats.insert(layer, format);
|
|
if let Some((width, height, fps, bitrate)) = offer_format(&self.formats, &layers) {
|
|
let mut config = self.streams.peer_config().clone();
|
|
config.set_h264_format(width, height, fps, bitrate);
|
|
if config.h264_profile_level_ids != self.streams.peer_config().h264_profile_level_ids {
|
|
debug!(width, height, fps, bitrate, "H.264 offered for the stream's largest layer");
|
|
self.streams.set_peer_config(config);
|
|
}
|
|
}
|
|
match layers.iter_mut().find(|l| l.id == layer) {
|
|
Some(spec) if format.automatic && spec.bitrate != format.bitrate => {
|
|
spec.bitrate = format.bitrate;
|
|
self.streams.set_layers(layers)
|
|
}
|
|
_ => Ok(()),
|
|
}
|
|
}
|
|
|
|
async fn input(&mut self, input: StreamInput) {
|
|
let result = match input {
|
|
StreamInput::Cmd(cmd) => self.command(cmd).await,
|
|
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, 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(())
|
|
}
|
|
};
|
|
if let Err(e) = result {
|
|
let session = self.session;
|
|
self.emit(Event::Error { session, message: format!("stream: {e}") });
|
|
}
|
|
}
|
|
|
|
async fn command(&mut self, cmd: StreamCmd) -> Result<(), voelin_stream::SessionError> {
|
|
let session = self.session;
|
|
match cmd {
|
|
StreamCmd::Start { setup, auto_accept } => {
|
|
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 });
|
|
})
|
|
}
|
|
StreamCmd::Stop => self.streams.stop(),
|
|
StreamCmd::Respond { viewer, accept } => {
|
|
self.streams.respond(ClientId(viewer), accept).await
|
|
}
|
|
StreamCmd::Kick { viewer } => self.streams.kick(ClientId(viewer)),
|
|
StreamCmd::Watch { stream_id } => self.streams.watch(&stream_id, "").map(|()| {
|
|
self.emit(Event::WatchState { session, stream_id, state: WatchState::Requested });
|
|
}),
|
|
StreamCmd::Leave { stream_id } => self.streams.leave(&stream_id),
|
|
StreamCmd::RequestKeyframe { stream_id } => {
|
|
self.streams.request_keyframe(&stream_id);
|
|
Ok(())
|
|
}
|
|
StreamCmd::Undecodable { stream_id } => self.streams.video_undecodable(&stream_id),
|
|
StreamCmd::WatchLayer { stream_id, layer } => self
|
|
.streams
|
|
.set_watch_layer(&stream_id, layer)
|
|
.map(|()| self.watch_layers(&stream_id)),
|
|
StreamCmd::Layers(layers) => {
|
|
self.layers = layers.clone();
|
|
// Without a stream they are used for the next one.
|
|
if self.streams.streamer().is_some() {
|
|
self.streams.set_layers(layers)
|
|
} else {
|
|
Ok(())
|
|
}
|
|
}
|
|
StreamCmd::LayerFormat { layer, format } => self.layer_format(layer, format),
|
|
StreamCmd::SrtpProfiles(names) => {
|
|
self.streams.set_srtp_profiles(parse_srtp_profiles(&names));
|
|
Ok(())
|
|
}
|
|
StreamCmd::Frame(frame) => {
|
|
self.streams.write_frame(&frame);
|
|
Ok(())
|
|
}
|
|
StreamCmd::VideoFrame(frame, format) => {
|
|
self.streams.write_frame_in(&frame, Some(format));
|
|
Ok(())
|
|
}
|
|
StreamCmd::Friends(friends) => {
|
|
self.friends = friends;
|
|
Ok(())
|
|
}
|
|
StreamCmd::Directory(entries) => {
|
|
self.gateway.lock().unwrap_or_else(PoisonError::into_inner).entries = entries;
|
|
self.add_directory_streams();
|
|
Ok(())
|
|
}
|
|
StreamCmd::Shutdown(_) => Ok(()),
|
|
}
|
|
}
|
|
|
|
/// 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().0;
|
|
for info in entries {
|
|
let stopped =
|
|
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, "stream from the gateway directory");
|
|
self.streams.discovered(info.into());
|
|
}
|
|
}
|
|
}
|
|
|
|
fn own_stream(&self, event: OwnStreamEvent) {
|
|
let _ = self.link.send(LinkEvent::OwnStream(event));
|
|
}
|
|
|
|
/// 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.requests.send(request);
|
|
}
|
|
Output::Event(event) => self.event(event),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn event(&mut self, event: StreamEvent) {
|
|
let session = self.session;
|
|
match event {
|
|
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(),
|
|
None => Arc::new(LayerFeedback::new()),
|
|
};
|
|
let sink = StreamSink {
|
|
tx: self.tx.clone(),
|
|
live: Arc::new(AtomicBool::new(true)),
|
|
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 }) => {
|
|
match self.join_decision(viewer) {
|
|
// Answered through the input queue, as the user would.
|
|
Some(accept) => {
|
|
debug!(
|
|
viewer = viewer.0,
|
|
accept, "join request answered by stream.permissions"
|
|
);
|
|
let _ =
|
|
self.tx.send(StreamCmd::Respond { viewer: viewer.0, accept }.into());
|
|
}
|
|
None => {
|
|
self.emit(Event::StreamViewerRequest {
|
|
session,
|
|
viewer: viewer.0,
|
|
message,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
StreamEvent::Streamer(StreamerEvent::Viewers(viewers)) => {
|
|
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).
|
|
StreamEvent::Streamer(StreamerEvent::KeyframeRequest { layer }) => {
|
|
self.emit(Event::StreamKeyframeRequest { session, layer });
|
|
}
|
|
StreamEvent::Streamer(StreamerEvent::LayerBitrate { layer, bitrate }) => {
|
|
self.emit(Event::StreamLayerBitrate { session, layer, bitrate });
|
|
}
|
|
StreamEvent::Streamer(StreamerEvent::Ended(reason)) => {
|
|
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 });
|
|
}
|
|
let state = StreamState::Ended(reason.into());
|
|
self.emit(Event::StreamState { session, state });
|
|
}
|
|
StreamEvent::Watch { id, event } => {
|
|
let state = match event {
|
|
WatchEvent::Accepted => WatchState::Connecting,
|
|
WatchEvent::Connected => WatchState::Connected,
|
|
WatchEvent::Ended(reason) => {
|
|
if self.audio {
|
|
let _ = self.link.send(LinkEvent::StreamAudioEnded(id.clone()));
|
|
}
|
|
WatchState::Ended(reason.into())
|
|
}
|
|
WatchEvent::Layers(_) => return self.watch_layers(&id),
|
|
WatchEvent::Frame(frame) => {
|
|
if let (MediaKind::Audio, true) = (frame.kind, self.audio) {
|
|
let _ = self.link.send(LinkEvent::StreamAudio {
|
|
stream: id.clone(),
|
|
time: frame.time.rebase(Frequency::FORTY_EIGHT_KHZ).numer(),
|
|
data: frame.data.clone(),
|
|
});
|
|
}
|
|
let _ = self.frames.send(StreamFrame { session, stream_id: id, frame });
|
|
return;
|
|
}
|
|
};
|
|
self.emit(Event::WatchState { session, stream_id: id, state });
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Tell the layers of watched stream `id` and the one we asked for.
|
|
fn watch_layers(&self, id: &str) {
|
|
let Some(watched) = self.streams.watching().find(|v| v.id() == id) else { return };
|
|
self.emit(Event::WatchLayers {
|
|
session: self.session,
|
|
stream_id: id.to_owned(),
|
|
layers: watched.layers().to_vec(),
|
|
layer: watched.layer(),
|
|
});
|
|
}
|
|
|
|
/// The answer `stream.permissions` gives to a join request; `None`: ask.
|
|
fn join_decision(&self, viewer: ClientId) -> Option<bool> {
|
|
match *self.settings.current().get_arc(&STREAM_PERMISSIONS) {
|
|
StreamPermissions::Everyone => Some(true),
|
|
StreamPermissions::Nobody => Some(false),
|
|
// Friends are let in; others: ask.
|
|
StreamPermissions::Friends => self.friends.contains(&viewer.0).then_some(true),
|
|
// Our channel is let in; viewers from other channels: ask.
|
|
StreamPermissions::Channel => {
|
|
let discovery = self.streams.discovery();
|
|
let own = discovery.own_channel();
|
|
(own.is_some() && discovery.channel_of(viewer) == own).then_some(true)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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);
|
|
}
|
|
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 self.audio {
|
|
let _ = self.link.send(LinkEvent::StreamAudioEnded(stream_id.clone()));
|
|
}
|
|
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() });
|
|
}
|
|
}
|
|
}
|
|
|
|
// 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};
|
|
|
|
use tokio::time::timeout;
|
|
use voelin_stream::{FrameSource, SyntheticSource};
|
|
|
|
use super::*;
|
|
use crate::audio::{AudioHandle, AudioIn};
|
|
use crate::settings::Settings;
|
|
|
|
const CLIENTS: [u16; 2] = [5, 6];
|
|
|
|
/// The notifications the server sends for `request` from `from`, per receiver.
|
|
/// Every offer the fake server relayed, from all tests of this process.
|
|
fn lock_offers() -> std::sync::MutexGuard<'static, Vec<String>> {
|
|
static OFFERS: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
|
OFFERS.lock().unwrap_or_else(PoisonError::into_inner)
|
|
}
|
|
|
|
fn relay(from: u16, request: Request) -> Vec<(u16, StreamNotification)> {
|
|
let both = |n: StreamNotification| CLIENTS.map(|c| (c, n.clone())).to_vec();
|
|
if let Request::Respond { offer: Some(sdp), .. } = &request {
|
|
lock_offers().push(sdp.clone());
|
|
}
|
|
match request {
|
|
Request::Setup(setup) => CLIENTS
|
|
.map(|c| {
|
|
let info = voelin_stream::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,
|
|
viewers: Some(0),
|
|
};
|
|
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) })
|
|
}
|
|
Request::StreamInfo { .. } => Vec::new(),
|
|
}
|
|
}
|
|
|
|
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")
|
|
}
|
|
|
|
type Handles = Arc<Vec<StreamHandle>>;
|
|
|
|
/// Two stream tasks (sessions 1 and 2) whose commands go through a fake
|
|
/// server; `audio` is the viewer's audio thread.
|
|
fn pair(
|
|
audio: Option<AudioHandle>,
|
|
) -> (Handles, broadcast::Receiver<Event>, broadcast::Receiver<StreamFrame>) {
|
|
pair_with(audio, &Settings::in_memory())
|
|
}
|
|
|
|
/// [`pair`] with `settings` for both tasks.
|
|
fn pair_with(
|
|
audio: Option<AudioHandle>,
|
|
settings: &Settings,
|
|
) -> (Handles, broadcast::Receiver<Event>, broadcast::Receiver<StreamFrame>) {
|
|
let (handles, rx, frames, _) = pair_full(audio, settings, false, PeerConfig::loopback());
|
|
(handles, rx, frames)
|
|
}
|
|
|
|
/// [`pair_with`] with peers of `config`; 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,
|
|
config: PeerConfig,
|
|
) -> (
|
|
Handles,
|
|
broadcast::Receiver<Event>,
|
|
broadcast::Receiver<StreamFrame>,
|
|
mpsc::UnboundedReceiver<OwnStreamEvent>,
|
|
) {
|
|
// The streamer's own-stream events, out of the link's events.
|
|
let (own_tx, mut link_rx) = mpsc::unbounded_channel::<LinkEvent>();
|
|
let (own_out, own_rx) = mpsc::unbounded_channel();
|
|
tokio::spawn(async move {
|
|
while let Some(event) = link_rx.recv().await {
|
|
if let LinkEvent::OwnStream(event) = event {
|
|
let _ = own_out.send(event);
|
|
}
|
|
}
|
|
});
|
|
// The viewer's link events: what the session does with the audio of
|
|
// watched streams, it does with its audio thread.
|
|
let (viewer_tx, mut viewer_rx) = mpsc::unbounded_channel::<LinkEvent>();
|
|
let has_audio = audio.is_some();
|
|
tokio::spawn(async move {
|
|
while let Some(event) = viewer_rx.recv().await {
|
|
match (event, &audio) {
|
|
(LinkEvent::StreamAudio { stream, time, data }, Some(audio)) => {
|
|
audio.send(AudioIn::StreamAudio { stream, time, data });
|
|
}
|
|
(LinkEvent::StreamAudioEnded(stream), Some(audio)) => {
|
|
audio.send(AudioIn::StreamEnded(stream));
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
});
|
|
let (events, rx) = broadcast::channel(4096);
|
|
let (frames, frames_rx) = broadcast::channel(4096);
|
|
let mut requests = Vec::new();
|
|
let mut handles = Vec::new();
|
|
for (i, clid) in CLIENTS.into_iter().enumerate() {
|
|
let (request_tx, request_rx) = mpsc::unbounded_channel();
|
|
let config = config.clone();
|
|
let session = i as u64 + 1;
|
|
handles.push(StreamHandle::spawn(
|
|
session,
|
|
clid,
|
|
config,
|
|
request_tx,
|
|
events.clone(),
|
|
frames.clone(),
|
|
session == 2 && has_audio,
|
|
SharedSettings::new(settings.clone()),
|
|
if session == 1 { own_tx.clone() } else { viewer_tx.clone() },
|
|
));
|
|
requests.push(request_rx);
|
|
}
|
|
let handles = Arc::new(handles);
|
|
// The server: relays requests from one task as notifications to the others.
|
|
for (i, mut request_rx) in requests.into_iter().enumerate() {
|
|
let handles = handles.clone();
|
|
tokio::spawn(async move {
|
|
while let Some(request) = request_rx.recv().await {
|
|
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));
|
|
}
|
|
}
|
|
});
|
|
}
|
|
(handles, rx, frames_rx, own_rx)
|
|
}
|
|
|
|
/// Session 1 streams (auto-accepting), session 2 watches; returns the sink
|
|
/// once the viewer is connected.
|
|
async fn live_and_watching(
|
|
handles: &Handles,
|
|
rx: &mut broadcast::Receiver<Event>,
|
|
) -> StreamSink {
|
|
let setup = StreamSetup { name: "t".into(), ..Default::default() };
|
|
handles[0].send(StreamCmd::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(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;
|
|
handles[1].send(StreamCmd::Watch { stream_id: "s-1".into() });
|
|
wait(rx, |e| match e {
|
|
Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()),
|
|
_ => None,
|
|
})
|
|
.await;
|
|
sink.unwrap()
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn stream_tasks_through_fake_server() {
|
|
// The viewer's audio thread.
|
|
let (audio, audio_rx) = AudioHandle::channel();
|
|
let (handles, mut rx, mut frames_rx) = pair(Some(audio));
|
|
let sink = live_and_watching(&handles, &mut rx).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(StreamCmd::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();
|
|
|
|
// Stream audio went to the viewer's audio thread, in 20 ms steps,
|
|
// and the ended stream was forgotten there (the link events pass
|
|
// through a task on their way).
|
|
let mut received: Vec<AudioIn> = Vec::new();
|
|
timeout(Duration::from_secs(5), async {
|
|
while !matches!(received.last(), Some(AudioIn::StreamEnded(_))) {
|
|
received.extend(audio_rx.try_iter());
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
|
}
|
|
})
|
|
.await
|
|
.expect("the stream's audio ended");
|
|
let times: Vec<u64> = received
|
|
.iter()
|
|
.filter_map(|m| match m {
|
|
AudioIn::StreamAudio { stream, time, .. } if stream == "s-1" => Some(*time),
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
assert!(times.len() >= 10, "{} audio frames", times.len());
|
|
assert!(times.windows(2).all(|w| w[1] > w[0] && (w[1] - w[0]) % 960 == 0), "{times:?}");
|
|
assert!(matches!(received.last(), Some(AudioIn::StreamEnded(id)) if id == "s-1"));
|
|
|
|
// Errors surface as events.
|
|
handles[1].send(StreamCmd::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(StreamCmd::Shutdown("bye".into()));
|
|
}
|
|
|
|
/// Simulcast layers and the SRTP setting through the stream tasks: the
|
|
/// viewer gets the top layer only, the sink carries keyframe requests and
|
|
/// the bitrate target per layer.
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn layers_through_stream_tasks() {
|
|
let (handles, mut rx, mut frames_rx) = pair(None);
|
|
let layers = vec![
|
|
LayerSpec { id: 0, min_bitrate: 800_000, ..LayerSpec::single(2_000_000) },
|
|
LayerSpec { id: 1, scale: 0.5, ..LayerSpec::single(500_000) },
|
|
];
|
|
// Set before the stream starts: kept for it.
|
|
handles[0].send(StreamCmd::Layers(layers.clone()));
|
|
// The viewer is the DTLS server: its order decides.
|
|
handles[1].send(StreamCmd::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);
|
|
assert!(keyframes.contains(0), "{keyframes:?}");
|
|
|
|
let feeder = tokio::spawn({
|
|
let sink = sink.clone();
|
|
async move {
|
|
let mut source = SyntheticSource::with_layers(30, 0, true, &layers);
|
|
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 = 0;
|
|
timeout(Duration::from_secs(10), async {
|
|
while video < 20 {
|
|
let f = frames_rx.recv().await.unwrap();
|
|
if f.frame.kind == MediaKind::Video {
|
|
assert_eq!(SyntheticSource::frame_layer(&f.frame.data), Some(0));
|
|
video += 1;
|
|
}
|
|
}
|
|
})
|
|
.await
|
|
.expect("no frames");
|
|
// Bandwidth estimates reach the viewer list and the layer's target.
|
|
let (mut info, mut bitrate) = (None, None);
|
|
wait(&mut rx, |e| {
|
|
match e {
|
|
Event::StreamViewers { session: 1, viewers } if viewers[0].estimate.is_some() => {
|
|
info = Some(viewers[0].clone());
|
|
}
|
|
Event::StreamLayerBitrate { session: 1, layer: 0, bitrate: b } => bitrate = Some(b),
|
|
_ => {}
|
|
}
|
|
(info.is_some() && bitrate.is_some()).then_some(())
|
|
})
|
|
.await;
|
|
let info = info.unwrap();
|
|
assert_eq!(info.layer, Some(0));
|
|
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");
|
|
|
|
handles[0].send(StreamCmd::Stop);
|
|
wait(&mut rx, |e| match e {
|
|
Event::WatchState { session: 2, state: WatchState::Ended(_), .. } => Some(()),
|
|
_ => None,
|
|
})
|
|
.await;
|
|
feeder.await.unwrap();
|
|
}
|
|
|
|
/// What the encoder tells about a layer reaches the live stream: the
|
|
/// largest layer's size, frame rate and bitrate set the H.264 level of
|
|
/// the next offer (both profiles), and an automatic bitrate goes into the
|
|
/// layer (which asks the viewer's layer for a keyframe, as every layer
|
|
/// change does); the same again changes nothing.
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn layer_formats_reach_the_live_stream() {
|
|
// The streamer offers H.264 (and the viewer takes it).
|
|
let config = PeerConfig { video_codecs: vec![VideoCodec::H264], ..PeerConfig::loopback() };
|
|
let (handles, mut rx, _frames, _) = pair_full(None, &Settings::in_memory(), false, config);
|
|
let setup = StreamSetup { name: "4K120".into(), ..Default::default() };
|
|
handles[0].send(StreamCmd::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();
|
|
let format =
|
|
|bitrate| LayerFormat { width: 3840, height: 2160, fps: 60, bitrate, automatic: true };
|
|
// Before the viewer asks: its offer is made after this.
|
|
sink.layer_format(0, format(60_000_000));
|
|
handles[1].send(StreamCmd::Watch { stream_id: "s-1".into() });
|
|
// Connected for the viewer and for the streamer, in either order: the
|
|
// streamer asks for a keyframe when its viewer connects, a moment after
|
|
// the viewer has seen the connection.
|
|
let (mut watching, mut served) = (false, false);
|
|
wait(&mut rx, |e| {
|
|
match e {
|
|
Event::WatchState { session: 2, state: WatchState::Connected, .. } => {
|
|
watching = true;
|
|
}
|
|
Event::StreamViewers { session: 1, viewers } => {
|
|
served |= viewers.iter().any(|v| v.state == ViewerState::Connected);
|
|
}
|
|
_ => {}
|
|
}
|
|
(watching && served).then_some(())
|
|
})
|
|
.await;
|
|
// 3840x2160 at 60 fps is level 5.2 (0x34) in both profiles.
|
|
let offers = lock_offers().clone();
|
|
assert!(
|
|
offers.iter().any(|o| o.contains("profile-level-id=640c34") && o.contains("42e034")),
|
|
"{offers:?}"
|
|
);
|
|
|
|
let keyframes = || {
|
|
let mut layers = LayerSet::new();
|
|
sink.take_layer_keyframes(&mut layers);
|
|
layers.contains(0)
|
|
};
|
|
// What asked for a keyframe so far (going live, the viewer's connecting
|
|
// and its first picture request) is done when a moment longer than the
|
|
// merging interval of requests (250 ms) passes with none.
|
|
for _ in 0..50 {
|
|
tokio::time::sleep(Duration::from_millis(300)).await;
|
|
if !keyframes() {
|
|
break;
|
|
}
|
|
}
|
|
sink.layer_format(0, format(9_000_000));
|
|
timeout(Duration::from_secs(5), async {
|
|
while !keyframes() {
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
|
}
|
|
})
|
|
.await
|
|
.expect("the layer did not change");
|
|
sink.layer_format(0, format(9_000_000));
|
|
tokio::time::sleep(Duration::from_millis(200)).await;
|
|
assert!(!keyframes(), "nothing changed");
|
|
handles[0].send(StreamCmd::Stop);
|
|
}
|
|
|
|
#[test]
|
|
fn the_offer_covers_the_largest_layer() {
|
|
let format = |width, height, fps, bitrate| LayerFormat {
|
|
width,
|
|
height,
|
|
fps,
|
|
bitrate,
|
|
automatic: false,
|
|
};
|
|
let layers = [
|
|
LayerSpec { max_bitrate: Some(12_000_000), ..LayerSpec::single(8_000_000) },
|
|
LayerSpec { id: 1, scale: 0.5, ..LayerSpec::single(2_000_000) },
|
|
];
|
|
let mut formats = BTreeMap::new();
|
|
assert_eq!(offer_format(&formats, &layers), None);
|
|
formats.insert(1, format(960, 540, 120, 2_000_000));
|
|
formats.insert(0, format(1920, 1080, 60, 8_000_000));
|
|
// Layer 0's size and its bitrate at its maximum, layer 1's rate.
|
|
assert_eq!(offer_format(&formats, &layers), Some((1920, 1080, 120, 12_000_000)));
|
|
// A layer the stream no longer has does not count.
|
|
formats.insert(7, format(7680, 4320, 30, 60_000_000));
|
|
assert_eq!(offer_format(&formats, &layers), Some((1920, 1080, 120, 12_000_000)));
|
|
}
|
|
|
|
/// 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 loopback = PeerConfig::loopback();
|
|
let (handles, mut rx, _frames, mut own) =
|
|
pair_full(None, &Settings::in_memory(), true, loopback);
|
|
let setup = StreamSetup {
|
|
name: "directory test".into(),
|
|
kind: StreamKind::Window,
|
|
..Default::default()
|
|
};
|
|
handles[0].send(StreamCmd::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: CLIENTS[0],
|
|
name: "directory test".into(),
|
|
kind: parse_kind(&kind_name(StreamKind::Window)),
|
|
bitrate: 0,
|
|
viewer_limit: 0,
|
|
audio: true,
|
|
viewers: None,
|
|
};
|
|
handles[1].send(StreamCmd::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(StreamCmd::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(StreamCmd::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(StreamCmd::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);
|
|
}
|
|
|
|
/// 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()));
|
|
}
|
|
|
|
// Every viewer state, stream kind (both ways) and leave reason.
|
|
for (state, expected) in [
|
|
(wire::ViewerState::Requested, ViewerState::Requested),
|
|
(wire::ViewerState::Connecting, ViewerState::Connecting),
|
|
(wire::ViewerState::Connected, ViewerState::Connected),
|
|
] {
|
|
assert_eq!(ViewerState::from(state), expected);
|
|
}
|
|
for (sent, kind) in [
|
|
(wire::StreamKind::Camera, StreamKind::Camera),
|
|
(wire::StreamKind::Screen, StreamKind::Screen),
|
|
(wire::StreamKind::Window, StreamKind::Window),
|
|
(wire::StreamKind::Other(9), StreamKind::Other(9)),
|
|
] {
|
|
assert_eq!(StreamKind::from(sent), kind);
|
|
assert_eq!(wire::StreamKind::from(kind), sent);
|
|
}
|
|
for (reason, expected) in [
|
|
(wire::LeaveReason::None, LeaveReason::None),
|
|
(wire::LeaveReason::Left, LeaveReason::Left),
|
|
(wire::LeaveReason::Denied, LeaveReason::Denied),
|
|
(wire::LeaveReason::Failed, LeaveReason::Failed),
|
|
(wire::LeaveReason::Kicked, LeaveReason::Kicked),
|
|
(wire::LeaveReason::Banned, LeaveReason::Banned),
|
|
(wire::LeaveReason::Other(42), LeaveReason::Other(42)),
|
|
] {
|
|
assert_eq!(LeaveReason::from(reason), expected);
|
|
assert_eq!(
|
|
EndReason::from(wire::EndReason::Removed(Some(reason))),
|
|
EndReason::Removed(Some(expected))
|
|
);
|
|
}
|
|
|
|
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")]
|
|
async fn permissions_answer_join_requests() {
|
|
let in_channels = |streamer: u64, viewer: u64| {
|
|
StreamInput::Clients(BTreeMap::from([
|
|
(CLIENTS[0], ClientState { channel: streamer, streaming: Some(false) }),
|
|
(CLIENTS[1], ClientState { channel: viewer, streaming: Some(false) }),
|
|
]))
|
|
};
|
|
for (permissions, viewer_channel, friend, expected) in [
|
|
(StreamPermissions::Everyone, 2, false, Some(true)),
|
|
(StreamPermissions::Channel, 1, false, Some(true)),
|
|
(StreamPermissions::Channel, 2, false, None),
|
|
(StreamPermissions::Nobody, 1, false, Some(false)),
|
|
(StreamPermissions::Friends, 1, false, None),
|
|
(StreamPermissions::Friends, 2, true, Some(true)),
|
|
] {
|
|
let settings = Settings::in_memory();
|
|
settings.set(&STREAM_PERMISSIONS, permissions).unwrap();
|
|
let (handles, mut rx, _frames) = pair_with(None, &settings);
|
|
for h in handles.iter() {
|
|
h.send(in_channels(1, viewer_channel));
|
|
}
|
|
if friend {
|
|
handles[0].send(StreamCmd::Friends(BTreeSet::from([CLIENTS[1]])));
|
|
}
|
|
let setup = StreamSetup { name: "p".into(), ..Default::default() };
|
|
handles[0].send(StreamCmd::Start { setup, auto_accept: false });
|
|
let (mut live, mut listed) = (false, false);
|
|
wait(&mut rx, |e| {
|
|
match e {
|
|
Event::StreamState { session: 1, state: StreamState::Live { .. } } => {
|
|
live = true
|
|
}
|
|
Event::StreamsChanged { session: 2, streams } => listed = !streams.is_empty(),
|
|
_ => {}
|
|
}
|
|
(live && listed).then_some(())
|
|
})
|
|
.await;
|
|
handles[1].send(StreamCmd::Watch { stream_id: "s-1".into() });
|
|
let answer = wait(&mut rx, |e| match e {
|
|
Event::WatchState { session: 2, state: WatchState::Connected, .. } => {
|
|
Some(Some(true))
|
|
}
|
|
Event::WatchState {
|
|
session: 2,
|
|
state: WatchState::Ended(EndReason::Denied),
|
|
..
|
|
} => Some(Some(false)),
|
|
Event::StreamViewerRequest { session: 1, .. } => Some(None),
|
|
_ => None,
|
|
})
|
|
.await;
|
|
assert_eq!(answer, expected, "{permissions:?}, viewer in channel {viewer_channel}");
|
|
for h in handles.iter() {
|
|
h.send(StreamCmd::Shutdown("done".into()));
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The whole path: test pattern → VP8 → stream task → str0m peers on
|
|
/// loopback → the viewer's frame bus → decoder. The pictures show the
|
|
/// moving rectangle.
|
|
#[cfg(feature = "media-desktop")]
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn test_pattern_through_stream_tasks() {
|
|
use std::sync::mpsc as std_mpsc;
|
|
|
|
use voelin_media::capture::SourceId;
|
|
use voelin_media::{Codec, Codecs};
|
|
|
|
use crate::media::{Streamer, StreamerConfig, VideoPipeline, rectangle_span};
|
|
|
|
let (handles, mut rx, mut frames_rx) = pair(None);
|
|
let sink = live_and_watching(&handles, &mut rx).await;
|
|
let codecs = Arc::new(Codecs::new());
|
|
let config = StreamerConfig {
|
|
source: SourceId::Synthetic,
|
|
synthetic_size: (320, 240),
|
|
bitrate_kbps: 1500,
|
|
..StreamerConfig::default()
|
|
};
|
|
let streamer = Streamer::start(&codecs, config).await.unwrap();
|
|
streamer.attach(Arc::new(sink.clone()));
|
|
|
|
let (tx, pictures) = std_mpsc::channel();
|
|
let pipeline = VideoPipeline::new(
|
|
codecs,
|
|
move |picture| {
|
|
let _ = tx.send(picture);
|
|
},
|
|
{
|
|
let handles = handles.clone();
|
|
move || handles[1].send(StreamCmd::RequestKeyframe { stream_id: "s-1".into() })
|
|
},
|
|
);
|
|
let input = pipeline.input();
|
|
let forward = tokio::spawn(async move {
|
|
while let Ok(f) = frames_rx.recv().await {
|
|
input.push(f.frame);
|
|
}
|
|
});
|
|
let spans = tokio::task::spawn_blocking(move || {
|
|
let mut spans = Vec::new();
|
|
while spans.len() < 15 {
|
|
let picture = pictures.recv_timeout(Duration::from_secs(10)).expect("no picture");
|
|
assert_eq!((picture.width, picture.height), (320, 240));
|
|
spans.push(rectangle_span(&picture));
|
|
}
|
|
spans
|
|
})
|
|
.await
|
|
.unwrap();
|
|
for (a, b) in &spans {
|
|
assert!((60..=68).contains(&(b - a + 1)), "{spans:?}");
|
|
}
|
|
assert_ne!(spans.first(), spans.last(), "the rectangle moves");
|
|
let stats = pipeline.stats();
|
|
assert_eq!(stats.codec, Some(Codec::Vp8));
|
|
assert!(stats.error.is_none(), "{stats:?}");
|
|
// The encoder counts a frame once the sink has taken it, so the picture
|
|
// can be at the viewer before the count has moved.
|
|
let mut sent = streamer.stats();
|
|
for _ in 0..500 {
|
|
if sent.video_frames >= 15 && sent.audio_frames > 0 {
|
|
break;
|
|
}
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
|
sent = streamer.stats();
|
|
}
|
|
assert!(sent.video_frames >= 15 && sent.audio_frames > 0, "{sent:?}");
|
|
|
|
handles[0].send(StreamCmd::Stop);
|
|
wait(&mut rx, |e| match e {
|
|
Event::WatchState { session: 2, state: WatchState::Ended(_), .. } => Some(()),
|
|
_ => None,
|
|
})
|
|
.await;
|
|
forward.abort();
|
|
drop(streamer);
|
|
}
|
|
}
|