What we share and what we watch are in the AppState now (Sharing, Watching), with the transitions of the engine's stream events (apply handles them, the Stream Studio's stream excepted), the user's choices (watch, leave, volume, quality, the share dialog's plan, the capture that started) and the rows and texts of the streams panel, the share card and the viewer, as plain data in streams/logic.rs with tests of their own. The Slint side (streams/bind.rs) writes the Bridge, owns the capture and the decoder, and attaches or drops them as an update says (StreamEffects). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1387 lines
45 KiB
Rust
1387 lines
45 KiB
Rust
//! The streams we share and the one we watch: their state, what the engine's
|
||
//! events and the user's choices do to it, and the rows and texts the
|
||
//! streams panel, the share dialog and the viewer show. The capture and the
|
||
//! decoder are the front end's: a transition says in the update's
|
||
//! [`StreamEffects`](crate::host::StreamEffects) when to attach, drop or
|
||
//! start them.
|
||
|
||
use std::sync::Arc;
|
||
use std::time::Instant;
|
||
|
||
use voelin_core::media::{AudioSourceSpec, audio_source_specs};
|
||
use voelin_core::settings::AudioSourceSetting;
|
||
use voelin_core::stream::{
|
||
EndReason, LayerId, LayerSpec, LeaveReason, StreamSetup, ViewerInfo, ViewerState,
|
||
};
|
||
use voelin_core::{Command, StreamState, WatchState};
|
||
|
||
use super::{kind_label, streamer};
|
||
use crate::bridge::{ShareForm, StreamItem, ViewerItem};
|
||
use crate::color::Rgb;
|
||
use crate::host::Cx;
|
||
use crate::image::ImageRef;
|
||
use crate::settings::{
|
||
BITRATE_CHOICES, FPS_CHOICES, LEGACY_BITRATE_CHOICES, LEGACY_FPS_CHOICES, ShareDefaults,
|
||
nearest_choice, parse_positive,
|
||
};
|
||
use crate::state::{AppState, SessionView};
|
||
|
||
/// What the share dialog asks of the capture.
|
||
pub struct CaptureRequest {
|
||
/// Frames per second.
|
||
pub fps: u32,
|
||
/// Video bitrate in kbit/s (0: automatic).
|
||
pub bitrate_kbps: u32,
|
||
/// Share sound too.
|
||
pub audio: bool,
|
||
/// Mixed into the stream's audio (`stream.audio_sources`).
|
||
pub audio_sources: Vec<AudioSourceSpec>,
|
||
/// The desktop portal's token of the last choice.
|
||
pub restore_token: Option<String>,
|
||
}
|
||
|
||
/// What the share dialog asks of the capture: the audio mixer's `sources`
|
||
/// (`stream.audio_sources`) while "Share system audio" is on; off, or with
|
||
/// no sources, no audio at all.
|
||
pub fn capture_request(
|
||
fps: u32,
|
||
bitrate_kbps: u32,
|
||
audio: bool,
|
||
sources: &[AudioSourceSetting],
|
||
restore_token: Option<String>,
|
||
) -> CaptureRequest {
|
||
let audio_sources = if audio { audio_source_specs(sources) } else { Vec::new() };
|
||
CaptureRequest {
|
||
fps,
|
||
bitrate_kbps,
|
||
audio: !audio_sources.is_empty(),
|
||
audio_sources,
|
||
restore_token,
|
||
}
|
||
}
|
||
|
||
/// The viewers of the sample share (`VOELIN_DEMO_UI`): two watch, one asks.
|
||
pub fn demo_viewers() -> Vec<ViewerInfo> {
|
||
let viewer = |id, state, message: &str| ViewerInfo {
|
||
client: id,
|
||
state,
|
||
message: message.into(),
|
||
layer: None,
|
||
estimate: None,
|
||
srtp_profile: None,
|
||
codec: None,
|
||
};
|
||
vec![
|
||
viewer(3, ViewerState::Connected, ""),
|
||
viewer(5, ViewerState::Connected, ""),
|
||
viewer(4, ViewerState::Requested, "Can I watch?"),
|
||
]
|
||
}
|
||
|
||
/// Our stream, as far as it is state: the capture that feeds it is the
|
||
/// front end's.
|
||
#[derive(Debug)]
|
||
pub struct Sharing {
|
||
/// The session it goes to.
|
||
pub session: i64,
|
||
/// The server confirmed the stream.
|
||
pub live: bool,
|
||
/// Who watches or asks to.
|
||
pub viewers: Vec<ViewerInfo>,
|
||
/// The capture ended by itself and the stream is being stopped.
|
||
pub stopping: bool,
|
||
}
|
||
|
||
/// The stream in the viewer, as far as it is state: the decoder is the front
|
||
/// end's.
|
||
#[derive(Debug)]
|
||
pub struct Watching {
|
||
/// `None` for the local demo stream.
|
||
pub session: Option<i64>,
|
||
/// The stream's id (`"demo"` for the local one).
|
||
pub stream_id: String,
|
||
/// The title shown.
|
||
pub title: String,
|
||
/// Who streams it.
|
||
pub streamer: String,
|
||
/// Shown over the picture; empty while it plays.
|
||
pub status: String,
|
||
/// Frames arrive.
|
||
pub connected: bool,
|
||
/// The stream ended (or we were removed).
|
||
pub ended: bool,
|
||
/// A picture was shown.
|
||
pub has_frame: bool,
|
||
/// Shown instead of the chat.
|
||
pub shown: bool,
|
||
/// When the picture started, for the elapsed time.
|
||
pub since: Option<Instant>,
|
||
/// The simulcast layers the streamer offers, largest first.
|
||
pub layers: Vec<LayerSpec>,
|
||
/// The layer chosen by hand; `None` follows the bandwidth estimate.
|
||
pub layer: Option<LayerId>,
|
||
}
|
||
|
||
impl Watching {
|
||
/// "12:34" since the picture started.
|
||
pub fn elapsed(&self) -> String {
|
||
let Some(since) = self.since else { return String::new() };
|
||
let seconds = since.elapsed().as_secs();
|
||
match seconds / 3600 {
|
||
0 => format!("{:02}:{:02}", seconds / 60, seconds % 60),
|
||
hours => format!("{hours}:{:02}:{:02}", (seconds / 60) % 60, seconds % 60),
|
||
}
|
||
}
|
||
|
||
/// "Auto" and one entry per layer the streamer offers.
|
||
pub fn qualities(&self) -> Vec<Arc<str>> {
|
||
if self.layers.len() < 2 {
|
||
return Vec::new();
|
||
}
|
||
let mut names: Vec<Arc<str>> = vec!["Auto".into()];
|
||
names.extend(self.layers.iter().map(|l| layer_name(l).into()));
|
||
names
|
||
}
|
||
|
||
/// The stream is on the server on screen (or is the local test stream).
|
||
pub fn here(&self, current: Option<i64>) -> bool {
|
||
self.session.is_none() || self.session == current
|
||
}
|
||
|
||
/// The position of the chosen layer among `qualities` (0: automatic).
|
||
pub fn chosen_quality(&self) -> i32 {
|
||
self.layer
|
||
.and_then(|id| self.layers.iter().position(|l| l.id == id))
|
||
.map_or(0, |i| i as i32 + 1)
|
||
}
|
||
}
|
||
|
||
/// "720p · 2.4 Mbit/s", or the scale when the size is not fixed.
|
||
pub fn layer_name(layer: &LayerSpec) -> String {
|
||
let size = match layer.size {
|
||
Some((_, h)) => format!("{h}p"),
|
||
None => format!("{:.0}%", layer.scale * 100.0),
|
||
};
|
||
format!("{size} · {:.1} Mbit/s", layer.bitrate as f64 / 1_000_000.0)
|
||
}
|
||
|
||
/// What the viewer says when a watched stream ended.
|
||
pub fn end_text(reason: &EndReason, streamer: &str) -> String {
|
||
match reason {
|
||
EndReason::Local => "You left the stream.".into(),
|
||
EndReason::Denied => format!("{streamer} did not let you watch."),
|
||
EndReason::Stopped => "The stream has ended.".into(),
|
||
EndReason::Removed(Some(LeaveReason::Kicked | LeaveReason::Banned)) => {
|
||
format!("{streamer} removed you from the stream.")
|
||
}
|
||
EndReason::Removed(_) => "You were removed from the stream.".into(),
|
||
EndReason::Failed(e) => format!("The stream failed: {e}"),
|
||
}
|
||
}
|
||
|
||
/// What the status line says when our stream ended other than by us.
|
||
pub fn share_end_text(reason: &EndReason) -> String {
|
||
match reason {
|
||
EndReason::Failed(e) => format!("Sharing failed: {e}"),
|
||
_ => "Sharing ended.".into(),
|
||
}
|
||
}
|
||
|
||
/// How many watch stream `id`: the server's count (TeamSpeak 6 tells it),
|
||
/// else the gateway directory's.
|
||
pub fn viewer_count<L>(view: &SessionView<L>, id: &str) -> Option<u32> {
|
||
let native = view.streams.iter().find(|s| s.id == id).and_then(|s| s.viewers);
|
||
native.or_else(|| view.stream_viewers.get(id).copied())
|
||
}
|
||
|
||
/// "8 Mbit/s", "640 kbit/s" (the stream's announced bitrate, kbit/s); "" for 0.
|
||
pub fn bitrate_text(kbps: u32) -> String {
|
||
match kbps {
|
||
0 => String::new(),
|
||
1..=999 => format!("{kbps} kbit/s"),
|
||
_ if kbps.is_multiple_of(1000) => format!("{} Mbit/s", kbps / 1000),
|
||
_ => format!("{:.1} Mbit/s", f64::from(kbps) / 1000.0),
|
||
}
|
||
}
|
||
|
||
// What the engine tells.
|
||
|
||
/// Someone asks to watch our stream.
|
||
pub fn viewer_request<L>(state: &AppState<L>, cx: &mut Cx<'_>, session: i64, viewer: u16) {
|
||
let name = state
|
||
.sessions
|
||
.get(&session)
|
||
.map_or_else(|| format!("client {viewer}"), |view| view.nickname(viewer));
|
||
cx.status(format!("{name} wants to watch your stream"));
|
||
}
|
||
|
||
/// The viewers of our stream and their state.
|
||
pub fn viewers<L>(
|
||
state: &mut AppState<L>,
|
||
cx: &mut Cx<'_>,
|
||
session: i64,
|
||
viewers: Vec<ViewerInfo>,
|
||
) {
|
||
if let Some(share) = state.share.as_mut().filter(|s| s.session == session) {
|
||
share.viewers = viewers;
|
||
cx.update.refresh.streams = true;
|
||
}
|
||
}
|
||
|
||
/// Our stream went live or ended.
|
||
pub fn share_state<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64, stream: StreamState) {
|
||
let Some(share) = state.share.as_mut().filter(|s| s.session == session) else { return };
|
||
match stream {
|
||
StreamState::Starting => {}
|
||
StreamState::Live { sink, .. } => {
|
||
share.live = true;
|
||
cx.update.stream.attach = Some(sink);
|
||
cx.status("You are sharing your screen");
|
||
}
|
||
StreamState::Ended(reason) => {
|
||
let local = reason == EndReason::Local || share.stopping;
|
||
state.share = None;
|
||
cx.update.stream.drop_share = true;
|
||
state.share_error = if local { String::new() } else { share_end_text(&reason) };
|
||
cx.status(if local { "You stopped sharing".into() } else { share_end_text(&reason) });
|
||
cx.update.stream.mixer = true;
|
||
}
|
||
}
|
||
cx.update.refresh.streams = true;
|
||
}
|
||
|
||
/// The stream we watch connects, ends, ...
|
||
pub fn watch_state<L>(
|
||
state: &mut AppState<L>,
|
||
cx: &mut Cx<'_>,
|
||
session: i64,
|
||
stream_id: &str,
|
||
watching: WatchState,
|
||
) {
|
||
let Some(watch) = state
|
||
.watch
|
||
.as_mut()
|
||
.filter(|w| w.session == Some(session) && w.stream_id == stream_id && !w.ended)
|
||
else {
|
||
return;
|
||
};
|
||
match watching {
|
||
WatchState::Requested => {
|
||
watch.status = format!("Waiting for {} to let you watch…", watch.streamer);
|
||
}
|
||
WatchState::Connecting => {
|
||
watch.status = format!("Connecting to {}…", watch.streamer);
|
||
}
|
||
WatchState::Connected => {
|
||
watch.connected = true;
|
||
if !watch.has_frame {
|
||
watch.status = "Waiting for the picture…".into();
|
||
}
|
||
}
|
||
WatchState::Ended(reason) => {
|
||
watch.ended = true;
|
||
cx.update.stream.drop_decoder = true;
|
||
watch.status = end_text(&reason, &watch.streamer);
|
||
}
|
||
}
|
||
cx.update.refresh.viewer = true;
|
||
cx.update.refresh.streams = true;
|
||
}
|
||
|
||
/// The layers the streamer of the watched stream offers.
|
||
pub fn watch_layers<L>(
|
||
state: &mut AppState<L>,
|
||
cx: &mut Cx<'_>,
|
||
session: i64,
|
||
stream_id: &str,
|
||
layers: Vec<LayerSpec>,
|
||
layer: Option<LayerId>,
|
||
) {
|
||
if let Some(watch) =
|
||
state.watch.as_mut().filter(|w| w.session == Some(session) && w.stream_id == stream_id)
|
||
{
|
||
watch.layers = layers;
|
||
watch.layer = layer;
|
||
cx.update.refresh.viewer = true;
|
||
}
|
||
}
|
||
|
||
// What the user does: watching.
|
||
|
||
/// Stop watching and close the viewer; a window of its own stays (for the
|
||
/// next stream).
|
||
pub fn stop_watching<L>(state: &mut AppState<L>, cx: &mut Cx<'_>) {
|
||
if let Some(watch) = state.watch.take()
|
||
&& let Some(session) = watch.session
|
||
&& !watch.ended
|
||
{
|
||
cx.send(Command::LeaveStream { session: session as u64, stream_id: watch.stream_id });
|
||
}
|
||
cx.update.stream.drop_decoder = true;
|
||
cx.update.stream.leave_fullscreen = true;
|
||
watching_changed(cx);
|
||
}
|
||
|
||
/// What changes with the viewer: its header, the streams panel, and the
|
||
/// members panel beside it (our channel's people lead it).
|
||
fn watching_changed(cx: &mut Cx<'_>) {
|
||
let r = &mut cx.update.refresh;
|
||
(r.viewer, r.streams, r.tree) = (true, true, true);
|
||
}
|
||
|
||
/// Watch stream `stream_id` of the current session: ask the streamer, and
|
||
/// show the viewer; the session, when the stream is known (the front end
|
||
/// then starts decoding).
|
||
pub fn watch_stream<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, stream_id: &str) -> Option<i64> {
|
||
let session = state.current?;
|
||
let view = state.sessions.get(&session)?;
|
||
let info = view.streams.iter().find(|s| s.id == stream_id)?;
|
||
let streamer = view.nickname(info.streamer);
|
||
let title =
|
||
if info.name.is_empty() { format!("{streamer}'s stream") } else { info.name.clone() };
|
||
// A window of its own stays, for this stream.
|
||
stop_watching(state, cx);
|
||
cx.send(Command::WatchStream { session: session as u64, stream_id: stream_id.to_owned() });
|
||
if state.stream_volume != 100.0 {
|
||
cx.send(Command::SetStreamVolume {
|
||
session: session as u64,
|
||
stream_id: stream_id.to_owned(),
|
||
volume: state.stream_volume / 100.0,
|
||
});
|
||
}
|
||
state.watch = Some(Watching {
|
||
session: Some(session),
|
||
stream_id: stream_id.to_owned(),
|
||
title,
|
||
status: format!("Asking {streamer} to let you watch…"),
|
||
streamer,
|
||
connected: false,
|
||
ended: false,
|
||
has_frame: false,
|
||
shown: true,
|
||
since: None,
|
||
layers: Vec::new(),
|
||
layer: None,
|
||
});
|
||
watching_changed(cx);
|
||
Some(session)
|
||
}
|
||
|
||
/// Watch the stream of `client` (a click on a streaming user in the channel
|
||
/// tree or the members): the stream to watch at once if it is known, else
|
||
/// as soon as the lookup brings it (it may have started in another channel
|
||
/// or before we joined).
|
||
pub fn watch_client<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, client: u16) -> Option<String> {
|
||
let session = state.current?;
|
||
let view = state.sessions.get(&session)?;
|
||
if view.state.own_client == Some(client) {
|
||
return None;
|
||
}
|
||
if let Some(id) = view.streams.iter().find(|s| s.streamer == client).map(|s| s.id.clone()) {
|
||
state.pending_watch = None;
|
||
Some(id)
|
||
} else if view.presence.clients.get(&client).is_some_and(|c| c.streaming == Some(true)) {
|
||
let name = view.nickname(client);
|
||
state.pending_watch = Some((session, client));
|
||
cx.status(format!("Looking up {name}'s stream…"));
|
||
None
|
||
} else {
|
||
None
|
||
}
|
||
}
|
||
|
||
/// The first stream of our channel that is not ours (`VOELIN_OPEN=watch`).
|
||
pub fn first_stream<L>(state: &AppState<L>) -> Option<String> {
|
||
let view = state.sessions.get(&state.current?)?;
|
||
view.streams.iter().find(|s| view.state.own_client != Some(s.streamer)).map(|s| s.id.clone())
|
||
}
|
||
|
||
/// The local test stream in the viewer (`VOELIN_DEMO_STREAM`).
|
||
pub fn start_demo<L>(state: &mut AppState<L>, cx: &mut Cx<'_>) {
|
||
stop_watching(state, cx);
|
||
state.watch = Some(Watching {
|
||
session: None,
|
||
stream_id: "demo".into(),
|
||
title: "Test pattern".into(),
|
||
streamer: "local preview".into(),
|
||
status: "Starting the local preview…".into(),
|
||
connected: true,
|
||
ended: false,
|
||
has_frame: false,
|
||
shown: true,
|
||
since: None,
|
||
layers: Vec::new(),
|
||
layer: None,
|
||
});
|
||
watching_changed(cx);
|
||
}
|
||
|
||
/// The sample data's first stream of our channel: its id, title and
|
||
/// streamer, for the test pattern to be dressed as (`VOELIN_OPEN=watch`).
|
||
pub fn demo_sample<L>(state: &AppState<L>) -> Option<(String, String, String)> {
|
||
let view = state.sessions.get(&state.current?)?;
|
||
view.streams.first().map(|s| (s.id.clone(), s.name.clone(), view.nickname(s.streamer)))
|
||
}
|
||
|
||
/// A decoded picture arrived: the first one clears the status over the
|
||
/// picture and starts the clock. `true` for the first.
|
||
pub fn picture_shown<L>(state: &mut AppState<L>) -> bool {
|
||
let Some(watch) = &mut state.watch else { return false };
|
||
let first = !watch.has_frame;
|
||
watch.has_frame = true;
|
||
if first {
|
||
watch.status.clear();
|
||
watch.since = Some(Instant::now());
|
||
}
|
||
first
|
||
}
|
||
|
||
/// The viewer is shown instead of the chat, or hidden.
|
||
pub fn show_viewer<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, shown: bool) {
|
||
if let Some(watch) = &mut state.watch {
|
||
watch.shown = shown;
|
||
}
|
||
if !shown {
|
||
cx.update.stream.leave_fullscreen = true;
|
||
}
|
||
watching_changed(cx);
|
||
}
|
||
|
||
/// The watched stream's volume in percent, kept between streams.
|
||
pub fn set_volume<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, percent: f32) {
|
||
state.stream_volume = percent.round().clamp(0.0, 200.0);
|
||
if let Some(watch) = &state.watch
|
||
&& let Some(session) = watch.session
|
||
{
|
||
cx.send(Command::SetStreamVolume {
|
||
session: session as u64,
|
||
stream_id: watch.stream_id.clone(),
|
||
volume: state.stream_volume / 100.0,
|
||
});
|
||
}
|
||
}
|
||
|
||
/// A simulcast layer of the watched stream (0: follow the bandwidth
|
||
/// estimate), asked of the streamer; the engine confirms with
|
||
/// `WatchLayers`.
|
||
pub fn set_quality<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, index: i32) {
|
||
let Some(watch) = &mut state.watch else { return };
|
||
watch.layer = usize::try_from(index - 1).ok().and_then(|i| watch.layers.get(i)).map(|l| l.id);
|
||
if let Some(session) = watch.session {
|
||
cx.send(Command::SetWatchLayer {
|
||
session: session as u64,
|
||
stream_id: watch.stream_id.clone(),
|
||
layer: watch.layer,
|
||
});
|
||
}
|
||
cx.update.refresh.viewer = true;
|
||
}
|
||
|
||
/// The watched stream's decoder could never show a picture: what the
|
||
/// viewer says (once connected, while no picture came).
|
||
pub fn decoder_failed<L>(state: &mut AppState<L>, error: &str) {
|
||
if let Some(watch) = &mut state.watch
|
||
&& watch.connected
|
||
&& !watch.has_frame
|
||
{
|
||
watch.status = if error.contains("H264") || error.contains("OpenH264") {
|
||
format!("{error}. Enable H.264 in Settings → Streaming to watch this stream.")
|
||
} else {
|
||
format!("Cannot show the picture: {error}")
|
||
};
|
||
}
|
||
}
|
||
|
||
// What the user does: sharing.
|
||
|
||
/// The sources of the share dialog arrived, or could not be listed.
|
||
pub fn sources_listed<L, T>(state: &mut AppState<L>, result: Result<Vec<T>, String>) -> Vec<T> {
|
||
match result {
|
||
Ok(sources) => {
|
||
if state.share.is_none() {
|
||
state.share_error.clear();
|
||
}
|
||
sources
|
||
}
|
||
Err(e) => {
|
||
state.share_error = e;
|
||
Vec::new()
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The share dialog's form: the first source, a name from our nickname, the
|
||
/// last choices (`fps` and `bitrate` are the stored settings).
|
||
pub fn share_form<L>(state: &AppState<L>, fps: u32, bitrate: u32) -> ShareForm {
|
||
let defaults = &state.settings.share;
|
||
let nickname = state
|
||
.current
|
||
.and_then(|id| state.bookmarks.iter().find(|b| b.id == id))
|
||
.map(|b| b.nickname.clone());
|
||
ShareForm {
|
||
source: 0,
|
||
name: match nickname {
|
||
Some(nick) if !nick.is_empty() => format!("{nick}'s screen").into(),
|
||
_ => "Screen".into(),
|
||
},
|
||
fps_index: nearest_choice(&FPS_CHOICES, fps) as i32,
|
||
fps: fps.to_string().into(),
|
||
bitrate_index: nearest_choice(&BITRATE_CHOICES, bitrate) as i32,
|
||
// Automatic (0): the field stays empty.
|
||
bitrate: if bitrate == 0 { String::new() } else { bitrate.to_string() }.into(),
|
||
audio: defaults.audio,
|
||
auto_accept: defaults.auto_accept,
|
||
}
|
||
}
|
||
|
||
/// What starting to share comes to.
|
||
pub struct SharePlan {
|
||
/// The session it goes to.
|
||
pub session: i64,
|
||
/// The source picked (an index of the dialog's list).
|
||
pub source: usize,
|
||
/// Frames per second chosen (the next share starts from it).
|
||
pub fps: u32,
|
||
/// Bitrate chosen, kbit/s (0: automatic; the next share starts from it).
|
||
pub bitrate: u32,
|
||
/// What the capture is asked for.
|
||
pub request: CaptureRequest,
|
||
/// What the stream is set up with.
|
||
pub setup: StreamSetup,
|
||
/// Accept the viewers that ask.
|
||
pub auto_accept: bool,
|
||
}
|
||
|
||
/// The share dialog's Start: the choices read from the form, the capture
|
||
/// asked for. Nothing starts when the Stream Studio is live there, or a
|
||
/// share is starting or running.
|
||
pub fn plan_share<L>(
|
||
state: &mut AppState<L>,
|
||
cx: &mut Cx<'_>,
|
||
form: &ShareForm,
|
||
studio_live_here: bool,
|
||
sources: &[AudioSourceSetting],
|
||
) -> Option<SharePlan> {
|
||
let session = state.current?;
|
||
if state.share_busy || state.share.is_some() {
|
||
return None;
|
||
}
|
||
if studio_live_here {
|
||
state.share_error = "The Stream Studio is live here: end that stream first.".into();
|
||
cx.update.refresh.streams = true;
|
||
return None;
|
||
}
|
||
// Typed values (no maximum), else the chosen presets (bitrate 0:
|
||
// automatic).
|
||
let choice =
|
||
|i: i32, choices: &[u32]| choices[usize::try_from(i).unwrap_or(0).min(choices.len() - 1)];
|
||
let fps = parse_positive(&form.fps).unwrap_or_else(|| choice(form.fps_index, &FPS_CHOICES));
|
||
let bitrate = parse_positive(&form.bitrate)
|
||
.unwrap_or_else(|| choice(form.bitrate_index, &BITRATE_CHOICES));
|
||
let defaults = ShareDefaults {
|
||
fps_index: nearest_choice(&LEGACY_FPS_CHOICES, fps),
|
||
bitrate_index: nearest_choice(&LEGACY_BITRATE_CHOICES, bitrate),
|
||
audio: form.audio,
|
||
auto_accept: form.auto_accept,
|
||
};
|
||
let token = state.settings.portal_restore_token.clone();
|
||
let request = capture_request(fps, bitrate, form.audio, sources, token);
|
||
state.settings.share = defaults;
|
||
cx.persist(crate::host::Persist::Settings);
|
||
state.share_busy = true;
|
||
state.share_error.clear();
|
||
cx.update.refresh.streams = true;
|
||
let setup = StreamSetup {
|
||
name: form.name.trim().to_owned(),
|
||
bitrate,
|
||
audio: request.audio,
|
||
..StreamSetup::default()
|
||
};
|
||
Some(SharePlan {
|
||
session,
|
||
source: usize::try_from(form.source).unwrap_or(0),
|
||
fps,
|
||
bitrate,
|
||
request,
|
||
setup,
|
||
auto_accept: form.auto_accept,
|
||
})
|
||
}
|
||
|
||
/// What the front end knows of a capture that started.
|
||
pub struct CaptureStarted {
|
||
/// The desktop portal's token for this choice, to keep.
|
||
pub restore_token: Option<String>,
|
||
/// The bitrate the size captured comes to (for the automatic choice).
|
||
pub automatic_bitrate: u32,
|
||
/// The capture has sound.
|
||
pub has_audio: bool,
|
||
/// Why it has none, when sound was asked for.
|
||
pub audio_error: Option<String>,
|
||
}
|
||
|
||
/// The capture started (or not): go live. `true` if the front end keeps the
|
||
/// capture (and meters its audio).
|
||
pub fn capture_ready<L>(
|
||
state: &mut AppState<L>,
|
||
cx: &mut Cx<'_>,
|
||
session: i64,
|
||
mut setup: StreamSetup,
|
||
auto_accept: bool,
|
||
result: Result<CaptureStarted, String>,
|
||
) -> bool {
|
||
state.share_busy = false;
|
||
cx.update.refresh.streams = true;
|
||
let started = match result {
|
||
Err(e) => {
|
||
state.share_error = format!("Could not start the capture: {e}");
|
||
return false;
|
||
}
|
||
Ok(started) => started,
|
||
};
|
||
if let Some(token) = started.restore_token
|
||
&& state.settings.portal_restore_token.as_ref() != Some(&token)
|
||
{
|
||
state.settings.portal_restore_token = Some(token);
|
||
cx.persist(crate::host::Persist::Settings);
|
||
}
|
||
if setup.bitrate == 0 {
|
||
// Automatic: what it comes to for the size captured.
|
||
setup.bitrate = started.automatic_bitrate;
|
||
}
|
||
if setup.audio && !started.has_audio {
|
||
setup.audio = false;
|
||
let reason = started.audio_error.unwrap_or_default();
|
||
cx.status(format!("Sharing without sound: {reason}"));
|
||
}
|
||
// Sample data has no server: live at once, with viewers.
|
||
let (live, viewers) = if cx.host.demo_ui() {
|
||
(true, demo_viewers())
|
||
} else {
|
||
let session = session as u64;
|
||
// One layer, whatever a studio stream had before.
|
||
cx.send(Command::SetStreamLayers { session, layers: Vec::new() });
|
||
cx.send(Command::StartStream { session, setup, auto_accept });
|
||
(false, Vec::new())
|
||
};
|
||
state.share = Some(Sharing { session, live, viewers, stopping: false });
|
||
// The mixer's rows follow this capture's sources.
|
||
cx.update.stream.mixer = true;
|
||
true
|
||
}
|
||
|
||
/// Stop sharing.
|
||
pub fn stop_share<L>(state: &mut AppState<L>, cx: &mut Cx<'_>) {
|
||
let Some(share) = &mut state.share else { return };
|
||
share.stopping = true;
|
||
let session = share.session;
|
||
if cx.host.demo_ui() {
|
||
share_state(state, cx, session, StreamState::Ended(EndReason::Local));
|
||
} else {
|
||
cx.send(Command::StopStream { session: session as u64 });
|
||
}
|
||
}
|
||
|
||
/// Answer a viewer that asked to watch our stream.
|
||
pub fn respond_viewer<L>(state: &AppState<L>, cx: &mut Cx<'_>, viewer: u16, accept: bool) {
|
||
if let Some(share) = &state.share {
|
||
cx.send(Command::AcceptViewer { session: share.session as u64, viewer, accept });
|
||
}
|
||
}
|
||
|
||
/// Remove a viewer of our stream.
|
||
pub fn kick_viewer<L>(state: &AppState<L>, cx: &mut Cx<'_>, viewer: u16) {
|
||
if let Some(share) = &state.share {
|
||
cx.send(Command::KickViewer { session: share.session as u64, viewer });
|
||
}
|
||
}
|
||
|
||
/// Once a second, with whether the capture ended by itself: stop the
|
||
/// stream then.
|
||
pub fn capture_ended<L>(state: &mut AppState<L>, cx: &mut Cx<'_>) {
|
||
if let Some(share) = &mut state.share
|
||
&& share.live
|
||
&& !share.stopping
|
||
{
|
||
share.stopping = true;
|
||
cx.send(Command::StopStream { session: share.session as u64 });
|
||
}
|
||
}
|
||
|
||
// What is shown.
|
||
|
||
/// What the streams panel shows besides the state.
|
||
pub struct StreamsFacts<'a> {
|
||
/// The local test stream is offered (`VOELIN_DEMO_STREAM`).
|
||
pub demo: bool,
|
||
/// The Stream Studio streams to the session on screen.
|
||
pub studio_live_here: bool,
|
||
/// The running capture of our share.
|
||
pub capture: Option<&'a CaptureFacts>,
|
||
}
|
||
|
||
/// The running capture, as the share card shows it.
|
||
pub struct CaptureFacts {
|
||
/// The line about what is sent.
|
||
pub status: String,
|
||
/// What it captures.
|
||
pub source_name: String,
|
||
/// It has sound.
|
||
pub has_audio: bool,
|
||
}
|
||
|
||
/// The share dialog's and the share card's facts.
|
||
pub struct ShareView {
|
||
/// "live", "starting" or "" (none).
|
||
pub state: &'static str,
|
||
/// The capture is being started.
|
||
pub busy: bool,
|
||
/// Why the last share did not start.
|
||
pub error: String,
|
||
/// The capture has sound.
|
||
pub audio: bool,
|
||
/// Who watches or asks to.
|
||
pub viewers: Vec<ViewerItem>,
|
||
/// How many ask.
|
||
pub requests: i32,
|
||
/// What the card says.
|
||
pub status: String,
|
||
}
|
||
|
||
/// The streams panel.
|
||
pub struct StreamsView {
|
||
/// Streams can be watched and shared here.
|
||
pub available: bool,
|
||
/// The streams listed.
|
||
pub items: Vec<StreamItem>,
|
||
/// Our share.
|
||
pub share: ShareView,
|
||
}
|
||
|
||
/// The streams panel, the voice card's streams and the share card.
|
||
pub fn streams_view<L>(state: &AppState<L>, facts: &StreamsFacts<'_>) -> StreamsView {
|
||
let current = state.current;
|
||
let view = current.and_then(|id| state.sessions.get(&id));
|
||
let mut items: Vec<StreamItem> = Vec::new();
|
||
if let Some(view) = view.filter(|v| v.streams_available()) {
|
||
// Every channel's streams (they can be watched from anywhere), ours
|
||
// first.
|
||
let own_channel = view.state.own_channel;
|
||
let mut streams: Vec<_> = view.streams.iter().collect();
|
||
streams.sort_by_key(|s| view.channel_of(s.streamer) != own_channel);
|
||
for s in streams {
|
||
// Also the sample data's test pattern dressed as this stream
|
||
// (`VOELIN_OPEN=watch`), which has no session.
|
||
let watching = state.watch.as_ref().is_some_and(|w| {
|
||
(w.session == current || w.session.is_none()) && w.stream_id == s.id && !w.ended
|
||
});
|
||
let own = view.state.own_client == Some(s.streamer);
|
||
items.push(StreamItem {
|
||
id: s.id.clone().into(),
|
||
name: s.name.clone().into(),
|
||
channel: view.other_channel_name(s.streamer).into(),
|
||
streamer_id: i32::from(s.streamer),
|
||
viewers: viewer_count(view, &s.id).unwrap_or(0) as i32,
|
||
audio: s.audio,
|
||
watching,
|
||
own,
|
||
// Our own stream from the studio shows its preview.
|
||
studio: own && facts.studio_live_here,
|
||
kind: kind_label(&s.kind).into(),
|
||
bitrate: bitrate_text(s.bitrate).into(),
|
||
..streamer(&view.nickname(s.streamer), view.avatar(s.streamer))
|
||
});
|
||
}
|
||
// Streams that started before we joined, or in another channel: the
|
||
// server did not announce them, and the engine is looking them up
|
||
// (they arrive in `StreamsChanged` like the others). Until then only
|
||
// the streaming flag is known.
|
||
for c in view.presence.clients.values() {
|
||
let announced = view.streams.iter().any(|s| s.streamer == c.id);
|
||
if c.streaming == Some(true) && !announced && view.state.own_client != Some(c.id) {
|
||
items.push(StreamItem {
|
||
name: c.nickname.clone().into(),
|
||
channel: view.other_channel_name(c.id).into(),
|
||
streamer_id: i32::from(c.id),
|
||
..streamer(&c.nickname, view.avatar(c.id))
|
||
});
|
||
}
|
||
}
|
||
}
|
||
if facts.demo {
|
||
items.push(StreamItem {
|
||
id: "demo".into(),
|
||
name: "Test pattern".into(),
|
||
audio: false,
|
||
watching: state.watch.as_ref().is_some_and(|w| w.session.is_none() && !w.ended),
|
||
own: false,
|
||
..streamer("local preview", None)
|
||
});
|
||
}
|
||
let available = facts.demo || view.is_some_and(|v| v.streams_available());
|
||
|
||
let share = state.share.as_ref().filter(|s| Some(s.session) == current);
|
||
let share_state = match share {
|
||
Some(s) if s.live => "live",
|
||
Some(_) => "starting",
|
||
None if state.share_busy => "starting",
|
||
None => "",
|
||
};
|
||
let viewers: Vec<ViewerItem> = share
|
||
.map(|s| {
|
||
s.viewers
|
||
.iter()
|
||
.map(|v| ViewerItem {
|
||
client: i32::from(v.client),
|
||
name: view.map_or_else(String::new, |view| view.nickname(v.client)).into(),
|
||
state: match v.state {
|
||
ViewerState::Requested => "requested",
|
||
ViewerState::Connecting => "connecting",
|
||
ViewerState::Connected => "connected",
|
||
}
|
||
.into(),
|
||
message: v.message.clone().into(),
|
||
avatar: crate::avatar::image(view.and_then(|view| view.avatar(v.client))),
|
||
})
|
||
.collect()
|
||
})
|
||
.unwrap_or_default();
|
||
let requests = viewers.iter().filter(|v| &*v.state == "requested").count() as i32;
|
||
let status = match (share, facts.capture) {
|
||
(Some(s), Some(capture)) if s.live => capture.status.clone(),
|
||
(Some(_), Some(capture)) => format!("Starting the stream of {}…", capture.source_name),
|
||
(Some(_), None) => String::new(),
|
||
(None, _) if state.share_busy => "Starting the capture…".into(),
|
||
(None, _) => String::new(),
|
||
};
|
||
StreamsView {
|
||
available,
|
||
items,
|
||
share: ShareView {
|
||
state: share_state,
|
||
busy: state.share_busy,
|
||
error: state.share_error.clone(),
|
||
audio: share.is_some() && facts.capture.is_some_and(|c| c.has_audio),
|
||
viewers,
|
||
requests,
|
||
status,
|
||
},
|
||
}
|
||
}
|
||
|
||
/// The viewer's header: the facts that are not state of the player.
|
||
pub struct ViewerView {
|
||
/// The title.
|
||
pub title: String,
|
||
/// Shown over the picture.
|
||
pub status: String,
|
||
/// The stream ended.
|
||
pub ended: bool,
|
||
/// A picture is shown.
|
||
pub has_frame: bool,
|
||
/// The volume in percent.
|
||
pub volume: f32,
|
||
/// "by Nova · H264 · 1920×1080 · ...".
|
||
pub info: String,
|
||
/// Who streams.
|
||
pub streamer: String,
|
||
/// The streamer's avatar picture.
|
||
pub avatar: ImageRef,
|
||
/// The streamer's initials.
|
||
pub initials: Arc<str>,
|
||
/// The streamer's colour.
|
||
pub tint: Rgb,
|
||
/// The streamer's client id, -1 if unknown.
|
||
pub streamer_id: i32,
|
||
/// The streamer's channel.
|
||
pub channel: String,
|
||
/// Since the picture started.
|
||
pub elapsed: String,
|
||
/// How many watch.
|
||
pub count: i32,
|
||
/// "Auto" and the layers, empty without a choice.
|
||
pub qualities: Vec<Arc<str>>,
|
||
/// Which of them is chosen.
|
||
pub quality: i32,
|
||
/// What the decoder says it decodes.
|
||
pub detail: String,
|
||
}
|
||
|
||
/// The viewer's header for the stream in `watch`; `decoded` is what its
|
||
/// decoder says it decodes.
|
||
pub fn viewer_view<L>(state: &AppState<L>, watch: &Watching, decoded: &str) -> ViewerView {
|
||
// The watched stream's server, which the main window may have left while
|
||
// the stream plays in its own.
|
||
let view = match watch.session {
|
||
Some(id) => state.sessions.get(&id),
|
||
None => state.current.and_then(|id| state.sessions.get(&id)),
|
||
};
|
||
let info = [format!("by {}", watch.streamer), decoded.to_owned()]
|
||
.into_iter()
|
||
.filter(|s| !s.is_empty())
|
||
.collect::<Vec<_>>()
|
||
.join(" · ");
|
||
let streamer_id = view
|
||
.and_then(|v| v.streams.iter().find(|s| s.id == watch.stream_id))
|
||
.map_or(-1, |s| i32::from(s.streamer));
|
||
let face = streamer(
|
||
&watch.streamer,
|
||
view.zip(u16::try_from(streamer_id).ok()).and_then(|(v, id)| v.avatar(id)),
|
||
);
|
||
let channel = u16::try_from(streamer_id).ok().and_then(|id| {
|
||
let view = view?;
|
||
let channel = view.presence.channels.get(&view.channel_of(id)?)?;
|
||
Some(crate::tree::channel_title(channel).0.to_owned())
|
||
});
|
||
ViewerView {
|
||
title: watch.title.clone(),
|
||
status: watch.status.clone(),
|
||
ended: watch.ended,
|
||
has_frame: watch.has_frame,
|
||
volume: state.stream_volume,
|
||
info,
|
||
streamer: watch.streamer.clone(),
|
||
avatar: face.avatar,
|
||
initials: face.initials,
|
||
tint: face.tint,
|
||
streamer_id,
|
||
channel: channel.unwrap_or_default(),
|
||
elapsed: watch.elapsed(),
|
||
count: view.and_then(|v| viewer_count(v, &watch.stream_id)).unwrap_or(0) as i32,
|
||
qualities: watch.qualities(),
|
||
quality: watch.chosen_quality(),
|
||
detail: decoded.to_owned(),
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use voelin_core::stream::StreamInfo;
|
||
use voelin_core::{AudioSettings, SessionState, VoiceState};
|
||
use voelin_model::{Capabilities, ChannelInfo, ClientInfo, Presence};
|
||
use voelin_store::Bookmark;
|
||
|
||
use super::*;
|
||
use crate::bridge::ChatLine;
|
||
use crate::host::testing::Fake;
|
||
use crate::settings::{ClientPlaybackMap, UiSettings};
|
||
|
||
type State = AppState<Vec<ChatLine>>;
|
||
|
||
/// Server 1, connected with voice into Games (2) as Me (10); Alice (11)
|
||
/// streams there ("s1"), and Bob (12), in the Lobby, started before we
|
||
/// joined (no stream listed yet).
|
||
fn state() -> State {
|
||
let bookmark = Bookmark {
|
||
id: 1,
|
||
name: "Nightfall".into(),
|
||
address: "ts.example".into(),
|
||
nickname: "Me".into(),
|
||
..Default::default()
|
||
};
|
||
let mut st = AppState::new(
|
||
vec![bookmark],
|
||
UiSettings::default(),
|
||
AudioSettings::default(),
|
||
ClientPlaybackMap::new(),
|
||
);
|
||
let mut presence = Presence::default();
|
||
for (id, name) in [(1, "Lobby"), (2, "Games")] {
|
||
presence
|
||
.channels
|
||
.insert(id, ChannelInfo { id, name: name.into(), ..Default::default() });
|
||
}
|
||
for (id, channel, name, streaming) in
|
||
[(10, 2, "Me", false), (11, 2, "Alice", true), (12, 1, "Bob", true)]
|
||
{
|
||
presence.clients.insert(
|
||
id,
|
||
ClientInfo {
|
||
id,
|
||
channel,
|
||
nickname: name.into(),
|
||
streaming: Some(streaming),
|
||
..Default::default()
|
||
},
|
||
);
|
||
}
|
||
let view = st.sessions.entry(1).or_default();
|
||
view.presence = Arc::new(presence);
|
||
view.capabilities = Capabilities { streams: true, ..Default::default() };
|
||
view.state = SessionState {
|
||
voice: VoiceState::Connected,
|
||
own_channel: Some(2),
|
||
own_client: Some(10),
|
||
..Default::default()
|
||
};
|
||
view.streams = vec![StreamInfo {
|
||
id: "s1".into(),
|
||
streamer: 11,
|
||
name: "Speedrun".into(),
|
||
kind: voelin_core::stream::StreamKind::Screen,
|
||
bitrate: 4608,
|
||
viewer_limit: 0,
|
||
audio: true,
|
||
viewers: Some(3),
|
||
}];
|
||
st
|
||
}
|
||
|
||
fn layer(id: LayerId, height: u32, bitrate: u64) -> LayerSpec {
|
||
LayerSpec {
|
||
id,
|
||
scale: 1.0,
|
||
size: Some((height * 16 / 9, height)),
|
||
max_fps: None,
|
||
bitrate,
|
||
max_bitrate: None,
|
||
min_bitrate: 0,
|
||
rid: None,
|
||
}
|
||
}
|
||
|
||
/// From the click on a stream to its end: what is asked of the engine,
|
||
/// what the viewer says at each step, and what the front end drops.
|
||
#[test]
|
||
fn watching_a_stream_from_ask_to_end() {
|
||
let mut st = state();
|
||
let host = Fake::default();
|
||
let mut cx = Cx::new(&host);
|
||
assert_eq!(watch_stream(&mut st, &mut cx, "nope"), None);
|
||
assert!(st.watch.is_none() && cx.update.commands.is_empty());
|
||
|
||
st.stream_volume = 150.0;
|
||
assert_eq!(watch_stream(&mut st, &mut cx, "s1"), Some(1));
|
||
let watch = st.watch.as_ref().unwrap();
|
||
assert_eq!(watch.status, "Asking Alice to let you watch…");
|
||
assert_eq!((watch.title.as_str(), watch.streamer.as_str()), ("Speedrun", "Alice"));
|
||
assert!(watch.shown && watch.here(Some(1)) && !watch.here(Some(2)));
|
||
assert!(matches!(
|
||
cx.update.commands.as_slice(),
|
||
[
|
||
Command::WatchStream { session: 1, stream_id },
|
||
Command::SetStreamVolume { session: 1, volume, .. },
|
||
] if stream_id == "s1" && *volume == 1.5
|
||
));
|
||
let r = cx.update.refresh;
|
||
assert!(r.viewer && r.streams && r.tree);
|
||
// The stream before it is left: nothing to leave the first time.
|
||
assert!(cx.update.stream.drop_decoder && cx.update.stream.leave_fullscreen);
|
||
|
||
// The steps of the connection.
|
||
let step = |st: &mut State, now: WatchState| {
|
||
let mut cx = Cx::new(&host);
|
||
watch_state(st, &mut cx, 1, "s1", now);
|
||
cx.update
|
||
};
|
||
assert!(step(&mut st, WatchState::Requested).refresh.viewer);
|
||
assert_eq!(st.watch.as_ref().unwrap().status, "Waiting for Alice to let you watch…");
|
||
step(&mut st, WatchState::Connecting);
|
||
assert_eq!(st.watch.as_ref().unwrap().status, "Connecting to Alice…");
|
||
step(&mut st, WatchState::Connected);
|
||
let watch = st.watch.as_ref().unwrap();
|
||
assert!(watch.connected);
|
||
assert_eq!(watch.status, "Waiting for the picture…");
|
||
// Another stream's state is not ours.
|
||
let mut other = Cx::new(&host);
|
||
watch_state(&mut st, &mut other, 1, "s2", WatchState::Ended(EndReason::Stopped));
|
||
assert!(!st.watch.as_ref().unwrap().ended && other.update.refresh.is_empty());
|
||
|
||
// The first picture clears the status and starts the clock.
|
||
assert!(picture_shown(&mut st));
|
||
assert!(!picture_shown(&mut st));
|
||
let watch = st.watch.as_ref().unwrap();
|
||
assert!(watch.has_frame && watch.status.is_empty() && watch.since.is_some());
|
||
// A decoder that fails matters only while no picture came.
|
||
decoder_failed(&mut st, "no H264 decoder");
|
||
assert!(st.watch.as_ref().unwrap().status.is_empty());
|
||
|
||
// The streamer offers layers: the choice goes to the streamer.
|
||
let mut cx = Cx::new(&host);
|
||
watch_layers(
|
||
&mut st,
|
||
&mut cx,
|
||
1,
|
||
"s1",
|
||
vec![layer(0, 1080, 6_000_000), layer(1, 720, 2_400_000)],
|
||
None,
|
||
);
|
||
let view = viewer_view(&st, st.watch.as_ref().unwrap(), "H264 · 1920×1080");
|
||
assert_eq!(
|
||
view.qualities.iter().map(|q| &**q).collect::<Vec<_>>(),
|
||
["Auto", "1080p · 6.0 Mbit/s", "720p · 2.4 Mbit/s"]
|
||
);
|
||
assert_eq!((view.quality, view.streamer_id, view.count), (0, 11, 3));
|
||
assert_eq!((view.channel.as_str(), view.streamer.as_str()), ("Games", "Alice"));
|
||
assert_eq!(view.info, "by Alice · H264 · 1920×1080");
|
||
let mut cx = Cx::new(&host);
|
||
set_quality(&mut st, &mut cx, 2);
|
||
assert!(matches!(
|
||
cx.update.commands.as_slice(),
|
||
[Command::SetWatchLayer { session: 1, layer: Some(1), .. }]
|
||
));
|
||
assert_eq!(st.watch.as_ref().unwrap().chosen_quality(), 2);
|
||
|
||
// It ends: the decoder goes, the viewer says why, and it stays ended.
|
||
let up = step(&mut st, WatchState::Ended(EndReason::Removed(Some(LeaveReason::Kicked))));
|
||
assert!(up.stream.drop_decoder);
|
||
assert_eq!(st.watch.as_ref().unwrap().status, "Alice removed you from the stream.");
|
||
let up = step(&mut st, WatchState::Connecting);
|
||
assert!(up.refresh.is_empty());
|
||
// Leaving a stream that ended tells the server nothing.
|
||
let mut cx = Cx::new(&host);
|
||
stop_watching(&mut st, &mut cx);
|
||
assert!(st.watch.is_none() && cx.update.commands.is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn leaving_a_stream_that_runs_tells_the_server() {
|
||
let mut st = state();
|
||
let host = Fake::default();
|
||
let mut cx = Cx::new(&host);
|
||
watch_stream(&mut st, &mut cx, "s1");
|
||
let mut cx = Cx::new(&host);
|
||
stop_watching(&mut st, &mut cx);
|
||
assert!(matches!(
|
||
cx.update.commands.as_slice(),
|
||
[Command::LeaveStream { session: 1, stream_id }] if stream_id == "s1"
|
||
));
|
||
// A click on a streaming client watches its stream at once, or looks
|
||
// it up first; ours is no stream to watch.
|
||
let mut cx = Cx::new(&host);
|
||
assert_eq!(watch_client(&mut st, &mut cx, 11).as_deref(), Some("s1"));
|
||
assert_eq!(watch_client(&mut st, &mut cx, 12), None);
|
||
assert_eq!(st.pending_watch, Some((1, 12)));
|
||
assert_eq!(cx.update.status.as_deref(), Some("Looking up Bob's stream…"));
|
||
assert_eq!(watch_client(&mut st, &mut cx, 10), None);
|
||
assert_eq!(first_stream(&st).as_deref(), Some("s1"));
|
||
}
|
||
|
||
/// The streams panel: the streams listed with their streamers, then those
|
||
/// still being looked up; the share card follows the share.
|
||
#[test]
|
||
fn the_streams_panel_and_the_share_card() {
|
||
let mut st = state();
|
||
let no_capture = StreamsFacts { demo: false, studio_live_here: false, capture: None };
|
||
let view = streams_view(&st, &no_capture);
|
||
assert!(view.available);
|
||
let names: Vec<_> =
|
||
view.items.iter().map(|i| (&*i.streamer, &*i.name, i.viewers)).collect();
|
||
assert_eq!(names, [("Alice", "Speedrun", 3), ("Bob", "Bob", 0)]);
|
||
let alice = &view.items[0];
|
||
assert_eq!((&*alice.kind, &*alice.bitrate, alice.audio), ("Screen", "4.6 Mbit/s", true));
|
||
assert!(!alice.watching && !alice.own);
|
||
assert_eq!(view.items[1].id.len(), 0, "a stream that is being looked up has no id");
|
||
assert_eq!(view.share.state, "");
|
||
|
||
// Watching one marks its card.
|
||
let host = Fake::default();
|
||
watch_stream(&mut st, &mut Cx::new(&host), "s1");
|
||
assert!(streams_view(&st, &no_capture).items[0].watching);
|
||
|
||
// The share starts: the dialog's values become a plan.
|
||
let form = ShareForm {
|
||
source: 2,
|
||
name: " My screen ".into(),
|
||
fps_index: 1,
|
||
fps: "".into(),
|
||
bitrate_index: 2,
|
||
bitrate: "".into(),
|
||
audio: true,
|
||
auto_accept: true,
|
||
};
|
||
let mut cx = Cx::new(&host);
|
||
let plan = plan_share(&mut st, &mut cx, &form, false, &[]).unwrap();
|
||
assert_eq!((plan.session, plan.source, plan.fps, plan.bitrate), (1, 2, 30, 4608));
|
||
assert_eq!(plan.setup.name, "My screen");
|
||
assert!(!plan.request.audio, "no sources picked: no sound");
|
||
assert!(st.share_busy && st.settings.share.auto_accept && st.settings.share.audio);
|
||
assert_eq!(st.settings.share.fps_index, 1);
|
||
assert!(cx.update.persist.contains(&crate::host::Persist::Settings));
|
||
let busy = streams_view(&st, &no_capture);
|
||
assert_eq!(
|
||
(busy.share.state, busy.share.status.as_str()),
|
||
("starting", "Starting the capture…")
|
||
);
|
||
// A second start while one is starting does nothing.
|
||
assert!(plan_share(&mut st, &mut Cx::new(&host), &form, false, &[]).is_none());
|
||
|
||
// The capture is there: the stream is asked for, and starts live.
|
||
let started = CaptureStarted {
|
||
restore_token: Some("tok".into()),
|
||
automatic_bitrate: 0,
|
||
has_audio: false,
|
||
audio_error: Some("no source".into()),
|
||
};
|
||
let mut cx = Cx::new(&host);
|
||
let setup = StreamSetup { audio: true, ..plan.setup };
|
||
assert!(capture_ready(&mut st, &mut cx, 1, setup, true, Ok(started)));
|
||
assert_eq!(st.settings.portal_restore_token.as_deref(), Some("tok"));
|
||
assert_eq!(cx.update.status.as_deref(), Some("Sharing without sound: no source"));
|
||
assert!(matches!(
|
||
cx.update.commands.as_slice(),
|
||
[
|
||
Command::SetStreamLayers { session: 1, .. },
|
||
Command::StartStream { session: 1, setup, auto_accept: true },
|
||
] if !setup.audio
|
||
));
|
||
assert!(!st.share_busy && st.share.as_ref().is_some_and(|s| !s.live));
|
||
assert!(cx.update.stream.mixer);
|
||
let capture = CaptureFacts {
|
||
status: "Screen · 1920×1080".into(),
|
||
source_name: "Screen".into(),
|
||
has_audio: false,
|
||
};
|
||
let facts = StreamsFacts { capture: Some(&capture), ..no_capture };
|
||
let view = streams_view(&st, &facts);
|
||
assert_eq!(
|
||
(view.share.state, view.share.status.as_str()),
|
||
("starting", "Starting the stream of Screen…")
|
||
);
|
||
|
||
// Someone asks to watch: it is in the card, and in the status line.
|
||
let ask = ViewerInfo {
|
||
client: 11,
|
||
state: ViewerState::Requested,
|
||
message: "hi".into(),
|
||
..demo_viewers().remove(0)
|
||
};
|
||
let mut cx = Cx::new(&host);
|
||
viewers(&mut st, &mut cx, 1, vec![ask]);
|
||
viewer_request(&st, &mut cx, 1, 11);
|
||
assert_eq!(cx.update.status.as_deref(), Some("Alice wants to watch your stream"));
|
||
let view = streams_view(&st, &facts);
|
||
assert_eq!(view.share.requests, 1);
|
||
assert_eq!(
|
||
(&*view.share.viewers[0].name, &*view.share.viewers[0].state),
|
||
("Alice", "requested")
|
||
);
|
||
let mut cx = Cx::new(&host);
|
||
respond_viewer(&st, &mut cx, 11, true);
|
||
kick_viewer(&st, &mut cx, 11);
|
||
assert!(matches!(
|
||
cx.update.commands.as_slice(),
|
||
[
|
||
Command::AcceptViewer { session: 1, viewer: 11, accept: true },
|
||
Command::KickViewer { session: 1, viewer: 11 },
|
||
]
|
||
));
|
||
|
||
// The capture ended by itself: the stream is stopped, once.
|
||
let mut cx = Cx::new(&host);
|
||
st.share.as_mut().unwrap().live = true;
|
||
capture_ended(&mut st, &mut cx);
|
||
capture_ended(&mut st, &mut cx);
|
||
assert_eq!(cx.update.commands.len(), 1);
|
||
// It ended with the capture, and ends: that was ours to stop.
|
||
let mut cx = Cx::new(&host);
|
||
share_state(&mut st, &mut cx, 1, StreamState::Ended(EndReason::Stopped));
|
||
assert!(st.share.is_none() && st.share_error.is_empty());
|
||
assert_eq!(cx.update.status.as_deref(), Some("You stopped sharing"));
|
||
// And one that ends not by us: the capture goes, the dialog says why.
|
||
st.share = Some(Sharing { session: 1, live: true, viewers: Vec::new(), stopping: false });
|
||
let mut cx = Cx::new(&host);
|
||
share_state(&mut st, &mut cx, 1, StreamState::Ended(EndReason::Failed("encoder".into())));
|
||
assert!(st.share.is_none() && cx.update.stream.drop_share && cx.update.stream.mixer);
|
||
assert_eq!(st.share_error, "Sharing failed: encoder");
|
||
assert_eq!(cx.update.status.as_deref(), Some("Sharing failed: encoder"));
|
||
}
|
||
|
||
/// The Stream Studio's stream is its own, and our share and the sample
|
||
/// sessions behave as the engine would.
|
||
#[test]
|
||
fn the_studio_and_the_sample_share() {
|
||
let mut st = state();
|
||
let host = Fake { demo: true, ..Default::default() };
|
||
let started = CaptureStarted {
|
||
restore_token: None,
|
||
automatic_bitrate: 8000,
|
||
has_audio: true,
|
||
audio_error: None,
|
||
};
|
||
let mut cx = Cx::new(&host);
|
||
assert!(capture_ready(&mut st, &mut cx, 1, StreamSetup::default(), false, Ok(started)));
|
||
// Sample data has no server: live at once, with viewers, nothing sent.
|
||
let share = st.share.as_ref().unwrap();
|
||
assert!(share.live && share.viewers.len() == 3 && cx.update.commands.is_empty());
|
||
// "Stop" ends it at once, by us.
|
||
let mut cx = Cx::new(&host);
|
||
stop_share(&mut st, &mut cx);
|
||
assert!(st.share.is_none() && st.share_error.is_empty());
|
||
assert_eq!(cx.update.status.as_deref(), Some("You stopped sharing"));
|
||
// A capture that did not start.
|
||
let mut cx = Cx::new(&host);
|
||
assert!(!capture_ready(
|
||
&mut st,
|
||
&mut cx,
|
||
1,
|
||
StreamSetup::default(),
|
||
false,
|
||
Err("denied".into())
|
||
));
|
||
assert_eq!(st.share_error, "Could not start the capture: denied");
|
||
// The studio is live where the share would go: nothing starts.
|
||
let form = ShareForm::default();
|
||
let mut cx = Cx::new(&host);
|
||
assert!(plan_share(&mut st, &mut cx, &form, true, &[]).is_none());
|
||
assert_eq!(st.share_error, "The Stream Studio is live here: end that stream first.");
|
||
}
|
||
|
||
#[test]
|
||
fn the_dialog_starts_from_the_last_choices() {
|
||
let mut st = state();
|
||
let form = share_form(&st, 60, 0);
|
||
assert_eq!(&*form.name, "Me's screen");
|
||
assert_eq!(
|
||
(form.fps_index, &*form.fps, form.bitrate_index, &*form.bitrate),
|
||
(2, "60", 0, "")
|
||
);
|
||
st.settings.share.audio = true;
|
||
assert!(share_form(&st, 30, 8000).audio);
|
||
// Sources listed: the error of an earlier try goes; an error stays.
|
||
st.share_error = "old".into();
|
||
assert_eq!(sources_listed(&mut st, Ok(vec![("a", "b")])).len(), 1);
|
||
assert!(st.share_error.is_empty());
|
||
assert!(sources_listed::<_, ()>(&mut st, Err("none".into())).is_empty());
|
||
assert_eq!(st.share_error, "none");
|
||
}
|
||
|
||
#[test]
|
||
fn bitrates() {
|
||
assert_eq!(bitrate_text(0), "");
|
||
assert_eq!(bitrate_text(640), "640 kbit/s");
|
||
assert_eq!(bitrate_text(8000), "8 Mbit/s");
|
||
assert_eq!(bitrate_text(4608), "4.6 Mbit/s");
|
||
}
|
||
|
||
/// What the share dialog's mixer holds goes to the capture, with each
|
||
/// source's gain and mute; "Share system audio" off (or nothing picked)
|
||
/// shares no audio at all.
|
||
#[test]
|
||
fn the_share_carries_the_picked_audio() {
|
||
use voelin_core::media::{AppMatch, AudioSourceKind};
|
||
use voelin_core::settings::{AudioSourceKindSetting, AudioSourceSetting};
|
||
let app = AudioSourceKindSetting::App { name: Some("firefox".into()), pid: None };
|
||
let picked = [
|
||
AudioSourceSetting { gain: 0.5, ..AudioSourceSetting::new(app) },
|
||
AudioSourceSetting {
|
||
muted: true,
|
||
..AudioSourceSetting::new(AudioSourceKindSetting::Microphone)
|
||
},
|
||
];
|
||
let request = capture_request(30, 4608, true, &picked, None);
|
||
assert!(request.audio);
|
||
let kinds: Vec<_> = request.audio_sources.iter().map(|s| s.kind.clone()).collect();
|
||
let firefox = AudioSourceKind::App(AppMatch::Name("firefox".into()));
|
||
assert_eq!(kinds, [firefox, AudioSourceKind::Microphone]);
|
||
let mix: Vec<_> = request.audio_sources.iter().map(|s| (s.gain, s.muted)).collect();
|
||
assert_eq!(mix, [(0.5, false), (1.0, true)]);
|
||
assert_eq!((request.fps, request.bitrate_kbps), (30, 4608));
|
||
|
||
let off = capture_request(30, 4608, false, &picked, None);
|
||
assert!(!off.audio && off.audio_sources.is_empty());
|
||
let none = capture_request(30, 4608, true, &[], None);
|
||
assert!(!none.audio && none.audio_sources.is_empty());
|
||
}
|
||
}
|