diff --git a/crates/voelin-media/src/capture/mod.rs b/crates/voelin-media/src/capture/mod.rs index 7f4863e..2dbc3aa 100644 --- a/crates/voelin-media/src/capture/mod.rs +++ b/crates/voelin-media/src/capture/mod.rs @@ -60,6 +60,8 @@ pub enum SourceId { Portal, /// The synthetic test pattern. Synthetic, + /// The Stream Studio's composite ([`crate::studio::StudioCapture`]). + Studio, } /// A source as shown in a picker. diff --git a/crates/voelin-media/src/studio/camera.rs b/crates/voelin-media/src/studio/camera.rs index ba1c210..62c8467 100644 --- a/crates/voelin-media/src/studio/camera.rs +++ b/crates/voelin-media/src/studio/camera.rs @@ -29,6 +29,8 @@ use crate::Result; use crate::capture::synthetic::SyntheticScreen; use crate::capture::{CaptureOptions, ScreenCapture, SourceId}; use crate::studio::compose::Feed; +use crate::studio::scene::Background; +use crate::studio::segment::BackgroundFilter; use crate::studio::source::FeedSink; /// The id of the camera that is always available: the test pattern. @@ -147,6 +149,7 @@ impl Capture { size: Option<(u32, u32)>, fps: u32, feed: Arc, + background: Background, ) -> Result { let fps = fps.max(1); let wanted = match device.trim() { @@ -160,8 +163,12 @@ impl Capture { let (w, h) = size.unwrap_or((1280, 720)); let mut screen = SyntheticScreen::new(w.max(2), h.max(2)); let options = CaptureOptions { fps, cursor: false, ..CaptureOptions::default() }; - let sink = Box::new(FeedSink::new(feed, Arc::new(AtomicU32::new(fps)))); - screen.start_sink(&SourceId::Synthetic, &options, sink).await?; + let mut sink = FeedSink::new(feed, Arc::new(AtomicU32::new(fps))); + if background.needs_mask() { + sink = sink + .with_background(BackgroundFilter::with_default_segmenter(background.clone())); + } + screen.start_sink(&SourceId::Synthetic, &options, Box::new(sink)).await?; return Ok(Self { backend: "synthetic", device: wanted, @@ -172,13 +179,14 @@ impl Capture { } #[cfg(all(target_os = "linux", feature = "pipewire"))] { - let stream = pipewire_camera::Stream::start(&wanted, size, fps, feed).await?; + let stream = + pipewire_camera::Stream::start(&wanted, size, fps, feed, background).await?; debug!(device = %wanted, "camera through PipeWire"); Ok(Self { backend: "pipewire", device: wanted, screen: None, stream: Some(stream) }) } #[cfg(not(all(target_os = "linux", feature = "pipewire")))] { - let _ = (size, feed); + let _ = (size, feed, background); Err(crate::Error::CaptureUnavailable { backend: BACKEND, reason: format!("no camera backend for {wanted:?} in this build"), @@ -472,6 +480,8 @@ mod pipewire_camera { use crate::frame::{FrameRef, PixelsRef, PlaneRef}; use crate::pool::FramePool; use crate::studio::compose::Feed; + use crate::studio::scene::Background; + use crate::studio::segment::BackgroundFilter; use crate::studio::source::deliver; use crate::{Error, Result}; @@ -503,16 +513,17 @@ mod pipewire_camera { size: Option<(u32, u32)>, fps: u32, feed: Arc, + background: Background, ) -> Result { // The daemon first: it needs no dialog. A sandbox refuses it, and // then the portal's connection is the only way in. - let direct = connect(None, device, size, fps, feed.clone()); + let direct = connect(None, device, size, fps, feed.clone(), background.clone()); match direct { Ok(thread) => Ok(Self { backend: "pipewire", _thread: thread }), Err(direct) => { debug!("PipeWire cameras: {direct}; asking the camera portal"); let fd = portal_fd().await?; - let thread = connect(Some(fd), device, size, fps, feed)?; + let thread = connect(Some(fd), device, size, fps, feed, background)?; Ok(Self { backend: "portal", _thread: thread }) } } @@ -555,19 +566,21 @@ mod pipewire_camera { size: Option<(u32, u32)>, fps: u32, feed: Arc, + background: Background, ) -> Result { let device = device.to_owned(); PwThread::spawn("voelin-camera", fd, move |core, mainloop| { // No target node: the session manager connects the stream to the // default camera. Picking one of several by `api.v4l2.path` // needs a registry round trip and is not done yet. - camera_stream(core, mainloop, None, &device, size, fps, feed) + camera_stream(core, mainloop, None, &device, size, fps, feed, background) }) .map_err(|e| Error::Capture { backend: BACKEND, message: e }) } struct State { feed: Arc, + filter: Option, pool: FramePool, pacer: FramePacer, started: Instant, @@ -586,6 +599,7 @@ mod pipewire_camera { size: Option<(u32, u32)>, fps: u32, feed: Arc, + background: Background, ) -> std::result::Result { let props = pw::properties::properties! { *pw::keys::MEDIA_TYPE => "Video", @@ -596,6 +610,9 @@ mod pipewire_camera { .map_err(|e| format!("PipeWire stream: {e}"))?; let state = State { feed, + filter: background + .needs_mask() + .then(|| BackgroundFilter::with_default_segmenter(background)), pool: FramePool::new(), pacer: FramePacer::new(Some(fps)), started: Instant::now(), @@ -795,7 +812,7 @@ mod pipewire_camera { other => return packed(state, other, width, height, stride, bytes, timestamp), }; let frame = FrameRef { width, height, timestamp, pixels }; - deliver(&mut state.pool, &state.feed, &frame) + deliver(&mut state.pool, &state.feed, &frame, state.filter.as_mut()) } /// YUY2 / UYVY / RGB / BGR straight into a pooled RGBA frame. @@ -868,6 +885,9 @@ mod pipewire_camera { } } } + if let Some(filter) = state.filter.as_mut() { + filter.apply(target)?; + } state.feed.put(slot.clone()); Ok(()) } @@ -931,7 +951,8 @@ mod tests { panic!("no camera on this machine"); }; let feed = Arc::new(Feed::new()); - let capture = Capture::start(&camera.id, None, 15, feed.clone()).await.unwrap(); + let capture = + Capture::start(&camera.id, None, 15, feed.clone(), Background::Keep).await.unwrap(); let started = std::time::Instant::now(); while feed.delivered() < 3 && started.elapsed() < Duration::from_secs(20) { tokio::time::sleep(Duration::from_millis(50)).await; @@ -953,7 +974,9 @@ mod tests { #[tokio::test] async fn the_synthetic_camera_delivers() { let feed = Arc::new(Feed::new()); - let capture = Capture::start(SYNTHETIC, Some((64, 48)), 30, feed.clone()).await.unwrap(); + let capture = Capture::start(SYNTHETIC, Some((64, 48)), 30, feed.clone(), Background::Keep) + .await + .unwrap(); assert_eq!(capture.backend(), "synthetic"); assert_eq!(capture.device(), SYNTHETIC); let started = std::time::Instant::now(); diff --git a/crates/voelin-media/src/studio/mod.rs b/crates/voelin-media/src/studio/mod.rs index 19fd5de..44c46cf 100644 --- a/crates/voelin-media/src/studio/mod.rs +++ b/crates/voelin-media/src/studio/mod.rs @@ -8,11 +8,1267 @@ //! - [`source`]: the live input behind each of a scene's sources (colour, //! text, image, screen, window, camera) //! - [`camera`]: listing and capturing cameras +//! - [`segment`]: person segmentation and background blur //! - [`output`]: what the encoded packets go to besides the stream //! (recording, the replay buffer, WHIP) +//! +//! [`Studio`] ties them together and is what a UI drives: one +//! [`Command`] per thing a person can do, a stream of [`Event`]s back, and a +//! preview tap ([`Studio::preview`]) the UI reads at its own size and rate. +//! +//! # How it runs +//! +//! Each source runs on its own thread and publishes into a +//! [`compose::Feed`]. One compose thread ticks at the output frame rate, +//! draws the live scene into a pooled frame, offers it to the preview tap and +//! hands it to whatever [`crate::capture::FrameSink`] is attached — the +//! streamer's, through [`StudioCapture`], which is an ordinary +//! [`crate::ScreenCapture`] backend. So the studio needs nothing new of the +//! encoders, of simulcast or of the peers: it is just another screen source. +//! +//! Encoded packets come back the other way through [`Studio::write_packet`], +//! which tees them to every [`output::OutputSink`]. Recording and the replay +//! buffer therefore work with no stream live at all. +//! +//! Everything is changeable while running, and nothing is capped: any number +//! of scenes, sources and outputs, and a replay window limited only by the +//! setting. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use tokio::sync::broadcast; +use tracing::{debug, warn}; + +use crate::capture::{ + BoxFuture, CaptureOptions, CaptureSource, FrameSink, ScreenCapture, SourceId, +}; +use crate::codec::Codec; +use crate::frame::VideoFrame; +use crate::handoff::Handoff; +use crate::studio::compose::{ComposeStats, Compositor, Feed, RgbaScaler}; +use crate::studio::output::replay::{ReplayBuffer, ReplayStats}; +use crate::studio::output::{OutputSink, Packet, Track}; +use crate::studio::scene::{Background, Crop, Scene, Scenes, Source, SourceKind, Transform}; +use crate::studio::source::Input; +use crate::{Error, Result}; pub mod camera; pub mod compose; pub mod output; pub mod scene; +pub mod segment; pub mod source; + +/// Events buffered per subscriber before the oldest is dropped. +const EVENTS: usize = 256; +/// How long the compose thread waits before checking whether to stop. +const POLL: Duration = Duration::from_millis(100); + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// What a source's transform, crop, opacity or background should become; +/// `None` leaves it alone. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SourceChange { + pub name: Option, + pub kind: Option, + pub transform: Option, + pub crop: Option, + pub opacity: Option, + pub visible: Option, + pub locked: Option, + pub background: Option, +} + +/// An output to add ([`Command::AddOutput`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum OutputSpec { + /// Record to a file; the name decides WebM or Matroska. + Record { path: PathBuf }, + /// WHIP (or RTMP, which says it is not implemented yet). + Url { url: String, token: Option }, +} + +/// What a UI asks the studio to do. Everything takes effect from the next +/// composed frame. +#[derive(Clone, Debug, PartialEq)] +pub enum Command { + /// Replace the whole scene graph (loading a scene file, or the + /// `studio.scenes` setting). + SetScenes(Box), + /// A new, empty scene; the reply event carries its id. + AddScene { + name: String, + }, + RemoveScene { + scene: u64, + }, + RenameScene { + scene: u64, + name: String, + }, + /// Switch what is composited, live. + SetActiveScene { + scene: u64, + }, + /// Output size and frame rate of the composite. + SetOutput { + width: u32, + height: u32, + fps: u32, + }, + + AddSource { + scene: u64, + name: String, + kind: SourceKind, + }, + RemoveSource { + scene: u64, + source: u64, + }, + UpdateSource { + scene: u64, + source: u64, + change: Box, + }, + /// Move a source to position `to` in the scene's order (0 is furthest + /// back). + ReorderSource { + scene: u64, + source: u64, + to: usize, + }, + + /// Size and rate of the downscaled preview the UI reads. + SetPreview { + width: u32, + height: u32, + fps: u32, + }, + + StartRecording { + path: PathBuf, + }, + StopRecording, + /// Window and memory limit of the replay buffer; 0 seconds turns it off. + SetReplay { + seconds: u32, + memory_mb: u64, + }, + /// Write what the replay buffer holds. + SaveClip { + path: PathBuf, + }, + + AddOutput(OutputSpec), + RemoveOutput { + id: u64, + }, + + /// Start the outputs that push somewhere and report [`State::Live`]; the + /// TeamSpeak stream itself is started by the engine around the studio. + GoLive, + /// Stop them again. Recording and the replay buffer keep running. + EndStream, +} + +/// Where the studio is. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum State { + /// Composing, nothing pushed out. + #[default] + Idle, + Live, +} + +/// The studio's own idea of what it is doing, for the UI's header (LIVE, the +/// timer, REC). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Status { + pub state: State, + /// How long it has been live. + pub live_for: Duration, + pub recording: Option, + pub recorded_for: Duration, + pub active_scene: u64, + pub output: (u32, u32), + pub fps: u32, + /// Outputs that are pushing (WHIP; not the recording). + pub outputs: usize, +} + +/// One source in [`Stats`]. Rates are over the last second. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SourceStats { + pub id: u64, + pub label: String, + pub kind: &'static str, + pub width: u32, + pub height: u32, + pub frames: u64, + pub fps: f64, + /// Frames the source produced that the composite never used. + pub dropped: u64, + pub error: Option, +} + +/// One output in [`Stats`]. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct OutputStats { + pub id: u64, + pub name: String, + pub bytes: u64, + pub kbps: f64, + pub error: Option, +} + +/// What the studio has done. Rates are over the last second. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Stats { + pub status: Status, + pub compose: ComposeStats, + /// Composed frames a second. + pub fps: f64, + pub sources: Vec, + pub outputs: Vec, + pub replay: ReplayStats, + /// Frames the preview tap produced. + pub preview_frames: u64, + /// Frames handed to the streamer. + pub delivered: u64, +} + +/// What the studio tells its UI. +#[derive(Clone, Debug, PartialEq)] +pub enum Event { + /// Anything in [`Status`] changed. + State(Status), + /// Once a second. + Stats(Box), + /// The scene graph changed and should be persisted (`studio.scenes`). + Scenes(Arc), + /// A scene or source was created; its id, so a UI can select it. + SceneAdded { + scene: u64, + }, + SourceAdded { + scene: u64, + source: u64, + }, + RecordingStarted { + path: PathBuf, + }, + RecordingStopped { + path: PathBuf, + duration: Duration, + bytes: u64, + }, + ClipSaved { + path: PathBuf, + duration: Duration, + }, + OutputAdded { + id: u64, + name: String, + }, + OutputRemoved { + id: u64, + name: String, + }, + /// Something went wrong; the studio keeps going. + Error { + context: String, + message: String, + }, +} + +/// One output, with the id the UI removes it by. +struct Output { + id: u64, + sink: Box, + /// A recording's file (a sink only knows its own short name). + path: Option, + started: Instant, + /// Rate over the last second. + kbps: f64, + last_bytes: u64, + /// Pushes somewhere (counts towards [`Status::outputs`]). + pushes: bool, + error: Option, +} + +/// The scene the compose thread draws, published whenever anything changes. +struct Live { + scene: Scene, + /// One per `scene.sources`, in order. + feeds: Vec>>, + revision: u64, + size: (u32, u32), + fps: u32, +} + +impl Default for Live { + fn default() -> Self { + Self { + scene: Scene::new(0, ""), + feeds: Vec::new(), + revision: 0, + size: (1920, 1080), + fps: 30, + } + } +} + +/// State the threads share. +struct Shared { + live: Mutex>, + /// The streamer's sink, while it is capturing us. + sink: Mutex>>, + preview: Arc>, + preview_size: Mutex<(u32, u32)>, + preview_fps: AtomicU32, + preview_frames: AtomicU64, + delivered: AtomicU64, + stop: AtomicBool, + events: broadcast::Sender, + /// The outputs, and the replay buffer which is always there (off when its + /// window is zero). + outputs: Mutex>, + replay: Mutex, + /// Which layer the file outputs take. + layer: AtomicU32, + /// The codec of the last packet, which a WHIP output must offer. + codec: Mutex>, + compose: Mutex, + recording: Mutex>, + live_since: Mutex>, + state: Mutex, +} + +impl Shared { + fn stopped(&self) -> bool { + self.stop.load(Ordering::Relaxed) + } + + fn send(&self, event: Event) { + let _ = self.events.send(event); + } + + fn fail(&self, context: impl Into, message: impl std::fmt::Display) { + let (context, message) = (context.into(), message.to_string()); + warn!(context, "studio: {message}"); + self.send(Event::Error { context, message }); + } +} + +/// The studio engine; see the [module docs](self). Stops its threads when +/// dropped. +pub struct Studio { + shared: Arc, + /// The scene graph and the inputs behind it, which only the controller + /// touches. + graph: Mutex, + threads: Vec>, +} + +/// The controller's own state. +struct Graph { + scenes: Scenes, + /// The input of every source of the active scene, by source id. + inputs: Vec<(u64, Input)>, + revision: u64, + next_output: u64, + preview: (u32, u32, u32), +} + +impl Studio { + /// Start a studio for `scenes`, composing at once so a preview has + /// something to show before anything is live. + /// + /// Must run on a Tokio runtime: the portal and camera sources talk D-Bus. + pub async fn start(scenes: Scenes) -> Result { + scenes.check().map_err(Error::InvalidFrame)?; + let (events, _) = broadcast::channel(EVENTS); + let shared = Arc::new(Shared { + live: Mutex::new(Arc::new(Live { + size: scenes.size(), + fps: scenes.fps(), + ..Live::default() + })), + sink: Mutex::new(None), + preview: Arc::new(Handoff::new()), + preview_size: Mutex::new((480, 270)), + preview_fps: AtomicU32::new(15), + preview_frames: AtomicU64::new(0), + delivered: AtomicU64::new(0), + stop: AtomicBool::new(false), + events, + outputs: Mutex::new(Vec::new()), + replay: Mutex::new(ReplayBuffer::new(Duration::ZERO, 512, 0, 2)), + layer: AtomicU32::new(0), + codec: Mutex::new(None), + compose: Mutex::new(ComposeStats::default()), + recording: Mutex::new(None), + live_since: Mutex::new(None), + state: Mutex::new(State::Idle), + }); + let studio = Self { + shared: shared.clone(), + graph: Mutex::new(Graph { + scenes, + inputs: Vec::new(), + revision: 0, + next_output: 1, + preview: (480, 270, 15), + }), + threads: Vec::new(), + }; + studio.rebuild().await; + let mut studio = studio; + let compose = shared.clone(); + studio.threads.push( + std::thread::Builder::new() + .name("voelin-studio-compose".into()) + .spawn(move || compose_loop(&compose)) + .map_err(Error::Io)?, + ); + let stats = shared.clone(); + studio.threads.push( + std::thread::Builder::new() + .name("voelin-studio-stats".into()) + .spawn(move || stats_loop(&stats)) + .map_err(Error::Io)?, + ); + Ok(studio) + } + + /// Events for a UI. Late subscribers miss what happened before. + pub fn events(&self) -> broadcast::Receiver { + self.shared.events.subscribe() + } + + /// The preview tap: the newest downscaled RGBA frame, latest-wins. The + /// UI takes what it can and never blocks the composite. + pub fn preview(&self) -> Arc> { + self.shared.preview.clone() + } + + /// The scene graph as it stands, to persist or to show. + pub fn scenes(&self) -> Scenes { + lock(&self.graph).scenes.clone() + } + + pub fn status(&self) -> Status { + self.shared.status() + } + + /// The cameras that can be used as sources. + pub fn cameras(&self) -> Vec { + camera::list() + } + + /// Which simulcast layer the file outputs and WHIP take (the streamer's + /// layer ids). Default 0. + pub fn set_layer(&self, layer: u32) { + self.shared.layer.store(layer, Ordering::Relaxed); + } + + /// A [`ScreenCapture`] backend that hands the composite to the streamer. + pub fn capture(self: &Arc) -> StudioCapture { + StudioCapture { shared: self.shared.clone() } + } + + /// Do what `command` says. + pub async fn apply(&self, command: Command) -> Result<()> { + match command { + Command::SetScenes(scenes) => { + scenes.check().map_err(Error::InvalidFrame)?; + lock(&self.graph).scenes = *scenes; + } + Command::AddScene { name } => { + let mut graph = lock(&self.graph); + let id = graph.scenes.next_scene_id(); + graph.scenes.scenes.push(Scene::new(id, name)); + if graph.scenes.scenes.len() == 1 { + graph.scenes.active = id; + } + drop(graph); + self.shared.send(Event::SceneAdded { scene: id }); + } + Command::RemoveScene { scene } => { + let mut graph = lock(&self.graph); + graph.scenes.scenes.retain(|s| s.id != scene); + if graph.scenes.active == scene { + graph.scenes.active = graph.scenes.scenes.first().map_or(0, |s| s.id); + } + } + Command::RenameScene { scene, name } => { + let mut graph = lock(&self.graph); + graph.scenes.scene_mut(scene).ok_or_else(|| no_scene(scene))?.name = name; + } + Command::SetActiveScene { scene } => { + let mut graph = lock(&self.graph); + if graph.scenes.scene(scene).is_none() { + return Err(no_scene(scene)); + } + graph.scenes.active = scene; + } + Command::SetOutput { width, height, fps } => { + let mut graph = lock(&self.graph); + graph.scenes.width = width; + graph.scenes.height = height; + graph.scenes.fps = fps; + graph.scenes.check().map_err(Error::InvalidFrame)?; + } + Command::AddSource { scene, name, kind } => { + let mut graph = lock(&self.graph); + let target = graph.scenes.scene_mut(scene).ok_or_else(|| no_scene(scene))?; + let id = target.next_source_id(); + target.sources.push(Source { name, ..Source::new(id, kind) }); + drop(graph); + self.shared.send(Event::SourceAdded { scene, source: id }); + } + Command::RemoveSource { scene, source } => { + let mut graph = lock(&self.graph); + let target = graph.scenes.scene_mut(scene).ok_or_else(|| no_scene(scene))?; + target.sources.retain(|s| s.id != source); + } + Command::UpdateSource { scene, source, change } => { + let mut graph = lock(&self.graph); + let Some(target) = graph + .scenes + .scene_mut(scene) + .ok_or_else(|| no_scene(scene))? + .source_mut(source) + else { + return Err(Error::SourceNotFound(SourceId::Window(source))); + }; + let change = *change; + if let Some(name) = change.name { + target.name = name; + } + if let Some(kind) = change.kind { + target.kind = kind; + } + if let Some(transform) = change.transform { + target.transform = transform; + } + if let Some(crop) = change.crop { + target.crop = crop; + } + if let Some(opacity) = change.opacity { + target.opacity = opacity.clamp(0.0, 1.0); + } + if let Some(visible) = change.visible { + target.visible = visible; + } + if let Some(locked) = change.locked { + target.locked = locked; + } + if let Some(background) = change.background { + target.background = background; + } + graph.scenes.check().map_err(Error::InvalidFrame)?; + } + Command::ReorderSource { scene, source, to } => { + let mut graph = lock(&self.graph); + let target = graph.scenes.scene_mut(scene).ok_or_else(|| no_scene(scene))?; + let Some(from) = target.sources.iter().position(|s| s.id == source) else { + return Err(Error::SourceNotFound(SourceId::Window(source))); + }; + let moved = target.sources.remove(from); + let to = to.min(target.sources.len()); + target.sources.insert(to, moved); + } + Command::SetPreview { width, height, fps } => { + let mut graph = lock(&self.graph); + graph.preview = (width.max(2), height.max(2), fps.max(1)); + let preview = graph.preview; + drop(graph); + *lock(&self.shared.preview_size) = (preview.0, preview.1); + self.shared.preview_fps.store(preview.2, Ordering::Relaxed); + return Ok(()); + } + Command::StartRecording { path } => return self.start_recording(&path), + Command::StopRecording => return self.stop_recording(), + Command::SetReplay { seconds, memory_mb } => { + let mut replay = lock(&self.shared.replay); + replay.set_length(Duration::from_secs(u64::from(seconds))); + replay.set_memory_mb(memory_mb); + drop(replay); + self.shared.state_changed(); + return Ok(()); + } + Command::SaveClip { path } => { + let length = lock(&self.shared.replay).save_clip(&path)?; + self.shared.send(Event::ClipSaved { path, duration: length }); + return Ok(()); + } + Command::AddOutput(spec) => return self.add_output(spec).await, + Command::RemoveOutput { id } => { + let mut outputs = lock(&self.shared.outputs); + let Some(at) = outputs.iter().position(|o| o.id == id) else { + return Err(Error::InvalidFrame(format!("no studio output {id}"))); + }; + let mut output = outputs.remove(at); + drop(outputs); + let name = output.sink.name().to_owned(); + if let Err(e) = output.sink.finish() { + self.shared.fail(name.clone(), e); + } + self.shared.send(Event::OutputRemoved { id, name }); + self.shared.state_changed(); + return Ok(()); + } + Command::GoLive => { + *lock(&self.shared.state) = State::Live; + *lock(&self.shared.live_since) = Some(Instant::now()); + self.shared.state_changed(); + return Ok(()); + } + Command::EndStream => { + *lock(&self.shared.state) = State::Idle; + *lock(&self.shared.live_since) = None; + self.shared.state_changed(); + return Ok(()); + } + } + // Every scene-graph command lands here: start and stop the inputs the + // new graph needs and publish it. + self.rebuild().await; + Ok(()) + } + + fn start_recording(&self, path: &Path) -> Result<()> { + if lock(&self.shared.recording).is_some() { + return Err(Error::InvalidFrame("already recording".into())); + } + let layer = self.shared.layer.load(Ordering::Relaxed); + let recorder = output::record::Recorder::start(path, layer, 2)?; + let id = { + let mut graph = lock(&self.graph); + let id = graph.next_output; + graph.next_output += 1; + id + }; + lock(&self.shared.outputs).push(Output { + id, + sink: Box::new(recorder), + path: Some(path.to_owned()), + started: Instant::now(), + kbps: 0.0, + last_bytes: 0, + pushes: false, + error: None, + }); + *lock(&self.shared.recording) = Some(id); + self.shared.send(Event::RecordingStarted { path: path.to_owned() }); + self.shared.state_changed(); + Ok(()) + } + + fn stop_recording(&self) -> Result<()> { + let Some(id) = lock(&self.shared.recording).take() else { + return Err(Error::InvalidFrame("not recording".into())); + }; + let mut outputs = lock(&self.shared.outputs); + let Some(at) = outputs.iter().position(|o| o.id == id) else { return Ok(()) }; + let mut output = outputs.remove(at); + drop(outputs); + let bytes = output.sink.bytes(); + let path = output.path.clone().unwrap_or_else(|| PathBuf::from(output.sink.name())); + let duration = self.shared.recorded_for(&output); + if let Err(e) = output.sink.finish() { + self.shared.fail("recording", e); + } + self.shared.send(Event::RecordingStopped { path, duration, bytes }); + self.shared.state_changed(); + Ok(()) + } + + async fn add_output(&self, spec: OutputSpec) -> Result<()> { + let layer = self.shared.layer.load(Ordering::Relaxed); + let (sink, pushes): (Box, bool) = match &spec { + OutputSpec::Record { path } => { + (Box::new(output::record::Recorder::start(path, layer, 2)?), false) + } + OutputSpec::Url { url, token } => { + if output::rtmp::Rtmp::handles(url) { + return Err(output::rtmp::Rtmp::connect(url, token.as_deref()) + .expect_err("the RTMP seam always refuses")); + } + #[cfg(feature = "whip")] + { + let codec = self.stream_codec(); + let whip = output::whip::Whip::start(url, token.as_deref(), codec, layer, true) + .await?; + (Box::new(whip), true) + } + #[cfg(not(feature = "whip"))] + { + return Err(Error::CaptureUnavailable { + backend: "whip", + reason: "this build has no WHIP output (feature `whip`)".into(), + }); + } + } + }; + let id = { + let mut graph = lock(&self.graph); + let id = graph.next_output; + graph.next_output += 1; + id + }; + let name = sink.name().to_owned(); + let path = match &spec { + OutputSpec::Record { path } => Some(path.clone()), + OutputSpec::Url { .. } => None, + }; + lock(&self.shared.outputs).push(Output { + id, + sink, + path, + started: Instant::now(), + kbps: 0.0, + last_bytes: 0, + pushes, + error: None, + }); + self.shared.send(Event::OutputAdded { id, name }); + self.shared.state_changed(); + Ok(()) + } + + /// The codec a WHIP output offers: whatever the streamer encodes, which + /// [`Studio::write_packet`] learns. VP8 until the first packet. + #[cfg(feature = "whip")] + fn stream_codec(&self) -> Codec { + lock(&self.shared.codec).unwrap_or(Codec::Vp8) + } + + /// Start and stop source inputs so they match the active scene, then + /// publish it to the compose thread. + async fn rebuild(&self) { + let (scene, size, fps, wanted) = { + let graph = lock(&self.graph); + let scene = graph.scenes.active().cloned().unwrap_or_else(|| Scene::new(0, "")); + let wanted: Vec<(u64, SourceKind, Background)> = scene + .sources + .iter() + .map(|s| (s.id, s.kind.clone(), s.background.clone())) + .collect(); + (scene, graph.scenes.size(), graph.scenes.fps(), wanted) + }; + // Drop the inputs of sources that are gone or that changed input. + { + let mut graph = lock(&self.graph); + graph.inputs.retain(|(id, input)| { + wanted.iter().any(|(w, kind, background)| { + w == id + && !restart(input.kind(), kind) + // A background filter is set up when the input starts. + && input.background().needs_mask() == background.needs_mask() + }) + }); + } + for (id, kind, background) in &wanted { + let known = lock(&self.graph).inputs.iter().any(|(i, _)| i == id); + if known { + continue; + } + let input = Input::start(kind.clone(), fps, background.clone()).await; + if let Some(error) = input.feed.error() { + self.shared.fail(kind.label(), error); + } + lock(&self.graph).inputs.push((*id, input)); + } + let mut graph = lock(&self.graph); + graph.revision += 1; + let revision = graph.revision; + let feeds: Vec>> = scene + .sources + .iter() + .map(|s| graph.inputs.iter().find(|(id, _)| *id == s.id).map(|(_, i)| i.feed.clone())) + .collect(); + for (_, input) in &graph.inputs { + input.set_fps(fps); + } + let scenes = Arc::new(graph.scenes.clone()); + drop(graph); + *lock(&self.shared.live) = Arc::new(Live { scene, feeds, revision, size, fps }); + self.shared.send(Event::Scenes(scenes)); + self.shared.state_changed(); + } + + /// Hand one encoded packet to every output. Called on the streamer's + /// encoder threads. + pub fn write_packet(&self, packet: &Packet<'_>) { + self.shared.write_packet(packet); + } + + /// Whether any output needs a keyframe now (a recording that just + /// started, a WHIP session that just connected). + pub fn needs_keyframe(&self) -> bool { + self.shared.needs_keyframe() + } + + /// Stop composing and close every output. + pub fn stop(&mut self) { + self.shared.stop.store(true, Ordering::Relaxed); + self.shared.preview.close(); + for thread in self.threads.drain(..) { + let _ = thread.join(); + } + for mut output in lock(&self.shared.outputs).drain(..) { + if let Err(e) = output.sink.finish() { + debug!("closing a studio output: {e}"); + } + } + lock(&self.graph).inputs.clear(); + } +} + +impl Drop for Studio { + fn drop(&mut self) { + self.stop(); + } +} + +fn no_scene(scene: u64) -> Error { + Error::InvalidFrame(format!("no studio scene {scene}")) +} + +/// Whether a kind change means the input must be started again. A text or +/// colour source is simply drawn again, but everything else opens a device. +fn restart(old: &SourceKind, new: &SourceKind) -> bool { + match (old, new) { + // The portal hands back a token we store in the scene; that alone is + // not a reason to ask the user again. + (SourceKind::Portal { cursor: a, .. }, SourceKind::Portal { cursor: b, .. }) => a != b, + _ => old != new, + } +} + +impl Shared { + fn status(&self) -> Status { + let live = lock(&self.live); + let outputs = lock(&self.outputs); + let recording = lock(&self.recording) + .and_then(|id| outputs.iter().find(|o| o.id == id)) + .and_then(|o| o.path.clone()); + let recorded_for = lock(&self.recording) + .and_then(|id| outputs.iter().find(|o| o.id == id)) + .map_or(Duration::ZERO, |o| self.recorded_for(o)); + Status { + state: *lock(&self.state), + live_for: lock(&self.live_since).map_or(Duration::ZERO, |at| at.elapsed()), + recording, + recorded_for, + active_scene: live.scene.id, + output: live.size, + fps: live.fps, + outputs: outputs.iter().filter(|o| o.pushes).count(), + } + } + + /// How long an output has been going. + fn recorded_for(&self, output: &Output) -> Duration { + output.started.elapsed() + } + + fn state_changed(&self) { + self.send(Event::State(self.status())); + } + + fn needs_keyframe(&self) -> bool { + let mut outputs = lock(&self.outputs); + let any = outputs.iter_mut().any(|o| o.sink.needs_keyframe()); + any || lock(&self.replay).needs_keyframe() + } + + fn write_packet(&self, packet: &Packet<'_>) { + if let Track::Video { codec, .. } = packet.track { + let mut known = lock(&self.codec); + if *known != Some(codec) { + *known = Some(codec); + } + } + if let Err(e) = lock(&self.replay).write(packet) { + self.fail("replay", e); + } + let mut failed = Vec::new(); + { + let mut outputs = lock(&self.outputs); + for output in outputs.iter_mut() { + if !output.sink.wants(packet.track) { + continue; + } + if let Err(e) = output.sink.write(packet) { + output.error = Some(e.to_string()); + failed.push((output.id, output.sink.name().to_owned(), e.to_string())); + } + } + outputs.retain(|o| !failed.iter().any(|(id, _, _)| *id == o.id)); + } + for (id, name, message) in failed { + self.fail(name.clone(), message); + self.send(Event::OutputRemoved { id, name }); + } + } +} + +/// The compose thread: draw the scene at the output rate, offer it to the +/// preview and hand it to the streamer. +fn compose_loop(shared: &Shared) { + let mut compositor = Compositor::new(0); + let mut preview = RgbaScaler::new(2); + let started = Instant::now(); + let mut pacer = crate::capture::FramePacer::new(Some(15)); + let mut preview_fps = 0; + let mut next = Instant::now(); + while !shared.stopped() { + let live = lock(&shared.live).clone(); + let interval = Duration::from_secs(1) / live.fps.max(1); + let want = shared.preview_fps.load(Ordering::Relaxed); + if want != preview_fps { + preview_fps = want; + pacer.set_fps(Some(want)); + } + compositor.set_size(live.size.0, live.size.1); + let timestamp = started.elapsed(); + let frame = match compositor.compose(&live.scene, live.revision, &live.feeds, timestamp) { + Ok(frame) => frame, + Err(e) => { + shared.fail("compose", e); + std::thread::sleep(POLL); + continue; + } + }; + // The preview, at its own size and rate. + if pacer.take(timestamp) { + let (pw, ph) = *lock(&shared.preview_size); + match preview.scale(&frame, pw, ph) { + Ok(small) => { + shared.preview.put(small); + shared.preview_frames.fetch_add(1, Ordering::Relaxed); + } + Err(e) => shared.fail("preview", e), + } + } + // The streamer, if it is capturing us. + { + let mut sink = lock(&shared.sink); + if let Some(sink) = sink.as_mut() + && sink.wants(timestamp) + { + if sink.frame(frame.view()) { + shared.delivered.fetch_add(1, Ordering::Relaxed); + } else { + debug!("the studio's frame sink went away"); + *lock(&shared.sink) = None; + } + } + } + drop(frame); + *lock(&shared.compose) = compositor.stats(); + next += interval; + let now = Instant::now(); + if next < now { + next = now; + } + std::thread::sleep((next - now).min(POLL)); + } +} + +/// Once a second: rates for [`Event::Stats`]. +fn stats_loop(shared: &Shared) { + let mut last = Instant::now(); + let mut frames = 0u64; + let mut per_source: Vec<(u64, u64)> = Vec::new(); + while !shared.stopped() { + std::thread::sleep(POLL); + let elapsed = last.elapsed(); + if elapsed < Duration::from_secs(1) { + continue; + } + last = Instant::now(); + let seconds = elapsed.as_secs_f64(); + let live = lock(&shared.live).clone(); + let mut sources = Vec::with_capacity(live.scene.sources.len()); + for (source, feed) in live.scene.sources.iter().zip(&live.feeds) { + let (delivered, dropped, size, error) = match feed { + Some(feed) => (feed.delivered(), feed.dropped(), feed.size(), feed.error()), + None => (0, 0, (0, 0), None), + }; + let previous = + per_source.iter().find(|(id, _)| *id == source.id).map_or(0, |(_, n)| *n); + sources.push(SourceStats { + id: source.id, + label: source.label().to_owned(), + kind: source.kind.label(), + width: size.0, + height: size.1, + frames: delivered, + fps: delivered.saturating_sub(previous) as f64 / seconds, + dropped, + error, + }); + } + per_source = sources.iter().map(|s| (s.id, s.frames)).collect(); + let outputs = { + let mut outputs = lock(&shared.outputs); + let mut stats = Vec::with_capacity(outputs.len()); + for output in outputs.iter_mut() { + let bytes = output.sink.bytes(); + output.kbps = + (bytes.saturating_sub(output.last_bytes) * 8) as f64 / seconds / 1000.0; + output.last_bytes = bytes; + stats.push(OutputStats { + id: output.id, + name: output.sink.name().to_owned(), + bytes, + kbps: output.kbps, + error: output.error.clone(), + }); + } + stats + }; + let composed = lock(&shared.compose).frames; + let fps = composed.saturating_sub(frames) as f64 / seconds; + frames = composed; + shared.send(Event::Stats(Box::new(Stats { + status: shared.status(), + compose: *lock(&shared.compose), + fps, + sources, + outputs, + replay: lock(&shared.replay).stats(), + preview_frames: shared.preview_frames.load(Ordering::Relaxed), + delivered: shared.delivered.load(Ordering::Relaxed), + }))); + } +} + +/// The studio as a [`ScreenCapture`] backend: what makes the composite a +/// video source of the existing streamer, with its encoders, simulcast and +/// peers unchanged. +pub struct StudioCapture { + shared: Arc, +} + +impl ScreenCapture for StudioCapture { + fn backend(&self) -> &'static str { + "studio" + } + + fn sources(&mut self) -> Result> { + let live = lock(&self.shared.live); + Ok(vec![CaptureSource { + id: SourceId::Studio, + name: "Stream Studio".into(), + width: live.size.0, + height: live.size.1, + primary: true, + }]) + } + + fn start( + &mut self, + source: &SourceId, + options: &CaptureOptions, + ) -> BoxFuture<'_, Result>> { + let (source, options) = (source.clone(), options.clone()); + Box::pin(async move { + if source != SourceId::Studio { + return Err(Error::SourceNotFound(source)); + } + let (sink, rx) = crate::capture::QueueSink::new(&options); + *lock(&self.shared.sink) = Some(Box::new(sink)); + Ok(rx) + }) + } + + fn start_sink( + &mut self, + source: &SourceId, + _options: &CaptureOptions, + sink: Box, + ) -> BoxFuture<'_, Result<()>> { + let source = source.clone(); + Box::pin(async move { + if source != SourceId::Studio { + return Err(Error::SourceNotFound(source)); + } + *lock(&self.shared.sink) = Some(sink); + Ok(()) + }) + } + + fn stop(&mut self) { + *lock(&self.shared.sink) = None; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::studio::scene::Colour; + + fn one_colour_scene() -> Scenes { + let mut scenes = Scenes { width: 64, height: 48, fps: 60, ..Scenes::default() }; + let mut scene = Scene::new(1, "Main"); + scene.sources.push(Source { + transform: Transform::full(64, 48), + ..Source::new(1, SourceKind::Colour { colour: Colour::rgb(9, 8, 7), size: (64, 48) }) + }); + scenes.scenes.push(scene); + scenes.active = 1; + scenes + } + + #[tokio::test] + async fn it_composes_into_the_preview_and_follows_commands() { + let studio = Studio::start(one_colour_scene()).await.unwrap(); + let preview = studio.preview(); + studio.apply(Command::SetPreview { width: 32, height: 24, fps: 60 }).await.unwrap(); + let started = Instant::now(); + let frame = loop { + if let Some(frame) = preview.wait_timeout(Duration::from_millis(200)) { + break frame; + } + assert!(started.elapsed() < Duration::from_secs(5), "no preview frame"); + }; + assert_eq!((frame.width, frame.height), (32, 24)); + let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!("not RGBA") }; + assert_eq!(&p.data[..4], &[9, 8, 7, 255]); + + // Scenes and sources can be added, moved and removed while running. + studio.apply(Command::AddScene { name: "Break".into() }).await.unwrap(); + let scenes = studio.scenes(); + assert_eq!(scenes.scenes.len(), 2); + let break_id = scenes.scenes[1].id; + studio + .apply(Command::AddSource { + scene: break_id, + name: "Slate".into(), + kind: SourceKind::Colour { colour: Colour::rgb(1, 2, 3), size: (64, 48) }, + }) + .await + .unwrap(); + studio.apply(Command::SetActiveScene { scene: break_id }).await.unwrap(); + assert_eq!(studio.status().active_scene, break_id); + // The new scene's source draws. + let frame = loop { + let frame = preview.wait_timeout(Duration::from_secs(2)).expect("a preview frame"); + let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!() }; + if p.data[..3] == [1, 2, 3] { + break frame; + } + assert!(started.elapsed() < Duration::from_secs(10), "the scene never switched"); + }; + drop(frame); + + studio.apply(Command::RemoveScene { scene: break_id }).await.unwrap(); + assert_eq!(studio.scenes().scenes.len(), 1); + assert!(studio.apply(Command::SetActiveScene { scene: 99 }).await.is_err()); + assert!(studio.apply(Command::RenameScene { scene: 99, name: "x".into() }).await.is_err()); + } + + #[tokio::test] + async fn go_live_and_recording_change_the_status() { + let studio = Studio::start(one_colour_scene()).await.unwrap(); + let mut events = studio.events(); + assert_eq!(studio.status().state, State::Idle); + studio.apply(Command::GoLive).await.unwrap(); + assert_eq!(studio.status().state, State::Live); + studio.apply(Command::EndStream).await.unwrap(); + assert_eq!(studio.status().state, State::Idle); + + // A recording is an output; stopping one that is not running fails. + assert!(studio.apply(Command::StopRecording).await.is_err()); + let dir = std::env::temp_dir().join(format!("voelin-studio-ctl-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("out.webm"); + studio.apply(Command::StartRecording { path: path.clone() }).await.unwrap(); + assert_eq!(studio.status().recording.as_deref(), Some(path.as_path())); + assert!(studio.needs_keyframe(), "a fresh recording wants a keyframe"); + assert!(studio.apply(Command::StartRecording { path: path.clone() }).await.is_err()); + studio.apply(Command::StopRecording).await.unwrap(); + assert!(studio.status().recording.is_none()); + + // The replay buffer is off until it is given a window. + assert!(studio.apply(Command::SaveClip { path: dir.join("clip.webm") }).await.is_err()); + studio.apply(Command::SetReplay { seconds: 5, memory_mb: 8 }).await.unwrap(); + // Still no keyframe in it, so still no clip. + assert!(studio.apply(Command::SaveClip { path: dir.join("clip.webm") }).await.is_err()); + + // Events arrived for all of it. + let mut seen = Vec::new(); + while let Ok(event) = events.try_recv() { + seen.push(event); + } + assert!(seen.iter().any(|e| matches!(e, Event::RecordingStarted { .. })), "{seen:?}"); + assert!(seen.iter().any(|e| matches!(e, Event::RecordingStopped { .. })), "{seen:?}"); + assert!(seen.iter().any(|e| matches!(e, Event::State(_))), "{seen:?}"); + std::fs::remove_dir_all(&dir).ok(); + } + + #[tokio::test] + async fn packets_reach_the_outputs_and_the_studio_is_a_capture_backend() { + let studio = Arc::new(Studio::start(one_colour_scene()).await.unwrap()); + let dir = std::env::temp_dir().join(format!("voelin-studio-tee-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + studio + .apply(Command::AddOutput(OutputSpec::Record { path: dir.join("tee.webm") })) + .await + .unwrap(); + studio.apply(Command::SetReplay { seconds: 2, memory_mb: 4 }).await.unwrap(); + for n in 0..30u64 { + studio.write_packet(&Packet { + track: Track::Video { codec: Codec::Vp8, layer: 0 }, + pts_90khz: n * 3000, + keyframe: n.is_multiple_of(15), + width: 64, + height: 48, + data: &[1, 2, 3, 4], + }); + } + { + let outputs = lock(&studio.shared.outputs); + assert_eq!(outputs.len(), 1); + assert!(outputs[0].sink.bytes() > 0); + } + assert!(lock(&studio.shared.replay).stats().packets > 0); + // An RTMP url is refused with its reason, not silently dropped. + let e = studio + .apply(Command::AddOutput(OutputSpec::Url { + url: "rtmp://live.example/app".into(), + token: None, + })) + .await + .unwrap_err() + .to_string(); + assert!(e.contains("FFmpeg"), "{e}"); + + // The studio is a capture backend the streamer can use unchanged. + let mut capture = studio.capture(); + assert_eq!(capture.backend(), "studio"); + let listed = capture.sources().unwrap(); + assert_eq!(listed[0].id, SourceId::Studio); + assert_eq!((listed[0].width, listed[0].height), (64, 48)); + let frames = capture.start(&SourceId::Studio, &CaptureOptions::default()).await.unwrap(); + let mut frames = frames; + let frame = frames.recv_timeout(Duration::from_secs(5)).expect("a composed frame"); + assert_eq!((frame.width, frame.height), (64, 48)); + assert!(studio.shared.delivered.load(Ordering::Relaxed) > 0); + capture.stop(); + std::fs::remove_dir_all(&dir).ok(); + } +} diff --git a/crates/voelin-media/src/studio/segment.rs b/crates/voelin-media/src/studio/segment.rs new file mode 100644 index 0000000..7c996a8 --- /dev/null +++ b/crates/voelin-media/src/studio/segment.rs @@ -0,0 +1,741 @@ +//! Background replacement: blur, an image or a colour behind the person. +//! +//! A [`Segmenter`] produces a small greyscale [`Mask`] — 255 where the person +//! is — on a thread of its own and at a lower rate than the video, because +//! segmentation costs far more than a frame does and a mask is still good +//! enough a few frames later. The frame path takes the newest mask through a +//! latest-wins handoff, upsamples and feathers it, and mixes the person over a +//! background it makes with [`blur_rgba`], an image or a colour. +//! +//! The blur is a three-pass box blur (which approximates a Gaussian closely +//! enough that nobody sees the difference at these radii), separable and with +//! a running sum, so its cost does not grow with the radius. It runs in bands +//! on a [`Workers`] pool over pooled buffers: no allocation per frame. +//! +//! # What segments +//! +//! [`Ellipse`] is the segmenter that is always there: a centred oval, which is +//! roughly where a person sits in front of a camera. It is honest about being +//! a placeholder — it exercises the mask path and the tests, and gives a +//! usable "blur everything but the middle" — but it does not find a person. +//! +//! A real segmenter is a small neural network (the MediaPipe-style selfie +//! segmentation models are what this is sized for: one 256x144 or 256x256 +//! input, one mask output). That is not in this build: nothing here loads an +//! ONNX model yet, so [`Background::Blur`](crate::studio::scene::Background) +//! blurs around an oval rather than around a person. The seam is +//! [`Segmenter`]; a model-backed implementation drops in behind it without +//! touching the frame path. + +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use tracing::warn; + +use crate::frame::{FrameData, VideoFrame}; +use crate::handoff::Handoff; +use crate::studio::scene::{Background, Colour}; +use crate::studio::source::image_frame; +use crate::workers::{Slots, Workers}; +use crate::{Error, Result}; + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// How often a mask is computed by default, however fast the video runs. +pub const DEFAULT_MASK_FPS: u32 = 10; +/// The width a frame is reduced to before segmentation; the height follows +/// the aspect ratio. +const SEGMENT_WIDTH: u32 = 256; + +/// A greyscale coverage map: 255 where the subject is, 0 where the background +/// is. Usually much smaller than the frame. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Mask { + pub width: u32, + pub height: u32, + /// `width * height` bytes. + pub data: Vec, +} + +impl Mask { + pub fn new(width: u32, height: u32) -> Self { + let (width, height) = (width.max(1), height.max(1)); + Self { width, height, data: vec![0; width as usize * height as usize] } + } + + /// Resize the buffer for `width` x `height`, keeping the allocation. + pub fn resize(&mut self, width: u32, height: u32) { + let (width, height) = (width.max(1), height.max(1)); + self.width = width; + self.height = height; + self.data.clear(); + self.data.resize(width as usize * height as usize, 0); + } + + /// The mask value at a point of a `width` x `height` frame, bilinear. + fn sample(&self, x: u32, y: u32, width: u32, height: u32) -> u8 { + let fx = (u64::from(x) * u64::from(self.width) / u64::from(width.max(1))) as u32; + let fy = (u64::from(y) * u64::from(self.height) / u64::from(height.max(1))) as u32; + let (fx, fy) = (fx.min(self.width - 1), fy.min(self.height - 1)); + self.data[fy as usize * self.width as usize + fx as usize] + } +} + +/// Something that says where the subject is. +pub trait Segmenter: Send { + /// For logs and the UI. + fn name(&self) -> &'static str; + + /// The size the frame should be reduced to before [`Segmenter::mask`]. + fn input_size(&self, width: u32, height: u32) -> (u32, u32) { + let width = width.clamp(1, SEGMENT_WIDTH); + let height = + (u64::from(width) * u64::from(height.max(1)) / u64::from(width.max(1)).max(1)) as u32; + (width, height.max(1)) + } + + /// Fill `mask` from `frame` (packed RGBA at the size + /// [`Segmenter::input_size`] asked for). + fn mask(&mut self, frame: &VideoFrame, mask: &mut Mask) -> Result<()>; +} + +/// The segmenter that is always available: a centred oval covering most of +/// the frame. See the [module docs](self) for what it is and is not. +#[derive(Clone, Copy, Debug, Default)] +pub struct Ellipse { + /// Half-width of the oval as a fraction of the frame. + pub half_width: f32, + /// Half-height, as a fraction. + pub half_height: f32, +} + +impl Ellipse { + /// The proportions a person in front of a camera roughly fills. + pub fn person() -> Self { + Self { half_width: 0.33, half_height: 0.48 } + } +} + +impl Segmenter for Ellipse { + fn name(&self) -> &'static str { + "ellipse" + } + + fn mask(&mut self, frame: &VideoFrame, mask: &mut Mask) -> Result<()> { + mask.resize(frame.width, frame.height); + let (w, h) = (mask.width as f32, mask.height as f32); + let (cx, cy) = (w / 2.0, h * 0.55); + let (rx, ry) = + ((self.half_width.max(0.01) * w).max(1.0), (self.half_height.max(0.01) * h).max(1.0)); + for y in 0..mask.height { + for x in 0..mask.width { + let dx = (x as f32 + 0.5 - cx) / rx; + let dy = (y as f32 + 0.5 - cy) / ry; + let d = dx * dx + dy * dy; + // 1 inside, fading to 0 over the last tenth of the radius. + let coverage = ((1.1 - d) / 0.2).clamp(0.0, 1.0); + mask.data[y as usize * mask.width as usize + x as usize] = (coverage * 255.0) as u8; + } + } + Ok(()) + } +} + +/// Blur `plane` (packed RGBA, `stride` bytes per row) in place with a +/// three-pass box blur of radius `radius`, using `scratch` (at least as +/// large) as the second buffer. Allocates nothing. +pub fn blur_rgba( + workers: &mut Workers, + plane: &mut [u8], + scratch: &mut [u8], + width: usize, + height: usize, + stride: usize, + radius: usize, +) -> Result<()> { + if radius == 0 || width == 0 || height == 0 { + return Ok(()); + } + let needed = stride * (height - 1) + width * 4; + if plane.len() < needed || scratch.len() < needed { + return Err(Error::InvalidFrame("the blur buffers are too small".into())); + } + // Three box passes approximate a Gaussian; each pass is horizontal then + // vertical, so six sweeps in all. + for _ in 0..3 { + blur_rows(workers, plane, scratch, width, height, stride, radius); + blur_columns(workers, scratch, plane, width, height, stride, radius); + } + Ok(()) +} + +/// One horizontal box pass from `src` into `dst`. +fn blur_rows( + workers: &mut Workers, + src: &[u8], + dst: &mut [u8], + width: usize, + height: usize, + stride: usize, + radius: usize, +) { + let tasks = workers.tasks(height); + let band = height.div_ceil(tasks); + let tasks = height.div_ceil(band); + let slots = Slots::new(dst.chunks_mut(band * stride).take(tasks).enumerate()); + workers.run(slots.len(), &|task| { + let Some((i, out)) = slots.take(task) else { return }; + let rows = i * band..((i + 1) * band).min(height); + for y in rows.clone() { + let row = &src[y * stride..][..width * 4]; + let line = &mut out[(y - rows.start) * stride..][..width * 4]; + // A running sum over the window, one channel at a time. + let mut sum = [0u32; 4]; + let mut count = 0u32; + for x in 0..=radius.min(width - 1) { + for c in 0..4 { + sum[c] += u32::from(row[x * 4 + c]); + } + count += 1; + } + for x in 0..width { + for c in 0..4 { + line[x * 4 + c] = ((sum[c] + count / 2) / count) as u8; + } + // Slide: drop the pixel leaving, add the one entering. + if x >= radius { + let out_x = x - radius; + for c in 0..4 { + sum[c] -= u32::from(row[out_x * 4 + c]); + } + count -= 1; + } + let in_x = x + radius + 1; + if in_x < width { + for c in 0..4 { + sum[c] += u32::from(row[in_x * 4 + c]); + } + count += 1; + } + } + } + }); +} + +/// One vertical box pass from `src` into `dst`. +/// +/// Split into bands of rows, like every other pass, so each task writes its +/// own slice: a band restarts the running sum at its first row, which costs +/// `radius` extra reads per column per band and keeps the pass free of +/// `unsafe`. +fn blur_columns( + workers: &mut Workers, + src: &[u8], + dst: &mut [u8], + width: usize, + height: usize, + stride: usize, + radius: usize, +) { + let tasks = workers.tasks(height); + let band = height.div_ceil(tasks); + let tasks = height.div_ceil(band); + let slots = Slots::new(dst.chunks_mut(band * stride).take(tasks).enumerate()); + workers.run(slots.len(), &|task| { + let Some((i, out)) = slots.take(task) else { return }; + let rows = i * band..((i + 1) * band).min(height); + for x in 0..width { + let mut sum = [0u32; 4]; + let mut count = 0u32; + let first = rows.start.saturating_sub(radius); + let last = (rows.start + radius).min(height - 1); + for y in first..=last { + for c in 0..4 { + sum[c] += u32::from(src[y * stride + x * 4 + c]); + } + count += 1; + } + for y in rows.clone() { + let at = (y - rows.start) * stride + x * 4; + for c in 0..4 { + out[at + c] = ((sum[c] + count / 2) / count) as u8; + } + if y >= radius { + let leaving = y - radius; + for c in 0..4 { + sum[c] -= u32::from(src[leaving * stride + x * 4 + c]); + } + count -= 1; + } + let entering = y + radius + 1; + if entering < height { + for c in 0..4 { + sum[c] += u32::from(src[entering * stride + x * 4 + c]); + } + count += 1; + } + } + } + }); +} + +/// What goes behind the subject. +enum Backdrop { + /// The frame itself, blurred by this radius. + Blur(usize), + /// An image, already scaled to the frame (packed RGBA). + Image(VideoFrame), + Colour([u8; 4]), +} + +/// Replaces the background of the frames of one source; see the +/// [module docs](self). +pub struct BackgroundFilter { + mode: Arc>, + /// Newest frame for the segmenter, and newest mask for the frame path. + to_segmenter: Arc>, + masks: Arc>, + mask: Option>, + workers: Workers, + /// Scratch for the blur (two planes: the blurred copy and its pass + /// buffer). + scratch: Vec, + scaler: crate::studio::compose::RgbaScaler, + backdrop: Option<(Background, Backdrop)>, + thread: Option>, + stop: Arc, + masks_made: Arc, + mask_fps: Arc, + segmenter: &'static str, +} + +impl BackgroundFilter { + /// A filter running `segmenter` at [`DEFAULT_MASK_FPS`]. + pub fn new(mode: Background, segmenter: Box) -> Self { + let to_segmenter = Arc::new(Handoff::new()); + let masks = Arc::new(Handoff::new()); + let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let masks_made = Arc::new(AtomicU64::new(0)); + let mask_fps = Arc::new(AtomicU32::new(DEFAULT_MASK_FPS)); + let name = segmenter.name(); + let thread = { + let (frames, out) = (to_segmenter.clone(), masks.clone()); + let (stop, made, fps) = (stop.clone(), masks_made.clone(), mask_fps.clone()); + std::thread::Builder::new() + .name("voelin-studio-segment".into()) + .spawn(move || segment_loop(segmenter, &frames, &out, &stop, &made, &fps)) + .ok() + }; + Self { + mode: Arc::new(Mutex::new(mode)), + to_segmenter, + masks, + mask: None, + workers: Workers::new("voelin-blur", 0), + scratch: Vec::new(), + scaler: crate::studio::compose::RgbaScaler::new(2), + backdrop: None, + thread, + stop, + masks_made, + mask_fps, + segmenter: name, + } + } + + /// A filter with the built-in [`Ellipse`] segmenter. + pub fn with_default_segmenter(mode: Background) -> Self { + Self::new(mode, Box::new(Ellipse::person())) + } + + /// The mode, changed while running (a scene edit). + pub fn set_mode(&self, mode: Background) { + *lock(&self.mode) = mode; + } + + pub fn mode(&self) -> Background { + lock(&self.mode).clone() + } + + /// How often a mask is computed. + pub fn set_mask_fps(&self, fps: u32) { + self.mask_fps.store(fps.max(1), Ordering::Relaxed); + } + + pub fn masks(&self) -> u64 { + self.masks_made.load(Ordering::Relaxed) + } + + pub fn segmenter(&self) -> &'static str { + self.segmenter + } + + /// Replace the background of `frame` (packed RGBA, in place). Does + /// nothing while the mode is [`Background::Keep`] or before the first + /// mask. + pub fn apply(&mut self, frame: &mut VideoFrame) -> Result<()> { + let mode = lock(&self.mode).clone(); + if !mode.needs_mask() { + return Ok(()); + } + if !matches!(frame.data, FrameData::Rgba(_)) { + return Err(Error::InvalidFrame("background replacement needs RGBA".into())); + } + // Offer the segmenter a small copy and take its newest mask. + self.feed_segmenter(frame)?; + if let Some(mask) = self.masks.take() { + self.mask = Some(mask); + } + let Some(mask) = self.mask.clone() else { return Ok(()) }; + let (width, height) = (frame.width as usize, frame.height as usize); + self.make_backdrop(&mode, frame)?; + let FrameData::Rgba(plane) = &mut frame.data else { unreachable!("checked above") }; + let stride = plane.stride; + let backdrop = self.backdrop.as_ref().map(|(_, b)| b); + match backdrop { + Some(Backdrop::Blur(radius)) => { + let needed = stride * height; + if self.scratch.len() < needed * 2 { + self.scratch.resize(needed * 2, 0); + } + let (blurred, scratch) = self.scratch.split_at_mut(needed); + blurred[..plane.data.len().min(needed)] + .copy_from_slice(&plane.data[..plane.data.len().min(needed)]); + blur_rgba(&mut self.workers, blurred, scratch, width, height, stride, *radius)?; + mix(&mut self.workers, &mut plane.data, blurred, stride, width, height, &mask); + } + Some(Backdrop::Image(image)) => { + let FrameData::Rgba(behind) = &image.data else { + return Err(Error::InvalidFrame("the background image is not RGBA".into())); + }; + let behind = behind.data.clone(); + mix(&mut self.workers, &mut plane.data, &behind, stride, width, height, &mask); + } + Some(Backdrop::Colour(rgba)) => { + let rgba = *rgba; + fill_behind(&mut self.workers, &mut plane.data, stride, width, height, &mask, rgba); + } + None => {} + } + Ok(()) + } + + /// Hand the segmenter a reduced copy of the frame, if it wants one. + fn feed_segmenter(&mut self, frame: &VideoFrame) -> Result<()> { + if self.to_segmenter.is_closed() { + return Ok(()); + } + let width = frame.width.clamp(1, SEGMENT_WIDTH); + let height = (u64::from(width) * u64::from(frame.height) / u64::from(frame.width.max(1))) + .max(1) as u32; + let small = self.scaler.scale(frame, width, height)?; + self.to_segmenter.put(small); + Ok(()) + } + + /// Build (or reuse) what goes behind the subject. + fn make_backdrop(&mut self, mode: &Background, frame: &VideoFrame) -> Result<()> { + let stale = match (&self.backdrop, mode) { + (Some((had, Backdrop::Image(image))), Background::Image { .. }) => { + had != mode || image.width != frame.width || image.height != frame.height + } + (Some((had, _)), _) => had != mode, + (None, _) => true, + }; + if !stale { + // A blur radius follows the frame height, which may have changed. + if let (Some((_, Backdrop::Blur(radius))), Background::Blur { strength }) = + (&mut self.backdrop, mode) + { + *radius = blur_radius(*strength, frame.height); + } + return Ok(()); + } + let backdrop = match mode { + Background::Keep => return Ok(()), + Background::Blur { strength } => Backdrop::Blur(blur_radius(*strength, frame.height)), + Background::Colour { colour } => Backdrop::Colour(opaque(*colour)), + Background::Image { path } => { + let image = image_frame(path)?; + // Cover the frame, so no edge of it shows. + let scaled = self.scaler.scale(&image, frame.width, frame.height)?; + Backdrop::Image((*scaled).clone()) + } + }; + self.backdrop = Some((mode.clone(), backdrop)); + Ok(()) + } +} + +impl Drop for BackgroundFilter { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + self.to_segmenter.close(); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +/// The blur radius in pixels of a strength given as a fraction of the height. +fn blur_radius(strength: f32, height: u32) -> usize { + let radius = (strength.clamp(0.0, 1.0) * height as f32).round(); + (radius as usize).min(height as usize / 2).max(if strength > 0.0 { 1 } else { 0 }) +} + +fn opaque(colour: Colour) -> [u8; 4] { + [colour.r, colour.g, colour.b, 255] +} + +/// `frame = frame * mask + behind * (1 - mask)`, in bands of rows. +fn mix( + workers: &mut Workers, + frame: &mut [u8], + behind: &[u8], + stride: usize, + width: usize, + height: usize, + mask: &Mask, +) { + let tasks = workers.tasks(height); + let band = height.div_ceil(tasks); + let tasks = height.div_ceil(band); + let slots = Slots::new(frame.chunks_mut(band * stride).take(tasks).enumerate()); + workers.run(slots.len(), &|task| { + let Some((i, out)) = slots.take(task) else { return }; + let rows = i * band..((i + 1) * band).min(height); + for y in rows.clone() { + let line = &mut out[(y - rows.start) * stride..][..width * 4]; + let back = &behind[y * stride..][..width * 4]; + for x in 0..width { + let m = u32::from(mask.sample(x as u32, y as u32, width as u32, height as u32)); + if m == 255 { + continue; + } + for c in 0..4 { + let front = u32::from(line[x * 4 + c]) * m; + let rear = u32::from(back[x * 4 + c]) * (255 - m); + line[x * 4 + c] = ((front + rear + 127) / 255) as u8; + } + line[x * 4 + 3] = 255; + } + } + }); +} + +/// As [`mix`], with a flat colour behind. +fn fill_behind( + workers: &mut Workers, + frame: &mut [u8], + stride: usize, + width: usize, + height: usize, + mask: &Mask, + rgba: [u8; 4], +) { + let tasks = workers.tasks(height); + let band = height.div_ceil(tasks); + let tasks = height.div_ceil(band); + let slots = Slots::new(frame.chunks_mut(band * stride).take(tasks).enumerate()); + workers.run(slots.len(), &|task| { + let Some((i, out)) = slots.take(task) else { return }; + let rows = i * band..((i + 1) * band).min(height); + for y in rows.clone() { + let line = &mut out[(y - rows.start) * stride..][..width * 4]; + for x in 0..width { + let m = u32::from(mask.sample(x as u32, y as u32, width as u32, height as u32)); + if m == 255 { + continue; + } + for c in 0..4 { + let front = u32::from(line[x * 4 + c]) * m; + let rear = u32::from(rgba[c]) * (255 - m); + line[x * 4 + c] = ((front + rear + 127) / 255) as u8; + } + line[x * 4 + 3] = 255; + } + } + }); +} + +/// The segmenter's thread: the newest frame in, a mask out, at its own rate. +fn segment_loop( + mut segmenter: Box, + frames: &Handoff, + masks: &Handoff, + stop: &std::sync::atomic::AtomicBool, + made: &AtomicU64, + fps: &AtomicU32, +) { + let mut mask = Mask::default(); + let mut next = Instant::now(); + while !stop.load(Ordering::Relaxed) { + let Some(frame) = frames.wait_timeout(Duration::from_millis(100)) else { continue }; + let now = Instant::now(); + if now < next { + continue; + } + next = now + Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1); + match segmenter.mask(&frame, &mut mask) { + Ok(()) => { + masks.put(Arc::new(mask.clone())); + made.fetch_add(1, Ordering::Relaxed); + } + Err(e) => warn!("segmentation failed: {e}"), + } + } +} + +/// A `width` x `height` RGBA frame of one colour. +#[cfg(test)] +fn flat_rgba(width: u32, height: u32, rgba: [u8; 4]) -> VideoFrame { + let mut frame = VideoFrame::black_i420(width, height); + let mut data = Vec::with_capacity(width as usize * height as usize * 4); + for _ in 0..u64::from(width) * u64::from(height) { + data.extend_from_slice(&rgba); + } + frame.data = FrameData::Rgba(crate::frame::Plane::new(data, width as usize * 4)); + frame +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pixel(frame: &VideoFrame, x: u32, y: u32) -> [u8; 4] { + let FrameData::Rgba(p) = &frame.data else { panic!("not RGBA") }; + p.row(y as usize, frame.width as usize * 4)[x as usize * 4..][..4].try_into().unwrap() + } + + #[test] + fn the_blur_spreads_a_dot_and_keeps_a_flat_field() { + let mut workers = Workers::new("test-blur", 4); + let (w, h) = (64usize, 48usize); + let stride = w * 4; + // A flat field stays flat (the box blur is normalised). + let mut flat = vec![0u8; stride * h]; + for px in flat.chunks_exact_mut(4) { + px.copy_from_slice(&[40, 80, 120, 255]); + } + let mut scratch = vec![0u8; stride * h]; + blur_rgba(&mut workers, &mut flat, &mut scratch, w, h, stride, 5).unwrap(); + assert!(flat.chunks_exact(4).all(|px| px[..3] == [40, 80, 120]), "a flat field changed"); + + // A white block spreads and dims (a single pixel would not survive + // three integer passes, and no real picture looks like one). + let mut dot = vec![0u8; stride * h]; + for px in dot.chunks_exact_mut(4) { + px[3] = 255; + } + for y in h / 2 - 4..h / 2 + 4 { + for x in w / 2 - 4..w / 2 + 4 { + dot[y * stride + x * 4..][..3].copy_from_slice(&[255, 255, 255]); + } + } + blur_rgba(&mut workers, &mut dot, &mut scratch, w, h, stride, 4).unwrap(); + let at = |x: usize, y: usize| dot[y * stride + x * 4]; + assert!(at(w / 2, h / 2) > 0 && at(w / 2, h / 2) < 255, "the block did not dim"); + assert!(at(w / 2 + 6, h / 2) > 0, "the block did not spread sideways"); + assert!(at(w / 2, h / 2 + 6) > 0, "the block did not spread down"); + assert_eq!(at(0, 0), 0, "the corner should still be black"); + // Radius 0 is a no-op, and buffers that are too small are refused. + let mut small = vec![0u8; 8]; + assert!(blur_rgba(&mut workers, &mut small, &mut scratch, w, h, stride, 1).is_err()); + blur_rgba(&mut workers, &mut small, &mut scratch, w, h, stride, 0).unwrap(); + } + + #[test] + fn the_ellipse_covers_the_middle_and_not_the_corners() { + let mut segmenter = Ellipse::person(); + let mut mask = Mask::default(); + segmenter.mask(&flat_rgba(64, 64, [1, 2, 3, 255]), &mut mask).unwrap(); + assert_eq!((mask.width, mask.height), (64, 64)); + assert_eq!(mask.data[35 * 64 + 32], 255, "the middle is the subject"); + assert_eq!(mask.data[0], 0, "the corner is background"); + assert_eq!(mask.data[63 * 64 + 63], 0); + assert_eq!(segmenter.name(), "ellipse"); + // The edge fades rather than stepping. + let edge: Vec = (0..64).map(|x| mask.data[35 * 64 + x]).collect(); + assert!(edge.iter().any(|&v| v > 0 && v < 255), "no feathering: {edge:?}"); + } + + #[test] + fn a_colour_background_replaces_everything_but_the_subject() { + let mut filter = BackgroundFilter::with_default_segmenter(Background::Colour { + colour: Colour::rgb(200, 0, 0), + }); + assert_eq!(filter.segmenter(), "ellipse"); + let mut frame = flat_rgba(64, 64, [0, 255, 0, 255]); + // Wait for the first mask. + let started = Instant::now(); + while filter.masks() == 0 && started.elapsed() < Duration::from_secs(5) { + filter.apply(&mut frame.clone()).unwrap(); + std::thread::sleep(Duration::from_millis(10)); + } + assert!(filter.masks() > 0, "the segmenter produced no mask"); + // Give the handoff a moment, then apply for real. + for _ in 0..10 { + filter.apply(&mut frame).unwrap(); + if pixel(&frame, 0, 0)[0] > 100 { + break; + } + std::thread::sleep(Duration::from_millis(20)); + } + assert_eq!(pixel(&frame, 32, 35), [0, 255, 0, 255], "the subject is untouched"); + assert_eq!(pixel(&frame, 0, 0), [200, 0, 0, 255], "the corner became the colour"); + + // Keep does nothing at all. + filter.set_mode(Background::Keep); + let mut green = flat_rgba(8, 8, [0, 255, 0, 255]); + filter.apply(&mut green).unwrap(); + assert_eq!(pixel(&green, 0, 0), [0, 255, 0, 255]); + assert_eq!(filter.mode(), Background::Keep); + // Keep does not even look at the pixels, so I420 passes through. + filter.apply(&mut VideoFrame::black_i420(8, 8)).unwrap(); + // Any other mode needs RGBA and says so. + filter.set_mode(Background::Blur { strength: 0.05 }); + assert!(filter.apply(&mut VideoFrame::black_i420(8, 8)).is_err()); + } + + #[test] + fn a_blurred_background_keeps_the_subject_sharp() { + let mut filter = + BackgroundFilter::with_default_segmenter(Background::Blur { strength: 0.1 }); + filter.set_mask_fps(60); + // A checkerboard, so blurring is visible. + let mut frame = flat_rgba(64, 64, [0, 0, 0, 255]); + { + let FrameData::Rgba(p) = &mut frame.data else { panic!() }; + for y in 0..64usize { + for x in 0..64usize { + if (x / 2 + y / 2) % 2 == 0 { + p.data[y * 256 + x * 4..][..3].copy_from_slice(&[255, 255, 255]); + } + } + } + } + let original = frame.clone(); + let started = Instant::now(); + loop { + filter.apply(&mut frame).unwrap(); + if filter.masks() > 0 && pixel(&frame, 0, 0) != pixel(&original, 0, 0) { + break; + } + assert!(started.elapsed() < Duration::from_secs(10), "the blur never ran"); + std::thread::sleep(Duration::from_millis(20)); + frame = original.clone(); + } + // The corner is background: blurred towards grey. + let corner = pixel(&frame, 1, 1); + assert!((60..200).contains(&corner[0]), "the corner is not blurred: {corner:?}"); + // The middle is the subject: still full contrast between neighbours. + let a = pixel(&frame, 32, 35)[0]; + let b = pixel(&frame, 34, 35)[0]; + assert!(a.abs_diff(b) > 100, "the subject lost its contrast: {a} vs {b}"); + assert!(blur_radius(0.1, 720) > 1); + assert_eq!(blur_radius(0.0, 720), 0); + } +} diff --git a/crates/voelin-media/src/studio/source.rs b/crates/voelin-media/src/studio/source.rs index fe6be97..f08f06e 100644 --- a/crates/voelin-media/src/studio/source.rs +++ b/crates/voelin-media/src/studio/source.rs @@ -29,7 +29,8 @@ use crate::frame::{FrameData, FrameRef, PixelFormat, PixelsRef, Plane, VideoFram use crate::pool::FramePool; use crate::studio::camera; use crate::studio::compose::Feed; -use crate::studio::scene::{Align, Colour, SourceKind}; +use crate::studio::scene::{Align, Background, Colour, SourceKind}; +use crate::studio::segment::BackgroundFilter; use crate::{Error, Result}; /// The UI's font, for text sources without one of their own. The same file @@ -175,6 +176,8 @@ pub struct FeedSink { fps: Arc, pacer: FramePacer, rate: u32, + /// Background replacement, if this source has any. + filter: Option, } impl FeedSink { @@ -182,7 +185,21 @@ impl FeedSink { /// capturing. pub fn new(feed: Arc, fps: Arc) -> Self { let rate = fps.load(Ordering::Relaxed).max(1); - Self { feed, pool: FramePool::new(), fps, pacer: FramePacer::new(Some(rate)), rate } + Self { + feed, + pool: FramePool::new(), + fps, + pacer: FramePacer::new(Some(rate)), + rate, + filter: None, + } + } + + /// Replace the background of every frame; see + /// [`crate::studio::segment`]. + pub fn with_background(mut self, filter: BackgroundFilter) -> Self { + self.filter = Some(filter); + self } fn follow_rate(&mut self) -> u32 { @@ -213,7 +230,7 @@ impl FrameSink for FeedSink { return false; } self.pacer.keep(frame.timestamp); - match deliver(&mut self.pool, &self.feed, &frame) { + match deliver(&mut self.pool, &self.feed, &frame, self.filter.as_mut()) { Ok(()) => true, Err(e) => { warn!("cannot take a studio source frame: {e}"); @@ -224,13 +241,22 @@ impl FrameSink for FeedSink { } } -/// Copy `frame` into a pooled frame and publish it. -pub fn deliver(pool: &mut FramePool, feed: &Feed, frame: &FrameRef<'_>) -> Result<()> { +/// Copy `frame` into a pooled frame, replace its background if `filter` says +/// so, and publish it. +pub fn deliver( + pool: &mut FramePool, + feed: &Feed, + frame: &FrameRef<'_>, + filter: Option<&mut BackgroundFilter>, +) -> Result<()> { frame.validate()?; let (width, height) = (frame.width, frame.height); let row = width as usize * 4; + // Background replacement works on RGBA, so a filtered BGRA source is + // converted rather than copied. + let filtering = filter.as_ref().is_some_and(|f| f.mode().needs_mask()); let format = match frame.pixels { - PixelsRef::Bgra(_) => PixelFormat::Bgra, + PixelsRef::Bgra(_) if !filtering => PixelFormat::Bgra, // I420, NV12 and the rest become RGBA. _ => PixelFormat::Rgba, }; @@ -241,13 +267,21 @@ pub fn deliver(pool: &mut FramePool, feed: &Feed, frame: &FrameRef<'_>) -> Resul return Err(Error::InvalidFrame("the studio source pool is not packed".into())); }; match frame.pixels { - PixelsRef::Bgra(src) | PixelsRef::Rgba(src) => { + PixelsRef::Rgba(src) => { + for y in 0..height as usize { + plane.data[y * plane.stride..][..row].copy_from_slice(src.row(y, row)); + } + } + PixelsRef::Bgra(src) if !filtering => { for y in 0..height as usize { plane.data[y * plane.stride..][..row].copy_from_slice(src.row(y, row)); } } _ => crate::convert::to_rgba_ref(frame, &mut plane.data, plane.stride)?, } + if filtering && let Some(filter) = filter { + filter.apply(target)?; + } feed.put(slot.clone()); Ok(()) } @@ -287,6 +321,8 @@ fn screen_backend(name: Option<&str>) -> Result> { pub struct Input { pub feed: Arc, kind: SourceKind, + /// What the frames' background should become, shared with the filter. + background: Background, fps: Arc, /// Stopped when dropped. screen: Option>, @@ -300,12 +336,13 @@ impl Input { /// cannot start has its reason in [`Feed::error`] and draws nothing. /// /// Must run on a Tokio runtime for the portal kinds (they talk D-Bus). - pub async fn start(kind: SourceKind, fps: u32) -> Self { + pub async fn start(kind: SourceKind, fps: u32, background: Background) -> Self { let feed = Arc::new(Feed::new()); let mut input = Self { feed: feed.clone(), fps: Arc::new(AtomicU32::new(fps.max(1))), kind, + background, screen: None, camera: None, restore_token: None, @@ -339,8 +376,14 @@ impl Input { } SourceKind::Camera { device, size, fps, .. } => { let rate = fps.unwrap_or_else(|| self.fps.load(Ordering::Relaxed)); - let capture = - camera::Capture::start(device, *size, rate, self.feed.clone()).await?; + let capture = camera::Capture::start( + device, + *size, + rate, + self.feed.clone(), + self.background.clone(), + ) + .await?; debug!(device = %capture.backend(), "studio camera"); self.camera = Some(capture); } @@ -357,7 +400,13 @@ impl Input { cursor, ..CaptureOptions::default() }; - let sink = Box::new(FeedSink::new(self.feed.clone(), self.fps.clone())); + let mut sink = FeedSink::new(self.feed.clone(), self.fps.clone()); + if self.background.needs_mask() { + sink = sink.with_background(BackgroundFilter::with_default_segmenter( + self.background.clone(), + )); + } + let sink: Box = Box::new(sink); match kind { SourceKind::Pattern { size } => { let mut screen = SyntheticScreen::new(size.0.max(2), size.1.max(2)); @@ -388,6 +437,11 @@ impl Input { &self.kind } + /// What its frames' background becomes. + pub fn background(&self) -> &Background { + &self.background + } + /// Frame-rate cap; the capture follows without restarting. pub fn set_fps(&self, fps: u32) { self.fps.store(fps.max(1), Ordering::Relaxed); @@ -503,7 +557,8 @@ mod tests { #[tokio::test] async fn the_test_pattern_and_static_kinds_feed() { - let input = Input::start(SourceKind::Pattern { size: (64, 48) }, 30).await; + let input = + Input::start(SourceKind::Pattern { size: (64, 48) }, 30, Background::Keep).await; let started = std::time::Instant::now(); while input.feed.delivered() == 0 && started.elapsed() < Duration::from_secs(5) { tokio::time::sleep(Duration::from_millis(10)).await; @@ -515,14 +570,22 @@ mod tests { assert!(matches!(frame.data, FrameData::Bgra(_) | FrameData::Rgba(_))); input.set_fps(5); - let colour = - Input::start(SourceKind::Colour { colour: Colour::rgb(4, 5, 6), size: (8, 8) }, 30) - .await; + let colour = Input::start( + SourceKind::Colour { colour: Colour::rgb(4, 5, 6), size: (8, 8) }, + 30, + Background::Keep, + ) + .await; assert_eq!(colour.feed.delivered(), 1, "drawn once"); assert_eq!(pixel(&colour.feed.take().unwrap(), 0, 0), [4, 5, 6, 255]); // A broken source reports and draws nothing. - let broken = Input::start(SourceKind::Image { path: "/nonexistent.png".into() }, 30).await; + let broken = Input::start( + SourceKind::Image { path: "/nonexistent.png".into() }, + 30, + Background::Keep, + ) + .await; assert!(broken.feed.error().is_some()); assert!(broken.feed.take().is_none()); }