From 0acc5349544ce833a7fa13d454776f09039f0b22 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 07:07:12 +0300 Subject: [PATCH] voelin-ui: drive the Stream Studio from the engine The studio screens now run on the engine's studio: scenes and sources are its scene graph (switch, add, rename, remove, reorder, show, lock, transform, crop, opacity, background effect), the preview is its preview tap turned into pictures on a thread of its own (latest wins, so a busy UI skips frames instead of holding up the composite), and a Streamer started for it encodes the composite from the start, so Record Clip and recordings work before going live. Going live starts a TeamSpeak stream in our voice channel and attaches that streamer to it, then tells the studio; viewers, requests and the connection quality (the viewers' bandwidth estimates and the composed frame rate) show in the header. The audio mixer is stream.audio_sources with the mixer's meters, read lock-free about 15 times a second; a gain drag goes to the mixer at once and is stored at the end. The stream settings are a new studio.ui key; title, game and go-live message, and three switches that keep overlay text sources (viewer count, chat, now playing) in the live scene. The game goes into the stream's name, which is all a TeamSpeak stream has and what the gateway's directory shows. Layers, bitrate and output size are the stream.* and studio.* keys, followed while streaming. The detached window has its own globals; the same models are set on both and both are wired to this controller. With VOELIN_DEMO_UI the studio runs from synthetic sources and tones on settings in memory, and VOELIN_OPEN=studio[:window|live|record|] opens each state for screenshots, which now also capture the studio's window. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-ui/src/app.rs | 11 + crates/voelin-ui/src/appearance.rs | 1 + crates/voelin-ui/src/bind/mod.rs | 6 +- crates/voelin-ui/src/bind/studio.rs | 137 ++ crates/voelin-ui/src/dev.rs | 44 +- crates/voelin-ui/src/lib.rs | 1 + crates/voelin-ui/src/studio.rs | 2044 +++++++++++++++++ crates/voelin-ui/src/video.rs | 42 +- crates/voelin-ui/src/vm/mod.rs | 1 + crates/voelin-ui/src/vm/studio.rs | 727 ++++++ .../voelin-ui/ui/screens/studio-parts.slint | 4 +- crates/voelin-ui/ui/studio-bridge.slint | 3 - 12 files changed, 3011 insertions(+), 10 deletions(-) create mode 100644 crates/voelin-ui/src/bind/studio.rs create mode 100644 crates/voelin-ui/src/studio.rs create mode 100644 crates/voelin-ui/src/vm/studio.rs diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 578b06d..6e52435 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -48,6 +48,7 @@ fn open_settings(dir: &Path, overrides: &[String]) -> Settings { for key in appearance_keys() { prefs.register(key); } + prefs.register(&crate::studio::STUDIO_UI); let config = std::env::var_os("VOELIN_CONFIG") .map(PathBuf::from) .or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists())); @@ -260,6 +261,8 @@ pub(crate) struct App { pub open_client_pending: bool, /// The notices are in the About page's model. pub notices_loaded: bool, + /// The Stream Studio (studio.rs). + pub studio: crate::studio::StudioState, } thread_local! { @@ -443,6 +446,7 @@ pub fn run(options: RunOptions) -> Result<()> { autoshare: switches.autoshare, open_client_pending: switches.open_client, notices_loaded: false, + studio: Default::default(), }; APP.with(|a| *a.borrow_mut() = Some(app)); crate::bind::wire(&ui); @@ -670,6 +674,13 @@ impl App { Event::SettingRejected { key, message } => { self.set_status(format!("Setting {key}: {message}")); } + // The Stream Studio's stream (studio.rs). + Event::StreamState { session, state } if self.studio_streams_to(session as i64) => { + self.studio_stream_state(state); + } + Event::StreamViewers { session, viewers } if self.studio_streams_to(session as i64) => { + self.studio_viewers(viewers); + } event => self.stream_event(event), } } diff --git a/crates/voelin-ui/src/appearance.rs b/crates/voelin-ui/src/appearance.rs index 8f82162..ac4cc5f 100644 --- a/crates/voelin-ui/src/appearance.rs +++ b/crates/voelin-ui/src/appearance.rs @@ -32,6 +32,7 @@ impl App { image_cache_mb: cache_mb as f32, }); bridge.set_image_cache_usage(images::usage_text().into()); + self.studio_theme(); } /// The settings page changed the form: store the keys (they apply diff --git a/crates/voelin-ui/src/bind/mod.rs b/crates/voelin-ui/src/bind/mod.rs index 8537548..92ff348 100644 --- a/crates/voelin-ui/src/bind/mod.rs +++ b/crates/voelin-ui/src/bind/mod.rs @@ -6,8 +6,11 @@ mod emoji; mod servers; mod settings; mod streams; +pub(crate) mod studio; -use crate::app::MainWindow; +use slint::ComponentHandle; + +use crate::app::{MainWindow, StudioBridge}; /// Connect every callback of the window. pub(crate) fn wire(ui: &MainWindow) { @@ -16,4 +19,5 @@ pub(crate) fn wire(ui: &MainWindow) { streams::wire(ui); settings::wire(ui); emoji::wire(ui); + studio::wire(&ui.global::()); } diff --git a/crates/voelin-ui/src/bind/studio.rs b/crates/voelin-ui/src/bind/studio.rs new file mode 100644 index 0000000..1d3a0c1 --- /dev/null +++ b/crates/voelin-ui/src/bind/studio.rs @@ -0,0 +1,137 @@ +//! The Stream Studio's callbacks, for the main window and for the studio's +//! own window (each has its own StudioBridge global). + +use voelin_core::studio::Command; + +use crate::app::{StudioBridge, with_app}; + +/// Slint ids are ints; the studio's are u64. +fn id(value: i32) -> u64 { + u64::try_from(value).unwrap_or(u64::MAX) +} + +fn index(value: i32) -> usize { + usize::try_from(value).unwrap_or(usize::MAX) +} + +pub(crate) fn wire(bridge: &StudioBridge) { + // From a page's init: run it after the page is built, outside of Slint's + // update. + bridge.on_open(|| { + let _ = slint::invoke_from_event_loop(|| { + with_app(|app| app.studio_open()); + }); + }); + bridge.on_detach(|| { + with_app(|app| app.studio_detach()); + }); + bridge.on_dock(|| { + with_app(|app| app.studio_dock()); + }); + + bridge.on_select_scene(|scene| { + with_app(|app| app.studio_scene_command(Command::SetActiveScene { scene: id(scene) })); + }); + bridge.on_add_scene(|| { + with_app(|app| app.studio_add_scene()); + }); + bridge.on_rename_scene(|scene, name| { + let name = name.trim().to_owned(); + if !name.is_empty() { + with_app(|app| { + app.studio_scene_command(Command::RenameScene { scene: id(scene), name }) + }); + } + }); + bridge.on_remove_scene(|scene| { + with_app(|app| app.studio_scene_command(Command::RemoveScene { scene: id(scene) })); + }); + + bridge.on_list_sources(|kind| with_app(|app| app.studio_list_sources(&kind)).unwrap_or(false)); + bridge.on_add_picked(|_, i| { + with_app(|app| app.studio_add_picked(index(i))); + }); + bridge.on_add_source(|form| { + with_app(|app| app.studio_add_source(&form)); + }); + bridge.on_source_form(|source| { + with_app(|app| app.studio_source_form(id(source))).unwrap_or_default() + }); + bridge.on_apply_source(|form| { + with_app(|app| app.studio_apply_source(&form)); + }); + bridge.on_toggle_source(|source| { + with_app(|app| app.studio_toggle_source(id(source))); + }); + bridge.on_source_action(|source, action| { + with_app(|app| app.studio_source_action(id(source), &action)); + }); + bridge.on_main_source(|kind| { + with_app(|app| app.studio_main_source(&kind)); + }); + + bridge.on_list_audio(|| { + with_app(|app| app.studio_list_audio()); + }); + bridge.on_add_audio(|i| { + with_app(|app| app.studio_add_audio(index(i))); + }); + bridge.on_set_gain(|i, db, done| { + with_app(|app| app.studio_set_gain(index(i), db, done)); + }); + bridge.on_toggle_mute(|i| { + with_app(|app| app.studio_toggle_mute(index(i))); + }); + bridge.on_remove_audio(|i| { + with_app(|app| app.studio_remove_audio(index(i))); + }); + + bridge.on_edit_form(|key, value| { + with_app(|app| app.studio_edit(&key, &value)); + }); + bridge.on_set_output(|w, h, fps| { + with_app(|app| app.studio_set_output(&w, &h, &fps)); + }); + bridge.on_set_layer(|i, layer| { + with_app(|app| app.studio_set_layer(index(i), &layer)); + }); + bridge.on_add_layer(|| { + with_app(|app| app.studio_add_layer()); + }); + bridge.on_remove_layer(|i| { + with_app(|app| app.studio_remove_layer(index(i))); + }); + bridge.on_advanced_settings(|| { + with_app(|app| app.studio_advanced()); + }); + + bridge.on_save_clip(|| { + with_app(|app| app.studio_save_clip()); + }); + bridge.on_toggle_recording(|| { + with_app(|app| app.studio_toggle_recording()); + }); + bridge.on_open_recordings(|| { + with_app(|app| app.studio_open_recordings()); + }); + bridge.on_go_live(|| { + with_app(|app| app.studio_go_live()); + }); + bridge.on_end_stream(|| { + with_app(|app| app.studio_end()); + }); + bridge.on_settings_form(|| with_app(|app| app.studio_settings_form()).unwrap_or_default()); + bridge.on_apply_settings(|form| { + with_app(|app| app.studio_apply_settings(&form)); + }); + + bridge.on_respond_viewer(|client, accept| { + with_app(|app| app.studio_respond_viewer(u16::try_from(client).unwrap_or(0), accept)); + }); + bridge.on_send_chat(|text| { + with_app(|app| app.studio_send_chat(text.to_string())); + }); + bridge.on_open_chat(|| { + with_app(|app| app.studio_open_chat()); + }); +} diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index af1832e..f532bfe 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -15,7 +15,13 @@ //! appearance, or 0-4), `about`, `share`, `bookmark` (add a server), //! `emoji` (the picker), `client` (the volume dialog of the first other //! client once connected), `panel` / `no-panel` (the right panel), -//! `tab:` (phone layout). +//! `tab:` (phone layout), +//! `studio[:]`: the Stream Studio (with `VOELIN_DEMO_UI` a demo +//! studio from synthetic sources), `studio:window` in a window of its own, +//! `studio:live` going live, `studio:record`, or a dialog: `studio:source`, +//! `studio:audio`, `studio:camera`, `studio:scene`, `studio:settings`. +//! A screenshot also saves the studio's window (`-window.png`) and +//! draws it over the main window. //! - `VOELIN_AUTOWATCH=1`: watch the first stream that shows up. //! - `VOELIN_AUTOSHARE=test-pattern`: share the test pattern (accepting //! everyone) once connected to a TeamSpeak 6 server. @@ -24,7 +30,7 @@ use std::sync::Arc; use std::time::Duration; use anyhow::Result; -use slint::ComponentHandle; +use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer}; use voelin_core::stream::{StreamInfo, StreamKind}; use voelin_core::{Event, ObserveState, SessionState, Source, VoiceState}; use voelin_model::{ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerFlavor}; @@ -137,6 +143,12 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { "panel" => nav.set_right_panel_open(true), "no-panel" => nav.set_right_panel_open(false), "tab" => nav.set_mobile_tab(mobile_tab(arg)), + "studio" => { + if arg != "window" { + nav.invoke_open_studio(); + } + with_app(|app| app.studio_dev(arg)); + } // Opened once connected (settings_page.rs). "client" => {} other => eprintln!("VOELIN_OPEN: unknown screen {other:?}"), @@ -163,7 +175,33 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { } fn save_screenshot(ui: &MainWindow, path: &std::path::Path) -> Result<()> { - let image = ui.window().take_snapshot()?; + let mut image = ui.window().take_snapshot()?; + if let Some(studio) = with_app(|app| app.studio_snapshot()).flatten() { + let stem = path.file_stem().unwrap_or_default().to_string_lossy(); + save_png(&studio, &path.with_file_name(format!("{stem}-window.png")))?; + paste(&mut image, &studio); + } + save_png(&image, path) +} + +/// Draw `top` over the bottom right of `image` with a border, as a second +/// window sits on a desktop. +fn paste(image: &mut SharedPixelBuffer, top: &SharedPixelBuffer) { + let (w, h) = (image.width() as usize, image.height() as usize); + let (tw, th) = (top.width() as usize, top.height() as usize); + let (x0, y0) = (w.saturating_sub(tw + 24), h.saturating_sub(th + 24)); + let border = Rgba8Pixel { r: 0x3f, g: 0x7b, b: 0xff, a: 0xff }; + let pixels = image.make_mut_slice(); + for y in y0.saturating_sub(1)..(y0 + th + 1).min(h) { + for x in x0.saturating_sub(1)..(x0 + tw + 1).min(w) { + let (ty, tx) = (y.wrapping_sub(y0), x.wrapping_sub(x0)); + pixels[y * w + x] = + if ty < th && tx < tw { top.as_slice()[ty * tw + tx] } else { border }; + } + } +} + +fn save_png(image: &SharedPixelBuffer, path: &std::path::Path) -> Result<()> { let file = std::io::BufWriter::new(std::fs::File::create(path)?); let mut encoder = png::Encoder::new(file, image.width(), image.height()); encoder.set_color(png::ColorType::Rgba); diff --git a/crates/voelin-ui/src/lib.rs b/crates/voelin-ui/src/lib.rs index d6e2eab..0a72f7b 100644 --- a/crates/voelin-ui/src/lib.rs +++ b/crates/voelin-ui/src/lib.rs @@ -12,6 +12,7 @@ mod servers; mod settings; mod settings_page; mod streams; +mod studio; mod video; mod vm; diff --git a/crates/voelin-ui/src/studio.rs b/crates/voelin-ui/src/studio.rs new file mode 100644 index 0000000..b80a82b --- /dev/null +++ b/crates/voelin-ui/src/studio.rs @@ -0,0 +1,2044 @@ +//! 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 +//! VecModels) 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::PathBuf; +use std::rc::Rc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Weak}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use slint::{ + ComponentHandle, Model, ModelRc, Rgba8Pixel, SharedPixelBuffer, SharedString, VecModel, +}; +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, Latest, Streamer, StreamerConfigUpdate, StreamerStats, audio_apps, + audio_source_specs, 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, StreamSetup, ViewerInfo, ViewerState}; +use voelin_core::studio::scene::{ + Align, Background, Colour, Fit, Scene, Scenes, Source, SourceKind, Transform, +}; +use voelin_core::studio::{self, SourceChange, Stats, Status, Studio, camera}; +use voelin_core::{Command, StreamState}; +use voelin_model::{ChatMessage, ChatTarget}; + +use crate::app::{ + App, ChatLine, Nav, Page, StudioAudio, StudioBridge, StudioForm, StudioLayer, StudioNav, + StudioPick, StudioScene, StudioSettingsForm, StudioSource, StudioSourceForm, StudioStatus, + StudioViewer, StudioWindow, Tab, Theme, later, with_app, +}; +use crate::settings::parse_positive; +use crate::video::CaptureRequest; +use crate::vm; +use crate::vm::studio::{OVERLAY_CHAT, OVERLAY_NOW_PLAYING, OVERLAY_VIEWERS, Overlay}; + +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: Rc>, + sources: Rc>, + audio: Rc>, + layers: Rc>, + viewers: Rc>, + destinations: Rc>, + picks: Rc>, + /// The chat while there is no destination. + no_chat: Rc>, +} + +/// 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. + 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 }; + main.sources = vec![ + source( + 1, + "Game Capture", + SourceKind::Pattern { size: (1280, 720) }, + Transform { fit: Fit::Cover, ..Transform::full(1920, 1080) }, + ), + 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). + 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() + } + + 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(ModelRc::from(m.scenes.clone())); + bridge.set_sources(ModelRc::from(m.sources.clone())); + bridge.set_audio(ModelRc::from(m.audio.clone())); + bridge.set_layers(ModelRc::from(m.layers.clone())); + bridge.set_viewers(ModelRc::from(m.viewers.clone())); + bridge.set_destinations(ModelRc::from(m.destinations.clone())); + bridge.set_picks(ModelRc::from(m.picks.clone())); + bridge.set_chat(ModelRc::from(m.no_chat.clone())); + } + + /// 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::