From 0d2ad3f2505bd4387530cb116e1d5ef7c22938a7 Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 21 Oct 2026 06:48:18 +0300 Subject: [PATCH] Split the streams controller: the state, the events and the rows into voelin-ui-vm 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 --- crates/voelin-ui-vm/src/events/mod.rs | 40 +- crates/voelin-ui-vm/src/events/tests.rs | 132 +- crates/voelin-ui-vm/src/host.rs | 96 +- crates/voelin-ui-vm/src/state.rs | 7 + crates/voelin-ui-vm/src/streams/logic.rs | 1386 +++++++++++++++++ .../src/{streams.rs => streams/mod.rs} | 5 +- crates/voelin-ui/src/app.rs | 16 +- crates/voelin-ui/src/host.rs | 45 +- crates/voelin-ui/src/popout.rs | 6 +- crates/voelin-ui/src/servers.rs | 3 +- crates/voelin-ui/src/streams.rs | 1025 ------------ crates/voelin-ui/src/streams/bind.rs | 425 +++++ crates/voelin-ui/src/streams/mod.rs | 19 + crates/voelin-ui/src/studio/bind.rs | 6 +- crates/voelin-ui/src/studio/mod.rs | 8 + crates/voelin-ui/src/video.rs | 9 +- docs/ui.md | 40 +- 17 files changed, 2125 insertions(+), 1143 deletions(-) create mode 100644 crates/voelin-ui-vm/src/streams/logic.rs rename crates/voelin-ui-vm/src/{streams.rs => streams/mod.rs} (93%) delete mode 100644 crates/voelin-ui/src/streams.rs create mode 100644 crates/voelin-ui/src/streams/bind.rs create mode 100644 crates/voelin-ui/src/streams/mod.rs diff --git a/crates/voelin-ui-vm/src/events/mod.rs b/crates/voelin-ui-vm/src/events/mod.rs index a5ef10f..233540e 100644 --- a/crates/voelin-ui-vm/src/events/mod.rs +++ b/crates/voelin-ui-vm/src/events/mod.rs @@ -6,11 +6,10 @@ //! the state the same way. //! //! In [`Update::rest`] come back the events whose state is not in the -//! [`AppState`] yet: a stream we share or watch (`Share` and `Watch` hold -//! the capture and the decoder), the Stream Studio's stream, a setting that -//! changed (the settings service), and the friends, pokes and offline -//! messages that `social.rs` of the Slint client keeps. They move here with -//! their areas (docs/ui.md, "Controllers still to split"). +//! [`AppState`]: the Stream Studio's stream (`Host::studio_streams_to`), a +//! setting that changed (the settings service), and the friends, pokes and +//! offline messages that `social.rs` of the Slint client keeps. They move +//! here with their areas (docs/ui.md, "Controllers still to split"). mod gateway; @@ -27,6 +26,7 @@ use crate::previews::fetch_previews; use crate::servers::{AfterConnect, JoinStep, after_connect, join_password}; use crate::settings::LastVoice; use crate::state::{AppState, Lines, SessionView}; +use crate::streams::logic as streams; /// Apply an event to the state; see the [module](self). pub fn apply(state: &mut AppState, host: &dyn Host, event: Event) -> Update { @@ -39,6 +39,13 @@ pub fn apply(state: &mut AppState, host: &dyn Host, event: Event) - } fn dispatch(state: &mut AppState, cx: &mut Cx<'_>, event: Event) { + // The Stream Studio's stream is the studio's. + if let Event::StreamState { session, .. } | Event::StreamViewers { session, .. } = &event + && cx.host.studio_streams_to(*session as i64) + { + cx.update.rest = Some(event); + return; + } match event { Event::State { session, state: now } => session_state(state, cx, session as i64, now), Event::ServerInfo { session, name, backend, capabilities } => { @@ -214,9 +221,26 @@ fn dispatch(state: &mut AppState, cx: &mut Cx<'_>, event: Event) { cx.update.watch = Some(stream); } } - // What a stream we share or watch, the studio's stream and the - // settings service make of the rest, the front end keeps (see the - // module's note). + // The streams we share and watch. + Event::StreamState { session, state: now } => { + streams::share_state(state, cx, session as i64, now); + } + Event::StreamViewerRequest { session, viewer, .. } => { + streams::viewer_request(state, cx, session as i64, viewer); + } + Event::StreamViewers { session, viewers } => { + streams::viewers(state, cx, session as i64, viewers); + } + Event::WatchState { session, stream_id, state: now } => { + streams::watch_state(state, cx, session as i64, &stream_id, now); + } + Event::WatchLayers { session, stream_id, layers, layer } => { + streams::watch_layers(state, cx, session as i64, &stream_id, layers, layer); + } + // Also flagged on the sink, which the encoder reads. + Event::StreamKeyframeRequest { .. } | Event::StreamLayerBitrate { .. } => {} + // What the settings service and the friends make of the rest, the + // front end keeps (see the module's note). event => cx.update.rest = Some(event), } } diff --git a/crates/voelin-ui-vm/src/events/tests.rs b/crates/voelin-ui-vm/src/events/tests.rs index e496511..41fc7c3 100644 --- a/crates/voelin-ui-vm/src/events/tests.rs +++ b/crates/voelin-ui-vm/src/events/tests.rs @@ -1,11 +1,11 @@ //! Tapes of engine events replayed through [`apply`] against a fake host: //! the state they leave, and what each update asks of a front end. -use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; +use voelin_core::StreamState; use voelin_core::gateway::Pin; use voelin_core::stream::StreamInfo; use voelin_core::{ @@ -21,65 +21,11 @@ use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, MessageSource use super::*; use crate::bridge::ChatLine; use crate::host::Refresh; +use crate::host::testing::Fake; use crate::settings::{ClientPlayback, ClientPlaybackMap, LastVoice, UiSettings}; type State = AppState>; -/// The front end of the tests: answers what the transitions ask and keeps -/// what they store. -#[derive(Default)] -struct Fake { - demo: bool, - shown: Cell, - watching: bool, - autowatch: bool, - limit: u64, - /// What the store has: server unique id, its chats' reads. - reads: HashMap>, - /// What was stored. - written: RefCell>, -} - -impl Host for Fake { - fn demo_ui(&self) -> bool { - self.demo - } - - fn chat_shown(&self) -> bool { - self.shown.get() - } - - fn watching(&self) -> bool { - self.watching - } - - fn autowatch(&self) -> bool { - self.autowatch - } - - fn preview_limit(&self) -> u64 { - self.limit - } - - fn fetch_images(&self) -> bool { - false - } - - fn chat_reads(&self, server_uid: &str) -> Result, String> { - Ok(self.reads.get(server_uid).cloned().unwrap_or_default()) - } - - fn set_chat_read( - &self, - server_uid: &str, - target: &StoredTarget, - read: &ChatRead, - ) -> Result<(), String> { - self.written.borrow_mut().push((server_uid.to_owned(), target.clone(), *read)); - Ok(()) - } -} - fn state() -> State { let bookmark = Bookmark { id: 1, @@ -668,7 +614,7 @@ fn talking_the_meter_and_groups() { /// The streams the voice connection lists: the one a lookup waited for is /// to be watched; the rest of the stream events are the front end's. #[test] -fn streams_are_listed_and_the_rest_is_handed_back() { +fn streams_are_listed_and_a_lookup_is_watched() { let mut st = state(); let host = Fake::default(); run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]); @@ -706,8 +652,8 @@ fn streams_are_listed_and_the_rest_is_handed_back() { vec![Event::StreamsChanged { session: 1, streams: vec![stream("s3", 11)] }], ); assert_eq!(ups[0].watch.as_deref(), Some("s3")); - // What watching and sharing make of the other stream events is the front - // end's (and so is a setting that changed). + // Keyframe requests are the encoder's, read from the sink; a setting that + // changed is the settings service's: the front end keeps it. let ups = run( &mut st, &host, @@ -716,9 +662,73 @@ fn streams_are_listed_and_the_rest_is_handed_back() { Event::SettingChanged { key: "audio".into() }, ], ); - assert!(matches!(ups[0].rest, Some(Event::StreamKeyframeRequest { .. }))); + assert!(ups[0].rest.is_none() && ups[0].refresh.is_empty() && ups[0].commands.is_empty()); assert!(matches!(&ups[1].rest, Some(Event::SettingChanged { key }) if key == "audio")); - assert!(ups[0].refresh.is_empty() && ups[0].commands.is_empty()); +} + +/// The streams of the events: the studio's stream is the studio's; ours and +/// the one we watch change the state and say what the capture and the +/// decoder are to do. +#[test] +fn the_streams_we_share_and_watch_follow_the_events() { + use crate::streams::logic::{Sharing, Watching, demo_viewers}; + use voelin_core::WatchState; + use voelin_core::stream::EndReason; + + let mut st = state(); + run(&mut st, &Fake::default(), vec![Event::Presence { session: 1, presence: presence() }]); + st.share = Some(Sharing { session: 1, live: true, viewers: Vec::new(), stopping: false }); + st.watch = Some(Watching { + session: Some(1), + stream_id: "s1".into(), + title: "Speedrun".into(), + streamer: "Alice".into(), + status: String::new(), + connected: true, + ended: false, + has_frame: true, + shown: true, + since: None, + layers: Vec::new(), + layer: None, + }); + // The studio streams to the server: its events are handed back as they + // are, and our share is not touched. + let studio = Fake { studio: Some(1), ..Default::default() }; + let ups = run( + &mut st, + &studio, + vec![ + Event::StreamViewers { session: 1, viewers: demo_viewers() }, + Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Stopped) }, + ], + ); + assert!(matches!(ups[0].rest, Some(Event::StreamViewers { .. }))); + assert!(matches!(ups[1].rest, Some(Event::StreamState { .. }))); + assert!(st.share.as_ref().unwrap().viewers.is_empty() && st.share.as_ref().unwrap().live); + // Elsewhere they are ours. + let host = Fake::default(); + let ups = run( + &mut st, + &host, + vec![ + Event::StreamViewers { session: 1, viewers: demo_viewers() }, + Event::StreamViewerRequest { session: 1, viewer: 11, message: "hi".into() }, + Event::WatchState { + session: 1, + stream_id: "s1".into(), + state: WatchState::Ended(EndReason::Stopped), + }, + Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Local) }, + ], + ); + assert!(ups[0].refresh.streams && ups[0].rest.is_none()); + assert_eq!(ups[1].status.as_deref(), Some("Alice wants to watch your stream")); + let watch = st.watch.as_ref().unwrap(); + assert!(watch.ended && ups[2].stream.drop_decoder); + assert_eq!(watch.status, "The stream has ended."); + assert!(st.share.is_none() && ups[3].stream.drop_share && ups[3].stream.mixer); + assert_eq!(ups[3].status.as_deref(), Some("You stopped sharing")); } /// Pictures linked in a chat are downloaded once, up to the limit. diff --git a/crates/voelin-ui-vm/src/host.rs b/crates/voelin-ui-vm/src/host.rs index 1b19ceb..04775c4 100644 --- a/crates/voelin-ui-vm/src/host.rs +++ b/crates/voelin-ui-vm/src/host.rs @@ -10,7 +10,7 @@ use std::path::PathBuf; -use voelin_core::{Command, Event, GatewayRequest}; +use voelin_core::{Command, Event, GatewayRequest, StreamSink}; use voelin_model::ChatTarget; use voelin_store::{ChatRead, ChatTarget as StoredTarget}; @@ -32,6 +32,10 @@ pub trait Host { /// that shows up. fn autowatch(&self) -> bool; + /// The Stream Studio streams to this session: the events of that stream + /// are its own. + fn studio_streams_to(&self, session: i64) -> bool; + /// The largest picture previewed in chats, in bytes (0: none), from /// `ui.image_preview_kb`. fn preview_limit(&self) -> u64; @@ -122,6 +126,22 @@ pub struct PasswordPrompt { pub wrong: bool, } +/// What the streams we share and watch need of the front end, which owns the +/// capture and the decoder. +#[derive(Debug, Default)] +pub struct StreamEffects { + /// Encode into the live stream: the sink of our stream. + pub attach: Option, + /// Our stream is over: the capture stops. + pub drop_share: bool, + /// The watched stream is over, or left: its decoder stops. + pub drop_decoder: bool, + /// The audio mixer's rows follow the capture again. + pub mixer: bool, + /// The player leaves full screen. + pub leave_fullscreen: bool, +} + /// What a transition tells its front end, besides the changed state. #[derive(Debug, Default)] pub struct Update { @@ -150,6 +170,8 @@ pub struct Update { /// A stream to watch (its id): the one a lookup was waiting for, or the /// development switch's. pub watch: Option, + /// The capture and the decoder. + pub stream: StreamEffects, /// A server connected or answered: the development switch that shares /// the test pattern may start now. pub autoshare: bool, @@ -219,3 +241,75 @@ impl<'a> Cx<'a> { self.update.chats.push((id, target.clone())); } } + +/// A front end for the tests of the transitions. +#[cfg(test)] +pub(crate) mod testing { + use std::cell::{Cell, RefCell}; + use std::collections::HashMap; + + use voelin_store::{ChatRead, ChatTarget as StoredTarget}; + + use super::Host; + + /// The front end of the tests: answers what the transitions ask and keeps + /// what they store. + #[derive(Default)] + pub(crate) struct Fake { + pub(crate) demo: bool, + pub(crate) shown: Cell, + pub(crate) watching: bool, + pub(crate) autowatch: bool, + /// The session the Stream Studio streams to. + pub(crate) studio: Option, + pub(crate) limit: u64, + /// What the store has: server unique id, its chats' reads. + pub(crate) reads: HashMap>, + /// What was stored. + pub(crate) written: RefCell>, + } + + impl Host for Fake { + fn demo_ui(&self) -> bool { + self.demo + } + + fn chat_shown(&self) -> bool { + self.shown.get() + } + + fn watching(&self) -> bool { + self.watching + } + + fn autowatch(&self) -> bool { + self.autowatch + } + + fn studio_streams_to(&self, session: i64) -> bool { + self.studio == Some(session) + } + + fn preview_limit(&self) -> u64 { + self.limit + } + + fn fetch_images(&self) -> bool { + false + } + + fn chat_reads(&self, server_uid: &str) -> Result, String> { + Ok(self.reads.get(server_uid).cloned().unwrap_or_default()) + } + + fn set_chat_read( + &self, + server_uid: &str, + target: &StoredTarget, + read: &ChatRead, + ) -> Result<(), String> { + self.written.borrow_mut().push((server_uid.to_owned(), target.clone(), *read)); + Ok(()) + } + } +} diff --git a/crates/voelin-ui-vm/src/state.rs b/crates/voelin-ui-vm/src/state.rs index ea37a4f..ce1bc1f 100644 --- a/crates/voelin-ui-vm/src/state.rs +++ b/crates/voelin-ui-vm/src/state.rs @@ -25,6 +25,7 @@ use crate::bridge::ChatLine; use crate::chat::{LineCache, Previous}; use crate::image::ImageRef; use crate::settings::{ClientPlaybackMap, DeviceChoices, UiSettings}; +use crate::streams::logic::{Sharing, Watching}; /// The store's name of a chat. pub fn store_target(target: &ChatTarget) -> voelin_store::ChatTarget { @@ -568,6 +569,10 @@ pub struct AppState { /// Our unique ids (TeamSpeak 3 and 6 of every identity): messages by /// them are ours ([`crate::social::own_message`]). pub own_uids: HashSet, + /// Our stream (the capture that feeds it is the front end's). + pub share: Option, + /// The stream in the viewer (its decoder is the front end's). + pub watch: Option, } impl AppState { @@ -608,6 +613,8 @@ impl AppState { gateways_looked_up: HashSet::new(), uploads: HashMap::new(), own_uids: HashSet::new(), + share: None, + watch: None, } } } diff --git a/crates/voelin-ui-vm/src/streams/logic.rs b/crates/voelin-ui-vm/src/streams/logic.rs new file mode 100644 index 0000000..e48b51b --- /dev/null +++ b/crates/voelin-ui-vm/src/streams/logic.rs @@ -0,0 +1,1386 @@ +//! 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, + /// The desktop portal's token of the last choice. + pub restore_token: Option, +} + +/// 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, +) -> 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 { + 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, + /// 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, + /// 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, + /// The simulcast layers the streamer offers, largest first. + pub layers: Vec, + /// The layer chosen by hand; `None` follows the bandwidth estimate. + pub layer: Option, +} + +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> { + if self.layers.len() < 2 { + return Vec::new(); + } + let mut names: Vec> = 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) -> 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(view: &SessionView, id: &str) -> Option { + 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(state: &AppState, 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( + state: &mut AppState, + cx: &mut Cx<'_>, + session: i64, + viewers: Vec, +) { + 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(state: &mut AppState, 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( + state: &mut AppState, + 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( + state: &mut AppState, + cx: &mut Cx<'_>, + session: i64, + stream_id: &str, + layers: Vec, + layer: Option, +) { + 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(state: &mut AppState, 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(state: &mut AppState, cx: &mut Cx<'_>, stream_id: &str) -> Option { + 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(state: &mut AppState, cx: &mut Cx<'_>, client: u16) -> Option { + 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(state: &AppState) -> Option { + 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(state: &mut AppState, 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(state: &AppState) -> 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(state: &mut AppState) -> 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(state: &mut AppState, 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(state: &mut AppState, 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(state: &mut AppState, 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(state: &mut AppState, 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(state: &mut AppState, result: Result, String>) -> Vec { + 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(state: &AppState, 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( + state: &mut AppState, + cx: &mut Cx<'_>, + form: &ShareForm, + studio_live_here: bool, + sources: &[AudioSourceSetting], +) -> Option { + 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, + /// 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, +} + +/// The capture started (or not): go live. `true` if the front end keeps the +/// capture (and meters its audio). +pub fn capture_ready( + state: &mut AppState, + cx: &mut Cx<'_>, + session: i64, + mut setup: StreamSetup, + auto_accept: bool, + result: Result, +) -> 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(state: &mut AppState, 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(state: &AppState, 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(state: &AppState, 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(state: &mut AppState, 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, + /// 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, + /// Our share. + pub share: ShareView, +} + +/// The streams panel, the voice card's streams and the share card. +pub fn streams_view(state: &AppState, facts: &StreamsFacts<'_>) -> StreamsView { + let current = state.current; + let view = current.and_then(|id| state.sessions.get(&id)); + let mut items: Vec = 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 = 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, + /// 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>, + /// 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(state: &AppState, 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::>() + .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>; + + /// 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::>(), + ["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()); + } +} diff --git a/crates/voelin-ui-vm/src/streams.rs b/crates/voelin-ui-vm/src/streams/mod.rs similarity index 93% rename from crates/voelin-ui-vm/src/streams.rs rename to crates/voelin-ui-vm/src/streams/mod.rs index af50de7..4621edc 100644 --- a/crates/voelin-ui-vm/src/streams.rs +++ b/crates/voelin-ui-vm/src/streams/mod.rs @@ -1,5 +1,8 @@ //! Streams on the voice view, the phone's Activity tab and Home: what is -//! shared, and who shares it. +//! shared, and who shares it; [`logic`] has the state of the streams we +//! share and watch, and what happens to them. + +pub mod logic; use std::path::PathBuf; diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 5d645d5..b6e5c85 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -30,8 +30,8 @@ use voelin_store::{Bookmark, MemorySecrets, Secrets, Store}; use crate::bind::rows::Rows; use crate::hotkey::GlobalPtt; use crate::settings::{CLIENT_PLAYBACK, ClientPlaybackMap, UI, UiSettings, appearance_keys}; -use crate::streams::{Share, Watch}; -use crate::video::Video; +use crate::streams::Share; +use crate::video::{Decoder, Video}; use crate::vm; slint::include_modules!(); @@ -228,10 +228,10 @@ pub(crate) struct App { pub prefs: Settings, pub ptt: GlobalPtt, pub video: Video, - /// Our stream. + /// The capture of our stream (`state.share` has the rest of it). pub share: Option, - /// The stream in the viewer. - pub watch: Option, + /// The decoder of the stream in the viewer (`state.watch` has the rest). + pub decoder: Option, /// `VOELIN_DEMO_STREAM`: the viewer shows a local test stream. pub demo: bool, /// `VOELIN_DEMO_UI`: sample servers, channels and chat (dev.rs). @@ -441,7 +441,7 @@ pub fn run(options: RunOptions) -> Result<()> { ptt, video, share: None, - watch: None, + decoder: None, demo: switches.demo_stream, demo_ui: switches.demo_ui, autoshare: switches.autoshare, @@ -515,7 +515,9 @@ pub fn run(options: RunOptions) -> Result<()> { for id in ids { app.save_reads(id); } - app.watch = None; + app.state.watch = None; + app.decoder = None; + app.state.share = None; app.share = None; if own && !app.demo_ui { for id in app.state.sessions.keys() { diff --git a/crates/voelin-ui/src/host.rs b/crates/voelin-ui/src/host.rs index fe9e4a3..e314ef9 100644 --- a/crates/voelin-ui/src/host.rs +++ b/crates/voelin-ui/src/host.rs @@ -12,6 +12,7 @@ use voelin_store::{ChatRead, ChatTarget as StoredTarget, Store}; use crate::app::{App, AppState, Bridge, MainWindow, Nav}; use crate::settings::UI_IMAGE_PREVIEW_KB; +use crate::studio::StudioState; use crate::vm::host::{Cx, Host, PasswordPrompt, Persist, Refresh, Update}; /// What the transitions ask while they run: the window, the store and the @@ -22,6 +23,7 @@ pub(crate) struct SlintHost<'a> { pub ui: &'a slint::Weak, pub store: &'a Store, pub prefs: &'a Settings, + pub studio: &'a StudioState, } impl Host for SlintHost<'_> { @@ -41,6 +43,10 @@ impl Host for SlintHost<'_> { std::env::var("VOELIN_AUTOWATCH").is_ok_and(|v| v == "1") } + fn studio_streams_to(&self, session: i64) -> bool { + self.studio.streams_to(session) + } + fn preview_limit(&self) -> u64 { u64::from(self.prefs.get(&UI_IMAGE_PREVIEW_KB)) * 1024 } @@ -65,13 +71,14 @@ impl Host for SlintHost<'_> { impl App { /// Run `f` with the state and the host, and return what it returns. - fn with_host(&mut self, f: impl FnOnce(&mut AppState, &SlintHost<'_>) -> R) -> R { + pub(crate) fn with_host(&mut self, f: impl FnOnce(&mut AppState, &SlintHost<'_>) -> R) -> R { let host = SlintHost { demo_ui: self.demo_ui, - watching: self.watch.is_some(), + watching: self.state.watch.is_some(), ui: &self.ui, store: &self.store, prefs: &self.prefs, + studio: &self.studio, }; f(&mut self.state, &host) } @@ -111,6 +118,7 @@ impl App { warnings, chats, watch, + stream, autoshare, first_client, rest, @@ -122,12 +130,30 @@ impl App { for path in &reloaded { crate::images::reloaded(path); } - if let Some(text) = status { - self.set_status(text); - } for command in commands { self.engine.send(command); } + // The capture and the decoder. + if let Some(sink) = stream.attach + && let Some(share) = &self.share + { + share.capture.attach(sink); + } + if stream.drop_share { + self.share = None; + } + if stream.drop_decoder { + self.decoder = None; + } + if stream.leave_fullscreen { + self.set_fullscreen(false); + } + if stream.mixer { + self.mixer_refresh(); + } + if let Some(text) = status { + self.set_status(text); + } for what in persist { self.keep(what); } @@ -224,9 +250,8 @@ impl App { } } - /// The events whose state the view model does not hold yet: a setting - /// that changed, the studio's stream, and the streams we share and - /// watch. + /// The events whose state the view model does not hold: a setting that + /// changed, and the studio's stream. fn event_rest(&mut self, event: Event) { match event { Event::SettingChanged { key } => self.setting_changed(&key), @@ -237,7 +262,9 @@ impl App { Event::StreamViewers { session, viewers } if self.studio_streams_to(session as i64) => { self.studio_viewers(viewers); } - event => self.stream_event(event), + // The rest (friends, pokes, offline messages) is looked at by + // social.rs, before and after. + _ => {} } } } diff --git a/crates/voelin-ui/src/popout.rs b/crates/voelin-ui/src/popout.rs index da66ea3..fa06a7b 100644 --- a/crates/voelin-ui/src/popout.rs +++ b/crates/voelin-ui/src/popout.rs @@ -42,7 +42,8 @@ impl App { /// The player into a window of its own. pub(crate) fn viewer_pop_out(&mut self) { // One window on Android. - if cfg!(target_os = "android") || self.popout.window.is_some() || self.watch.is_none() { + if cfg!(target_os = "android") || self.popout.window.is_some() || self.state.watch.is_none() + { return; } // The main window's full screen was the player's. @@ -86,7 +87,7 @@ impl App { /// The player back into the main window, on the stream's server page. pub(crate) fn viewer_dock(&mut self) { let Some(window) = self.close_popout() else { return }; - if let Some(watch) = &mut self.watch { + if let Some(watch) = &mut self.state.watch { watch.shown = true; } if let Some(ui) = self.ui.upgrade() { @@ -95,6 +96,7 @@ impl App { // The main window may have gone to another server meanwhile: else // the stream would play on, unseen. let session = self + .state .watch .as_ref() .and_then(|w| w.session) diff --git a/crates/voelin-ui/src/servers.rs b/crates/voelin-ui/src/servers.rs index 8c383b0..89ff997 100644 --- a/crates/voelin-ui/src/servers.rs +++ b/crates/voelin-ui/src/servers.rs @@ -526,7 +526,8 @@ impl App { self.models.members.sync(&members); // The people in our channel first while their view is shown (not // while the stream plays in a window of its own). - let watching = self.watch.as_ref().is_some_and(|w| w.shown) && self.popout.window.is_none(); + let watching = + self.state.watch.as_ref().is_some_and(|w| w.shown) && self.popout.window.is_none(); let voice_first = connected && (self.state.voice_view || watching); let everyone = vm::tree::server_members(&input, voice_first); let filter = self.state.member_filter.trim().to_lowercase(); diff --git a/crates/voelin-ui/src/streams.rs b/crates/voelin-ui/src/streams.rs deleted file mode 100644 index 9fe84dd..0000000 --- a/crates/voelin-ui/src/streams.rs +++ /dev/null @@ -1,1025 +0,0 @@ -//! Streams (TeamSpeak 6): the streams panel, sharing our screen and the -//! viewer. The engine runs the stream sessions; `video.rs` captures, -//! encodes and decodes. - -use std::sync::Arc; -use std::time::Duration; - -use slint::{ComponentHandle, Model}; -use tracing::warn; -use voelin_core::media::{Streamer, audio_source_specs}; -use voelin_core::settings::{ - AudioSourceSetting, STREAM_AUDIO_SOURCES, STREAM_BITRATE_KBPS, STREAM_FPS, -}; -use voelin_core::stream::{ - EndReason, LayerId, LayerSpec, LeaveReason, StreamSetup, ViewerInfo, ViewerState, -}; -use voelin_core::{Command, Event, StreamState, WatchState}; - -use crate::app::{App, Bridge, later, with_app}; -use crate::bind::convert; -use crate::settings::{ - BITRATE_CHOICES, FPS_CHOICES, LEGACY_BITRATE_CHOICES, LEGACY_FPS_CHOICES, ShareDefaults, - nearest_choice, parse_positive, -}; -use crate::video::{self, Capture, CaptureRequest, Decoder}; -use crate::vm::bridge::{ShareForm, SourceItem, StreamItem, ViewerItem}; - -/// Our stream. -pub(crate) struct Share { - pub session: i64, - /// Stops capturing when dropped. - capture: Capture, - /// The server confirmed the stream. - live: bool, - viewers: Vec, - /// The capture ended by itself and the stream is being stopped. - stopping: bool, - /// The audio mixer's meters (the studio's rows), about 15 times a second. - _meters: slint::Timer, -} - -/// 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. -fn capture_request( - fps: u32, - bitrate_kbps: u32, - audio: bool, - sources: &[AudioSourceSetting], - restore_token: Option, -) -> 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. -fn demo_viewers() -> Vec { - 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?"), - ] -} - -/// The stream in the viewer. -pub(crate) struct Watch { - /// `None` for the local demo stream. - pub(crate) session: Option, - stream_id: String, - title: String, - streamer: String, - /// Shown over the picture; empty while it plays. - status: String, - connected: bool, - ended: bool, - has_frame: bool, - /// Shown instead of the chat. - pub(crate) shown: bool, - decoder: Option, - /// When the picture started, for the elapsed time. - since: Option, - /// The simulcast layers the streamer offers, largest first. - layers: Vec, - /// The layer chosen by hand; `None` follows the bandwidth estimate. - layer: Option, -} - -impl Watch { - /// "12:34" since the picture started. - 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. - fn qualities(&self) -> Vec> { - if self.layers.len() < 2 { - return Vec::new(); - } - let mut names: Vec> = vec!["Auto".into()]; - names.extend(self.layers.iter().map(|l| layer_name(l).into())); - names - } -} - -/// "720p · 2.4 Mbit/s", or the scale when the size is not fixed. -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) -} - -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}"), - } -} - -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. -fn viewer_count(view: &crate::app::SessionView, id: &str) -> Option { - 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. -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), - } -} - -/// Show or hide the pointer over `window`. In full screen the player hides -/// it with its controls: Slint applies a TouchArea's cursor only when the -/// pointer moves, so the window is told directly. (No pointer on Android.) -pub(crate) fn show_cursor(window: &slint::Window, shown: bool) { - #[cfg(not(target_os = "android"))] - { - use slint::winit_030::WinitWindowAccessor; - window.with_winit_window(|w| w.set_cursor_visible(shown)); - } - #[cfg(target_os = "android")] - let _ = (window, shown); -} - -impl App { - pub(crate) fn stream_event(&mut self, event: Event) { - match event { - Event::StreamState { session, state } => self.share_state(session as i64, state), - Event::StreamViewerRequest { session, viewer, .. } => { - let name = self.state.sessions.entry(session as i64).or_default().nickname(viewer); - self.set_status(format!("{name} wants to watch your stream")); - } - Event::StreamViewers { session, viewers } => { - if let Some(share) = self.share.as_mut().filter(|s| s.session == session as i64) { - share.viewers = viewers; - self.refresh_streams(); - } - } - Event::WatchState { session, stream_id, state } => { - self.watch_state(session as i64, &stream_id, state); - } - Event::WatchLayers { session, stream_id, layers, layer } => { - if let Some(watch) = self - .watch - .as_mut() - .filter(|w| w.session == Some(session as i64) && w.stream_id == stream_id) - { - watch.layers = layers; - watch.layer = layer; - self.refresh_viewer(); - } - } - // Also flagged on the sink, which the encoder reads. - Event::StreamKeyframeRequest { .. } => {} - _ => {} - } - } - - fn share_state(&mut self, session: i64, state: StreamState) { - let Some(share) = self.share.as_mut().filter(|s| s.session == session) else { return }; - match state { - StreamState::Starting => {} - StreamState::Live { sink, .. } => { - share.live = true; - share.capture.attach(sink); - self.set_status("You are sharing your screen"); - } - StreamState::Ended(reason) => { - let local = reason == EndReason::Local || share.stopping; - self.share = None; - self.state.share_error = - if local { String::new() } else { share_end_text(&reason) }; - self.set_status(if local { - "You stopped sharing".into() - } else { - share_end_text(&reason) - }); - self.mixer_refresh(); - } - } - self.refresh_streams(); - } - - fn watch_state(&mut self, session: i64, stream_id: &str, state: WatchState) { - let Some(watch) = self - .watch - .as_mut() - .filter(|w| w.session == Some(session) && w.stream_id == stream_id && !w.ended) - else { - return; - }; - match state { - 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; - watch.decoder = None; - watch.status = end_text(&reason, &watch.streamer); - } - } - self.refresh_viewer(); - self.refresh_streams(); - } - - /// The streams panel, the share dialog's live part and the toolbar. - pub(crate) fn refresh_streams(&self) { - let Some(ui) = self.ui.upgrade() else { return }; - let bridge = ui.global::(); - let view = self.view(); - let current = self.state.current; - let mut items: Vec = 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); - // Our own stream from the studio shows its preview. - let studio = current.is_some_and(|c| self.studio_streams_to(c)); - for s in streams { - // Also the sample data's test pattern dressed as this stream - // (`VOELIN_OPEN=watch`), which has no session. - let watching = self.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, - studio: own && studio, - kind: crate::vm::streams::kind_label(&s.kind).into(), - bitrate: bitrate_text(s.bitrate).into(), - ..crate::vm::streams::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), - ..crate::vm::streams::streamer(&c.nickname, view.avatar(c.id)) - }); - } - } - } - if self.demo { - items.push(StreamItem { - id: "demo".into(), - name: "Test pattern".into(), - audio: false, - watching: self.watch.as_ref().is_some_and(|w| w.session.is_none() && !w.ended), - own: false, - ..crate::vm::streams::streamer("local preview", None) - }); - } - bridge.set_streams_available(self.demo || view.is_some_and(|v| v.streams_available())); - self.models.streams.sync(&items); - bridge.set_can_share(video::AVAILABLE); - - let share = self.share.as_ref().filter(|s| Some(s.session) == current); - let state = match share { - Some(s) if s.live => "live", - Some(_) => "starting", - None if self.state.share_busy => "starting", - None => "", - }; - bridge.set_share_state(state.into()); - bridge.set_share_busy(self.state.share_busy); - bridge.set_share_error(self.state.share_error.clone().into()); - bridge.set_share_audio(share.is_some_and(|s| s.capture.has_audio())); - let viewers: Vec = 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::vm::avatar::image( - view.and_then(|view| view.avatar(v.client)), - ), - }) - .collect() - }) - .unwrap_or_default(); - let requests = viewers.iter().filter(|v| &*v.state == "requested").count(); - bridge.set_share_requests(requests as i32); - self.models.viewers.sync(&viewers); - let status = match share { - Some(s) if s.live => s.capture.status(), - Some(s) => format!("Starting the stream of {}…", s.capture.source_name()), - None if self.state.share_busy => "Starting the capture…".into(), - None => String::new(), - }; - bridge.set_share_status(status.into()); - } - - /// The viewer in the main window and in its own: the same facts, but - /// the main window's player only while the stream is not popped out. - pub(crate) fn refresh_viewer(&self) { - let popped = self.popout.window.is_some(); - let Some(watch) = &self.watch else { - self.viewer_each(|bridge| { - bridge.set_viewer_open(false); - bridge.set_viewer_popped(popped); - bridge.set_viewer_has_frame(false); - bridge.set_viewer_frame(slint::Image::default()); - }); - return; - }; - if let Some(ui) = self.ui.upgrade() { - let bridge = ui.global::(); - let open = watch.shown && !popped && self.watch_here(); - if !open && bridge.get_viewer_open() && bridge.get_viewer_fullscreen() { - // The player goes, still in full screen: it may have hidden the cursor. - show_cursor(ui.window(), true); - } - bridge.set_viewer_open(open); - } - if let Some(window) = &self.popout.window { - window.global::().set_viewer_open(true); - } - // 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) => self.state.sessions.get(&id), - None => self.view(), - }; - let decoded = watch.decoder.as_ref().map(Decoder::info).unwrap_or_default(); - let info = [format!("by {}", watch.streamer), decoded.clone()] - .into_iter() - .filter(|s| !s.is_empty()) - .collect::>() - .join(" · "); - let streamer = view - .and_then(|v| v.streams.iter().find(|s| s.id == watch.stream_id)) - .map_or(-1, |s| i32::from(s.streamer)); - let face = crate::vm::streams::streamer( - &watch.streamer, - view.zip(u16::try_from(streamer).ok()).and_then(|(v, id)| v.avatar(id)), - ); - // The members are the current server's. - let members = &self.models.members; - let admin = self.watch_here() && members.rows().iter().any(|m| m.id == streamer && m.admin); - let channel = u16::try_from(streamer).ok().and_then(|id| { - let view = view?; - let channel = view.presence.channels.get(&view.channel_of(id)?)?; - Some(crate::vm::tree::channel_title(channel).0.to_owned()) - }); - let channel = slint::SharedString::from(channel.unwrap_or_default()); - let elapsed = slint::SharedString::from(watch.elapsed()); - let viewers = view.and_then(|v| viewer_count(v, &watch.stream_id)); - let qualities = watch.qualities(); - let chosen = watch - .layer - .and_then(|id| watch.layers.iter().position(|l| l.id == id)) - .map_or(0, |i| i as i32 + 1); - self.models.qualities.sync(&qualities); - self.viewer_each(|bridge| { - bridge.set_viewer_popped(popped); - bridge.set_viewer_title(watch.title.as_str().into()); - bridge.set_viewer_status(watch.status.as_str().into()); - bridge.set_viewer_ended(watch.ended); - bridge.set_viewer_has_frame(watch.has_frame); - bridge.set_viewer_volume(self.state.stream_volume); - bridge.set_viewer_info(info.as_str().into()); - bridge.set_viewer_streamer(watch.streamer.as_str().into()); - bridge.set_viewer_streamer_avatar(convert::image(&face.avatar)); - bridge.set_viewer_streamer_initials(face.initials.as_ref().into()); - bridge.set_viewer_streamer_tint(convert::color(face.tint)); - bridge.set_viewer_streamer_admin(admin); - bridge.set_viewer_channel(channel.clone()); - bridge.set_viewer_elapsed(elapsed.clone()); - bridge.set_viewer_count(viewers.unwrap_or(0) as i32); - if bridge.get_viewer_quality() != chosen { - bridge.set_viewer_quality(chosen); - } - bridge.set_viewer_quality_detail(decoded.as_str().into()); - }); - } - - /// The watched stream is on the server on screen (or is the local test - /// stream). - pub(crate) fn watch_here(&self) -> bool { - self.watch.as_ref().is_some_and(|w| w.session.is_none() || w.session == self.state.current) - } - - /// A simulcast layer of the watched stream (0: follow the bandwidth - /// estimate), asked of the streamer; the engine confirms with - /// `WatchLayers`. - pub(crate) fn set_stream_quality(&mut self, index: i32) { - let Some(watch) = &mut self.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 { - self.engine.send(Command::SetWatchLayer { - session: session as u64, - stream_id: watch.stream_id.clone(), - layer: watch.layer, - }); - } - self.refresh_viewer(); - } - - /// Once a second: statistics, a capture that ended, decoder problems. - pub(crate) fn tick_streams(&mut self) { - if let Some(share) = &mut self.share - && share.live - && !share.stopping - && share.capture.ended() - { - share.stopping = true; - self.engine.send(Command::StopStream { session: share.session as u64 }); - } - if let Some(watch) = &mut self.watch - && watch.connected - && !watch.has_frame - && let Some(error) = watch.decoder.as_ref().and_then(Decoder::error) - { - 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}") - }; - } - if self.share.is_some() { - self.refresh_streams(); - } - // The share dialog's audio mixer (studio/). - self.mixer_tick(); - if self.watch.is_some() { - self.refresh_viewer(); - } - } - - // Sharing. - - /// Fill the share dialog: sources and the last choices. - pub(crate) fn open_share(&mut self) -> ShareForm { - let test_pattern = cfg!(debug_assertions) - || self.demo - || std::env::var("VOELIN_TEST_PATTERN").is_ok_and(|v| v == "1"); - let restorable = self.state.settings.portal_restore_token.is_some(); - let sources = match self.video.sources(test_pattern, restorable) { - Ok(sources) => { - if self.share.is_none() { - self.state.share_error.clear(); - } - sources - } - Err(e) => { - self.state.share_error = e; - Vec::new() - } - }; - if let Some(ui) = self.ui.upgrade() { - let items: Vec = sources - .into_iter() - .map(|(name, detail)| SourceItem { name: name.into(), detail: detail.into() }) - .collect(); - ui.global::().set_share_sources(convert::model(&items)); - } - self.refresh_streams(); - // Its audio: the Stream Studio's mixer rows and picker. - self.mixer_show(); - let defaults = &self.state.settings.share; - let nickname = - self.state.current.and_then(|id| self.bookmark(id)).map(|b| b.nickname.clone()); - let (fps, bitrate) = (self.prefs.get(&STREAM_FPS), self.prefs.get(&STREAM_BITRATE_KBPS)); - 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, - } - } - - /// The share dialog's form with the test pattern chosen. - fn test_pattern_form(&mut self) -> Option { - let mut form = self.open_share(); - let ui = self.ui.upgrade()?; - let sources = ui.global::().get_share_sources(); - let pattern = (0..sources.row_count()) - .find(|&i| sources.row_data(i).is_some_and(|s| s.name == "Test pattern"))?; - form.source = pattern as i32; - Some(form) - } - - /// Development switch `VOELIN_AUTOSHARE`: share the test pattern once. - pub(crate) fn autoshare(&mut self) { - if !self.autoshare || !self.view().is_some_and(|v| v.streams_available()) { - return; - } - self.autoshare = false; - if let Some(form) = self.test_pattern_form() { - self.start_share(ShareForm { auto_accept: true, ..form }); - } - } - - /// `VOELIN_OPEN=share:live` with sample data: the test pattern shared - /// with the sample mixer's sources (live at once, `capture_ready`). - pub(crate) fn demo_share(&mut self) { - if let Some(form) = self.test_pattern_form() { - self.start_share(ShareForm { audio: true, ..form }); - } - } - - pub(crate) fn start_share(&mut self, form: ShareForm) { - let Some(session) = self.state.current else { return }; - if self.state.share_busy || self.share.is_some() { - return; - } - if self.studio_streams_to(session) { - self.state.share_error = - "The Stream Studio is live here: end that stream first.".into(); - self.refresh_streams(); - return; - } - // 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)); - // The next share starts from these. - for result in - [self.prefs.set(&STREAM_FPS, fps), self.prefs.set(&STREAM_BITRATE_KBPS, bitrate)] - { - if let Err(e) = result { - warn!(%e, "could not store the share settings"); - } - } - 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, - }; - // The mixer's sources (the sample studio's with VOELIN_DEMO_UI). - let sources = self.studio_settings().get(&STREAM_AUDIO_SOURCES); - let token = self.state.settings.portal_restore_token.clone(); - let request = capture_request(fps, bitrate, form.audio, &sources, token); - self.state.settings.share = defaults; - self.store_settings(); - self.state.share_busy = true; - self.state.share_error.clear(); - self.refresh_streams(); - let setup = StreamSetup { - name: form.name.trim().to_owned(), - bitrate, - audio: request.audio, - ..StreamSetup::default() - }; - let auto_accept = form.auto_accept; - let runtime = self.engine.runtime().clone(); - let source = usize::try_from(form.source).unwrap_or(0); - self.video.start_capture(&runtime, source, request, move |result| { - later(move |app| app.capture_ready(session, setup, auto_accept, result)); - }); - } - - /// The capture started (or not): go live. - fn capture_ready( - &mut self, - session: i64, - mut setup: StreamSetup, - auto_accept: bool, - result: Result, - ) { - self.state.share_busy = false; - match result { - Err(e) => { - self.state.share_error = format!("Could not start the capture: {e}"); - } - Ok(capture) => { - if let Some(token) = capture.restore_token() - && self.state.settings.portal_restore_token.as_ref() != Some(&token) - { - self.state.settings.portal_restore_token = Some(token); - self.store_settings(); - } - if setup.bitrate == 0 { - // Automatic: what it comes to for the size captured. - setup.bitrate = capture.streamer().bitrate_kbps(); - } - if setup.audio && !capture.has_audio() { - setup.audio = false; - let reason = capture.audio_error().unwrap_or_default(); - self.set_status(format!("Sharing without sound: {reason}")); - } - // Sample data has no server: live at once, with viewers. - let (live, viewers) = if self.demo_ui { - (true, demo_viewers()) - } else { - let session = session as u64; - // One layer, whatever a studio stream had before. - self.engine.send(Command::SetStreamLayers { session, layers: Vec::new() }); - self.engine.send(Command::StartStream { session, setup, auto_accept }); - (false, Vec::new()) - }; - let meters = slint::Timer::default(); - meters.start(slint::TimerMode::Repeated, Duration::from_millis(66), || { - with_app(|app| app.studio_meters()); - }); - self.share = Some(Share { - session, - capture, - live, - viewers, - stopping: false, - _meters: meters, - }); - // The mixer's rows follow this capture's sources. - self.mixer_refresh(); - } - } - self.refresh_streams(); - } - - pub(crate) fn stop_share(&mut self) { - let Some(share) = &mut self.share else { return }; - share.stopping = true; - let session = share.session; - if self.demo_ui { - self.share_state(session, StreamState::Ended(EndReason::Local)); - } else { - self.engine.send(Command::StopStream { session: session as u64 }); - } - } - - /// The running share's streamer (the mixer's rows, studio/). - pub(crate) fn share_streamer(&self) -> Option<&Streamer> { - self.share.as_ref().map(|s| s.capture.streamer()) - } - - /// `stream.audio_sources` changed (the mixer, the settings, another - /// window): a running share mixes the new sources. - pub(crate) fn share_audio_changed(&mut self) { - if self.share.is_none() { - return; - } - let sources = audio_source_specs(&self.studio_settings().get(&STREAM_AUDIO_SOURCES)); - let codecs = self.video.codecs(); - let Some(share) = &self.share else { return }; - if let Err(e) = share.capture.follow_audio(&codecs, sources) { - self.set_status(format!("Stream audio: {e}")); - } - self.mixer_refresh(); - } - - pub(crate) fn respond_viewer(&mut self, viewer: u16, accept: bool) { - if let Some(share) = &self.share { - let session = share.session as u64; - self.engine.send(Command::AcceptViewer { session, viewer, accept }); - } - } - - pub(crate) fn kick_viewer(&mut self, viewer: u16) { - if let Some(share) = &self.share { - self.engine.send(Command::KickViewer { session: share.session as u64, viewer }); - } - } - - // Watching. - - pub(crate) fn watch_stream(&mut self, stream_id: String) { - if stream_id == "demo" && self.demo { - self.start_demo(); - return; - } - let Some(session) = self.state.current else { return }; - let Some(view) = self.state.sessions.get(&session) else { return }; - let Some(info) = view.streams.iter().find(|s| s.id == stream_id) else { return }; - 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. - self.stop_watching(); - self.engine - .send(Command::WatchStream { session: session as u64, stream_id: stream_id.clone() }); - if self.state.stream_volume != 100.0 { - self.engine.send(Command::SetStreamVolume { - session: session as u64, - stream_id: stream_id.clone(), - volume: self.state.stream_volume / 100.0, - }); - } - let wake = || later(|app| app.show_picture()); - let decoder = self.video.watch(&self.engine, session as u64, &stream_id, wake); - self.watch = Some(Watch { - session: Some(session), - stream_id, - title, - status: format!("Asking {streamer} to let you watch…"), - streamer, - connected: false, - ended: false, - has_frame: false, - shown: true, - decoder: Some(decoder), - since: None, - layers: Vec::new(), - layer: None, - }); - self.refresh_viewer(); - self.refresh_streams(); - // The people in our channel lead the members panel beside the viewer. - self.refresh_tree(); - } - - /// Watch the stream of `client` (a click on a streaming user in the - /// channel tree or the members): 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(crate) fn watch_client(&mut self, client: u16) { - let Some(session) = self.state.current else { return }; - let Some(view) = self.state.sessions.get(&session) else { return }; - if view.state.own_client == Some(client) { - return; - } - if let Some(id) = view.streams.iter().find(|s| s.streamer == client).map(|s| s.id.clone()) { - self.state.pending_watch = None; - self.watch_stream(id); - } else if view.presence.clients.get(&client).is_some_and(|c| c.streaming == Some(true)) { - let name = view.nickname(client); - self.state.pending_watch = Some((session, client)); - self.set_status(format!("Looking up {name}'s stream…")); - } - } - - /// `VOELIN_OPEN=watch`: watch the first stream of our channel. - pub(crate) fn watch_first_stream(&mut self) { - let Some(id) = self.view().and_then(|v| { - v.streams.iter().find(|s| v.state.own_client != Some(s.streamer)).map(|s| s.id.clone()) - }) else { - return; - }; - self.watch_stream(id); - } - - /// The local test stream in the viewer (`VOELIN_DEMO_STREAM`). - pub(crate) fn start_demo(&mut self) { - self.stop_watching(); - self.watch = Some(Watch { - 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, - decoder: None, - since: None, - layers: Vec::new(), - layer: None, - }); - let runtime = self.engine.runtime().clone(); - let wake = || later(|app| app.show_picture()); - self.video.demo(&runtime, wake, |result| { - later(move |app| { - let Some(watch) = app.watch.as_mut().filter(|w| w.session.is_none()) else { - return; - }; - match result { - Ok(decoder) => watch.decoder = Some(decoder), - Err(e) => watch.status = format!("The preview failed: {e}"), - } - app.refresh_viewer(); - }); - }); - self.refresh_viewer(); - self.refresh_streams(); - // The people in our channel lead the members panel beside the viewer. - self.refresh_tree(); - } - - /// `VOELIN_OPEN=watch` with sample data: the local test pattern in the - /// viewer, dressed as the first stream of our channel. - pub(crate) fn demo_watch(&mut self) { - let sample = self.view().and_then(|v| { - v.streams.first().map(|s| (s.id.clone(), s.name.clone(), v.nickname(s.streamer))) - }); - self.start_demo(); - if let (Some(watch), Some((id, title, streamer))) = (&mut self.watch, sample) { - (watch.stream_id, watch.title, watch.streamer) = (id, title, streamer); - } - self.refresh_viewer(); - // Its card shows it as watched. - self.refresh_streams(); - } - - /// A decoded picture is waiting. - fn show_picture(&mut self) { - let Some(watch) = &mut self.watch else { return }; - let Some(image) = watch.decoder.as_ref().and_then(Decoder::take_picture) else { return }; - let first = !watch.has_frame; - watch.has_frame = true; - if first { - watch.status.clear(); - watch.since = Some(std::time::Instant::now()); - } - // Only the window with the player: each would scale it again. - self.with_player(|bridge, _| bridge.set_viewer_frame(image)); - if first { - self.refresh_viewer(); - } - } - - pub(crate) fn show_viewer(&mut self, shown: bool) { - // Shown in the main window: from a window of its own, it comes back. - if shown && self.popout.window.is_some() { - self.viewer_dock(); - return; - } - if let Some(watch) = &mut self.watch { - watch.shown = shown; - } - if !shown { - self.set_fullscreen(false); - } - self.refresh_viewer(); - self.refresh_streams(); - // The people in our channel lead the members panel beside the viewer. - self.refresh_tree(); - } - - /// Stop watching and close the viewer, its own window too. - pub(crate) fn leave_stream(&mut self) { - self.close_popout(); - self.stop_watching(); - } - - /// Stop watching; a window of its own stays (for the next stream). - fn stop_watching(&mut self) { - if let Some(watch) = self.watch.take() - && let Some(session) = watch.session - && !watch.ended - { - self.engine - .send(Command::LeaveStream { session: session as u64, stream_id: watch.stream_id }); - } - self.set_fullscreen(false); - self.refresh_viewer(); - self.refresh_streams(); - // The people in our channel lead the members panel beside the viewer. - self.refresh_tree(); - } - - pub(crate) fn set_stream_volume(&mut self, percent: f32) { - self.state.stream_volume = percent.round().clamp(0.0, 200.0); - if let Some(watch) = &self.watch - && let Some(session) = watch.session - { - self.engine.send(Command::SetStreamVolume { - session: session as u64, - stream_id: watch.stream_id.clone(), - volume: self.state.stream_volume / 100.0, - }); - } - } - - pub(crate) fn toggle_fullscreen(&mut self) { - let mut full = false; - self.with_player(|bridge, _| full = !bridge.get_viewer_fullscreen()); - self.set_fullscreen(full); - } - - /// The window with the player in full screen, or back. - pub(crate) fn set_fullscreen(&self, full: bool) { - self.with_player(|bridge, window| { - if bridge.get_viewer_fullscreen() == full { - return; - } - bridge.set_viewer_fullscreen(full); - window.set_fullscreen(full); - if !full { - // The player that hid the cursor may be gone already. - show_cursor(window, true); - } - }); - } -} - -#[cfg(test)] -mod tests { - #[test] - fn bitrates() { - assert_eq!(super::bitrate_text(0), ""); - assert_eq!(super::bitrate_text(640), "640 kbit/s"); - assert_eq!(super::bitrate_text(8000), "8 Mbit/s"); - assert_eq!(super::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 = super::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 = super::capture_request(30, 4608, false, &picked, None); - assert!(!off.audio && off.audio_sources.is_empty()); - let none = super::capture_request(30, 4608, true, &[], None); - assert!(!none.audio && none.audio_sources.is_empty()); - } -} diff --git a/crates/voelin-ui/src/streams/bind.rs b/crates/voelin-ui/src/streams/bind.rs new file mode 100644 index 0000000..c5196ad --- /dev/null +++ b/crates/voelin-ui/src/streams/bind.rs @@ -0,0 +1,425 @@ +//! The Slint side of the streams: the Bridge writes of the streams panel, +//! the share dialog and the viewer, the capture and the decoder, the +//! viewer's window. The state and its transitions are in +//! `voelin_ui_vm::streams::logic`. + +use std::time::Duration; + +use slint::{ComponentHandle, Model}; +use tracing::warn; +use voelin_core::media::{Streamer, audio_source_specs}; +use voelin_core::settings::{STREAM_AUDIO_SOURCES, STREAM_BITRATE_KBPS, STREAM_FPS}; +use voelin_core::stream::StreamSetup; + +use super::Share; +use crate::app::{App, Bridge, later, with_app}; +use crate::bind::convert; +use crate::video::{self, Capture, Decoder}; +use crate::vm::bridge::{ShareForm, SourceItem}; +use crate::vm::streams::logic::{ + self as logic, CaptureFacts, CaptureStarted, SharePlan, StreamsFacts, viewer_view, +}; + +/// Show or hide the pointer over `window`. In full screen the player hides +/// it with its controls: Slint applies a TouchArea's cursor only when the +/// pointer moves, so the window is told directly. (No pointer on Android.) +pub(crate) fn show_cursor(window: &slint::Window, shown: bool) { + #[cfg(not(target_os = "android"))] + { + use slint::winit_030::WinitWindowAccessor; + window.with_winit_window(|w| w.set_cursor_visible(shown)); + } + #[cfg(target_os = "android")] + let _ = (window, shown); +} + +impl App { + /// The streams panel, the voice card's streams and the share card. + pub(crate) fn refresh_streams(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + let current = self.state.current; + let capture = self.share.as_ref().map(|s| CaptureFacts { + status: s.capture.status(), + source_name: s.capture.source_name().to_owned(), + has_audio: s.capture.has_audio(), + }); + let facts = StreamsFacts { + demo: self.demo, + studio_live_here: current.is_some_and(|c| self.studio_streams_to(c)), + capture: capture.as_ref(), + }; + let view = logic::streams_view(&self.state, &facts); + bridge.set_streams_available(view.available); + self.models.streams.sync(&view.items); + bridge.set_can_share(video::AVAILABLE); + let share = view.share; + bridge.set_share_state(share.state.into()); + bridge.set_share_busy(share.busy); + bridge.set_share_error(share.error.into()); + bridge.set_share_audio(share.audio); + bridge.set_share_requests(share.requests); + self.models.viewers.sync(&share.viewers); + bridge.set_share_status(share.status.into()); + } + + /// The viewer in the main window and in its own: the same facts, but + /// the main window's player only while the stream is not popped out. + pub(crate) fn refresh_viewer(&self) { + let popped = self.popout.window.is_some(); + let Some(watch) = &self.state.watch else { + self.viewer_each(|bridge| { + bridge.set_viewer_open(false); + bridge.set_viewer_popped(popped); + bridge.set_viewer_has_frame(false); + bridge.set_viewer_frame(slint::Image::default()); + }); + return; + }; + if let Some(ui) = self.ui.upgrade() { + let bridge = ui.global::(); + let open = watch.shown && !popped && self.watch_here(); + if !open && bridge.get_viewer_open() && bridge.get_viewer_fullscreen() { + // The player goes, still in full screen: it may have hidden the cursor. + show_cursor(ui.window(), true); + } + bridge.set_viewer_open(open); + } + if let Some(window) = &self.popout.window { + window.global::().set_viewer_open(true); + } + let decoded = self.decoder.as_ref().map(Decoder::info).unwrap_or_default(); + let view = viewer_view(&self.state, watch, &decoded); + // The members are the current server's. + let admin = self.watch_here() + && self.models.members.rows().iter().any(|m| m.id == view.streamer_id && m.admin); + self.models.qualities.sync(&view.qualities); + let channel = slint::SharedString::from(view.channel.as_str()); + let elapsed = slint::SharedString::from(view.elapsed.as_str()); + self.viewer_each(|bridge| { + bridge.set_viewer_popped(popped); + bridge.set_viewer_title(view.title.as_str().into()); + bridge.set_viewer_status(view.status.as_str().into()); + bridge.set_viewer_ended(view.ended); + bridge.set_viewer_has_frame(view.has_frame); + bridge.set_viewer_volume(view.volume); + bridge.set_viewer_info(view.info.as_str().into()); + bridge.set_viewer_streamer(view.streamer.as_str().into()); + bridge.set_viewer_streamer_avatar(convert::image(&view.avatar)); + bridge.set_viewer_streamer_initials(view.initials.as_ref().into()); + bridge.set_viewer_streamer_tint(convert::color(view.tint)); + bridge.set_viewer_streamer_admin(admin); + bridge.set_viewer_channel(channel.clone()); + bridge.set_viewer_elapsed(elapsed.clone()); + bridge.set_viewer_count(view.count); + if bridge.get_viewer_quality() != view.quality { + bridge.set_viewer_quality(view.quality); + } + bridge.set_viewer_quality_detail(view.detail.as_str().into()); + }); + } + + /// The watched stream is on the server on screen (or is the local test + /// stream). + pub(crate) fn watch_here(&self) -> bool { + self.state.watch.as_ref().is_some_and(|w| w.here(self.state.current)) + } + + /// A simulcast layer of the watched stream (0: follow the bandwidth + /// estimate), asked of the streamer; the engine confirms with + /// `WatchLayers`. + pub(crate) fn set_stream_quality(&mut self, index: i32) { + self.transition(|state, cx| logic::set_quality(state, cx, index)); + } + + /// Once a second: statistics, a capture that ended, decoder problems. + pub(crate) fn tick_streams(&mut self) { + if self.share.as_ref().is_some_and(|s| s.capture.ended()) { + self.transition(logic::capture_ended); + } + if self.state.watch.as_ref().is_some_and(|w| w.connected && !w.has_frame) + && let Some(error) = self.decoder.as_ref().and_then(Decoder::error) + { + logic::decoder_failed(&mut self.state, &error); + } + if self.state.share.is_some() { + self.refresh_streams(); + } + // The share dialog's audio mixer (studio/). + self.mixer_tick(); + if self.state.watch.is_some() { + self.refresh_viewer(); + } + } + + // Sharing. + + /// Fill the share dialog: sources and the last choices. + pub(crate) fn open_share(&mut self) -> ShareForm { + let test_pattern = cfg!(debug_assertions) + || self.demo + || std::env::var("VOELIN_TEST_PATTERN").is_ok_and(|v| v == "1"); + let restorable = self.state.settings.portal_restore_token.is_some(); + let sources = + logic::sources_listed(&mut self.state, self.video.sources(test_pattern, restorable)); + if let Some(ui) = self.ui.upgrade() { + let items: Vec = sources + .into_iter() + .map(|(name, detail)| SourceItem { name: name.into(), detail: detail.into() }) + .collect(); + ui.global::().set_share_sources(convert::model(&items)); + } + self.refresh_streams(); + // Its audio: the Stream Studio's mixer rows and picker. + self.mixer_show(); + let (fps, bitrate) = (self.prefs.get(&STREAM_FPS), self.prefs.get(&STREAM_BITRATE_KBPS)); + logic::share_form(&self.state, fps, bitrate) + } + + /// The share dialog's form with the test pattern chosen. + fn test_pattern_form(&mut self) -> Option { + let mut form = self.open_share(); + let ui = self.ui.upgrade()?; + let sources = ui.global::().get_share_sources(); + let pattern = (0..sources.row_count()) + .find(|&i| sources.row_data(i).is_some_and(|s| s.name == "Test pattern"))?; + form.source = pattern as i32; + Some(form) + } + + /// Development switch `VOELIN_AUTOSHARE`: share the test pattern once. + pub(crate) fn autoshare(&mut self) { + if !self.autoshare || !self.view().is_some_and(|v| v.streams_available()) { + return; + } + self.autoshare = false; + if let Some(form) = self.test_pattern_form() { + self.start_share(ShareForm { auto_accept: true, ..form }); + } + } + + /// `VOELIN_OPEN=share:live` with sample data: the test pattern shared + /// with the sample mixer's sources (live at once, `capture_ready`). + pub(crate) fn demo_share(&mut self) { + if let Some(form) = self.test_pattern_form() { + self.start_share(ShareForm { audio: true, ..form }); + } + } + + pub(crate) fn start_share(&mut self, form: ShareForm) { + let Some(session) = self.state.current else { return }; + // The mixer's sources (the sample studio's with VOELIN_DEMO_UI). + let sources = self.studio_settings().get(&STREAM_AUDIO_SOURCES); + let studio_live_here = self.studio_streams_to(session); + let Some(plan) = self.transition(|state, cx| { + logic::plan_share(state, cx, &form, studio_live_here, &sources) + }) else { + return; + }; + let SharePlan { session, source, fps, bitrate, request, setup, auto_accept } = plan; + // The next share starts from these. + for result in + [self.prefs.set(&STREAM_FPS, fps), self.prefs.set(&STREAM_BITRATE_KBPS, bitrate)] + { + if let Err(e) = result { + warn!(%e, "could not store the share settings"); + } + } + let runtime = self.engine.runtime().clone(); + self.video.start_capture(&runtime, source, request, move |result| { + later(move |app| app.capture_ready(session, setup, auto_accept, result)); + }); + } + + /// The capture started (or not): go live. + fn capture_ready( + &mut self, + session: i64, + setup: StreamSetup, + auto_accept: bool, + result: Result, + ) { + let started = result.as_ref().map(started).map_err(Clone::clone); + let (keep, update) = self.with_host(|state, host| { + let mut cx = crate::vm::host::Cx::new(host); + let keep = logic::capture_ready(state, &mut cx, session, setup, auto_accept, started); + (keep, cx.update) + }); + // The capture is kept before the update is carried out: the mixer's + // rows it asks for follow it. + if let (true, Ok(capture)) = (keep, result) { + let meters = slint::Timer::default(); + meters.start(slint::TimerMode::Repeated, Duration::from_millis(66), || { + with_app(|app| app.studio_meters()); + }); + self.share = Some(Share { capture, _meters: meters }); + } + self.perform(update); + } + + pub(crate) fn stop_share(&mut self) { + self.transition(logic::stop_share); + } + + /// The running share's streamer (the mixer's rows, studio/). + pub(crate) fn share_streamer(&self) -> Option<&Streamer> { + self.share.as_ref().map(|s| s.capture.streamer()) + } + + /// `stream.audio_sources` changed (the mixer, the settings, another + /// window): a running share mixes the new sources. + pub(crate) fn share_audio_changed(&mut self) { + if self.share.is_none() { + return; + } + let sources = audio_source_specs(&self.studio_settings().get(&STREAM_AUDIO_SOURCES)); + let codecs = self.video.codecs(); + let Some(share) = &self.share else { return }; + if let Err(e) = share.capture.follow_audio(&codecs, sources) { + self.set_status(format!("Stream audio: {e}")); + } + self.mixer_refresh(); + } + + pub(crate) fn respond_viewer(&mut self, viewer: u16, accept: bool) { + self.transition(|state, cx| logic::respond_viewer(state, cx, viewer, accept)); + } + + pub(crate) fn kick_viewer(&mut self, viewer: u16) { + self.transition(|state, cx| logic::kick_viewer(state, cx, viewer)); + } + + // Watching. + + pub(crate) fn watch_stream(&mut self, stream_id: String) { + if stream_id == "demo" && self.demo { + self.start_demo(); + return; + } + let Some(session) = self.transition(|state, cx| logic::watch_stream(state, cx, &stream_id)) + else { + return; + }; + let wake = || later(|app| app.show_picture()); + self.decoder = Some(self.video.watch(&self.engine, session as u64, &stream_id, wake)); + self.refresh_viewer(); + } + + /// Watch the stream of `client` (a click on a streaming user in the + /// channel tree or the members): 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(crate) fn watch_client(&mut self, client: u16) { + if let Some(id) = self.transition(|state, cx| logic::watch_client(state, cx, client)) { + self.watch_stream(id); + } + } + + /// `VOELIN_OPEN=watch`: watch the first stream of our channel. + pub(crate) fn watch_first_stream(&mut self) { + if let Some(id) = logic::first_stream(&self.state) { + self.watch_stream(id); + } + } + + /// The local test stream in the viewer (`VOELIN_DEMO_STREAM`). + pub(crate) fn start_demo(&mut self) { + self.transition(logic::start_demo); + let runtime = self.engine.runtime().clone(); + let wake = || later(|app| app.show_picture()); + self.video.demo(&runtime, wake, |result| { + later(move |app| { + let Some(watch) = app.state.watch.as_mut().filter(|w| w.session.is_none()) else { + return; + }; + match result { + Ok(decoder) => app.decoder = Some(decoder), + Err(e) => watch.status = format!("The preview failed: {e}"), + } + app.refresh_viewer(); + }); + }); + } + + /// `VOELIN_OPEN=watch` with sample data: the local test pattern in the + /// viewer, dressed as the first stream of our channel. + pub(crate) fn demo_watch(&mut self) { + let sample = logic::demo_sample(&self.state); + self.start_demo(); + if let (Some(watch), Some((id, title, streamer))) = (&mut self.state.watch, sample) { + (watch.stream_id, watch.title, watch.streamer) = (id, title, streamer); + } + self.refresh_viewer(); + // Its card shows it as watched. + self.refresh_streams(); + } + + /// A decoded picture is waiting. + fn show_picture(&mut self) { + if self.state.watch.is_none() { + return; + } + let Some(image) = self.decoder.as_ref().and_then(Decoder::take_picture) else { return }; + let first = logic::picture_shown(&mut self.state); + // Only the window with the player: each would scale it again. + self.with_player(|bridge, _| bridge.set_viewer_frame(image)); + if first { + self.refresh_viewer(); + } + } + + pub(crate) fn show_viewer(&mut self, shown: bool) { + // Shown in the main window: from a window of its own, it comes back. + if shown && self.popout.window.is_some() { + self.viewer_dock(); + return; + } + self.transition(|state, cx| logic::show_viewer(state, cx, shown)); + } + + /// Stop watching and close the viewer, its own window too. + pub(crate) fn leave_stream(&mut self) { + self.close_popout(); + self.stop_watching(); + } + + /// Stop watching; a window of its own stays (for the next stream). + fn stop_watching(&mut self) { + self.transition(logic::stop_watching); + } + + pub(crate) fn set_stream_volume(&mut self, percent: f32) { + self.transition(|state, cx| logic::set_volume(state, cx, percent)); + } + + pub(crate) fn toggle_fullscreen(&mut self) { + let mut full = false; + self.with_player(|bridge, _| full = !bridge.get_viewer_fullscreen()); + self.set_fullscreen(full); + } + + /// The window with the player in full screen, or back. + pub(crate) fn set_fullscreen(&self, full: bool) { + self.with_player(|bridge, window| { + if bridge.get_viewer_fullscreen() == full { + return; + } + bridge.set_viewer_fullscreen(full); + window.set_fullscreen(full); + if !full { + // The player that hid the cursor may be gone already. + show_cursor(window, true); + } + }); + } +} + +/// What the state needs to know of a capture that started. +fn started(capture: &Capture) -> CaptureStarted { + CaptureStarted { + restore_token: capture.restore_token(), + automatic_bitrate: capture.streamer().bitrate_kbps(), + has_audio: capture.has_audio(), + audio_error: capture.audio_error(), + } +} diff --git a/crates/voelin-ui/src/streams/mod.rs b/crates/voelin-ui/src/streams/mod.rs new file mode 100644 index 0000000..c337cbc --- /dev/null +++ b/crates/voelin-ui/src/streams/mod.rs @@ -0,0 +1,19 @@ +//! Streams (TeamSpeak 6): the streams panel, sharing our screen and the +//! viewer. The engine runs the stream sessions; `video.rs` captures, +//! encodes and decodes. What is state of the streams (what we share, what we +//! watch, the rows and texts) is in `voelin_ui_vm::streams::logic`; `bind` +//! has the Bridge writes, the capture and the decoder. + +mod bind; + +use crate::video::Capture; + +pub(crate) use bind::show_cursor; + +/// The capture that feeds our stream, while we share (`AppState::share` has +/// the rest): it stops when dropped. +pub(crate) struct Share { + pub capture: Capture, + /// The audio mixer's meters (the studio's rows), about 15 times a second. + _meters: slint::Timer, +} diff --git a/crates/voelin-ui/src/studio/bind.rs b/crates/voelin-ui/src/studio/bind.rs index 5cb3b6e..fd9a3cc 100644 --- a/crates/voelin-ui/src/studio/bind.rs +++ b/crates/voelin-ui/src/studio/bind.rs @@ -490,7 +490,7 @@ impl App { if self.studio.run.is_some() { return; } - if self.share.is_some() { + if self.state.share.is_some() { self.mixer_refresh(); } if !self.ui.upgrade().is_some_and(|ui| ui.global::