//! 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::