diff --git a/crates/voelin-ui-vm/src/state.rs b/crates/voelin-ui-vm/src/state.rs index cc91fbc..bdc81f2 100644 --- a/crates/voelin-ui-vm/src/state.rs +++ b/crates/voelin-ui-vm/src/state.rs @@ -192,7 +192,9 @@ impl Tab { cache: Default::default(), } } +} +impl Tab { /// A private chat (on the Direct Messages page, not in the chat strip). pub fn is_private(&self) -> bool { matches!(self.target, ChatTarget::Private(_)) @@ -356,7 +358,7 @@ impl Default for SessionView { } } -impl SessionView { +impl SessionView { /// Streams can be watched and shared: TeamSpeak 6, connected with voice. pub fn streams_available(&self) -> bool { self.capabilities.streams && self.state.voice == VoiceState::Connected @@ -441,13 +443,6 @@ impl SessionView { true } - /// A new tab for `target`, read as far as the store says. - pub fn new_tab(&self, target: ChatTarget, title: String) -> Tab { - let mut tab = Tab::new(target, title); - tab.read_from(&self.reads); - tab - } - /// The session's gateway offers this feature /// (`voelin_gateway_proto::feature`). pub fn gateway_has(&self, feature: &str) -> bool { @@ -482,6 +477,15 @@ impl SessionView { } } +impl SessionView { + /// A new tab for `target`, read as far as the store says. + pub fn new_tab(&self, target: ChatTarget, title: String) -> Tab { + let mut tab = Tab::new(target, title); + tab.read_from(&self.reads); + tab + } +} + /// The data the screens share, apart from the engine and the toolkit: the /// servers and what is known of their sessions, the settings the screens /// show and the dialogs' targets. diff --git a/crates/voelin-ui-vm/src/studio/logic.rs b/crates/voelin-ui-vm/src/studio/logic.rs new file mode 100644 index 0000000..f43f81b --- /dev/null +++ b/crates/voelin-ui-vm/src/studio/logic.rs @@ -0,0 +1,1944 @@ +//! What the Stream Studio does and when, apart from the toolkit and the +//! engine's runtime: the stream settings panel's fields, where the stream +//! goes, what the header and the bottom bar say, which overlays the switches +//! ask for, what the layer, source, picker and mixer controls change. +//! +//! [`StudioData`] is the studio's state; the functions work on it, on the +//! settings service, the scene graph (`voelin_core::studio::scene`) and the +//! app's state ([`AppState`]), and return rows ([`crate::studio_bridge`]), +//! commands for the studio or messages for the status line. Running the +//! studio (its tasks, the preview, the windows, the encoder) is the front +//! end's: `voelin-ui`'s `studio/bind.rs`. + +use std::path::Path; +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; +use voelin_core::HistoryMessage; +use voelin_core::media::voelin_media::capture::{CaptureSource, SourceId}; +use voelin_core::media::{ + AudioApp, AudioSourceSpec, AudioSourceStats, StreamerStats, auto_bitrate, +}; +use voelin_core::settings::{ + AudioSourceKindSetting, AudioSourceSetting, Key, Kind, STREAM_AUDIO_SOURCES, + STREAM_BITRATE_KBPS, STREAM_LAYERS, STUDIO_RECORDING_DIR, STUDIO_REPLAY_MEMORY_MB, + STUDIO_REPLAY_SECONDS, STUDIO_SCENES, Settings, layer_specs, +}; +use voelin_core::stream::{ + EndReason, LayerSpec, StreamInfo, StreamKind, StreamSetup, ViewerInfo, ViewerState, +}; +use voelin_core::studio::scene::{ + Align, Background, Colour, Crop, Fit, Scene, Scenes, Source, SourceKind, Transform, +}; +use voelin_core::studio::{self, SourceChange, Stats, Status, camera}; +use voelin_model::{ChatMessage, ChatTarget, ClientId}; +use voelin_store::MessageSource; + +use super::{ + AudioLive, OVERLAY_CHAT, OVERLAY_NOW_PLAYING, OVERLAY_VIEWERS, Overlay, audio_label, clock, + format_line, next_layer, parse_layer, placement, quality, thousands, +}; +use crate::bridge::ChatLine; +use crate::image::ImageSource; +use crate::settings::parse_positive; +use crate::state::AppState; +use crate::studio_bridge::{ + StudioForm, StudioLayer, StudioPick, StudioSettingsForm, StudioSourceForm, StudioStatus, + StudioViewer, +}; + +/// The stream settings panel and the studio's own choices. +pub static STUDIO_UI: Key = Key::new( + "studio.ui", + Kind::Json, + "Stream Studio: title, game, go-live message, overlays, stream audio, preview size.", + StudioUi::default, +); + +/// The stream settings panel's fields (`studio.ui`). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct StudioUi { + /// The stream's title. + pub title: String, + /// Game or category: goes into the stream's name after the title. + pub game: String, + /// Sent to the channel's chat when the stream goes live. + pub message: String, + /// Overlay sources kept in the live scene ([`super::apply_overlays`]). + pub show_viewers: bool, + /// The stream chat's last lines as an overlay. + pub show_chat: bool, + /// The title and the game as an overlay. + pub show_now_playing: bool, + /// The stream's audio (the mixer's sources); off: none. + pub audio: bool, + /// The preview's width in pixels (its height follows the output) and + /// frame rate. + pub preview_width: u32, + /// The preview's frame rate. + pub preview_fps: u32, +} + +impl Default for StudioUi { + fn default() -> Self { + Self { + title: String::new(), + game: String::new(), + message: String::new(), + show_viewers: false, + show_chat: false, + show_now_playing: false, + audio: true, + preview_width: 960, + preview_fps: 15, + } + } +} + +/// The overlay text of what is on: the title and the game. +pub fn now_playing(ui: &StudioUi) -> Option { + let lines: Vec<&str> = + [ui.title.trim(), ui.game.trim()].into_iter().filter(|s| !s.is_empty()).collect(); + (!lines.is_empty()).then(|| lines.join("\n")) +} + +/// The stream's name: the title, and the game after it. TeamSpeak streams +/// have a name only, and the gateway's directory takes it from there. +pub fn stream_name(ui: &StudioUi) -> String { + match (ui.title.trim(), ui.game.trim()) { + (title, "") => title.to_owned(), + ("", game) => game.to_owned(), + (title, game) => format!("{title} — {game}"), + } +} + +/// A file name for a recording or a clip, stamped with the time. +pub fn file_name(what: &str) -> String { + format!("{what} {}.mkv", chrono::Local::now().format("%Y-%m-%d %H-%M-%S")) +} + +/// What a picker row adds. +pub enum Pick { + /// A source for the live scene. + Source { + /// Its name. + name: String, + /// What it shows. + kind: SourceKind, + }, + /// An audio source for the mixer. + Audio(AudioSourceSetting), +} + +/// The rows of a picker, each with what picking it adds. +pub type Picks = Vec<(Pick, StudioPick)>; + +/// Our stream from the studio. +pub struct Outgoing { + /// The session it goes to. + pub session: i64, + /// The server has it up. + pub live: bool, + /// Who watches or asked to. + pub viewers: Vec, +} + +/// What the studio knows apart from its running parts (the front end's). +#[derive(Default)] +pub struct StudioData { + /// Why it does not run or cannot stream. + pub error: String, + /// Where it keeps its keys: the app's settings, or with VOELIN_DEMO_UI + /// its own in memory (nothing stored). + pub settings: Option, + /// The scene graph as the studio last said. + pub scenes: Arc, + /// Live, recording, the output. + pub status: Status, + /// The statistics of the second. + pub stats: Option>, + /// What the stream's encoder does. + pub encoder: Option, + /// The stream settings panel. + pub ui: StudioUi, + /// The session the stream (and its chat) goes to. + pub destination: Option, + /// Our stream, once started. + pub stream: Option, + /// What the picker's rows add. + pub picks: Vec, + /// The overlays last asked for. + pub overlays: Vec, + /// Stats ticks it was not shown; it stops after a few. + pub hidden: u32, + /// Development switches waiting for the studio. + pub dev: Vec, +} + +/// What the header and the bottom bar say depends on, besides +/// [`StudioData`]: the front end's side of the picture. +pub struct StatusContext<'a> { + /// The studio runs. + pub running: bool, + /// Its encoder started. + pub has_encoder: bool, + /// The studio is in a window of its own. + pub detached: bool, + /// A quick share goes to the destination. + pub sharing: bool, + /// The destination's name ([`destination_name`]). + pub destination: Option, + /// The name of a viewer. + pub viewer_name: &'a dyn Fn(&ViewerInfo) -> String, +} + +impl StudioData { + /// `stream.bitrate_kbps`, an automatic one (0) as it comes to for the + /// output's size and frame rate. + pub fn bitrate_kbps(&self, settings: &Settings) -> u32 { + match settings.get(&STREAM_BITRATE_KBPS) { + 0 => { + let (width, height) = self.scenes.size(); + let bitrate = auto_bitrate(width, height, self.scenes.fps()); + u32::try_from(bitrate / 1000).unwrap_or(u32::MAX) + } + kbps => kbps, + } + } + + /// The stream's layers for the engine: `stream.layers`, or the single + /// layer at [`bitrate_kbps`](Self::bitrate_kbps). + pub fn session_layers(&self, settings: &Settings) -> Vec { + match layer_specs(&settings.get(&STREAM_LAYERS)) { + layers if layers.is_empty() => { + vec![LayerSpec::single(u64::from(self.bitrate_kbps(settings)) * 1000)] + } + layers => layers, + } + } + + /// The bitrate the stream is announced with: the top layer's, else + /// [`bitrate_kbps`](Self::bitrate_kbps). + pub fn go_live_bitrate(&self, settings: &Settings) -> u32 { + match settings.get(&STREAM_LAYERS).iter().map(|l| l.bitrate).max() { + Some(bps) => u32::try_from(bps / 1000).unwrap_or(u32::MAX), + None => self.bitrate_kbps(settings), + } + } + + /// How the stream starts. + pub fn stream_setup(&self, settings: &Settings) -> StreamSetup { + StreamSetup { + name: stream_name(&self.ui), + bitrate: self.go_live_bitrate(settings), + audio: self.ui.audio, + ..StreamSetup::default() + } + } + + /// Whether `session` is where the studio streams to. + pub fn streams_to(&self, session: i64) -> bool { + self.stream.as_ref().is_some_and(|s| s.session == session) + } + + /// A source of the live scene. + pub fn live_source(&self, id: u64) -> Option<&Source> { + self.scenes.active()?.source(id) + } + + /// The live scene. + pub fn live_scene(&self) -> Option { + self.scenes.active().map(|s| s.id) + } + + /// Streaming or recording: the studio runs although it is not shown. + pub fn busy(&self) -> bool { + self.stream.is_some() || self.status.recording.is_some() + } + + /// Viewers connected now. + pub fn watching(&self) -> usize { + self.stream + .as_ref() + .map_or(0, |s| s.viewers.iter().filter(|v| v.state == ViewerState::Connected).count()) + } + + /// Once a second: whether the studio keeps running (it does while it is + /// shown or busy, and for a few ticks after). + pub fn keep_running(&mut self, shown: bool) -> bool { + if shown || self.busy() { + self.hidden = 0; + true + } else { + self.hidden += 1; + self.hidden < 3 + } + } + + /// The size and rate of the preview: its width, the output's shape. + pub fn preview_command(&self) -> studio::Command { + let (w, h) = self.scenes.size(); + let width = self.ui.preview_width.max(16); + let height = ((u64::from(width) * u64::from(h) / u64::from(w.max(1))) as u32).max(2) & !1; + let fps = self.ui.preview_fps.max(1); + studio::Command::SetPreview { width, height, fps } + } + + /// New scenes came from the studio: whether the live scene changed and + /// whether the output's size did. + pub fn set_scenes(&mut self, scenes: Arc) -> (bool, bool) { + let switched = self.scenes.active().map(|s| s.id) != scenes.active().map(|s| s.id); + let resized = self.scenes.size() != scenes.size(); + self.scenes = scenes; + (switched, resized) + } + + /// Keep the destination while it works (and while live), else the + /// stream's, else the first one. + pub fn choose_destination(&mut self, list: &[(i64, String)]) { + let keep = self.stream.as_ref().map(|s| s.session).or(self.destination); + self.destination = keep.filter(|id| list.iter().any(|(d, _)| d == id)).or_else(|| { + self.stream.as_ref().map(|s| s.session).or(list.first().map(|(id, _)| *id)) + }); + } + + /// The stream settings panel's form. `destinations`: [`destinations`]. + pub fn form(&self, destinations: &[(i64, String)]) -> StudioForm { + let ui = &self.ui; + let destination = self + .destination + .and_then(|id| destinations.iter().position(|(d, _)| *d == id)) + .map_or(-1, |i| i as i32); + // Automatic (0): the field stays empty and says so. + let bitrate = self.settings.as_ref().map_or(0, |s| s.get(&STREAM_BITRATE_KBPS)); + let bitrate = if bitrate == 0 { String::new() } else { bitrate.to_string() }; + StudioForm { + destination, + title: ui.title.clone().into(), + game: ui.game.clone().into(), + message: ui.message.clone().into(), + show_viewers: ui.show_viewers, + show_chat: ui.show_chat, + show_now_playing: ui.show_now_playing, + audio: ui.audio, + bitrate: bitrate.into(), + } + } + + /// The header, the preview's badges and the bottom bar, and the viewers + /// that asked to watch. + pub fn status_view(&self, cx: &StatusContext<'_>) -> (StudioStatus, Vec) { + let live = self.stream.as_ref().is_some_and(|s| s.live); + let starting = self.stream.as_ref().is_some_and(|s| !s.live); + let encoder = self.encoder.as_ref(); + let (w, h) = self.scenes.size(); + let fps = self.scenes.fps(); + let settings = self.settings.as_ref(); + // What is sent: measured, else as set. + let measured: f64 = encoder.map_or(0.0, |e| e.layers.iter().map(|l| l.kbps).sum()); + let layers = settings.map(|s| s.get(&STREAM_LAYERS)).unwrap_or_default(); + let configured_bps: u64 = if layers.is_empty() { + settings.map_or(0, |s| u64::from(self.bitrate_kbps(s)) * 1000) + } else { + layers.iter().map(|l| l.bitrate).max().unwrap_or(0) + }; + let kbps = if measured > 0.0 { measured.round() as u64 } else { configured_bps / 1000 }; + // The viewers' bandwidth against the top layer's bitrate. + let bandwidth = self + .stream + .as_ref() + .and_then(|s| { + s.viewers + .iter() + .filter(|v| v.state == ViewerState::Connected) + .filter_map(|v| v.estimate) + .min() + }) + .filter(|_| configured_bps > 0) + .map(|e| e as f64 / configured_bps as f64); + let composed = self.stats.as_ref().map_or(f64::from(fps), |s| s.fps); + let (quality, quality_text) = quality(live, fps, composed, bandwidth); + let viewers = self.stream.as_ref().map_or(&[][..], |s| &s.viewers[..]); + let watching = viewers.iter().filter(|v| v.state == ViewerState::Connected).count(); + let hint = if !self.error.is_empty() { + self.error.clone() + } else if !cx.running || !cx.has_encoder { + "Starting the studio…".to_owned() + } else if cx.destination.is_none() { + "Join a voice channel on a TeamSpeak 6 server to go live.".to_owned() + } else if cx.sharing { + "Stop sharing your screen first.".to_owned() + } else if starting { + "Waiting for the server…".to_owned() + } else { + String::new() + }; + let replay = self.stats.as_ref().map(|s| &s.replay); + let replay_seconds = settings.map_or(0, |s| s.get(&STUDIO_REPLAY_SECONDS)); + let mut details = vec![format!( + "Composite {w}×{h}: {composed:.1} of {fps} fps, {:.1} ms a frame", + self.stats.as_ref().map_or(0.0, |s| s.compose.compose_time.as_secs_f64() * 1000.0) + )]; + if let Some(e) = encoder { + let codec = e.codec.map(|c| c.to_string()).unwrap_or_default(); + let backend = e.layers.first().and_then(|l| l.backend).map(|b| format!(" ({b})")); + details.push(format!( + "Encoder {codec}{}: {} layer(s), {} kbit/s", + backend.unwrap_or_default(), + e.layers.len(), + thousands(kbps) + )); + } + if let Some(r) = replay.filter(|_| replay_seconds > 0) { + details.push(format!( + "Replay buffer: {} s held, {:.1} MB", + r.duration.as_secs(), + (r.memory_bytes + r.spilled_bytes) as f64 / 1e6 + )); + } + let scene = self.scenes.active(); + let shows = |f: fn(&SourceKind) -> bool| { + scene.is_some_and(|s| s.sources.iter().any(|src| src.visible && f(&src.kind))) + }; + let status = StudioStatus { + running: cx.running, + destination: cx.destination.clone().unwrap_or_default().into(), + quality, + quality_text: quality_text.into(), + format: format_line(h, fps, kbps).into(), + details: details.join("\n").into(), + live, + starting, + elapsed: clock(self.status.live_for).into(), + viewers: watching as i32, + participants: viewers.len() as i32, + can_go_live: hint.is_empty() && !live && !starting, + hint: hint.into(), + recording: self.status.recording.is_some(), + recorded: clock(self.status.recorded_for).into(), + replay_seconds: replay_seconds as i32, + replay_held: replay + .map_or(String::new(), |r| format!("{} s", r.duration.as_secs())) + .into(), + output_width: w as i32, + output_height: h as i32, + fps: fps as i32, + detached: cx.detached, + can_detach: cfg!(not(target_os = "android")), + screen_shown: shows(|k| { + matches!( + k, + SourceKind::Screen { .. } + | SourceKind::Portal { .. } + | SourceKind::Pattern { .. } + ) + }), + camera_shown: shows(|k| matches!(k, SourceKind::Camera { .. })), + window_shown: shows(|k| matches!(k, SourceKind::Window { .. })), + }; + let requests: Vec = viewers + .iter() + .filter(|v| v.state == ViewerState::Requested) + .map(|v| StudioViewer { + client: i32::from(v.client), + name: (cx.viewer_name)(v).into(), + state: "requested".into(), + }) + .collect(); + (status, requests) + } + + /// The overlays the switches ask for; `chat` is called for the chat + /// overlay when it is on (see [`chat_tail`]). + pub fn wanted_overlays(&self, chat: impl FnOnce() -> Option) -> Vec { + let ui = &self.ui; + let chat = ui.show_chat.then(chat).flatten(); + vec![ + Overlay { + name: OVERLAY_VIEWERS, + text: ui.show_viewers.then(|| format!("{} watching", self.watching())), + }, + Overlay { name: OVERLAY_CHAT, text: chat }, + Overlay { + name: OVERLAY_NOW_PLAYING, + text: ui.show_now_playing.then(|| now_playing(ui)).flatten(), + }, + ] + } + + /// Remember the overlays asked for: the ones to send to the studio + /// (`force`: also when nothing changed, e.g. after a scene switch). + pub fn overlay_change(&mut self, force: bool, wanted: Vec) -> Option> { + (force || wanted != self.overlays).then(|| { + self.overlays.clone_from(&wanted); + wanted + }) + } +} + +/// The mixer's id of each audio source of the settings, if the mixer has +/// it (its meter is read from there). +pub fn meter_ids(sources: &[AudioSourceSetting], stats: &[AudioSourceStats]) -> Vec> { + sources + .iter() + .map(|setting| { + let kind = AudioSourceSpec::from(setting).kind; + stats.iter().find(|s| s.spec.kind == kind).map(|s| s.id) + }) + .collect() +} + +/// The last lines of the stream's chat, for the chat overlay. +pub fn chat_tail(chat: &[ChatLine], lines: usize) -> Option { + let count = chat.len(); + let text: Vec = chat[count.saturating_sub(lines)..] + .iter() + .map(|l| { + let line = format!("{}: {}", l.author, l.text); + match line.char_indices().nth(64) { + Some((at, _)) => format!("{}…", &line[..at]), + None => line, + } + }) + .collect(); + (!text.is_empty()).then(|| text.join("\n")) +} + +/// The mixer rows' live parts: the level (from the mixer's meters, +/// `levels`: dBFS peaks by row) and why a source captures nothing. +pub fn audio_live( + sources: &[AudioSourceSetting], + stats: &[AudioSourceStats], + levels: &[Option], +) -> Vec> { + sources + .iter() + .enumerate() + .map(|(i, setting)| { + let kind = AudioSourceSpec::from(setting).kind; + let error = stats.iter().find(|s| s.spec.kind == kind).and_then(|s| s.error.clone()); + let level = levels.get(i).copied().flatten()?; + Some(AudioLive { level: level.max(-100.0), error }) + }) + .collect() +} + +/// A source for the live scene (a new scene if there is none). +pub fn add_to_live_scene(scenes: &mut Scenes, mut source: Source) { + if scenes.active().is_none() { + let id = scenes.next_scene_id(); + scenes.scenes.push(Scene::new(id, "Scene 1")); + scenes.active = id; + } + if let Some(scene) = scenes.active_mut() { + source.id = scene.next_source_id(); + scene.sources.push(source); + } +} + +/// What the studio's event says in the status line, if it says anything. +pub fn event_message(event: &studio::Event) -> Option { + match event { + studio::Event::RecordingStarted { path } => { + Some(format!("Recording to {}", path.display())) + } + studio::Event::RecordingStopped { path, duration, bytes } => Some(format!( + "Saved a recording of {} ({:.1} MB) to {}", + clock(*duration), + *bytes as f64 / 1e6, + path.display() + )), + studio::Event::ClipSaved { path, duration } => { + Some(format!("Saved a clip of {} seconds to {}", duration.as_secs(), path.display())) + } + studio::Event::Error { context, message } => { + Some(format!("Stream Studio ({context}): {message}")) + } + _ => None, + } +} + +/// What the status line says when the stream ended. +pub fn ended_message(reason: Option<&EndReason>) -> String { + match reason { + Some(EndReason::Failed(e)) => format!("The stream failed: {e}"), + _ => "The stream has ended".into(), + } +} + +// Where the stream goes. + +/// Sessions the stream can go to: TeamSpeak 6 with voice, the current one +/// first; each with its name ([`destination_name`]). +pub fn destinations(state: &AppState) -> Vec<(i64, String)> { + let mut ids: Vec = state + .sessions + .iter() + .filter(|(_, v)| v.streams_available() && v.state.own_channel.is_some()) + .map(|(id, _)| *id) + .collect(); + ids.sort_by_key(|id| (Some(*id) != state.current, *id)); + ids.into_iter().map(|id| (id, destination_name(state, id))).collect() +} + +/// The channel and the server of a destination. +pub fn destination_parts(state: &AppState, id: i64) -> (String, String) { + let Some(view) = state.sessions.get(&id) else { return Default::default() }; + let channel = view + .state + .own_channel + .and_then(|c| view.presence.channels.get(&c)) + .map(|c| crate::tree::channel_title(c).0.to_owned()) + .unwrap_or_default(); + let server = if view.presence.server_name.is_empty() { + state.bookmarks.iter().find(|b| b.id == id).map(|b| b.name.clone()).unwrap_or_default() + } else { + view.presence.server_name.clone() + }; + (channel, server) +} + +/// "Chill Zone • Nightfall Guild". +pub fn destination_name(state: &AppState, id: i64) -> String { + let (channel, server) = destination_parts(state, id); + format!("{channel} • {server}") +} + +/// The destination list as the picker shows it. +pub fn destination_rows(state: &AppState, list: &[(i64, String)]) -> Vec { + list.iter() + .map(|(id, _)| { + let (channel, server) = destination_parts(state, *id); + StudioPick { + name: channel.into(), + detail: server.into(), + kind: "server".into(), + ..Default::default() + } + }) + .collect() +} + +/// The session and channel the stream (and its chat) goes to. +pub fn chat_target(state: &AppState, destination: Option) -> Option<(i64, u64)> { + let id = destination?; + Some((id, state.sessions.get(&id)?.state.own_channel?)) +} + +/// The destination channel's chat tab, made if need be: the channel's name +/// and whether the tab is new (its chat is to be opened). +pub fn chat_tab(state: &mut AppState, id: i64, channel: u64) -> (String, bool) { + let target = ChatTarget::Channel(channel); + let view = state.sessions.entry(id).or_default(); + let name = view + .presence + .channels + .get(&channel) + .map(|c| crate::tree::channel_title(c).0.to_owned()) + .unwrap_or_default(); + let new = !view.tabs.iter().any(|t| t.target == target); + if new { + let tab = view.new_tab(target, name.clone()); + view.tabs.push(tab); + } + (name, new) +} + +/// The name of a viewer of the stream in `session`. +pub fn viewer_name(state: &AppState, session: Option, client: ClientId) -> String { + session + .and_then(|id| state.sessions.get(&id)) + .map_or_else(|| format!("client {client}"), |v| v.nickname(client)) +} + +// The stream settings panel. + +/// What editing a field of the stream settings asks for. +#[derive(Debug, PartialEq)] +pub enum Edit { + /// Store these settings. + Ui(StudioUi), + /// The bitrate typed: kbit/s (0 automatic); `None` if it is not one. + Bitrate(Option), + /// A destination picked, by its index in the list. + Destination(Option), + /// Not a field. + Nothing, +} + +/// What the bitrate field's refusal says. +pub const BITRATE_HINT: &str = "The bitrate is a whole number of kbit/s, or auto."; + +/// A field of the stream settings was edited (`value` as typed; a switch's +/// is "true" or "false"). +pub fn edit(ui: &StudioUi, key: &str, value: &str) -> Edit { + let mut ui = ui.clone(); + let on = value == "true"; + match key { + "title" => ui.title = value.into(), + "game" => ui.game = value.into(), + "message" => ui.message = value.into(), + "show-viewers" => ui.show_viewers = on, + "show-chat" => ui.show_chat = on, + "show-now-playing" => ui.show_now_playing = on, + "audio" => ui.audio = on, + "bitrate" => { + // Nothing, 0 or "auto": automatic. + let auto = + matches!(value.trim(), "" | "0") || value.trim().eq_ignore_ascii_case("auto"); + return Edit::Bitrate(parse_positive(value).or(auto.then_some(0))); + } + "destination" => return Edit::Destination(value.parse::().ok()), + _ => return Edit::Nothing, + } + Edit::Ui(ui) +} + +/// The output's size and rate typed: all three must be numbers above 0. +pub fn parse_output(width: &str, height: &str, fps: &str) -> Option<(u32, u32, u32)> { + Some((parse_positive(width)?, parse_positive(height)?, parse_positive(fps)?)) +} + +/// What the output's refusal says. +pub const OUTPUT_HINT: &str = "The output is a width, a height and a frame rate above 0."; + +/// A row of the stream's layers was edited. `None`: there is no such layer; +/// else what is to be said. +pub fn set_layer(settings: &Settings, index: usize, row: &StudioLayer) -> Option> { + let mut layers = settings.get(&STREAM_LAYERS); + let old = layers.get(index)?; + match parse_layer(row, old) { + Ok(layer) => layers[index] = layer, + Err(e) => return Some(vec![format!("Layer {}: {e}", index + 1)]), + } + Some(settings.set(&STREAM_LAYERS, layers).err().map(|e| e.to_string()).into_iter().collect()) +} + +/// Add a layer (the first addition makes two), the bitrate of the stream +/// without layers being `bitrate_kbps`. +pub fn add_layer(settings: &Settings, bitrate_kbps: u32) -> Vec { + let mut layers = settings.get(&STREAM_LAYERS); + if layers.is_empty() { + layers.push(next_layer(&[], bitrate_kbps)); + } + layers.push(next_layer(&layers, bitrate_kbps)); + settings.set(&STREAM_LAYERS, layers).err().map(|e| e.to_string()).into_iter().collect() +} + +/// Remove a layer (no such one: nothing); one layer left is the single layer. +pub fn remove_layer(settings: &Settings, index: usize) -> Vec { + let mut layers = settings.get(&STREAM_LAYERS); + let mut said = Vec::new(); + if index < layers.len() { + layers.remove(index); + // One layer left is the single layer. + if layers.len() == 1 { + layers.clear(); + } + said.extend(settings.set(&STREAM_LAYERS, layers).err().map(|e| e.to_string())); + } + said +} + +/// What the studio settings dialog (replay buffer, recordings, preview) +/// shows. +pub fn settings_form(settings: &Settings, ui: &StudioUi) -> StudioSettingsForm { + StudioSettingsForm { + replay_seconds: settings.get(&STUDIO_REPLAY_SECONDS).to_string().into(), + replay_memory: settings.get(&STUDIO_REPLAY_MEMORY_MB).to_string().into(), + recording_dir: settings.get(&STUDIO_RECORDING_DIR).into(), + preview_width: ui.preview_width.to_string().into(), + preview_fps: ui.preview_fps.to_string().into(), + } +} + +/// What applying the studio settings dialog did. +#[derive(Debug, Default, PartialEq)] +pub struct SettingsApplied { + /// A number that was not one, to be said at once. + pub notes: Vec, + /// The first refusal of the settings, to be said last. + pub refused: Option, + /// The stream settings with the preview's new size and rate, if they + /// changed. + pub ui: Option, +} + +/// The studio settings dialog was applied. +pub fn apply_settings_form( + settings: &Settings, + ui: &StudioUi, + form: &StudioSettingsForm, +) -> SettingsApplied { + let number = |text: &str| text.trim().parse::().ok(); + let mut done = SettingsApplied::default(); + let mut errors = Vec::new(); + match number(&form.replay_seconds).and_then(|v| u32::try_from(v).ok()) { + Some(v) => errors.extend(settings.set(&STUDIO_REPLAY_SECONDS, v).err()), + None => done.notes.push("The replay buffer is a whole number of seconds.".into()), + } + match number(&form.replay_memory) { + Some(v) => errors.extend(settings.set(&STUDIO_REPLAY_MEMORY_MB, v).err()), + None => done.notes.push("The replay memory is a whole number of MB.".into()), + } + errors.extend(settings.set(&STUDIO_RECORDING_DIR, form.recording_dir.trim().to_owned()).err()); + let mut changed = ui.clone(); + if let (Some(width), Some(fps)) = + (parse_positive(&form.preview_width), parse_positive(&form.preview_fps)) + { + changed.preview_width = width; + changed.preview_fps = fps; + } + done.ui = (changed != *ui).then_some(changed); + done.refused = errors.first().map(ToString::to_string); + done +} + +// Scenes and sources. + +/// What a source control of the live scene does. +pub enum SourceStep { + /// A command for the studio. + Apply(studio::Command), + /// A change of the source. + Update(SourceChange), + /// Something for the status line. + Say(&'static str), +} + +/// A control of source `id` in the live scene: up, down, lock, remove, +/// next-camera, bg-keep, bg-blur. `cameras` lists the cameras when the next +/// one is asked for. `None`: nothing to do. +pub fn source_action( + scenes: &Scenes, + id: u64, + action: &str, + cameras: impl FnOnce() -> Vec, +) -> Option { + let scene = scenes.active()?; + let index = scene.sources.iter().position(|s| s.id == id)?; + let source = &scene.sources[index]; + let (scene, locked) = (scene.id, source.locked); + match action { + "up" | "down" => { + let to = if action == "up" { index + 1 } else { index.saturating_sub(1) }; + Some(SourceStep::Apply(studio::Command::ReorderSource { scene, source: id, to })) + } + "lock" => { + Some(SourceStep::Update(SourceChange { locked: Some(!locked), ..Default::default() })) + } + "remove" => Some(SourceStep::Apply(studio::Command::RemoveSource { scene, source: id })), + // The next camera (a phone's front and back), mirrored as that + // camera is by default. + "next-camera" => { + let SourceKind::Camera { device, size, fps, .. } = source.kind.clone() else { + return None; + }; + let name = source.name.clone(); + let cameras = cameras(); + let real: Vec<_> = cameras.iter().filter(|c| c.backend != "synthetic").collect(); + let at = real.iter().position(|c| c.id == device); + let next = at.map_or(real.first(), |i| real.get((i + 1) % real.len())); + let Some(next) = next.filter(|c| c.id != device) else { + return Some(SourceStep::Say("There is no other camera.")); + }; + let kind = + SourceKind::Camera { device: next.id.clone(), size, fps, mirror: next.mirrored }; + // A source named after its camera is named after the next. + let renamed = name.is_empty() || at.is_some_and(|i| real[i].name == name); + let name = renamed.then(|| next.name.clone()); + Some(SourceStep::Update(SourceChange { kind: Some(kind), name, ..Default::default() })) + } + "bg-keep" | "bg-blur" => { + let background = if action == "bg-blur" { + Background::Blur { strength: 0.04 } + } else { + Background::Keep + }; + Some(SourceStep::Update(SourceChange { + background: Some(background), + ..Default::default() + })) + } + _ => None, + } +} + +/// What the source dialog changes of `old`, and a notice when part of it is +/// left out (a locked source keeps its place unless it is unlocked). +pub fn source_change( + form: &StudioSourceForm, + old: &Source, +) -> Result<(SourceChange, Option<&'static str>), String> { + let mut change = super::change(form, old)?; + if old.locked && form.locked && (change.transform.is_some() || change.crop.is_some()) { + change.transform = None; + change.crop = None; + return Ok((change, Some("Unlock the source to move, resize or crop it."))); + } + Ok((change, None)) +} + +/// The visibility changes of the phone's source cards: showing `kind` +/// ("screen", "camera", else window) and hiding the other two, as (source, +/// visible) for the sources that change; and whether the live scene has a +/// source of the kind. +pub fn main_source_changes(scene: Option<&Scene>, kind: &str) -> (Vec<(u64, bool)>, bool) { + let wanted = |k: &SourceKind| match kind { + "screen" => matches!( + k, + SourceKind::Screen { .. } | SourceKind::Portal { .. } | SourceKind::Pattern { .. } + ), + "camera" => matches!(k, SourceKind::Camera { .. }), + _ => matches!(k, SourceKind::Window { .. }), + }; + let main = |k: &SourceKind| { + matches!( + k, + SourceKind::Screen { .. } + | SourceKind::Portal { .. } + | SourceKind::Pattern { .. } + | SourceKind::Camera { .. } + | SourceKind::Window { .. } + ) + }; + let sources: Vec<(u64, bool, bool, bool)> = scene + .map(|s| { + s.sources.iter().map(|s| (s.id, wanted(&s.kind), main(&s.kind), s.visible)).collect() + }) + .unwrap_or_default(); + let changes = sources.iter().filter(|s| s.2 && s.1 != s.3).map(|s| (s.0, s.1)).collect(); + (changes, sources.iter().any(|s| s.1)) +} + +// The pickers. + +fn pick_row(name: &str, detail: String, icon: &str) -> StudioPick { + StudioPick { name: name.into(), detail: detail.into(), kind: icon.into(), ..Default::default() } +} + +fn source_pick(name: &str, kind: SourceKind) -> Pick { + Pick::Source { name: name.into(), kind } +} + +fn camera_pick(device: String, name: String, detail: String, mirror: bool) -> (Pick, StudioPick) { + let kind = SourceKind::Camera { device, size: None, fps: None, mirror }; + (source_pick(&name, kind), pick_row(&name, detail, "camera")) +} + +/// The cameras to pick from. +pub fn camera_picks(cameras: &[camera::Camera]) -> Picks { + cameras + .iter() + .map(|c| { + let biggest = c.formats.iter().flat_map(|f| &f.sizes).max_by_key(|(w, h)| w * h); + let detail = biggest.map_or(String::new(), |(w, h)| format!("up to {w}×{h}")); + camera_pick(c.id.clone(), c.name.clone(), detail, c.mirrored) + }) + .collect() +} + +/// The demo never opens a device, not even to list it: the test pattern. +pub fn demo_camera_picks() -> Picks { + vec![camera_pick( + camera::SYNTHETIC.to_owned(), + "Test pattern".to_owned(), + "1280×720".to_owned(), + true, + )] +} + +/// The screens (`kind` "screen") or windows ("window") to pick from; the +/// test pattern too when `test_pattern`. +pub fn screen_picks(kind: &str, list: Vec, test_pattern: bool) -> Picks { + let mut picks: Picks = Vec::new(); + for s in list { + let size = if s.width > 0 { format!("{}×{}", s.width, s.height) } else { String::new() }; + match s.id { + SourceId::Monitor(monitor) if kind == "screen" => { + let detail = if s.primary { format!("{size} · primary") } else { size }; + let k = SourceKind::Screen { monitor, backend: None, cursor: true }; + picks.push((source_pick(&s.name, k), pick_row(&s.name, detail, "monitor"))); + } + SourceId::Window(handle) if kind == "window" => { + let k = SourceKind::Window { handle, backend: None, cursor: true }; + picks.push((source_pick(&s.name, k), pick_row(&s.name, size, "window"))); + } + SourceId::Portal => { + let k = SourceKind::Portal { restore_token: None, cursor: true }; + let name = if kind == "screen" { "Screen" } else { "Window" }; + let detail = "Your desktop asks what to share".to_owned(); + picks.push(( + source_pick(name, k), + pick_row("Choose with the system dialog", detail, "portal"), + )); + } + _ => {} + } + } + if test_pattern { + let k = SourceKind::Pattern { size: (1280, 720) }; + picks.push(( + source_pick("Test pattern", k), + pick_row("Test pattern", "1280×720".into(), "pattern"), + )); + } + picks +} + +/// The desktop's own dialog is the one choice: it is added at once. +pub fn only_portal(picks: &Picks) -> bool { + picks.len() == 1 && matches!(&picks[0].0, Pick::Source { kind: SourceKind::Portal { .. }, .. }) +} + +/// The new source of a picked row: named, placed in the output. +pub fn picked_source(pick: &Pick, output: (u32, u32)) -> Option { + let Pick::Source { name, kind } = pick else { return None }; + let mut source = Source::new(0, kind.clone()); + source.name.clone_from(name); + source.transform = placement(kind, output); + Some(source) +} + +/// What can be added to the mixer: the fixed sources, then the sample tones +/// (`demo`) or the applications that play audio (`apps`); a row is selected +/// when its source is mixed in already (`current`). +pub fn audio_picks(current: &[AudioSourceSetting], apps: Vec, demo: bool) -> Picks { + let mut picks: Picks = Vec::new(); + let mut add = + |setting: AudioSourceSetting, name: String, detail: String, icon: Option<&str>| { + let (_, _, kind) = audio_label(&setting.kind); + let row = StudioPick { + name: name.into(), + detail: detail.into(), + kind: kind.into(), + // An application's own icon, when it gave a file (Android + // does; a desktop icon theme name is left out). + icon: icon + .map(Path::new) + .filter(|p| p.is_absolute()) + .map(ImageSource::file) + .unwrap_or_default(), + selected: current.iter().any(|s| s.kind == setting.kind), + }; + picks.push((Pick::Audio(setting), row)); + }; + let fixed = [ + (AudioSourceKindSetting::Microphone, "Microphone", "What you say in voice, cleaned up"), + (AudioSourceKindSetting::Desktop, "Desktop audio", "Everything that plays, without Voelin"), + ( + AudioSourceKindSetting::Window, + "Audio of the shared window", + "Its application (X11 and Windows)", + ), + ]; + for (kind, name, detail) in fixed { + // A phone shares the whole screen: there is no window's app. + if cfg!(target_os = "android") && kind == AudioSourceKindSetting::Window { + continue; + } + add(AudioSourceSetting::new(kind), name.into(), detail.into(), None); + } + if demo { + for frequency in [440, 660, 330] { + let kind = AudioSourceKindSetting::Synthetic { frequency }; + let detail = format!("{frequency} Hz"); + add(AudioSourceSetting::new(kind), "Test tone".into(), detail, None); + } + } else { + for app in apps { + let name = app.binary.clone().unwrap_or_else(|| app.name.clone()); + let kind = AudioSourceKindSetting::App { name: Some(name), pid: None }; + let detail = app + .media + .clone() + .unwrap_or_else(|| if app.playing { "playing".into() } else { String::new() }); + add(AudioSourceSetting::new(kind), app.name, detail, app.icon.as_deref()); + } + } + picks +} + +// The mixer. + +/// Mix a picked source in, or take it out if it is (the picker chooses +/// several at once). +pub fn toggle_audio(sources: &mut Vec, setting: AudioSourceSetting) { + if sources.iter().any(|s| s.kind == setting.kind) { + sources.retain(|s| s.kind != setting.kind); + } else { + sources.push(setting); + } +} + +/// Set the gain of a source (linear). +pub fn set_gain(sources: &mut [AudioSourceSetting], index: usize, gain: f32) { + if let Some(s) = sources.get_mut(index) { + s.gain = gain; + } +} + +/// Mute a source, or unmute it. +pub fn toggle_mute(sources: &mut [AudioSourceSetting], index: usize) { + if let Some(s) = sources.get_mut(index) { + s.muted = !s.muted; + } +} + +/// Take a source out of the mixer. +pub fn remove_audio(sources: &mut Vec, index: usize) { + if index < sources.len() { + sources.remove(index); + } +} + +// Sample data (VOELIN_DEMO_UI). + +/// The demo studio of VOELIN_DEMO_UI: sample scenes from synthetic sources, +/// test tones, recordings in a temporary folder; in memory only. +pub fn demo_settings() -> (Settings, Vec) { + let settings = Settings::in_memory(); + let text = |text: &str, size_px: f32| SourceKind::Text { + text: text.into(), + font: None, + size_px, + colour: Colour::WHITE, + backdrop: Colour::CLEAR, + align: Align::Center, + padding: 0, + }; + let source = |id: u64, name: &str, kind: SourceKind, transform: Transform| Source { + name: name.into(), + transform, + ..Source::new(id, kind) + }; + let slate = |id: u64, name: &str, words: &str| { + let mut scene = Scene::new(id, name); + scene.sources = vec![ + source( + 1, + "Backdrop", + SourceKind::Colour { colour: Colour::rgb(16, 26, 60), size: (1920, 1080) }, + Transform::full(1920, 1080), + ), + source(2, "Title", text(words, 120.0), Transform::box_at(160.0, 440.0, 1600.0, 200.0)), + ]; + scene + }; + let camera = SourceKind::Camera { + device: camera::SYNTHETIC.into(), + size: None, + fps: None, + mirror: false, + }; + let mut main = Scene::new(1, "Main Stream"); + let mut cam = source(2, "Camera", camera.clone(), Transform::default()); + cam.transform = placement(&camera, (1920, 1080)); + cam.background = Background::Blur { strength: 0.04 }; + let mut game = source( + 1, + "Game Capture", + SourceKind::Pattern { size: (1280, 720) }, + Transform { fit: Fit::Cover, ..Transform::full(1920, 1080) }, + ); + // The pattern's frame counter sits in its top-left corner, under the + // preview's LIVE badge and timer: cropped away. + game.crop = Crop { top: 120, ..Crop::default() }; + main.sources = vec![game, cam]; + let mut chatting = Scene::new(2, "Just Chatting"); + chatting.sources = vec![source( + 1, + "Camera", + camera, + Transform { fit: Fit::Cover, ..Transform::full(1920, 1080) }, + )]; + let scenes = Scenes { + scenes: vec![ + main, + chatting, + slate(3, "Be Right Back", "Be right back"), + slate(4, "Starting Soon", "Starting soon"), + slate(5, "Ending", "Thanks for watching"), + ], + active: 1, + width: 1920, + height: 1080, + fps: 60, + }; + let tone = |frequency, gain| AudioSourceSetting { + gain, + ..AudioSourceSetting::new(AudioSourceKindSetting::Synthetic { frequency }) + }; + let recordings = std::env::temp_dir().join("voelin-demo-recordings"); + let results = [ + settings.set(&STUDIO_SCENES, scenes), + settings.set( + &STREAM_AUDIO_SOURCES, + vec![ + AudioSourceSetting { + gain: 0.49, + ..AudioSourceSetting::new(AudioSourceKindSetting::Microphone) + }, + tone(440, 0.25), + tone(660, 0.39), + ], + ), + settings.set(&STUDIO_RECORDING_DIR, recordings.display().to_string()), + settings.set( + &STUDIO_UI, + StudioUi { + title: "Exploring the Lands Between".into(), + game: "Adventure".into(), + message: "Going live in Chill Zone — exploring the Lands Between. Come hang!" + .into(), + show_viewers: true, + show_now_playing: true, + ..StudioUi::default() + }, + ), + ]; + // The demo goes on with what it has. + let problems = results.into_iter().filter_map(|r| r.err()).map(|e| e.to_string()).collect(); + (settings, problems) +} + +/// The sample viewers of the demo stream going live. +pub fn demo_viewers() -> Vec { + let viewer = |id: u16, state: ViewerState, estimate: u64| ViewerInfo { + client: id, + state, + message: String::new(), + layer: Some(0), + estimate: Some(estimate), + srtp_profile: None, + codec: None, + }; + vec![ + viewer(3, ViewerState::Connected, 12_000_000), + viewer(4, ViewerState::Connected, 9_500_000), + viewer(9, ViewerState::Connected, 20_000_000), + viewer(5, ViewerState::Connecting, 0), + viewer(6, ViewerState::Requested, 0), + ] +} + +/// The id of the stream the sample server announces for the demo studio. +pub const DEMO_STREAM_ID: &str = "demo-studio"; + +/// The stream the sample server announces for ours (`own`: our client id). +pub fn demo_stream(own: ClientId, name: String, audio: bool) -> StreamInfo { + StreamInfo { + id: DEMO_STREAM_ID.into(), + streamer: own, + name, + kind: StreamKind::Screen, + bitrate: 8000, + viewer_limit: 0, + audio, + viewers: Some(3), + } +} + +/// A message sent in the demo, as the engine would have echoed it. +pub fn demo_message( + target: ChatTarget, + author: String, + client: Option, + text: String, + ts_ms: i64, +) -> ChatMessage { + ChatMessage { + target, + author_name: author, + author_uid: client.map(|c| format!("demo-{c}")), + author_id: client, + text, + ts_ms, + via_relay: false, + blocked: false, + } +} + +/// A demo message as a session with stored history keeps it (in memory only: +/// the id is negative). +pub fn demo_stored(message: ChatMessage) -> HistoryMessage { + HistoryMessage { + id: -message.ts_ms, + message, + source: MessageSource::Voice, + remote_id: None, + topic_id: None, + reactions: Vec::new(), + pinned: false, + rev: 0, + } +} + +#[cfg(test)] +mod tests { + use voelin_core::VoiceState; + use voelin_core::media::voelin_media::capture::CaptureSource; + use voelin_core::settings::LayerSetting; + use voelin_core::studio::camera::Camera; + use voelin_store::Bookmark; + + use super::*; + use crate::settings::UiSettings; + + fn viewer(client: u16, state: ViewerState, estimate: Option) -> ViewerInfo { + ViewerInfo { + client, + state, + message: String::new(), + layer: None, + estimate, + srtp_profile: None, + codec: None, + } + } + + fn state_with(sessions: &[(i64, bool)]) -> AppState<()> { + let bookmarks = sessions + .iter() + .map(|(id, _)| Bookmark { + id: *id, + name: format!("Server {id}"), + ..Bookmark::default() + }) + .collect(); + let mut state = AppState::<()>::new( + bookmarks, + UiSettings::default(), + Default::default(), + Default::default(), + ); + for (id, streams) in sessions { + let view = state.sessions.entry(*id).or_default(); + view.capabilities.streams = *streams; + view.state.voice = VoiceState::Connected; + view.state.own_channel = Some(7); + } + state + } + + fn data_with_scenes() -> StudioData { + let mut data = StudioData::default(); + let mut scene = Scene::new(1, "Main"); + scene.sources = vec![ + Source { + name: "Screen".into(), + ..Source::new(1, SourceKind::Pattern { size: (1280, 720) }) + }, + Source { + name: "Cam".into(), + ..Source::new( + 2, + SourceKind::Camera { device: "a".into(), size: None, fps: None, mirror: false }, + ) + }, + ]; + data.scenes = Arc::new(Scenes { + scenes: vec![scene, Scene::new(2, "Break")], + active: 1, + width: 1920, + height: 1080, + fps: 60, + }); + data + } + + #[test] + fn the_stream_is_named_after_its_title_and_game() { + let ui = |title: &str, game: &str| StudioUi { + title: title.into(), + game: game.into(), + ..StudioUi::default() + }; + assert_eq!(stream_name(&ui(" Speedrun ", "Zelda")), "Speedrun — Zelda"); + assert_eq!(stream_name(&ui("Speedrun", " ")), "Speedrun"); + assert_eq!(stream_name(&ui("", "Zelda")), "Zelda"); + assert_eq!(now_playing(&ui("Speedrun", "Zelda")).as_deref(), Some("Speedrun\nZelda")); + assert_eq!(now_playing(&ui(" ", "")), None); + assert!(file_name("Clip").starts_with("Clip 2") && file_name("Clip").ends_with(".mkv")); + } + + #[test] + fn editing_a_field_of_the_panel() { + let ui = StudioUi::default(); + let edited = |key, value| match edit(&ui, key, value) { + Edit::Ui(ui) => ui, + other => panic!("{key}: {other:?}"), + }; + assert_eq!(edited("title", "Hello").title, "Hello"); + assert!(edited("show-chat", "true").show_chat); + assert!(!edited("audio", "false").audio); + assert_eq!(edit(&ui, "bitrate", " 4500 "), Edit::Bitrate(Some(4500))); + assert_eq!(edit(&ui, "bitrate", "Auto"), Edit::Bitrate(Some(0))); + assert_eq!(edit(&ui, "bitrate", ""), Edit::Bitrate(Some(0))); + assert_eq!(edit(&ui, "bitrate", "fast"), Edit::Bitrate(None)); + assert_eq!(edit(&ui, "destination", "2"), Edit::Destination(Some(2))); + assert_eq!(edit(&ui, "destination", "-"), Edit::Destination(None)); + assert_eq!(edit(&ui, "colour", "red"), Edit::Nothing); + assert_eq!(parse_output("1920", "1080", "60"), Some((1920, 1080, 60))); + assert_eq!(parse_output("1920", "0", "60"), None); + assert_eq!(parse_output("wide", "1080", "60"), None); + } + + #[test] + fn the_bitrate_is_automatic_for_the_output_or_as_set() { + let mut data = data_with_scenes(); + let settings = Settings::in_memory(); + settings.set(&STREAM_BITRATE_KBPS, 0).unwrap(); + assert_eq!( + u64::from(data.bitrate_kbps(&settings)) * 1000, + auto_bitrate(1920, 1080, 60) / 1000 * 1000 + ); + settings.set(&STREAM_BITRATE_KBPS, 6000).unwrap(); + assert_eq!(data.bitrate_kbps(&settings), 6000); + // Without layers: one layer at that bitrate; with: the layers. + let layers = data.session_layers(&settings); + assert_eq!(layers.len(), 1); + assert_eq!(data.go_live_bitrate(&settings), 6000); + settings + .set( + &STREAM_LAYERS, + vec![ + LayerSetting { bitrate: 8_000_000, ..LayerSetting::default() }, + LayerSetting { bitrate: 2_000_000, scale: 0.5, ..LayerSetting::default() }, + ], + ) + .unwrap(); + assert_eq!(data.session_layers(&settings).len(), 2); + assert_eq!(data.go_live_bitrate(&settings), 8000); + data.ui = StudioUi { title: "T".into(), audio: false, ..StudioUi::default() }; + let setup = data.stream_setup(&settings); + assert_eq!((setup.name.as_str(), setup.bitrate, setup.audio), ("T", 8000, false)); + } + + #[test] + fn the_studio_stops_after_a_few_ticks_hidden() { + let mut data = StudioData::default(); + assert!(data.keep_running(true)); + assert!(data.keep_running(false) && data.keep_running(false)); + assert!(!data.keep_running(false)); + // Shown again, or busy: the count starts over. + assert!(data.keep_running(true)); + assert_eq!(data.hidden, 0); + data.status.recording = Some("clip.mkv".into()); + assert!(data.busy() && data.keep_running(false) && data.keep_running(false)); + data.status.recording = None; + data.stream = Some(Outgoing { session: 1, live: false, viewers: Vec::new() }); + assert!(data.busy() && data.keep_running(false)); + } + + #[test] + fn the_preview_follows_the_shape_of_the_output() { + let mut data = data_with_scenes(); + let size = |data: &StudioData| match data.preview_command() { + studio::Command::SetPreview { width, height, fps } => (width, height, fps), + other => panic!("{other:?}"), + }; + assert_eq!(size(&data), (960, 540, 15)); + data.ui.preview_width = 1; + data.ui.preview_fps = 0; + assert_eq!(size(&data), (16, 8, 1)); + let mut scenes = (*data.scenes).clone(); + scenes.width = 1000; + scenes.height = 1000; + let (switched, resized) = data.set_scenes(Arc::new(scenes.clone())); + assert!((switched, resized) == (false, true)); + scenes.active = 2; + assert_eq!(data.set_scenes(Arc::new(scenes)), (true, false)); + } + + #[test] + fn destinations_are_sessions_with_streams_and_a_channel() { + let mut state = state_with(&[(3, true), (1, true), (2, false)]); + state.current = Some(3); + let list = destinations(&state); + // TeamSpeak 6 with voice only; the current one first. + assert_eq!(list.iter().map(|d| d.0).collect::>(), [3, 1]); + assert_eq!(list[0].1, " • Server 3"); + assert_eq!(chat_target(&state, Some(1)), Some((1, 7))); + assert_eq!(chat_target(&state, Some(9)), None); + assert_eq!(chat_target(&state, None), None); + let rows = destination_rows(&state, &list); + assert_eq!((&*rows[1].detail, &*rows[1].kind), ("Server 1", "server")); + // The tab of the destination's channel is made once. + assert_eq!(chat_tab(&mut state, 1, 7), (String::new(), true)); + assert_eq!(chat_tab(&mut state, 1, 7), (String::new(), false)); + assert_eq!(state.sessions[&1].tabs.len(), 2); + assert_eq!(viewer_name(&state, Some(1), 5), "client 5"); + assert_eq!(viewer_name(&state, None, 5), "client 5"); + } + + #[test] + fn the_destination_stays_while_it_works() { + let list = vec![(1, "a".to_owned()), (2, "b".to_owned())]; + let mut data = StudioData::default(); + data.choose_destination(&list); + assert_eq!(data.destination, Some(1)); + data.destination = Some(2); + data.choose_destination(&list); + assert_eq!(data.destination, Some(2)); + // Gone: the first. Live to a session that is gone from the list: it + // stays the stream's. + data.choose_destination(&list[..1]); + assert_eq!(data.destination, Some(1)); + data.stream = Some(Outgoing { session: 5, live: true, viewers: Vec::new() }); + assert!(data.streams_to(5) && !data.streams_to(1)); + data.choose_destination(&list); + assert_eq!(data.destination, Some(5)); + data.choose_destination(&[]); + assert_eq!(data.destination, Some(5)); + data.stream = None; + data.choose_destination(&[]); + assert_eq!(data.destination, None); + // The form says where in the list. + data.destination = Some(2); + let form = data.form(&list); + assert_eq!((form.destination, &*form.bitrate), (1, "")); + data.destination = Some(9); + assert_eq!(data.form(&list).destination, -1); + } + + #[test] + fn the_status_says_what_keeps_the_stream_from_going_live() { + let named = |v: &ViewerInfo| format!("viewer {}", v.client); + let mut data = data_with_scenes(); + let cx = |running, has_encoder, sharing, destination: Option<&str>| StatusContext { + running, + has_encoder, + detached: false, + sharing, + destination: destination.map(str::to_owned), + viewer_name: &named, + }; + let hint = + |data: &StudioData, cx: &StatusContext<'_>| data.status_view(cx).0.hint.to_string(); + assert_eq!(hint(&data, &cx(false, false, false, None)), "Starting the studio…"); + assert_eq!(hint(&data, &cx(true, false, false, Some("a"))), "Starting the studio…"); + assert_eq!( + hint(&data, &cx(true, true, false, None)), + "Join a voice channel on a TeamSpeak 6 server to go live." + ); + assert_eq!( + hint(&data, &cx(true, true, true, Some("a"))), + "Stop sharing your screen first." + ); + data.error = "The studio did not start".into(); + assert_eq!(hint(&data, &cx(true, true, false, Some("a"))), "The studio did not start"); + data.error.clear(); + let (status, requests) = data.status_view(&cx(true, true, false, Some("Chill • Guild"))); + assert!(status.can_go_live && status.hint.is_empty() && !status.live); + assert_eq!( + (&*status.destination, status.output_height, status.fps), + ("Chill • Guild", 1080, 60) + ); + assert!(requests.is_empty()); + assert!(status.screen_shown && status.camera_shown && !status.window_shown); + assert_eq!(&*status.format, "1080p • 60 FPS • 0 kbps"); + let settings = Settings::in_memory(); + settings.set(&STREAM_BITRATE_KBPS, 8250).unwrap(); + data.settings = Some(settings); + let (status, _) = data.status_view(&cx(true, true, false, Some("Chill • Guild"))); + assert_eq!(&*status.format, "1080p • 60 FPS • 8,250 kbps"); + // Going live: waiting, then live with viewers. + data.stream = Some(Outgoing { + session: 1, + live: false, + viewers: vec![ + viewer(4, ViewerState::Requested, None), + viewer(5, ViewerState::Connected, Some(4_000_000)), + ], + }); + let (status, requests) = data.status_view(&cx(true, true, false, Some("a"))); + assert!(status.starting && !status.can_go_live); + assert_eq!(&*status.hint, "Waiting for the server…"); + assert_eq!((status.viewers, status.participants), (1, 2)); + assert_eq!(requests.len(), 1); + assert_eq!((&*requests[0].name, &*requests[0].state), ("viewer 4", "requested")); + data.stream.as_mut().unwrap().live = true; + let (status, _) = data.status_view(&cx(true, true, false, Some("a"))); + assert!(status.live && !status.can_go_live && status.quality > 0); + } + + #[test] + fn overlays_follow_the_switches() { + let mut data = StudioData { + ui: StudioUi { + title: "T".into(), + game: "G".into(), + show_viewers: true, + show_now_playing: true, + ..StudioUi::default() + }, + stream: Some(Outgoing { + session: 1, + live: true, + viewers: vec![ + viewer(1, ViewerState::Connected, None), + viewer(2, ViewerState::Connecting, None), + ], + }), + ..StudioData::default() + }; + let wanted = data.wanted_overlays(|| panic!("the chat is off")); + assert_eq!(wanted[0].text.as_deref(), Some("1 watching")); + assert_eq!(wanted[1].text, None); + assert_eq!(wanted[2].text.as_deref(), Some("T\nG")); + // Sent the first time, and again when something changed or when forced. + assert!(data.overlay_change(false, wanted.clone()).is_some()); + assert!(data.overlay_change(false, wanted.clone()).is_none()); + assert!(data.overlay_change(true, wanted.clone()).is_some()); + data.ui.show_chat = true; + let with_chat = data.wanted_overlays(|| Some("a: hi".into())); + assert_eq!(with_chat[1].text.as_deref(), Some("a: hi")); + assert_eq!(data.overlay_change(false, with_chat).map(|w| w.len()), Some(3)); + } + + #[test] + fn the_chat_overlay_has_the_last_lines_cut_short() { + let line = |author: &str, text: &str| ChatLine { + author: author.into(), + text: text.into(), + ..ChatLine::default() + }; + assert_eq!(chat_tail(&[], 5), None); + let long = "x".repeat(100); + let lines = [line("a", "one"), line("b", "two"), line("c", &long)]; + assert_eq!( + chat_tail(&lines, 2).as_deref(), + Some(format!("b: two\nc: {}…", "x".repeat(61)).as_str()) + ); + assert_eq!(chat_tail(&lines, 9).unwrap().lines().count(), 3); + } + + #[test] + fn layers_are_edited_in_the_settings() { + let settings = Settings::in_memory(); + let row = |size: &str, bitrate: &str| StudioLayer { + size: size.into(), + bitrate: bitrate.into(), + ..StudioLayer::default() + }; + assert!(add_layer(&settings, 6000).is_empty()); + assert_eq!(settings.get(&STREAM_LAYERS).len(), 2); + assert_eq!(set_layer(&settings, 5, &row("1280x720", "2500")), None); + let said = set_layer(&settings, 1, &row("nonsense", "2500")).unwrap(); + assert!(said[0].starts_with("Layer 2: "), "{said:?}"); + assert_eq!(set_layer(&settings, 1, &row("1280x720", "2500")), Some(Vec::new())); + assert_eq!(settings.get(&STREAM_LAYERS)[1].size, Some((1280, 720))); + // One layer left is the single layer: none. + assert!(remove_layer(&settings, 0).is_empty()); + assert!(settings.get(&STREAM_LAYERS).is_empty()); + assert!(remove_layer(&settings, 3).is_empty()); + } + + #[test] + fn the_source_controls_make_commands_and_changes() { + let data = data_with_scenes(); + let scenes = &*data.scenes; + let act = |id, action: &str| source_action(scenes, id, action, Vec::new); + assert!(matches!( + act(1, "up"), + Some(SourceStep::Apply(studio::Command::ReorderSource { scene: 1, source: 1, to: 1 })) + )); + assert!(matches!( + act(2, "down"), + Some(SourceStep::Apply(studio::Command::ReorderSource { to: 0, .. })) + )); + assert!(matches!( + act(1, "remove"), + Some(SourceStep::Apply(studio::Command::RemoveSource { scene: 1, source: 1 })) + )); + assert!(matches!( + act(1, "lock"), + Some(SourceStep::Update(SourceChange { locked: Some(true), .. })) + )); + assert!(matches!( + act(1, "bg-blur"), + Some(SourceStep::Update(SourceChange { + background: Some(Background::Blur { .. }), + .. + })) + )); + assert!(matches!( + act(1, "bg-keep"), + Some(SourceStep::Update(SourceChange { background: Some(Background::Keep), .. })) + )); + assert!(act(9, "up").is_none() && act(1, "spin").is_none()); + // The next camera: not a camera, no other one, another one. + assert!(act(1, "next-camera").is_none()); + assert!(matches!( + act(2, "next-camera"), + Some(SourceStep::Say("There is no other camera.")) + )); + let camera = |id: &str, name: &str, mirrored| Camera { + id: id.into(), + name: name.into(), + backend: "v4l2", + formats: Vec::new(), + mirrored, + }; + let two = || vec![camera("a", "Cam", true), camera("b", "Back", false)]; + let Some(SourceStep::Update(change)) = source_action(scenes, 2, "next-camera", two) else { + panic!("no camera change"); + }; + // Named after its camera: named after the next; mirrored as that one is. + assert_eq!(change.name.as_deref(), Some("Back")); + assert!( + matches!(change.kind, Some(SourceKind::Camera { ref device, mirror: false, .. }) if device == "b") + ); + } + + #[test] + fn a_locked_source_keeps_its_place() { + let mut data = data_with_scenes(); + let id = 1; + let scene = Arc::make_mut(&mut data.scenes).active_mut().unwrap(); + scene.sources[0].locked = true; + let old = data.live_source(id).unwrap().clone(); + let form = StudioSourceForm { x: "100".into(), ..super::super::form(&old) }; + let (change, notice) = source_change(&form, &old).unwrap(); + assert!(change.transform.is_none() && change.crop.is_none()); + assert_eq!(notice, Some("Unlock the source to move, resize or crop it.")); + let unlocked = StudioSourceForm { locked: false, ..form }; + let (change, notice) = source_change(&unlocked, &old).unwrap(); + assert!(notice.is_none() && change.locked == Some(false)); + } + + #[test] + fn the_phones_source_cards_show_one_kind() { + let data = data_with_scenes(); + let scene = data.scenes.active(); + // Camera: the screen goes, the camera stays. + let (changes, has) = main_source_changes(scene, "camera"); + assert_eq!((changes, has), (vec![(1, false)], true)); + let (changes, has) = main_source_changes(scene, "screen"); + assert_eq!((changes, has), (vec![(2, false)], true)); + // No window: both go and one is to be added. + let (changes, has) = main_source_changes(scene, "window"); + assert_eq!((changes, has), (vec![(1, false), (2, false)], false)); + assert_eq!(main_source_changes(None, "screen"), (Vec::new(), false)); + } + + #[test] + fn pickers_list_what_can_be_added() { + let camera = |id: &str, mirrored| Camera { + id: id.into(), + name: format!("Camera {id}"), + backend: "v4l2", + formats: Vec::new(), + mirrored, + }; + let picks = camera_picks(&[camera("a", true)]); + assert_eq!((&*picks[0].1.name, &*picks[0].1.kind), ("Camera a", "camera")); + assert!(matches!( + &picks[0].0, + Pick::Source { kind: SourceKind::Camera { mirror: true, .. }, .. } + )); + assert_eq!(demo_camera_picks().len(), 1); + let sources = vec![ + CaptureSource { + id: SourceId::Monitor(0), + name: "DP-1".into(), + width: 2560, + height: 1440, + primary: true, + }, + CaptureSource { + id: SourceId::Monitor(1), + name: "HDMI-1".into(), + width: 1920, + height: 1080, + primary: false, + }, + CaptureSource { + id: SourceId::Window(9), + name: "Editor".into(), + width: 800, + height: 600, + primary: false, + }, + ]; + let screens = screen_picks("screen", sources.clone(), false); + assert_eq!(screens.iter().map(|p| &*p.1.name).collect::>(), ["DP-1", "HDMI-1"]); + assert_eq!(&*screens[0].1.detail, "2560×1440 · primary"); + let windows = screen_picks("window", sources, true); + assert_eq!( + windows.iter().map(|p| &*p.1.name).collect::>(), + ["Editor", "Test pattern"] + ); + // The desktop's own dialog alone is added at once. + let portal = CaptureSource { + id: SourceId::Portal, + name: "Portal".into(), + width: 0, + height: 0, + primary: false, + }; + let only = screen_picks("screen", vec![portal], false); + assert!(only_portal(&only)); + assert_eq!(&*only[0].1.name, "Choose with the system dialog"); + assert!(!only_portal(&screens)); + let source = picked_source(&only[0].0, (1920, 1080)).unwrap(); + assert_eq!((source.name.as_str(), source.id), ("Screen", 0)); + let tone = AudioSourceSetting::new(AudioSourceKindSetting::Synthetic { frequency: 440 }); + assert!(picked_source(&Pick::Audio(tone), (1920, 1080)).is_none()); + } + + #[test] + fn the_audio_picker_marks_what_is_mixed_in() { + let mic = AudioSourceSetting::new(AudioSourceKindSetting::Microphone); + let app = |name: &str, playing| AudioApp { + name: name.into(), + pid: None, + binary: Some(format!("{name}-bin")), + icon: None, + media: None, + streams: 1, + playing, + }; + let picks = audio_picks( + std::slice::from_ref(&mic), + vec![app("Music", true), app("Idle", false)], + false, + ); + let names: Vec<&str> = picks.iter().map(|p| &*p.1.name).collect(); + assert!( + names.starts_with(&["Microphone", "Desktop audio"]) + && names.ends_with(&["Music", "Idle"]) + ); + assert!(picks[0].1.selected && !picks[1].1.selected); + assert_eq!(&*picks[picks.len() - 2].1.detail, "playing"); + assert_eq!(&*picks[picks.len() - 1].1.detail, ""); + let demo = audio_picks(&[], vec![app("Ignored", true)], true); + assert_eq!(demo.iter().filter(|p| &*p.1.name == "Test tone").count(), 3); + assert!(demo.iter().all(|p| &*p.1.name != "Ignored")); + } + + #[test] + fn the_mixer_controls_change_the_sources() { + let mic = AudioSourceSetting::new(AudioSourceKindSetting::Microphone); + let desktop = AudioSourceSetting::new(AudioSourceKindSetting::Desktop); + let mut sources = vec![mic.clone()]; + toggle_audio(&mut sources, desktop.clone()); + assert_eq!(sources.len(), 2); + toggle_audio(&mut sources, mic); + assert_eq!(sources, [desktop]); + set_gain(&mut sources, 0, 0.25); + set_gain(&mut sources, 4, 9.0); + toggle_mute(&mut sources, 0); + toggle_mute(&mut sources, 4); + assert_eq!((sources[0].gain, sources[0].muted), (0.25, true)); + remove_audio(&mut sources, 3); + assert_eq!(sources.len(), 1); + remove_audio(&mut sources, 0); + assert!(sources.is_empty()); + // Rows: the meters' levels where the mixer has them, floored. + let sources = vec![ + AudioSourceSetting::new(AudioSourceKindSetting::Microphone), + AudioSourceSetting::new(AudioSourceKindSetting::Desktop), + ]; + let live = audio_live(&sources, &[], &[Some(-140.0), None]); + assert_eq!(live[0].as_ref().map(|l| l.level), Some(-100.0)); + assert!(live[1].is_none()); + assert_eq!(meter_ids(&sources, &[]), [None, None]); + } + + #[test] + fn the_settings_dialog_stores_what_it_can() { + let settings = Settings::in_memory(); + let ui = StudioUi::default(); + let form = settings_form(&settings, &ui); + let done = apply_settings_form(&settings, &ui, &form); + assert_eq!(done, SettingsApplied::default()); + let form = StudioSettingsForm { + replay_seconds: "30".into(), + replay_memory: "lots".into(), + recording_dir: " /tmp/rec ".into(), + preview_width: "640".into(), + preview_fps: "30".into(), + }; + let done = apply_settings_form(&settings, &ui, &form); + assert_eq!(done.notes, ["The replay memory is a whole number of MB."]); + assert_eq!(done.refused, None); + assert_eq!(done.ui.as_ref().map(|u| (u.preview_width, u.preview_fps)), Some((640, 30))); + assert_eq!(settings.get(&STUDIO_REPLAY_SECONDS), 30); + assert_eq!(settings.get(&STUDIO_RECORDING_DIR), "/tmp/rec"); + let again = settings_form(&settings, &done.ui.unwrap()); + assert_eq!((&*again.replay_seconds, &*again.preview_width), ("30", "640")); + } + + #[test] + fn the_live_scene_takes_a_new_source() { + let mut scenes = Scenes::default(); + add_to_live_scene(&mut scenes, Source::new(0, SourceKind::Pattern { size: (16, 16) })); + assert_eq!( + (scenes.scenes.len(), scenes.active().map(|s| s.name.as_str())), + (1, Some("Scene 1")) + ); + add_to_live_scene(&mut scenes, Source::new(0, SourceKind::Pattern { size: (16, 16) })); + let ids: Vec = scenes.active().unwrap().sources.iter().map(|s| s.id).collect(); + assert_eq!(ids, [1, 2]); + } + + #[test] + fn events_and_endings_have_words() { + let path = std::path::PathBuf::from("/tmp/x.mkv"); + assert_eq!( + event_message(&studio::Event::RecordingStarted { path: path.clone() }).as_deref(), + Some("Recording to /tmp/x.mkv") + ); + assert_eq!( + event_message(&studio::Event::ClipSaved { + path: path.clone(), + duration: std::time::Duration::from_secs(30) + }) + .as_deref(), + Some("Saved a clip of 30 seconds to /tmp/x.mkv") + ); + assert_eq!( + event_message(&studio::Event::RecordingStopped { + path, + duration: std::time::Duration::from_secs(61), + bytes: 2_500_000, + }) + .as_deref(), + Some("Saved a recording of 00:01:01 (2.5 MB) to /tmp/x.mkv") + ); + assert_eq!( + event_message(&studio::Event::Error { + context: "record".into(), + message: "disk full".into() + }) + .as_deref(), + Some("Stream Studio (record): disk full") + ); + assert_eq!(event_message(&studio::Event::State(Status::default())), None); + assert_eq!(ended_message(None), "The stream has ended"); + assert_eq!( + ended_message(Some(&EndReason::Failed("no route".into()))), + "The stream failed: no route" + ); + } + + #[test] + fn the_demo_studio_has_scenes_and_viewers() { + let (settings, problems) = demo_settings(); + assert!(problems.is_empty(), "{problems:?}"); + let scenes = settings.get(&STUDIO_SCENES); + assert_eq!(scenes.scenes.len(), 5); + assert_eq!(settings.get(&STREAM_AUDIO_SOURCES).len(), 3); + assert_eq!(settings.get(&STUDIO_UI).title, "Exploring the Lands Between"); + let viewers = demo_viewers(); + assert_eq!(viewers.iter().filter(|v| v.state == ViewerState::Connected).count(), 3); + let info = demo_stream(4, "Show".into(), true); + assert_eq!((info.id.as_str(), info.streamer, info.viewers), (DEMO_STREAM_ID, 4, Some(3))); + let message = demo_message(ChatTarget::Channel(2), "me".into(), Some(4), "hi".into(), 1234); + assert_eq!((message.author_uid.as_deref(), message.author_id), (Some("demo-4"), Some(4))); + assert_eq!(demo_stored(message).id, -1234); + } +} diff --git a/crates/voelin-ui-vm/src/studio.rs b/crates/voelin-ui-vm/src/studio/mod.rs similarity index 99% rename from crates/voelin-ui-vm/src/studio.rs rename to crates/voelin-ui-vm/src/studio/mod.rs index ef07b4a..a07da5c 100644 --- a/crates/voelin-ui-vm/src/studio.rs +++ b/crates/voelin-ui-vm/src/studio/mod.rs @@ -1,6 +1,9 @@ //! The Stream Studio's view models: scene, source, mixer and layer rows, //! the header's numbers, the source dialog's form, where new sources go and //! the overlay sources the stream settings' switches keep in the scenes. +//! Decisions of the studio (what it does when) are in [`logic`]. + +pub mod logic; use std::time::Duration; diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 5aeeef6..d2ab382 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -54,7 +54,7 @@ fn open_settings(dir: &Path, overrides: &[String]) -> Settings { for key in crate::settings::page_keys() { prefs.register(key); } - prefs.register(&crate::studio::STUDIO_UI); + prefs.register(&crate::vm::studio::logic::STUDIO_UI); let config = std::env::var_os("VOELIN_CONFIG") .map(PathBuf::from) .or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists())); diff --git a/crates/voelin-ui/src/studio.rs b/crates/voelin-ui/src/studio.rs deleted file mode 100644 index 5749ead..0000000 --- a/crates/voelin-ui/src/studio.rs +++ /dev/null @@ -1,2266 +0,0 @@ -//! The Stream Studio: the controller behind its page in the main window, its -//! window of its own and the phone layout (ui/screens/studio*.slint, -//! ui/studio-window.slint). -//! -//! The engine's studio (`voelin_core::studio`) composites the scenes; a -//! `Streamer` started for it encodes the composite from the start, so the -//! recording and the replay buffer need no live stream, and going live -//! attaches it to a TeamSpeak stream of our voice channel like any share. -//! The studio runs while it is shown, live or recording. -//! -//! Both windows' StudioBridge globals show the same models (shared -//! rows) and get the same values; their callbacks come here -//! (bind/studio.rs). Commands go to the studio through one task, in order. - -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Weak}; -use std::time::Duration; - -use serde::{Deserialize, Serialize}; -use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer}; -use tokio::sync::broadcast::error::RecvError; -use tokio::sync::{broadcast, mpsc}; -use tracing::warn; -use voelin_core::media::voelin_media::capture::SourceId; -use voelin_core::media::voelin_media::handoff::Handoff; -use voelin_core::media::voelin_media::mix::SourceHandle; -use voelin_core::media::voelin_media::{VideoFrame, convert}; -use voelin_core::media::{ - AudioApps, AudioSourceSpec, AudioSourceStats, Latest, Streamer, StreamerConfigUpdate, - StreamerStats, audio_apps, audio_source_specs, auto_bitrate, screen_sources, -}; -use voelin_core::settings::{ - AudioSourceKindSetting, AudioSourceSetting, Key, Kind, STREAM_AUDIO_SOURCES, - STREAM_BITRATE_KBPS, STREAM_LAYERS, STUDIO_RECORDING_DIR, STUDIO_REPLAY_MEMORY_MB, - STUDIO_REPLAY_SECONDS, STUDIO_SCENES, Settings, layer_specs, -}; -use voelin_core::stream::{ - EndReason, LayerSpec, StreamInfo, StreamKind, StreamSetup, ViewerInfo, ViewerState, -}; -use voelin_core::studio::scene::{ - Align, Background, Colour, Crop, Fit, Scene, Scenes, Source, SourceKind, Transform, -}; -use voelin_core::studio::{self, SourceChange, Stats, Status, Studio, camera}; -use voelin_core::{Command, HistoryMessage, HistorySource, StreamState}; -use voelin_model::{ChatMessage, ChatTarget}; -use voelin_store::MessageSource; - -use crate::app::{App, Nav, Page, StudioBridge, StudioNav, StudioWindow, later, with_app}; -use crate::bind::rows::Rows; -use crate::settings::parse_positive; -use crate::video::CaptureRequest; -use crate::vm; -use crate::vm::bridge::ChatLine; -use crate::vm::studio::{OVERLAY_CHAT, OVERLAY_NOW_PLAYING, OVERLAY_VIEWERS, Overlay}; -use crate::vm::studio_bridge::{ - StudioForm, StudioLayer, StudioPick, StudioSettingsForm, StudioSourceForm, StudioStatus, - StudioViewer, -}; - -type Picture = SharedPixelBuffer; - -/// The stream settings panel and the studio's own choices. -pub static STUDIO_UI: Key = Key::new( - "studio.ui", - Kind::Json, - "Stream Studio: title, game, go-live message, overlays, stream audio, preview size.", - StudioUi::default, -); - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default)] -pub struct StudioUi { - pub title: String, - /// Game or category: goes into the stream's name after the title. - pub game: String, - /// Sent to the channel's chat when the stream goes live. - pub message: String, - /// Overlay sources kept in the live scene (`vm::studio::apply_overlays`). - pub show_viewers: bool, - pub show_chat: bool, - pub show_now_playing: bool, - /// The stream's audio (the mixer's sources); off: none. - pub audio: bool, - /// The preview's width in pixels (its height follows the output) and - /// frame rate. - pub preview_width: u32, - pub preview_fps: u32, -} - -impl Default for StudioUi { - fn default() -> Self { - Self { - title: String::new(), - game: String::new(), - message: String::new(), - show_viewers: false, - show_chat: false, - show_now_playing: false, - audio: true, - preview_width: 960, - preview_fps: 15, - } - } -} - -/// The models both windows show. -#[derive(Default)] -struct Models { - scenes: Rows, - sources: Rows, - audio: Rows, - layers: Rows, - viewers: Rows, - destinations: Rows, - picks: Rows, - /// The destination channel's chat (`studio_sync_chat`). - chat: Rows, -} - -/// What a picker row adds. -enum Pick { - Source { name: String, kind: SourceKind }, - Audio(AudioSourceSetting), -} - -/// Our stream from the studio. -struct Outgoing { - session: i64, - live: bool, - viewers: Vec, -} - -/// A change of the scene graph, applied in order by one task. -enum Op { - Apply(studio::Command), - /// A source for the live scene (a new scene if there is none). - Add(Source), - /// Keep the overlay sources as asked. - Overlays(Vec), -} - -/// A running studio. -struct Running { - studio: Arc, - /// Encodes the composite; `None` until it started (or if it failed). - streamer: Option, - ops: mpsc::UnboundedSender, - /// The newest preview picture, for the UI thread. - pictures: Arc>, - /// Stops the preview thread. - stop: Arc, - tasks: Vec>, - /// The mixer's meters, about 15 times a second. - _meters: slint::Timer, -} - -impl Drop for Running { - fn drop(&mut self) { - self.stop.store(true, Ordering::Relaxed); - for task in &self.tasks { - task.abort(); - } - } -} - -/// The studio's state on the UI thread (`App::studio`). -#[derive(Default)] -pub(crate) struct StudioState { - models: Models, - /// The main window's globals have the models. - attached: bool, - /// The studio in a window of its own. - pub(crate) window: Option, - run: Option, - starting: bool, - /// Why it does not run or cannot stream. - error: String, - /// Where it keeps its keys: the app's settings, or with VOELIN_DEMO_UI - /// its own in memory (nothing stored). - settings: Option, - scenes: Arc, - status: Status, - stats: Option>, - encoder: Option, - ui: StudioUi, - destination: Option, - stream: Option, - picks: Vec, - /// Applications that play audio, for the audio picker. - apps: Option, - /// The mixer source of each audio row. - meters: Vec>, - /// The overlays last asked for. - overlays: Vec, - has_preview: bool, - /// Stats ticks it was not shown; it stops after a few. - hidden: u32, - /// Development switches waiting for the studio (dev.rs). - dev: Vec, -} - -/// Forward the studio's events to the UI thread. -async fn forward_events(mut events: broadcast::Receiver) { - loop { - match events.recv().await { - Ok(event) => later(move |app| app.studio_event(event)), - Err(RecvError::Lagged(_)) => {} - Err(RecvError::Closed) => break, - } - } -} - -/// Apply the ops one after the other. -async fn run_ops(studio: Weak, mut ops: mpsc::UnboundedReceiver) { - while let Some(op) = ops.recv().await { - let Some(studio) = studio.upgrade() else { break }; - let result = match op { - Op::Apply(command) => studio.apply(command).await, - Op::Add(mut source) => { - let mut scenes = studio.scenes(); - if scenes.active().is_none() { - let id = scenes.next_scene_id(); - scenes.scenes.push(Scene::new(id, "Scene 1")); - scenes.active = id; - } - if let Some(scene) = scenes.active_mut() { - source.id = scene.next_source_id(); - scene.sources.push(source); - } - studio.apply(studio::Command::SetScenes(Box::new(scenes))).await - } - Op::Overlays(wanted) => { - let mut scenes = studio.scenes(); - if vm::studio::apply_overlays(&mut scenes, &wanted) { - studio.apply(studio::Command::SetScenes(Box::new(scenes))).await - } else { - Ok(()) - } - } - }; - if let Err(e) = result { - later(move |app| app.set_status(format!("Stream Studio: {e}"))); - } - } -} - -/// Tell the UI thread when a key the studio follows changes elsewhere. -async fn watch_settings(settings: Settings) { - let mut audio = settings.watch(&STREAM_AUDIO_SOURCES); - let mut layers = settings.watch(&STREAM_LAYERS); - let mut bitrate = settings.watch(&STREAM_BITRATE_KBPS); - let mut ui = settings.watch(&STUDIO_UI); - loop { - tokio::select! { - Some(_) = audio.changed() => later(|app| app.studio_audio_changed()), - Some(_) = layers.changed() => later(|app| app.studio_encoding_changed()), - Some(_) = bitrate.changed() => later(|app| app.studio_encoding_changed()), - Some(_) = ui.changed() => later(|app| app.studio_ui_changed()), - else => break, - } - } -} - -/// Turn preview frames into pictures on a thread of its own; the UI thread -/// takes the newest when it gets to it. -fn spawn_preview( - handoff: Arc>, - pictures: Arc>, - stop: Arc, -) { - let spawned = - std::thread::Builder::new().name("voelin-studio-preview".into()).spawn(move || { - while !stop.load(Ordering::Relaxed) && !handoff.is_closed() { - let Some(frame) = handoff.wait_timeout(Duration::from_millis(250)) else { - continue; - }; - let mut picture = Picture::new(frame.width, frame.height); - let stride = frame.width as usize * 4; - if let Err(e) = convert::to_rgba(&frame, picture.make_mut_bytes(), stride) { - warn!("studio preview: {e}"); - continue; - } - if pictures.put(picture) { - later(|app| app.studio_picture()); - } - } - }); - if let Err(e) = spawned { - warn!("cannot show the studio's preview: {e}"); - } -} - -/// The demo studio of VOELIN_DEMO_UI: sample scenes from synthetic sources, -/// test tones, recordings in a temporary folder; in memory only. -fn demo_settings() -> Settings { - let settings = Settings::in_memory(); - let text = |text: &str, size_px: f32| SourceKind::Text { - text: text.into(), - font: None, - size_px, - colour: Colour::WHITE, - backdrop: Colour::CLEAR, - align: Align::Center, - padding: 0, - }; - let source = |id: u64, name: &str, kind: SourceKind, transform: Transform| Source { - name: name.into(), - transform, - ..Source::new(id, kind) - }; - let slate = |id: u64, name: &str, words: &str| { - let mut scene = Scene::new(id, name); - scene.sources = vec![ - source( - 1, - "Backdrop", - SourceKind::Colour { colour: Colour::rgb(16, 26, 60), size: (1920, 1080) }, - Transform::full(1920, 1080), - ), - source(2, "Title", text(words, 120.0), Transform::box_at(160.0, 440.0, 1600.0, 200.0)), - ]; - scene - }; - let camera = SourceKind::Camera { - device: camera::SYNTHETIC.into(), - size: None, - fps: None, - mirror: false, - }; - let mut main = Scene::new(1, "Main Stream"); - let mut cam = source(2, "Camera", camera.clone(), Transform::default()); - cam.transform = vm::studio::placement(&camera, (1920, 1080)); - cam.background = Background::Blur { strength: 0.04 }; - let mut game = source( - 1, - "Game Capture", - SourceKind::Pattern { size: (1280, 720) }, - Transform { fit: Fit::Cover, ..Transform::full(1920, 1080) }, - ); - // The pattern's frame counter sits in its top-left corner, under the - // preview's LIVE badge and timer: cropped away. - game.crop = Crop { top: 120, ..Crop::default() }; - main.sources = vec![game, cam]; - let mut chatting = Scene::new(2, "Just Chatting"); - chatting.sources = vec![source( - 1, - "Camera", - camera, - Transform { fit: Fit::Cover, ..Transform::full(1920, 1080) }, - )]; - let scenes = Scenes { - scenes: vec![ - main, - chatting, - slate(3, "Be Right Back", "Be right back"), - slate(4, "Starting Soon", "Starting soon"), - slate(5, "Ending", "Thanks for watching"), - ], - active: 1, - width: 1920, - height: 1080, - fps: 60, - }; - let tone = |frequency, gain| AudioSourceSetting { - gain, - ..AudioSourceSetting::new(AudioSourceKindSetting::Synthetic { frequency }) - }; - let recordings = std::env::temp_dir().join("voelin-demo-recordings"); - let results = [ - settings.set(&STUDIO_SCENES, scenes), - settings.set( - &STREAM_AUDIO_SOURCES, - vec![ - AudioSourceSetting { - gain: 0.49, - ..AudioSourceSetting::new(AudioSourceKindSetting::Microphone) - }, - tone(440, 0.25), - tone(660, 0.39), - ], - ), - settings.set(&STUDIO_RECORDING_DIR, recordings.display().to_string()), - settings.set( - &STUDIO_UI, - StudioUi { - title: "Exploring the Lands Between".into(), - game: "Adventure".into(), - message: "Going live in Chill Zone — exploring the Lands Between. Come hang!" - .into(), - show_viewers: true, - show_now_playing: true, - ..StudioUi::default() - }, - ), - ]; - for result in results { - if let Err(e) = result { - warn!("demo studio: {e}"); - } - } - settings -} - -/// The overlay text of what is on: the title and the game. -fn now_playing(ui: &StudioUi) -> Option { - let lines: Vec<&str> = - [ui.title.trim(), ui.game.trim()].into_iter().filter(|s| !s.is_empty()).collect(); - (!lines.is_empty()).then(|| lines.join("\n")) -} - -/// The stream's name: the title, and the game after it. TeamSpeak streams -/// have a name only, and the gateway's directory takes it from there. -pub fn stream_name(ui: &StudioUi) -> String { - match (ui.title.trim(), ui.game.trim()) { - (title, "") => title.to_owned(), - ("", game) => game.to_owned(), - (title, game) => format!("{title} — {game}"), - } -} - -fn file_name(what: &str) -> String { - format!("{what} {}.mkv", chrono::Local::now().format("%Y-%m-%d %H-%M-%S")) -} - -impl App { - /// The studio's settings (made once): its mixer's `stream.audio_sources` - /// are the share dialog's too. - pub(crate) fn studio_settings(&mut self) -> Settings { - let demo = self.demo_ui; - let prefs = &self.prefs; - self.studio - .settings - .get_or_insert_with(|| if demo { demo_settings() } else { prefs.clone() }) - .clone() - } - - fn studio_streamer(&self) -> Option<&Streamer> { - self.studio.run.as_ref()?.streamer.as_ref() - } - - /// The stream's layers for the engine: `stream.layers`, or the single - /// layer at [`studio_bitrate_kbps`](Self::studio_bitrate_kbps). - fn studio_session_layers(&self, settings: &Settings) -> Vec { - match layer_specs(&settings.get(&STREAM_LAYERS)) { - layers if layers.is_empty() => { - vec![LayerSpec::single(u64::from(self.studio_bitrate_kbps(settings)) * 1000)] - } - layers => layers, - } - } - - /// `stream.bitrate_kbps`, an automatic one (0) as it comes to for the - /// output's size and frame rate. - fn studio_bitrate_kbps(&self, settings: &Settings) -> u32 { - match settings.get(&STREAM_BITRATE_KBPS) { - 0 => { - let (width, height) = self.studio.scenes.size(); - let bitrate = auto_bitrate(width, height, self.studio.scenes.fps()); - u32::try_from(bitrate / 1000).unwrap_or(u32::MAX) - } - kbps => kbps, - } - } - - fn studio_op(&self, op: Op) { - if let Some(run) = &self.studio.run { - let _ = run.ops.send(op); - } - } - - /// `f` on the StudioBridge of the main window and of the studio window. - fn studio_each(&self, f: impl Fn(&StudioBridge)) { - if let Some(ui) = self.ui.upgrade() { - f(&ui.global::()); - } - if let Some(window) = &self.studio.window { - f(&window.global::()); - } - } - - /// The StudioNav of the window the studio is in. - fn studio_nav(&self, f: impl FnOnce(&StudioNav)) { - match (&self.studio.window, self.ui.upgrade()) { - (Some(window), _) => f(&window.global::()), - (None, Some(ui)) => f(&ui.global::()), - _ => {} - } - } - - fn studio_attach(&self, bridge: &StudioBridge) { - let m = &self.studio.models; - bridge.set_scenes(m.scenes.model()); - bridge.set_sources(m.sources.model()); - bridge.set_audio(m.audio.model()); - bridge.set_layers(m.layers.model()); - bridge.set_viewers(m.viewers.model()); - bridge.set_destinations(m.destinations.model()); - bridge.set_picks(m.picks.model()); - bridge.set_chat(m.chat.model()); - } - - /// Whether a studio page or window is on screen. - fn studio_shown(&self) -> bool { - self.studio.window.is_some() - || self.ui.upgrade().is_some_and(|ui| ui.global::