diff --git a/crates/voelin-media/src/studio/mod.rs b/crates/voelin-media/src/studio/mod.rs index 3ed24fb..b444c58 100644 --- a/crates/voelin-media/src/studio/mod.rs +++ b/crates/voelin-media/src/studio/mod.rs @@ -798,8 +798,10 @@ impl Studio { wanted.iter().any(|(w, kind, background)| { w == id && input.kind().same_input(kind) - // A background filter is set up when the input starts. - && input.background().needs_mask() == background.needs_mask() + // A background filter is set up when the input starts, + // with the effect it applies: another effect (or + // strength, image, colour) needs a new input. + && input.background() == background }) }); } @@ -1196,6 +1198,25 @@ mod tests { assert!(studio.apply(Command::RenameScene { scene: 99, name: "x".into() }).await.is_err()); } + #[tokio::test] + async fn a_new_background_effect_reaches_the_input() { + let studio = Studio::start(one_colour_scene()).await.unwrap(); + for background in [ + Background::Blur { strength: 0.02 }, + Background::Blur { strength: 0.08 }, + Background::Colour { colour: Colour::rgb(0, 200, 0) }, + Background::Keep, + ] { + let change = + SourceChange { background: Some(background.clone()), ..Default::default() }; + let command = Command::UpdateSource { scene: 1, source: 1, change: Box::new(change) }; + studio.apply(command).await.unwrap(); + let graph = lock(&studio.graph); + assert_eq!(graph.inputs.len(), 1); + assert_eq!(graph.inputs[0].1.background(), &background); + } + } + #[tokio::test] async fn go_live_and_recording_change_the_status() { let studio = Studio::start(one_colour_scene()).await.unwrap(); diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index cab0dc7..fc42ae1 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -50,6 +50,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())); @@ -389,6 +390,8 @@ pub(crate) struct App { /// Files being uploaded to a channel from the composer: session, /// channel and name, so the link can be posted when they are up. pub uploads: HashMap, + /// The Stream Studio (studio.rs). + pub studio: crate::studio::StudioState, } thread_local! { @@ -583,6 +586,7 @@ pub fn run(options: RunOptions) -> Result<()> { open_client_pending: switches.open_client, notices_loaded: false, uploads: HashMap::new(), + studio: Default::default(), }; APP.with(|a| *a.borrow_mut() = Some(app)); crate::bind::wire(&ui); @@ -852,6 +856,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 ca53583..93d329b 100644 --- a/crates/voelin-ui/src/appearance.rs +++ b/crates/voelin-ui/src/appearance.rs @@ -37,6 +37,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/chat.rs b/crates/voelin-ui/src/chat.rs index b275dc8..57fa9fc 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -170,6 +170,7 @@ impl App { if !shown { self.refresh_servers(); } + self.studio_chat_changed(id, &message.target); } /// Messages the engine stored: added or updated by their local id. @@ -218,6 +219,7 @@ impl App { if fresh > 0 && !shown { self.refresh_servers(); } + self.studio_chat_changed(id, target); } /// The page of messages before the oldest one shown. @@ -235,8 +237,14 @@ impl App { self.refresh_chat(); } - /// The lines of a tab, grouped and with everything the row shows. - fn lines_of(&self, view: &SessionView, tab: &Tab, messages: &[Msg]) -> Vec { + /// The lines of a tab, grouped and with everything the row shows (also + /// the stream chat of the Stream Studio, studio.rs). + pub(crate) fn lines_of( + &self, + view: &SessionView, + tab: &Tab, + messages: &[Msg], + ) -> Vec { let gateway = view.gateway_has(feature::PINS) || view.gateway_has(feature::REACTIONS) || view.gateway_has(feature::TOPICS); diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index eff4253..8ae1142 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -19,7 +19,13 @@ //! `topic:` (a topic's messages), `member` (the member card of the //! first other client), `watch` (the first stream; with sample data the //! local test pattern in its place), `popout` (the same, popped out), -//! `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. @@ -28,7 +34,7 @@ use std::sync::Arc; use std::time::Duration; use anyhow::Result; -use slint::ComponentHandle; +use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer}; use voelin_core::gateway::Pin; use voelin_core::stream::{StreamInfo, StreamKind}; use voelin_core::{ @@ -170,6 +176,12 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { }); ui.global::().set_viewer_popped(what == "popout"); } + "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:?}"), @@ -204,6 +216,8 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { eprintln!("screenshot failed: {e}"); } let _ = ui.hide(); + // Also when the studio's own window is open. + let _ = slint::quit_event_loop(); } }, ); @@ -213,7 +227,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 14ce7be..f8bb4ce 100644 --- a/crates/voelin-ui/src/lib.rs +++ b/crates/voelin-ui/src/lib.rs @@ -13,6 +13,7 @@ mod servers; mod settings; mod settings_page; mod streams; +mod studio; mod video; mod vm; diff --git a/crates/voelin-ui/src/streams.rs b/crates/voelin-ui/src/streams.rs index 1941fee..013e608 100644 --- a/crates/voelin-ui/src/streams.rs +++ b/crates/voelin-ui/src/streams.rs @@ -474,6 +474,11 @@ impl App { if self.share_busy || self.share.is_some() { return; } + if self.studio_streams_to(session) { + self.share_error = "The Stream Studio is live here: end that stream first.".into(); + self.refresh_streams(); + return; + } // Typed values (no maximum), else the chosen presets. let choice = |i: i32, choices: &[u32]| { choices[usize::try_from(i).unwrap_or(0).min(choices.len() - 1)] diff --git a/crates/voelin-ui/src/studio.rs b/crates/voelin-ui/src/studio.rs new file mode 100644 index 0000000..c18d396 --- /dev/null +++ b/crates/voelin-ui/src/studio.rs @@ -0,0 +1,2095 @@ +//! 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, 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, HistoryMessage, HistorySource, StreamState}; +use voelin_model::{ChatMessage, ChatTarget}; +use voelin_store::MessageSource; + +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 destination channel's chat (`studio_sync_chat`). + 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.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::