//! The Stream Studio on the Slint windows: running the engine's studio (its //! tasks, the preview, the encoder), putting the rows and values on both //! windows' StudioBridge, and the commands the controls send. What is //! decided is `voelin_ui_vm::studio::logic`. use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Weak}; use std::time::Duration; 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::handoff::Handoff; use voelin_core::media::voelin_media::{VideoFrame, convert}; use voelin_core::media::{ AudioApps, AudioSourceStats, Latest, Streamer, StreamerConfigUpdate, audio_apps, audio_source_specs, screen_sources, }; use voelin_core::settings::{ AudioSourceSetting, STREAM_AUDIO_SOURCES, STREAM_BITRATE_KBPS, STREAM_LAYERS, STUDIO_REPLAY_SECONDS, STUDIO_SCENES, Settings, layer_specs, }; use voelin_core::stream::{EndReason, LayerSpec, ViewerInfo, ViewerState}; use voelin_core::studio::scene::Source; use voelin_core::studio::{self, SourceChange, Studio, camera}; use voelin_core::{Command, HistorySource, StreamState}; use voelin_model::ChatTarget; use super::{Op, Picture, Running}; use crate::app::{App, Nav, Page, StudioBridge, StudioNav, StudioWindow, later, with_app}; use crate::video::CaptureRequest; use crate::vm; use crate::vm::bridge::ChatLine; use crate::vm::studio::logic::{self, Outgoing, Pick, STUDIO_UI, StudioUi}; use crate::vm::studio_bridge::{StudioLayer, StudioPick, StudioSettingsForm, StudioSourceForm}; /// 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(source) => { let mut scenes = studio.scenes(); logic::add_to_live_scene(&mut scenes, 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}"); } } 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 .data .settings .get_or_insert_with(|| { if demo { let (settings, problems) = logic::demo_settings(); for problem in problems { warn!("demo studio: {problem}"); } 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 { self.studio.data.session_layers(settings) } /// `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 { self.studio.data.bitrate_kbps(settings) } 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::