From bbe6dc039cc4b989cf6c3d3ec6b14eb4016295b0 Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 10:06:35 +0300 Subject: [PATCH 1/7] voelin-media: add the Stream Studio scene graph The studio needs a description of what it composites that survives a restart, so the UI's scenes and sources are one serde value (the `studio.scenes` setting) with a default for every field: adding a field later keeps older settings files loading. Co-Authored-By: Claude Opus 5 --- Cargo.lock | 2 + crates/voelin-media/Cargo.toml | 3 + crates/voelin-media/src/lib.rs | 1 + crates/voelin-media/src/studio/mod.rs | 7 + crates/voelin-media/src/studio/scene.rs | 636 ++++++++++++++++++++++++ 5 files changed, 649 insertions(+) create mode 100644 crates/voelin-media/src/studio/mod.rs create mode 100644 crates/voelin-media/src/studio/scene.rs diff --git a/Cargo.lock b/Cargo.lock index 2c2b55e..a921c1a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9182,6 +9182,8 @@ dependencies = [ "reqwest", "rtrb", "rustix 1.1.5", + "serde", + "serde_json", "sha2 0.10.9", "str0m", "thiserror 2.0.21", diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index 2d3fde2..b11e7be 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -43,6 +43,8 @@ openh264 = { version = "0.9.8", default-features = false, features = ["libloadin reqwest = { version = "0.13.5", default-features = false, features = ["rustls"], optional = true } # Lock-free single-producer rings from capture threads to the stream mixer. rtrb = "0.4.0" +# Scene graphs are serialised into the `studio.scenes` setting. +serde = { version = "1", features = ["derive"] } sha2 = { version = "0.10.9", optional = true } str0m = { version = "0.23.1", default-features = false, optional = true } thiserror = "2.0.21" @@ -71,6 +73,7 @@ windows-capture = "2.0.1" [dev-dependencies] criterion = "0.8" +serde_json = "1" # Logs of integration tests (`RUST_LOG`). tracing-subscriber = { version = "0.3", features = ["env-filter"] } tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread", "time"] } diff --git a/crates/voelin-media/src/lib.rs b/crates/voelin-media/src/lib.rs index e69b3c9..7a6a83f 100644 --- a/crates/voelin-media/src/lib.rs +++ b/crates/voelin-media/src/lib.rs @@ -39,6 +39,7 @@ pub mod mix; pub mod pool; pub mod queue; pub mod scale; +pub mod studio; pub mod workers; pub use capture::{AudioCapture, CaptureOptions, CaptureSource, ScreenCapture, SourceId}; diff --git a/crates/voelin-media/src/studio/mod.rs b/crates/voelin-media/src/studio/mod.rs new file mode 100644 index 0000000..cdca2f4 --- /dev/null +++ b/crates/voelin-media/src/studio/mod.rs @@ -0,0 +1,7 @@ +//! The Stream Studio: scenes of sources composited into one picture that the +//! streamer encodes, plus outputs that keep or forward the encoded packets. +//! +//! - [`scene`]: the scene graph (scenes, sources, transforms, crops), the +//! persisted shape of a studio + +pub mod scene; diff --git a/crates/voelin-media/src/studio/scene.rs b/crates/voelin-media/src/studio/scene.rs new file mode 100644 index 0000000..237fd22 --- /dev/null +++ b/crates/voelin-media/src/studio/scene.rs @@ -0,0 +1,636 @@ +//! The scene graph: scenes, their sources and how each source is placed. +//! +//! This is the persisted shape of a studio ([`Scenes`] is the value of the +//! `studio.scenes` setting), so every type here is serde-serialisable and +//! every field has a default: an older settings file keeps working when a +//! field is added. Nothing here captures, decodes or draws anything; the +//! compositor ([`crate::studio::compose`]) reads it and the sources +//! ([`crate::studio::source`]) do the work. +//! +//! There are no limits: any number of scenes, any number of sources per +//! scene. + +use std::path::PathBuf; + +use serde::{Deserialize, Serialize}; + +use crate::capture::SourceId; + +/// Straight (non-premultiplied) 8-bit colour. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Colour { + pub r: u8, + pub g: u8, + pub b: u8, + /// 255: opaque. + #[serde(default = "opaque")] + pub a: u8, +} + +fn opaque() -> u8 { + 255 +} + +impl Default for Colour { + fn default() -> Self { + Self::BLACK + } +} + +impl Colour { + pub const BLACK: Self = Self::rgb(0, 0, 0); + pub const WHITE: Self = Self::rgb(255, 255, 255); + /// Fully transparent. + pub const CLEAR: Self = Self { r: 0, g: 0, b: 0, a: 0 }; + + pub const fn rgb(r: u8, g: u8, b: u8) -> Self { + Self { r, g, b, a: 255 } + } + + pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self { + Self { r, g, b, a } + } + + /// The colour as RGBA bytes. + pub const fn to_rgba(self) -> [u8; 4] { + [self.r, self.g, self.b, self.a] + } +} + +/// How a source fills the box its [`Transform`] gives it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Fit { + /// Fill the box, changing the aspect ratio. + Stretch, + /// The whole source inside the box, keeping its aspect ratio (letterbox). + #[default] + Contain, + /// Fill the box keeping the aspect ratio, cropping what does not fit. + Cover, +} + +/// Where and how large a source is drawn, in output pixels. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Transform { + /// Top-left corner in output pixels; may be negative (drawn clipped). + pub x: f32, + pub y: f32, + /// The box to draw into. `None`: the source's own size (after the crop) + /// times [`scale`](Self::scale). + pub width: Option, + pub height: Option, + /// Factor on the source's own size, used where `width` / `height` are + /// `None`. + pub scale: f32, + pub fit: Fit, +} + +impl Default for Transform { + fn default() -> Self { + Self { x: 0.0, y: 0.0, width: None, height: None, scale: 1.0, fit: Fit::default() } + } +} + +impl Transform { + /// A box covering the whole `width` x `height` output. + pub fn full(width: u32, height: u32) -> Self { + Self::box_at(0.0, 0.0, width as f32, height as f32) + } + + /// A box at `(x, y)` of `width` x `height` output pixels. + pub fn box_at(x: f32, y: f32, width: f32, height: f32) -> Self { + Self { x, y, width: Some(width), height: Some(height), ..Self::default() } + } +} + +/// Pixels cut off each side of the source before it is placed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Crop { + pub left: u32, + pub top: u32, + pub right: u32, + pub bottom: u32, +} + +impl Crop { + pub fn is_none(&self) -> bool { + *self == Self::default() + } + + /// The cropped rectangle `(x, y, width, height)` of a `width` x `height` + /// source. Never empty: a crop that would leave nothing keeps one pixel. + pub fn apply(&self, width: u32, height: u32) -> (u32, u32, u32, u32) { + let x = self.left.min(width.saturating_sub(1)); + let y = self.top.min(height.saturating_sub(1)); + let w = width.saturating_sub(x + self.right).max(1).min(width - x); + let h = height.saturating_sub(y + self.bottom).max(1).min(height - y); + (x, y, w, h) + } +} + +/// What replaces the background of a camera or screen source; see +/// [`crate::studio::segment`]. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(tag = "mode", rename_all = "snake_case")] +pub enum Background { + /// Leave the frame alone (no segmentation runs). + #[default] + Keep, + /// Blur it. `strength` is the blur radius as a fraction of the frame + /// height (0.02 is a gentle blur, 0.1 a strong one). + Blur { + #[serde(default = "default_blur")] + strength: f32, + }, + /// Replace it with an image, scaled to cover the frame. + Image { path: PathBuf }, + /// Replace it with a colour. + Colour { colour: Colour }, +} + +fn default_blur() -> f32 { + 0.04 +} + +impl Background { + /// Whether this needs a person mask (and so the segmenter). + pub fn needs_mask(&self) -> bool { + !matches!(self, Self::Keep) + } +} + +/// How text is aligned in its box. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Align { + #[default] + Left, + Center, + Right, +} + +/// What a source shows. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum SourceKind { + /// A monitor, through one of the screen capture backends. + Screen { + #[serde(default)] + monitor: u32, + /// `portal`, `wlroots`, `x11`, `windows`; `None`: the best one for + /// this session. + #[serde(default)] + backend: Option, + #[serde(default = "yes")] + cursor: bool, + }, + /// A window by its native handle (X11 window id, Windows `HWND`). + Window { + handle: u64, + #[serde(default)] + backend: Option, + #[serde(default = "yes")] + cursor: bool, + }, + /// Whatever the desktop's ScreenCast portal dialog picks (Wayland). + Portal { + /// Token of an earlier choice: the desktop may skip its dialog. + #[serde(default)] + restore_token: Option, + #[serde(default = "yes")] + cursor: bool, + }, + /// A camera. `device` is a [`crate::studio::camera::Camera::id`]; empty: + /// the first camera found. + Camera { + #[serde(default)] + device: String, + /// Wanted capture size; `None`: the camera's default. + #[serde(default)] + size: Option<(u32, u32)>, + #[serde(default)] + fps: Option, + /// Mirror the picture (what people expect of a front camera). + #[serde(default)] + mirror: bool, + }, + /// A still image (PNG, JPEG, ...), with its alpha channel. + Image { path: PathBuf }, + /// Text rasterised with a TrueType font. + Text { + text: String, + /// A `.ttf` / `.otf` file; `None`: the bundled UI font. + #[serde(default)] + font: Option, + #[serde(default = "default_text_size")] + size_px: f32, + #[serde(default = "white")] + colour: Colour, + /// Filled behind the glyphs (transparent by default). Not named + /// `background`: [`Source::background`] is flattened into the same + /// object. + #[serde(default = "clear")] + backdrop: Colour, + #[serde(default)] + align: Align, + /// Pixels between the text and the edge of the source. + #[serde(default)] + padding: u32, + }, + /// A flat colour (a background, a divider, a placeholder). + Colour { + colour: Colour, + /// Its own size in pixels before the transform. + #[serde(default = "colour_size")] + size: (u32, u32), + }, + /// The synthetic test pattern (tests and previews). + Pattern { + #[serde(default = "pattern_size")] + size: (u32, u32), + }, +} + +fn yes() -> bool { + true +} + +fn default_text_size() -> f32 { + 48.0 +} + +fn white() -> Colour { + Colour::WHITE +} + +fn clear() -> Colour { + Colour::CLEAR +} + +fn colour_size() -> (u32, u32) { + (1920, 1080) +} + +fn pattern_size() -> (u32, u32) { + (1280, 720) +} + +impl SourceKind { + /// A short name for the kind, for logs and the UI. + pub fn label(&self) -> &'static str { + match self { + Self::Screen { .. } => "screen", + Self::Window { .. } => "window", + Self::Portal { .. } => "portal", + Self::Camera { .. } => "camera", + Self::Image { .. } => "image", + Self::Text { .. } => "text", + Self::Colour { .. } => "colour", + Self::Pattern { .. } => "pattern", + } + } + + /// The capture source this kind asks a [`crate::ScreenCapture`] backend + /// for, if it is a screen capture at all. + pub fn capture_source(&self) -> Option { + match self { + Self::Screen { monitor, .. } => Some(SourceId::Monitor(*monitor)), + Self::Window { handle, .. } => Some(SourceId::Window(*handle)), + Self::Portal { .. } => Some(SourceId::Portal), + Self::Pattern { .. } => Some(SourceId::Synthetic), + _ => None, + } + } + + /// Whether two kinds describe the same live input, so a source that + /// changes from one to the other need not restart (only its drawing + /// changes). + pub fn same_input(&self, other: &Self) -> bool { + match (self, other) { + // Text and colour are redrawn, not recaptured. + (Self::Text { .. }, Self::Text { .. }) | (Self::Colour { .. }, Self::Colour { .. }) => { + true + } + _ => self == other, + } + } +} + +/// One source of a scene. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Source { + /// Stable within its scene, for the UI and the controller API. + pub id: u64, + /// Shown in the source list; empty: [`SourceKind::label`]. + #[serde(default)] + pub name: String, + #[serde(flatten)] + pub kind: SourceKind, + #[serde(default)] + pub transform: Transform, + #[serde(default)] + pub crop: Crop, + /// 0: invisible, 1: opaque. + #[serde(default = "unity")] + pub opacity: f32, + #[serde(default = "yes")] + pub visible: bool, + /// The UI refuses to move or resize a locked source. + #[serde(default)] + pub locked: bool, + /// Background replacement (cameras and screens). + #[serde(default)] + pub background: Background, +} + +fn unity() -> f32 { + 1.0 +} + +impl Source { + /// A source of `kind` with id `id` and everything else default. + pub fn new(id: u64, kind: SourceKind) -> Self { + Self { + id, + name: String::new(), + kind, + transform: Transform::default(), + crop: Crop::default(), + opacity: 1.0, + visible: true, + locked: false, + background: Background::default(), + } + } + + /// Its name, or the kind's label. + pub fn label(&self) -> &str { + if self.name.is_empty() { self.kind.label() } else { &self.name } + } + + /// Whether it contributes anything to the composite. + pub fn drawn(&self) -> bool { + self.visible && self.opacity > 0.0 + } +} + +/// A scene: sources drawn back to front over a background. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Scene { + pub id: u64, + #[serde(default)] + pub name: String, + /// Drawn in order, so the last one is on top. + #[serde(default)] + pub sources: Vec, + /// Filled before the sources. + #[serde(default)] + pub background: Colour, +} + +impl Scene { + pub fn new(id: u64, name: impl Into) -> Self { + Self { id, name: name.into(), sources: Vec::new(), background: Colour::BLACK } + } + + pub fn source(&self, id: u64) -> Option<&Source> { + self.sources.iter().find(|s| s.id == id) + } + + pub fn source_mut(&mut self, id: u64) -> Option<&mut Source> { + self.sources.iter_mut().find(|s| s.id == id) + } + + /// The next free source id. + pub fn next_source_id(&self) -> u64 { + self.sources.iter().map(|s| s.id + 1).max().unwrap_or(1) + } +} + +/// Every scene of a studio and which one is live. The value of the +/// `studio.scenes` setting. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Scenes { + pub scenes: Vec, + /// The scene being composited; ignored if no scene has this id. + pub active: u64, + /// Output size of the composite. + pub width: u32, + pub height: u32, + pub fps: u32, +} + +impl Default for Scenes { + fn default() -> Self { + Self { scenes: Vec::new(), active: 0, width: 1920, height: 1080, fps: 30 } + } +} + +impl Scenes { + /// The live scene: the one with id [`active`](Self::active), else the + /// first. + pub fn active(&self) -> Option<&Scene> { + self.scenes.iter().find(|s| s.id == self.active).or_else(|| self.scenes.first()) + } + + pub fn active_mut(&mut self) -> Option<&mut Scene> { + let id = self.active().map(|s| s.id)?; + self.scenes.iter_mut().find(|s| s.id == id) + } + + pub fn scene(&self, id: u64) -> Option<&Scene> { + self.scenes.iter().find(|s| s.id == id) + } + + pub fn scene_mut(&mut self, id: u64) -> Option<&mut Scene> { + self.scenes.iter_mut().find(|s| s.id == id) + } + + /// The next free scene id. + pub fn next_scene_id(&self) -> u64 { + self.scenes.iter().map(|s| s.id + 1).max().unwrap_or(1) + } + + /// Output size, at least 2x2 and even (the encoders want even sizes). + pub fn size(&self) -> (u32, u32) { + (self.width.max(2) & !1, self.height.max(2) & !1) + } + + pub fn fps(&self) -> u32 { + self.fps.max(1) + } + + /// What is wrong with these scenes, if anything. Duplicate ids are the + /// one thing the rest of the studio cannot cope with. + pub fn check(&self) -> Result<(), String> { + for (i, scene) in self.scenes.iter().enumerate() { + if self.scenes[..i].iter().any(|s| s.id == scene.id) { + return Err(format!("scene id {} appears twice", scene.id)); + } + for (j, source) in scene.sources.iter().enumerate() { + if scene.sources[..j].iter().any(|s| s.id == source.id) { + return Err(format!( + "scene {}: source id {} appears twice", + scene.id, source.id + )); + } + if !(source.opacity.is_finite() && (0.0..=1.0).contains(&source.opacity)) { + return Err(format!( + "scene {} source {}: opacity must be between 0 and 1", + scene.id, source.id + )); + } + let t = &source.transform; + if !(t.x.is_finite() && t.y.is_finite() && t.scale.is_finite() && t.scale > 0.0) { + return Err(format!( + "scene {} source {}: position must be finite and scale above 0", + scene.id, source.id + )); + } + if [t.width, t.height].iter().flatten().any(|v| !(v.is_finite() && *v > 0.0)) { + return Err(format!( + "scene {} source {}: width and height must be finite and above 0", + scene.id, source.id + )); + } + if let Background::Blur { strength } = &source.background + && !(strength.is_finite() && *strength >= 0.0) + { + return Err(format!( + "scene {} source {}: blur strength must be a number >= 0", + scene.id, source.id + )); + } + } + } + if self.width == 0 || self.height == 0 { + return Err("the output size must not be zero".into()); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn serde_round_trip_and_defaults() { + let mut scenes = Scenes { width: 1280, height: 720, fps: 60, ..Scenes::default() }; + let mut main = Scene::new(1, "Main"); + main.sources.push(Source { + transform: Transform::full(1280, 720), + ..Source::new(1, SourceKind::Screen { monitor: 0, backend: None, cursor: true }) + }); + main.sources.push(Source { + name: "Cam".into(), + transform: Transform::box_at(960.0, 540.0, 320.0, 180.0), + crop: Crop { left: 10, top: 0, right: 10, bottom: 0 }, + opacity: 0.8, + background: Background::Blur { strength: 0.05 }, + ..Source::new( + 2, + SourceKind::Camera { + device: "cam0".into(), + size: Some((1280, 720)), + fps: Some(30), + mirror: true, + }, + ) + }); + main.sources.push(Source::new( + 3, + SourceKind::Text { + text: "LIVE".into(), + font: None, + size_px: 64.0, + colour: Colour::rgb(255, 64, 64), + backdrop: Colour::CLEAR, + align: Align::Center, + padding: 8, + }, + )); + scenes.scenes.push(main); + scenes.scenes.push(Scene::new(2, "Break")); + scenes.active = 2; + scenes.check().unwrap(); + + let json = serde_json::to_string(&scenes).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), scenes); + // The kind is flattened into the source, so a scene file reads well. + assert!(json.contains(r#""kind":"camera""#), "{json}"); + + // Everything but the ids and the kind has a default. + let terse: Scenes = serde_json::from_str( + r#"{"scenes":[{"id":7,"sources":[{"id":1,"kind":"colour", + "colour":{"r":1,"g":2,"b":3}}]}]}"#, + ) + .unwrap(); + let source = &terse.scenes[0].sources[0]; + assert_eq!(source.opacity, 1.0); + assert!(source.visible && !source.locked); + assert_eq!(source.transform, Transform::default()); + assert_eq!(source.background, Background::Keep); + assert_eq!( + source.kind, + SourceKind::Colour { colour: Colour::rgb(1, 2, 3), size: (1920, 1080) } + ); + // No active id: the first scene is live. + assert_eq!(terse.active().map(|s| s.id), Some(7)); + assert_eq!(terse.size(), (1920, 1080)); + } + + #[test] + fn check_rejects_duplicates_and_nonsense() { + let mut scenes = Scenes::default(); + scenes.scenes.push(Scene::new(1, "a")); + scenes.scenes.push(Scene::new(1, "b")); + assert!(scenes.check().unwrap_err().contains("scene id 1")); + scenes.scenes[1].id = 2; + scenes.check().unwrap(); + assert_eq!(scenes.next_scene_id(), 3); + + let scene = &mut scenes.scenes[0]; + scene + .sources + .push(Source::new(5, SourceKind::Colour { colour: Colour::BLACK, size: (4, 4) })); + scene.sources.push(Source::new(5, SourceKind::Pattern { size: (4, 4) })); + assert!(scenes.check().unwrap_err().contains("source id 5")); + scenes.scenes[0].sources[1].id = 6; + assert_eq!(scenes.scenes[0].next_source_id(), 7); + scenes.scenes[0].sources[0].opacity = 1.5; + assert!(scenes.check().unwrap_err().contains("opacity")); + scenes.scenes[0].sources[0].opacity = 1.0; + scenes.scenes[0].sources[0].transform.scale = 0.0; + assert!(scenes.check().unwrap_err().contains("scale")); + scenes.scenes[0].sources[0].transform = + Transform { width: Some(f32::INFINITY), ..Transform::default() }; + assert!(scenes.check().unwrap_err().contains("width and height")); + } + + #[test] + fn crop_and_labels() { + assert_eq!(Crop::default().apply(100, 50), (0, 0, 100, 50)); + assert_eq!(Crop { left: 10, top: 5, right: 20, bottom: 5 }.apply(100, 50), (10, 5, 70, 40)); + // A crop that leaves nothing keeps one pixel. + assert_eq!(Crop { left: 60, top: 0, right: 60, bottom: 0 }.apply(100, 50), (60, 0, 1, 50)); + assert_eq!(Crop { left: 200, top: 0, right: 0, bottom: 0 }.apply(100, 50), (99, 0, 1, 50)); + assert!(Crop::default().is_none()); + + let source = Source::new(1, SourceKind::Pattern { size: (2, 2) }); + assert_eq!(source.label(), "pattern"); + assert_eq!(source.kind.capture_source(), Some(SourceId::Synthetic)); + assert!(source.drawn()); + assert!(!Source { opacity: 0.0, ..source.clone() }.drawn()); + assert!(!Source { visible: false, ..source }.drawn()); + assert_eq!( + SourceKind::Window { handle: 9, backend: None, cursor: false }.capture_source(), + Some(SourceId::Window(9)) + ); + assert!(SourceKind::Image { path: "a.png".into() }.capture_source().is_none()); + } +} From 2183ee73c42354686ca330ba22f27553d43954ba Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 13:39:12 +0300 Subject: [PATCH 2/7] voelin-media: composite a studio scene into pooled frames The studio needs one picture per output frame from any number of sources that each run at their own pace, so the compositor takes each source's newest frame through a latest-wins handoff and draws the scene back to front into a pooled RGBA canvas, in bands of rows on a worker pool. The plan (destination rectangles and filter weights) is kept while neither the scene nor a source size changes, which is what lets a steady composite allocate nothing per frame -- the property tests/studio_alloc.rs pins down. Frames are RGBA because alpha blending and text need it; the streamer's existing conversion turns the canvas into I420 for the encoders in one SIMD pass. Scaling reuses scale.rs's weight tables with an inner loop for interleaved pixels, and a straight copy at 1:1, the common case for a screen that already matches the canvas. FramePool grew a format so the same recycling works for the canvas, and the preview tap scales the canvas down through the same filter. Co-Authored-By: Claude Opus 5 --- crates/voelin-media/src/pool.rs | 60 +- crates/voelin-media/src/scale.rs | 10 +- crates/voelin-media/src/studio/compose.rs | 984 ++++++++++++++++++++++ crates/voelin-media/src/studio/mod.rs | 3 + crates/voelin-media/tests/studio_alloc.rs | 195 +++++ 5 files changed, 1233 insertions(+), 19 deletions(-) create mode 100644 crates/voelin-media/src/studio/compose.rs create mode 100644 crates/voelin-media/tests/studio_alloc.rs diff --git a/crates/voelin-media/src/pool.rs b/crates/voelin-media/src/pool.rs index 34b8c5f..53a68e6 100644 --- a/crates/voelin-media/src/pool.rs +++ b/crates/voelin-media/src/pool.rs @@ -1,7 +1,7 @@ //! Recycled I420 frames. //! //! A [`FramePool`] belongs to one producer (e.g. the capture thread). It -//! hands out frames of one size for writing; the producer shares them as +//! hands out frames of one size and format for writing; the producer shares them as //! `Arc`, and once every consumer dropped its clone the frame is //! free again. Frames are allocated only when all are in use or the size //! changes, so a steady stream reuses the same few buffers. @@ -9,16 +9,22 @@ use std::sync::Arc; use std::time::Duration; -use crate::frame::{FrameData, Plane, VideoFrame, chroma_size}; +use crate::frame::{FrameData, PixelFormat, Plane, VideoFrame, chroma_size}; -/// Recycled I420 frames of one size (tightly packed planes). -#[derive(Default)] +/// Recycled frames of one size and pixel format (tightly packed planes). pub struct FramePool { frames: Vec>, size: (u32, u32), + format: PixelFormat, allocated: u64, } +impl Default for FramePool { + fn default() -> Self { + Self { frames: Vec::new(), size: (0, 0), format: PixelFormat::I420, allocated: 0 } + } +} + impl FramePool { pub fn new() -> Self { Self::default() @@ -29,16 +35,27 @@ impl FramePool { /// share it. Changing the size drops the pool's other frames (those still /// in use are freed by their last user). pub fn get(&mut self, width: u32, height: u32) -> &mut Arc { - if self.size != (width, height) { + self.get_format(width, height, PixelFormat::I420) + } + + /// As [`FramePool::get`], of `format` (I420, NV12, BGRA or RGBA). + pub fn get_format( + &mut self, + width: u32, + height: u32, + format: PixelFormat, + ) -> &mut Arc { + if self.size != (width, height) || self.format != format { self.frames.clear(); self.size = (width, height); + self.format = format; } let free = self.frames.iter_mut().position(|f| Arc::get_mut(f).is_some()); let index = match free { Some(i) => i, None => { self.allocated += 1; - self.frames.push(Arc::new(blank_i420(width, height))); + self.frames.push(Arc::new(blank(width, height, format))); self.frames.len() - 1 } }; @@ -60,19 +77,23 @@ impl FramePool { } } -/// A zeroed I420 frame with tightly packed planes. -fn blank_i420(width: u32, height: u32) -> VideoFrame { +/// A zeroed frame with tightly packed planes. +fn blank(width: u32, height: u32, format: PixelFormat) -> VideoFrame { + let (w, h) = (width as usize, height as usize); let (cw, ch) = chroma_size(width, height); - VideoFrame { - width, - height, - timestamp: Duration::ZERO, - data: FrameData::I420 { - y: Plane::filled(width as usize, height as usize, 0), + let data = match format { + PixelFormat::I420 => FrameData::I420 { + y: Plane::filled(w, h, 0), u: Plane::filled(cw, ch, 0), v: Plane::filled(cw, ch, 0), }, - } + PixelFormat::Nv12 => { + FrameData::Nv12 { y: Plane::filled(w, h, 0), uv: Plane::filled(cw * 2, ch, 0) } + } + PixelFormat::Bgra => FrameData::Bgra(Plane::filled(w * 4, h, 0)), + PixelFormat::Rgba => FrameData::Rgba(Plane::filled(w * 4, h, 0)), + }; + VideoFrame { width, height, timestamp: Duration::ZERO, data } } #[cfg(test)] @@ -96,5 +117,14 @@ mod tests { assert_eq!((d.width, d.height), (32, 16)); d.validate().unwrap(); assert_eq!(pool.len(), 1); + // So does a new format. + drop(d); + let e = pool.get_format(32, 16, PixelFormat::Rgba).clone(); + assert_eq!(e.format(), PixelFormat::Rgba); + e.validate().unwrap(); + assert_eq!(pool.len(), 1); + drop(e); + assert!(pool.get_format(32, 16, PixelFormat::Rgba).format() == PixelFormat::Rgba); + assert_eq!(pool.allocated(), 5, "a frame is reused within one size and format"); } } diff --git a/crates/voelin-media/src/scale.rs b/crates/voelin-media/src/scale.rs index 155662b..0784113 100644 --- a/crates/voelin-media/src/scale.rs +++ b/crates/voelin-media/src/scale.rs @@ -23,7 +23,8 @@ use crate::{Error, Result}; /// Fixed-point scale of filter weights. const ONE: u32 = 1 << 14; /// Fractional bits kept between the vertical and the horizontal pass. -const MID_BITS: u32 = 6; +/// [`crate::studio::compose`] uses the same two-pass layout for RGBA. +pub(crate) const MID_BITS: u32 = 6; /// Filter taps of one output coordinate: source index of the first tap, and /// where its weights start. @@ -36,14 +37,14 @@ struct Taps { /// The filter along one axis. #[derive(Clone, Debug, Default)] -struct Axis { +pub(crate) struct Axis { taps: Vec, weights: Vec, } impl Axis { /// Weights (summing to [`ONE`]) mapping `src` samples to `dst`. - fn new(src: usize, dst: usize) -> Self { + pub(crate) fn new(src: usize, dst: usize) -> Self { let mut axis = Self { taps: Vec::with_capacity(dst), weights: Vec::new() }; let ratio = src as f64 / dst as f64; let mut scratch: Vec<(usize, f64)> = Vec::new(); @@ -92,7 +93,8 @@ impl Axis { self.taps.push(Taps { start: taps[0].0 as u32, len: taps.len() as u32, weights: offset }); } - fn get(&self, o: usize) -> (usize, &[u32]) { + /// Source index of the first tap of output `o`, and its weights. + pub(crate) fn get(&self, o: usize) -> (usize, &[u32]) { let t = self.taps[o]; (t.start as usize, &self.weights[t.weights as usize..(t.weights + t.len) as usize]) } diff --git a/crates/voelin-media/src/studio/compose.rs b/crates/voelin-media/src/studio/compose.rs new file mode 100644 index 0000000..3078645 --- /dev/null +++ b/crates/voelin-media/src/studio/compose.rs @@ -0,0 +1,984 @@ +//! Compositing a scene into one picture. +//! +//! Each source runs on its own thread and publishes its newest picture into a +//! [`Feed`] (a one-slot latest-wins [`Handoff`]); the compositor takes the +//! newest one of every source and draws them back to front into a pooled +//! RGBA frame at the output size. A source that has not delivered a new +//! picture keeps the one it had, so a 5 fps camera does not blink in a 60 fps +//! composite. +//! +//! The plan (which source rectangle goes where, and the filter weights for +//! it) is rebuilt only when the scene, a source size or the output size +//! changes, and the canvas comes from a [`FramePool`], so a steady composite +//! allocates nothing: [`Compositor::compose`] is on the video path. +//! +//! Drawing is split into bands of output rows on a [`Workers`] pool; every +//! band draws every source that reaches into it, in scene order, so the +//! result is the same as drawing the whole canvas source by source. +//! +//! Scaling uses the same separable fixed-point filter as [`crate::scale`] +//! (area averaging down, bilinear up) with an inner loop for interleaved +//! RGBA, and a straight copy at 1:1. Sources with an alpha channel (images +//! and text) and sources below full opacity are blended over what is +//! already there. + +use std::ops::Range; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use crate::frame::{FrameData, PixelFormat, PlaneRef, VideoFrame}; +use crate::handoff::Handoff; +use crate::pool::FramePool; +use crate::scale::{Axis, MID_BITS}; +use crate::studio::scene::{Fit, Scene, SourceKind}; +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) +} + +/// What the compositor draws one source from: its newest picture, plus what +/// the source thread wants to report. +/// +/// Sources publish BGRA or RGBA frames (that is what compositing needs); +/// [`crate::convert::to_rgba`] turns a camera's YUV into one. +#[derive(Default)] +pub struct Feed { + frames: Handoff, + delivered: AtomicU64, + /// `width << 32 | height` of the last frame. + size: AtomicU64, + /// Why the source shows nothing (no such camera, the window closed, a + /// file that cannot be read, ...). + error: Mutex>, +} + +impl Feed { + pub fn new() -> Self { + Self::default() + } + + /// Offer the newest picture; an older one the compositor has not taken is + /// replaced. + pub fn put(&self, frame: Arc) { + self.size.store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed); + self.delivered.fetch_add(1, Ordering::Relaxed); + self.frames.put(frame); + } + + /// The newest picture, if one arrived since the last call. + pub fn take(&self) -> Option> { + self.frames.take() + } + + /// Frames the source delivered. + pub fn delivered(&self) -> u64 { + self.delivered.load(Ordering::Relaxed) + } + + /// Frames replaced before the compositor took them (the source is faster + /// than the composite). + pub fn dropped(&self) -> u64 { + self.frames.replaced() + } + + /// Size of the last frame, or `(0, 0)`. + pub fn size(&self) -> (u32, u32) { + let size = self.size.load(Ordering::Relaxed); + ((size >> 32) as u32, size as u32) + } + + pub fn set_error(&self, error: impl ToString) { + *lock(&self.error) = Some(error.to_string()); + } + + pub fn clear_error(&self) { + *lock(&self.error) = None; + } + + pub fn error(&self) -> Option { + lock(&self.error).clone() + } + + /// Tell the source thread to stop. + pub fn close(&self) { + self.frames.close(); + } + + pub fn is_closed(&self) -> bool { + self.frames.is_closed() + } +} + +/// `v / 255`, rounded. +#[inline] +fn div255(v: u32) -> u8 { + let t = v + 128; + ((t + (t >> 8)) >> 8) as u8 +} + +/// Write one RGB pixel with coverage `a` (0..=255) over `dst`. +#[inline] +fn put_pixel(dst: &mut [u8], rgb: [u8; 3], a: u32) { + if a == 255 { + dst[..3].copy_from_slice(&rgb); + } else if a > 0 { + for c in 0..3 { + dst[c] = div255(u32::from(rgb[c]) * a + u32::from(dst[c]) * (255 - a)); + } + } + // The canvas is opaque: it becomes I420 for the encoders. + dst[3] = 255; +} + +/// One source rectangle mapped onto the canvas, with its filter weights. +struct Blit { + /// Which of the scene's sources this draws. + source: usize, + /// Source rectangle after the crop, in source pixels. + sx: usize, + sy: usize, + sw: usize, + sh: usize, + /// Where the unclipped destination starts on the canvas (may be + /// negative). + dx: isize, + dy: isize, + /// Size of the unclipped destination. + dw: usize, + dh: usize, + /// Destination columns and rows on the canvas, in destination + /// coordinates. + cols: Range, + rows: Range, + x: Axis, + y: Axis, + /// Same size: copy rows instead of filtering. + direct: bool, + /// The source's bytes are B, G, R, A. + bgra: bool, + /// The source's alpha channel means something (images, text). + alpha: bool, + /// 0..=255. + opacity: u8, + /// Mirror horizontally (front cameras). + mirror: bool, +} + +impl Blit { + /// Destination rows of this blit inside canvas rows `band`. + fn band_rows(&self, band: &Range) -> Range { + let first = (band.start as isize - self.dy).max(self.rows.start as isize) as usize; + let last = (band.end as isize - self.dy).clamp(0, self.rows.end as isize) as usize; + first..last.max(first) + } + + /// Draw the rows of this blit that fall in canvas rows `band`. `out` + /// starts at canvas row `band.start`; `tmp` is scratch for one + /// vertically filtered source row. + fn draw( + &self, + src: PlaneRef<'_>, + out: &mut [u8], + out_stride: usize, + band: &Range, + tmp: &mut [u16], + ) { + let rows = self.band_rows(band); + if rows.is_empty() || self.cols.is_empty() { + return; + } + let opaque = self.opacity == 255 && !self.alpha; + for r in rows { + let line = ((self.dy + r as isize) as usize - band.start) * out_stride; + let out_x = (self.dx + self.cols.start as isize) as usize * 4; + let line = &mut out[line + out_x..][..self.cols.len() * 4]; + if self.direct { + self.copy_row(src, line, r, opaque); + } else { + self.filter_row(src, line, r, opaque, tmp); + } + } + } + + /// One destination row at 1:1. + fn copy_row(&self, src: PlaneRef<'_>, line: &mut [u8], r: usize, opaque: bool) { + let row = src.row(self.sy + r, (self.sx + self.sw) * 4); + let first = if self.mirror { self.dw - self.cols.end } else { self.cols.start }; + let row = &row[(self.sx + first) * 4..][..self.cols.len() * 4]; + if opaque && !self.bgra && !self.mirror { + line.copy_from_slice(row); + for px in line.chunks_exact_mut(4) { + px[3] = 255; + } + return; + } + let pixels = row.chunks_exact(4); + // Mirrored: the destination's first column is the source's last. + let opacity = u32::from(self.opacity); + let write = |px: &[u8], dst: &mut [u8]| { + let rgb = if self.bgra { [px[2], px[1], px[0]] } else { [px[0], px[1], px[2]] }; + let a = if self.alpha { opacity * u32::from(px[3]) / 255 } else { opacity }; + put_pixel(dst, rgb, a); + }; + if self.mirror { + for (px, dst) in pixels.rev().zip(line.chunks_exact_mut(4)) { + write(px, dst); + } + } else { + for (px, dst) in pixels.zip(line.chunks_exact_mut(4)) { + write(px, dst); + } + } + } + + /// One destination row through the separable filter: a vertical pass into + /// `tmp` (with [`MID_BITS`] fractional bits), then a horizontal one. + fn filter_row( + &self, + src: PlaneRef<'_>, + line: &mut [u8], + r: usize, + opaque: bool, + tmp: &mut [u16], + ) { + let bytes = self.sw * 4; + let (start, weights) = self.y.get(r); + const CHUNK: usize = 64; + let mut acc = [0u32; CHUNK]; + let mut x0 = 0; + while x0 < bytes { + let n = CHUNK.min(bytes - x0); + let acc = &mut acc[..n]; + acc.fill(0); + for (k, &w) in weights.iter().enumerate() { + let row = src.row(self.sy + start + k, (self.sx + self.sw) * 4); + for (a, &p) in acc.iter_mut().zip(&row[self.sx * 4 + x0..][..n]) { + *a += w * u32::from(p); + } + } + for (t, &a) in tmp[x0..x0 + n].iter_mut().zip(acc.iter()) { + *t = ((a + (1 << (13 - MID_BITS))) >> (14 - MID_BITS)) as u16; + } + x0 += n; + } + let opacity = u32::from(self.opacity); + for (i, dst) in line.chunks_exact_mut(4).enumerate() { + let ox = self.cols.start + i; + let (start, weights) = self.x.get(if self.mirror { self.dw - 1 - ox } else { ox }); + let mut px = [0u32; 4]; + for (k, &w) in weights.iter().enumerate() { + let tap = &tmp[(start + k) * 4..][..4]; + for (p, &t) in px.iter_mut().zip(tap) { + *p += w * u32::from(t); + } + } + const ROUND: u32 = 1 << (13 + MID_BITS); + let s = px.map(|p| ((p + ROUND) >> (14 + MID_BITS)).min(255) as u8); + let rgb = if self.bgra { [s[2], s[1], s[0]] } else { [s[0], s[1], s[2]] }; + let a = if opaque { + 255 + } else if self.alpha { + opacity * u32::from(s[3]) / 255 + } else { + opacity + }; + put_pixel(dst, rgb, a); + } + } +} + +/// How the compositor is doing. Read through [`Compositor::stats`]. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct ComposeStats { + pub frames: u64, + /// Mean time to composite a frame. + pub compose_time: Duration, + /// Times the plan was rebuilt (a scene change, a source that resized). + pub replans: u64, + /// Canvases the pool had to allocate. + pub allocated: u64, + pub threads: usize, +} + +/// Composites a scene into pooled RGBA frames; see the [module docs](self). +pub struct Compositor { + workers: Workers, + pool: FramePool, + size: (u32, u32), + /// Each scene source's newest picture (an empty feed keeps the last one). + held: Vec>>, + /// The source ids `held` belongs to. + held_ids: Vec, + blits: Vec, + /// One vertically filtered source row per band. + scratch: Vec>>, + /// The background colour as one output row, memcpy'd per row. + background: Vec, + /// What the plan was made for. + planned: Option<(u64, (u32, u32))>, + planned_sizes: Vec<(u32, u32)>, + frames: u64, + compose_ns: u64, + replans: u64, +} + +impl Compositor { + /// `threads` as in [`Workers::new`] (0: one per CPU). + pub fn new(threads: usize) -> Self { + Self { + workers: Workers::new("voelin-compose", threads), + pool: FramePool::new(), + size: (0, 0), + held: Vec::new(), + held_ids: Vec::new(), + blits: Vec::new(), + scratch: Vec::new(), + background: Vec::new(), + planned: None, + planned_sizes: Vec::new(), + frames: 0, + compose_ns: 0, + replans: 0, + } + } + + /// Output size of the composite; at least 2x2 and even. + pub fn set_size(&mut self, width: u32, height: u32) { + self.size = (width.max(2) & !1, height.max(2) & !1); + } + + pub fn size(&self) -> (u32, u32) { + self.size + } + + pub fn stats(&self) -> ComposeStats { + ComposeStats { + frames: self.frames, + compose_time: match self.frames { + 0 => Duration::ZERO, + n => Duration::from_nanos(self.compose_ns / n), + }, + replans: self.replans, + allocated: self.pool.allocated(), + threads: self.workers.threads(), + } + } + + /// Drop every picture held from an earlier scene. + pub fn reset(&mut self) { + self.held.clear(); + self.held_ids.clear(); + self.planned = None; + } + + /// Composite `scene` into a pooled RGBA frame stamped `timestamp`. + /// + /// `feeds[i]` is the live input of `scene.sources[i]` (`None`: not + /// running, drawn as nothing). `revision` must change whenever `scene` + /// does; the plan and its filter weights are kept while it and the source + /// sizes stay the same. + pub fn compose( + &mut self, + scene: &Scene, + revision: u64, + feeds: &[Option>], + timestamp: Duration, + ) -> Result> { + let (width, height) = self.size; + if width == 0 || height == 0 { + return Err(Error::InvalidFrame("the studio output size is not set".into())); + } + let started = Instant::now(); + self.collect(scene, feeds); + if self.planned != Some((revision, self.size)) + || self.planned_sizes.len() != scene.sources.len() + || self.held.iter().zip(&self.planned_sizes).any(|(held, planned)| { + held.as_ref().map_or((0, 0), |f| (f.width, f.height)) != *planned + }) { + self.plan(scene, revision); + } + let canvas = self.pool.get_format(width, height, PixelFormat::Rgba); + let frame = Arc::get_mut(canvas).expect("the pool hands out unshared frames"); + frame.timestamp = timestamp; + let FrameData::Rgba(plane) = &mut frame.data else { + return Err(Error::InvalidFrame("the studio canvas is not RGBA".into())); + }; + let stride = plane.stride; + let tasks = self.workers.tasks(height as usize); + let band = (height as usize).div_ceil(tasks); + let tasks = (height as usize).div_ceil(band); + while self.scratch.len() < tasks { + self.scratch.push(Mutex::new(Vec::new())); + } + let longest = self.blits.iter().map(|b| b.sw * 4).max().unwrap_or(0); + for slot in &mut self.scratch { + let tmp = slot.get_mut().unwrap_or_else(PoisonError::into_inner); + if tmp.len() < longest { + tmp.resize(longest, 0); + } + } + let slots = Slots::new(plane.data.chunks_mut(band * stride).take(tasks).enumerate()); + let (blits, held, background, scratch) = + (&self.blits, &self.held, &self.background, &self.scratch); + self.workers.run(slots.len(), &|task| { + let Some((i, out)) = slots.take(task) else { return }; + let rows = i * band..((i + 1) * band).min(height as usize); + for row in 0..rows.len() { + out[row * stride..][..background.len()].copy_from_slice(background); + } + let mut tmp = lock(&scratch[i]); + for blit in blits { + let Some(frame) = held[blit.source].as_ref() else { continue }; + let plane = match &frame.data { + FrameData::Bgra(p) | FrameData::Rgba(p) => p.view(), + // The plan only makes blits for packed sources. + _ => continue, + }; + blit.draw(plane, out, stride, &rows, &mut tmp); + } + }); + self.frames += 1; + self.compose_ns += started.elapsed().as_nanos() as u64; + Ok(canvas.clone()) + } + + /// Take each source's newest picture, keeping the last one of a source + /// that has nothing new. + fn collect(&mut self, scene: &Scene, feeds: &[Option>]) { + if self.held_ids.len() != scene.sources.len() + || self.held_ids.iter().ne(scene.sources.iter().map(|s| &s.id)) + { + // The scene's sources changed: keep each source's picture by id. + let old: Vec<(u64, Option>)> = + self.held_ids.drain(..).zip(self.held.drain(..)).collect(); + for source in &scene.sources { + self.held_ids.push(source.id); + let kept = old.iter().find(|(id, _)| *id == source.id); + self.held.push(kept.and_then(|(_, frame)| frame.clone())); + } + } + for (i, source) in scene.sources.iter().enumerate() { + // No live input, or not drawn: nothing, not even what it had. + let Some(Some(feed)) = feeds.get(i).filter(|_| source.drawn()) else { + self.held[i] = None; + continue; + }; + if let Some(frame) = feed.take() { + self.held[i] = Some(frame); + } + } + } + + /// Work out where every source goes and the filter weights for it. + fn plan(&mut self, scene: &Scene, revision: u64) { + let (width, height) = (self.size.0 as usize, self.size.1 as usize); + self.blits.clear(); + self.planned_sizes.clear(); + self.planned = Some((revision, self.size)); + self.replans += 1; + let rgba = scene.background.to_rgba(); + self.background.clear(); + self.background.reserve(width * 4); + for _ in 0..width { + self.background.extend_from_slice(&[rgba[0], rgba[1], rgba[2], 255]); + } + for (i, source) in scene.sources.iter().enumerate() { + let size = self.held[i].as_ref().map_or((0, 0), |f| (f.width, f.height)); + self.planned_sizes.push(size); + let Some(frame) = &self.held[i] else { continue }; + if !matches!(frame.data, FrameData::Bgra(_) | FrameData::Rgba(_)) { + continue; + } + let (cx, cy, mut cw, mut ch) = source.crop.apply(size.0, size.1); + let (mut sx, mut sy) = (cx as usize, cy as usize); + let t = &source.transform; + // The box the source is drawn into. + let bw = t.width.unwrap_or(cw as f32 * t.scale).max(1.0); + let bh = t.height.unwrap_or(ch as f32 * t.scale).max(1.0); + let (mut dx, mut dy) = (t.x, t.y); + let (mut dw, mut dh) = (bw, bh); + match t.fit { + Fit::Stretch => {} + Fit::Contain => { + // The whole source inside the box, centred. + let s = (bw / cw as f32).min(bh / ch as f32); + dw = (cw as f32 * s).max(1.0); + dh = (ch as f32 * s).max(1.0); + dx += (bw - dw) / 2.0; + dy += (bh - dh) / 2.0; + } + Fit::Cover => { + // Fill the box: crop the source to the box's aspect. + let s = (bw / cw as f32).max(bh / ch as f32); + let (kw, kh) = ((bw / s).round() as u32, (bh / s).round() as u32); + let (kw, kh) = (kw.clamp(1, cw), kh.clamp(1, ch)); + sx += ((cw - kw) / 2) as usize; + sy += ((ch - kh) / 2) as usize; + (cw, ch) = (kw, kh); + } + } + let (dw, dh) = (dw.round().max(1.0) as usize, dh.round().max(1.0) as usize); + let (dx, dy) = (dx.round() as isize, dy.round() as isize); + // Clip to the canvas, in destination coordinates. + let cols = clip(dx, dw, width); + let rows = clip(dy, dh, height); + if cols.is_empty() || rows.is_empty() { + continue; + } + let (sw, sh) = (cw as usize, ch as usize); + let mirror = matches!(source.kind, SourceKind::Camera { mirror: true, .. }); + self.blits.push(Blit { + source: i, + sx, + sy, + sw, + sh, + dx, + dy, + dw, + dh, + cols, + rows, + x: if sw == dw { Axis::default() } else { Axis::new(sw, dw) }, + y: if sh == dh { Axis::default() } else { Axis::new(sh, dh) }, + direct: sw == dw && sh == dh, + bgra: matches!(frame.data, FrameData::Bgra(_)), + alpha: matches!(source.kind, SourceKind::Image { .. } | SourceKind::Text { .. }), + opacity: (source.opacity.clamp(0.0, 1.0) * 255.0).round() as u8, + mirror, + }); + } + } +} + +/// The part of a `len`-wide destination starting at `at` that lies within +/// `0 .. limit`, in destination coordinates. +fn clip(at: isize, len: usize, limit: usize) -> Range { + let start = (-at).clamp(0, len as isize) as usize; + let end = (limit as isize - at).clamp(0, len as isize) as usize; + start..end.max(start) +} + +/// Resizes packed RGBA / BGRA images into RGBA, with the filter of +/// [`Compositor`]. Used for the studio's preview tap; weights are computed +/// once per size pair. +pub struct RgbaScaler { + workers: Workers, + pool: FramePool, + blit: Option, + scratch: Vec>>, +} + +impl RgbaScaler { + /// `threads` as in [`Workers::new`] (0: one per CPU). + pub fn new(threads: usize) -> Self { + Self { + workers: Workers::new("voelin-rgba-scale", threads), + pool: FramePool::new(), + blit: None, + scratch: Vec::new(), + } + } + + /// `frame` (BGRA or RGBA) as a pooled RGBA frame of `width` x `height`, + /// keeping its timestamp. Allocates only when a size changes or every + /// pooled frame is in use. + pub fn scale( + &mut self, + frame: &VideoFrame, + width: u32, + height: u32, + ) -> Result> { + let (width, height) = (width.max(1), height.max(1)); + let plane = match &frame.data { + FrameData::Bgra(p) | FrameData::Rgba(p) => p.view(), + _ => return Err(Error::InvalidFrame("the preview scaler needs BGRA or RGBA".into())), + }; + let (sw, sh) = (frame.width as usize, frame.height as usize); + let (dw, dh) = (width as usize, height as usize); + let bgra = matches!(frame.data, FrameData::Bgra(_)); + let stale = self + .blit + .as_ref() + .is_none_or(|b| (b.sw, b.sh, b.dw, b.dh, b.bgra) != (sw, sh, dw, dh, bgra)); + if stale { + self.blit = Some(Blit { + source: 0, + sx: 0, + sy: 0, + sw, + sh, + dx: 0, + dy: 0, + dw, + dh, + cols: 0..dw, + rows: 0..dh, + x: if sw == dw { Axis::default() } else { Axis::new(sw, dw) }, + y: if sh == dh { Axis::default() } else { Axis::new(sh, dh) }, + direct: sw == dw && sh == dh, + bgra, + alpha: false, + opacity: 255, + mirror: false, + }); + } + let blit = self.blit.as_ref().expect("just set"); + let out = self.pool.get_format(width, height, PixelFormat::Rgba); + let target = Arc::get_mut(out).expect("the pool hands out unshared frames"); + target.timestamp = frame.timestamp; + let FrameData::Rgba(dst) = &mut target.data else { + return Err(Error::InvalidFrame("the preview canvas is not RGBA".into())); + }; + let stride = dst.stride; + let tasks = self.workers.tasks(dh); + let band = dh.div_ceil(tasks); + let tasks = dh.div_ceil(band); + while self.scratch.len() < tasks { + self.scratch.push(Mutex::new(Vec::new())); + } + for slot in &mut self.scratch { + let tmp = slot.get_mut().unwrap_or_else(PoisonError::into_inner); + if tmp.len() < sw * 4 { + tmp.resize(sw * 4, 0); + } + } + let slots = Slots::new(dst.data.chunks_mut(band * stride).take(tasks).enumerate()); + let scratch = &self.scratch; + self.workers.run(slots.len(), &|task| { + let Some((i, out)) = slots.take(task) else { return }; + let rows = i * band..((i + 1) * band).min(dh); + blit.draw(plane, out, stride, &rows, &mut lock(&scratch[i])); + }); + Ok(out.clone()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::frame::Plane; + use crate::studio::scene::{Colour, Crop, Source, Transform}; + + /// A flat `width` x `height` RGBA frame. + fn flat(width: u32, height: u32, rgba: [u8; 4]) -> Arc { + let mut data = Vec::with_capacity(width as usize * height as usize * 4); + for _ in 0..width * height { + data.extend_from_slice(&rgba); + } + Arc::new(VideoFrame { + width, + height, + timestamp: Duration::ZERO, + data: FrameData::Rgba(Plane::new(data, width as usize * 4)), + }) + } + + /// A BGRA frame whose pixel `(x, y)` is `f(x, y)` as RGBA. + fn painted( + width: u32, + height: u32, + bgra: bool, + f: impl Fn(u32, u32) -> [u8; 4], + ) -> Arc { + let mut data = Vec::with_capacity(width as usize * height as usize * 4); + for y in 0..height { + for x in 0..width { + let p = f(x, y); + data.extend_from_slice(&if bgra { [p[2], p[1], p[0], p[3]] } else { p }); + } + } + let plane = Plane::new(data, width as usize * 4); + Arc::new(VideoFrame { + width, + height, + timestamp: Duration::ZERO, + data: if bgra { FrameData::Bgra(plane) } else { FrameData::Rgba(plane) }, + }) + } + + fn pixel(frame: &VideoFrame, x: u32, y: u32) -> [u8; 4] { + let FrameData::Rgba(p) = &frame.data else { panic!("not RGBA") }; + let row = p.row(y as usize, frame.width as usize * 4); + row[x as usize * 4..][..4].try_into().unwrap() + } + + /// Composite a scene whose sources are fed `frames` (one per source). + fn compose( + compositor: &mut Compositor, + scene: &Scene, + revision: u64, + frames: &[Option>], + ) -> Arc { + let feeds: Vec>> = frames + .iter() + .map(|frame| { + let feed = Arc::new(Feed::new()); + if let Some(frame) = frame { + feed.put(frame.clone()); + } + Some(feed) + }) + .collect(); + compositor.compose(scene, revision, &feeds, Duration::from_millis(1)).unwrap() + } + + #[test] + fn draws_sources_where_they_belong() { + let mut compositor = Compositor::new(4); + compositor.set_size(64, 32); + let mut scene = Scene::new(1, "t"); + scene.background = Colour::rgb(10, 20, 30); + // Full-size red background source and a green box at (16, 8) 8x4. + scene.sources.push(Source { + transform: Transform::full(64, 32), + ..Source::new(1, SourceKind::Colour { colour: Colour::WHITE, size: (64, 32) }) + }); + scene.sources.push(Source { + transform: Transform::box_at(16.0, 8.0, 8.0, 4.0), + ..Source::new(2, SourceKind::Colour { colour: Colour::WHITE, size: (8, 4) }) + }); + let red = flat(64, 32, [200, 0, 0, 255]); + let green = flat(8, 4, [0, 200, 0, 255]); + let out = compose(&mut compositor, &scene, 1, &[Some(red), Some(green)]); + assert_eq!((out.width, out.height), (64, 32)); + assert_eq!(out.timestamp, Duration::from_millis(1)); + assert_eq!(pixel(&out, 0, 0), [200, 0, 0, 255], "the full-size source"); + assert_eq!(pixel(&out, 16, 8), [0, 200, 0, 255], "the box's first pixel"); + assert_eq!(pixel(&out, 23, 11), [0, 200, 0, 255], "the box's last pixel"); + assert_eq!(pixel(&out, 24, 8), [200, 0, 0, 255], "one past the box"); + assert_eq!(pixel(&out, 16, 12), [200, 0, 0, 255], "one below the box"); + + // Without the background source the scene's background shows. + scene.sources.remove(0); + let green = flat(8, 4, [0, 200, 0, 255]); + let out = compose(&mut compositor, &scene, 2, &[Some(green)]); + assert_eq!(pixel(&out, 0, 0), [10, 20, 30, 255]); + assert_eq!(pixel(&out, 16, 8), [0, 200, 0, 255]); + } + + #[test] + fn blends_alpha_and_opacity() { + let mut compositor = Compositor::new(2); + compositor.set_size(8, 4); + let mut scene = Scene::new(1, "t"); + scene.background = Colour::rgb(0, 0, 0); + // A half-transparent white image over black, and a fully opaque one + // at half opacity. + scene.sources.push(Source { + transform: Transform::box_at(0.0, 0.0, 4.0, 4.0), + ..Source::new(1, SourceKind::Image { path: "x.png".into() }) + }); + scene.sources.push(Source { + transform: Transform::box_at(4.0, 0.0, 4.0, 4.0), + opacity: 0.5, + ..Source::new(2, SourceKind::Colour { colour: Colour::WHITE, size: (4, 4) }) + }); + let half = flat(4, 4, [255, 255, 255, 128]); + let solid = flat(4, 4, [255, 255, 255, 255]); + let out = compose(&mut compositor, &scene, 1, &[Some(half), Some(solid)]); + // 255 * 128/255 = 128 over black. + assert_eq!(pixel(&out, 0, 0), [128, 128, 128, 255], "image alpha"); + // Opacity 0.5 -> 128/255 coverage. + assert_eq!(pixel(&out, 4, 0), [128, 128, 128, 255], "source opacity"); + + // An invisible source and a zero-opacity one draw nothing. + scene.sources[0].visible = false; + scene.sources[1].opacity = 0.0; + let out = compose( + &mut compositor, + &scene, + 2, + &[Some(flat(4, 4, [255, 255, 255, 128])), Some(flat(4, 4, [255, 255, 255, 255]))], + ); + assert_eq!(pixel(&out, 0, 0), [0, 0, 0, 255]); + assert_eq!(pixel(&out, 4, 0), [0, 0, 0, 255]); + } + + #[test] + fn scales_crops_clips_and_swaps_channels() { + let mut compositor = Compositor::new(4); + compositor.set_size(16, 16); + let mut scene = Scene::new(1, "t"); + // A 4x4 source of four quadrant colours, drawn at 16x16: each + // quadrant is 8x8 in the output. + scene.sources.push(Source { + transform: Transform { fit: Fit::Stretch, ..Transform::full(16, 16) }, + ..Source::new(1, SourceKind::Colour { colour: Colour::WHITE, size: (4, 4) }) + }); + let quad = painted(4, 4, true, |x, y| match (x < 2, y < 2) { + (true, true) => [255, 0, 0, 255], + (false, true) => [0, 255, 0, 255], + (true, false) => [0, 0, 255, 255], + (false, false) => [255, 255, 0, 255], + }); + let out = compose(&mut compositor, &scene, 1, &[Some(quad.clone())]); + // BGRA input came out as RGBA, upscaled. + assert_eq!(pixel(&out, 1, 1), [255, 0, 0, 255]); + assert_eq!(pixel(&out, 14, 1), [0, 255, 0, 255]); + assert_eq!(pixel(&out, 1, 14), [0, 0, 255, 255]); + assert_eq!(pixel(&out, 14, 14), [255, 255, 0, 255]); + + // Crop to the bottom-right quadrant: it fills the output. + scene.sources[0].crop = Crop { left: 2, top: 2, right: 0, bottom: 0 }; + let out = compose(&mut compositor, &scene, 2, &[Some(quad.clone())]); + assert_eq!(pixel(&out, 0, 0), [255, 255, 0, 255]); + assert_eq!(pixel(&out, 15, 15), [255, 255, 0, 255]); + + // Half off the left edge: only the right half of the source shows. + scene.sources[0].crop = Crop::default(); + scene.sources[0].transform = + Transform { fit: Fit::Stretch, ..Transform::box_at(-8.0, 0.0, 16.0, 16.0) }; + let out = compose(&mut compositor, &scene, 3, &[Some(quad)]); + // Output column 4 is the source's column 2.6: the right half. + assert_eq!(pixel(&out, 4, 1), [0, 255, 0, 255], "the source's right half"); + assert_eq!(pixel(&out, 7, 14), [255, 255, 0, 255]); + assert_eq!(pixel(&out, 8, 1), [0, 0, 0, 255], "past the source"); + + // Entirely outside: nothing is drawn. + scene.sources[0].transform = Transform::box_at(100.0, 100.0, 4.0, 4.0); + let out = compose(&mut compositor, &scene, 4, &[Some(flat(4, 4, [9, 9, 9, 255]))]); + assert_eq!(pixel(&out, 0, 0), [0, 0, 0, 255]); + } + + #[test] + fn fit_letterboxes_and_covers() { + let mut compositor = Compositor::new(2); + compositor.set_size(16, 16); + let mut scene = Scene::new(1, "t"); + // A 16x8 source in a 16x16 box. + scene.sources.push(Source { + transform: Transform { fit: Fit::Contain, ..Transform::full(16, 16) }, + ..Source::new(1, SourceKind::Colour { colour: Colour::WHITE, size: (16, 8) }) + }); + let wide = + painted(16, 8, false, |_, y| if y < 4 { [255, 0, 0, 255] } else { [0, 0, 255, 255] }); + let out = compose(&mut compositor, &scene, 1, &[Some(wide.clone())]); + // Contain: 16x8 centred, rows 4..12 drawn, the rest background. + assert_eq!(pixel(&out, 0, 0), [0, 0, 0, 255], "letterbox above"); + assert_eq!(pixel(&out, 0, 4), [255, 0, 0, 255]); + assert_eq!(pixel(&out, 0, 11), [0, 0, 255, 255]); + assert_eq!(pixel(&out, 0, 12), [0, 0, 0, 255], "letterbox below"); + + // Cover: the box is filled, the source's sides are cropped. + scene.sources[0].transform = Transform { fit: Fit::Cover, ..Transform::full(16, 16) }; + let out = compose(&mut compositor, &scene, 2, &[Some(wide)]); + assert_eq!(pixel(&out, 0, 0), [255, 0, 0, 255], "no letterbox"); + assert_eq!(pixel(&out, 15, 15), [0, 0, 255, 255]); + } + + #[test] + fn a_source_keeps_its_last_picture() { + let mut compositor = Compositor::new(2); + compositor.set_size(4, 4); + let mut scene = Scene::new(1, "t"); + scene.sources.push(Source { + transform: Transform::full(4, 4), + ..Source::new(1, SourceKind::Colour { colour: Colour::WHITE, size: (4, 4) }) + }); + let feeds = vec![Some(Arc::new(Feed::new()))]; + let feed = feeds[0].clone().unwrap(); + feed.put(flat(4, 4, [7, 8, 9, 255])); + let out = compositor.compose(&scene, 1, &feeds, Duration::ZERO).unwrap(); + assert_eq!(pixel(&out, 0, 0), [7, 8, 9, 255]); + drop(out); + // Nothing new: the same picture again. + let out = compositor.compose(&scene, 1, &feeds, Duration::from_millis(33)).unwrap(); + assert_eq!(pixel(&out, 0, 0), [7, 8, 9, 255]); + assert_eq!(out.timestamp, Duration::from_millis(33)); + assert_eq!(feed.delivered(), 1); + drop(out); + // A feed that never delivered draws nothing but does not fail. + let out = compositor.compose(&scene, 2, &[None], Duration::ZERO).unwrap(); + assert_eq!(pixel(&out, 0, 0), [0, 0, 0, 255]); + } + + #[test] + fn plans_only_when_something_changed() { + let mut compositor = Compositor::new(2); + compositor.set_size(8, 8); + let mut scene = Scene::new(1, "t"); + scene.sources.push(Source { + transform: Transform::full(8, 8), + ..Source::new(1, SourceKind::Colour { colour: Colour::WHITE, size: (8, 8) }) + }); + let feeds = vec![Some(Arc::new(Feed::new()))]; + let feed = feeds[0].clone().unwrap(); + for _ in 0..5 { + feed.put(flat(8, 8, [1, 2, 3, 255])); + drop(compositor.compose(&scene, 1, &feeds, Duration::ZERO).unwrap()); + } + assert_eq!(compositor.stats().replans, 1, "the plan was kept"); + assert_eq!(compositor.stats().frames, 5); + // A source that resizes replans. + feed.put(flat(4, 4, [1, 2, 3, 255])); + drop(compositor.compose(&scene, 1, &feeds, Duration::ZERO).unwrap()); + assert_eq!(compositor.stats().replans, 2); + // So does a scene change. + feed.put(flat(4, 4, [1, 2, 3, 255])); + drop(compositor.compose(&scene, 2, &feeds, Duration::ZERO).unwrap()); + assert_eq!(compositor.stats().replans, 3); + assert!(compositor.stats().compose_time > Duration::ZERO); + assert_eq!(compositor.stats().threads, 2); + } + + #[test] + fn mirrors_a_camera() { + let mut compositor = Compositor::new(1); + compositor.set_size(4, 2); + let mut scene = Scene::new(1, "t"); + scene.sources.push(Source { + transform: Transform { fit: Fit::Stretch, ..Transform::full(4, 2) }, + ..Source::new( + 1, + SourceKind::Camera { device: String::new(), size: None, fps: None, mirror: true }, + ) + }); + // A column ramp, so mirroring is visible at 1:1 and when scaled. + let ramp = painted(4, 2, false, |x, _| [(x as u8 + 1) * 10, 0, 0, 255]); + let out = compose(&mut compositor, &scene, 1, &[Some(ramp.clone())]); + assert_eq!(pixel(&out, 0, 0)[0], 40); + assert_eq!(pixel(&out, 3, 0)[0], 10); + // Scaled to 8 wide: still mirrored. + compositor.set_size(8, 2); + let out = compose(&mut compositor, &scene, 2, &[Some(ramp)]); + assert!(pixel(&out, 0, 0)[0] > pixel(&out, 7, 0)[0], "mirrored while scaling"); + } + + #[test] + fn preview_scaler_downscales() { + let mut scaler = RgbaScaler::new(2); + // Left half red, right half blue; halved, the halves stay. + let frame = + painted(16, 8, true, |x, _| if x < 8 { [255, 0, 0, 255] } else { [0, 0, 255, 255] }); + let out = scaler.scale(&frame, 8, 4).unwrap(); + assert_eq!((out.width, out.height), (8, 4)); + assert_eq!(out.format(), PixelFormat::Rgba); + assert_eq!(pixel(&out, 0, 0), [255, 0, 0, 255]); + assert_eq!(pixel(&out, 7, 3), [0, 0, 255, 255]); + drop(out); + // 1:1 copies and keeps the timestamp. + let frame = VideoFrame { timestamp: Duration::from_millis(7), ..(*frame).clone() }; + let out = scaler.scale(&frame, 16, 8).unwrap(); + assert_eq!(out.timestamp, Duration::from_millis(7)); + assert_eq!(pixel(&out, 0, 0), [255, 0, 0, 255]); + assert_eq!(pixel(&out, 15, 7), [0, 0, 255, 255]); + // I420 is not a preview input. + assert!(scaler.scale(&VideoFrame::black_i420(4, 4), 2, 2).is_err()); + } + + #[test] + fn an_unset_output_size_fails() { + let mut compositor = Compositor::new(1); + let scene = Scene::new(1, "t"); + assert!(compositor.compose(&scene, 1, &[], Duration::ZERO).is_err()); + compositor.set_size(1, 1); + // Rounded up to the smallest even size. + assert_eq!(compositor.size(), (2, 2)); + compositor.reset(); + assert!(compositor.compose(&scene, 1, &[], Duration::ZERO).is_ok()); + } +} diff --git a/crates/voelin-media/src/studio/mod.rs b/crates/voelin-media/src/studio/mod.rs index cdca2f4..8b1b0bb 100644 --- a/crates/voelin-media/src/studio/mod.rs +++ b/crates/voelin-media/src/studio/mod.rs @@ -3,5 +3,8 @@ //! //! - [`scene`]: the scene graph (scenes, sources, transforms, crops), the //! persisted shape of a studio +//! - [`compose`]: the compositor, which draws the live scene into pooled +//! frames at the output size +pub mod compose; pub mod scene; diff --git a/crates/voelin-media/tests/studio_alloc.rs b/crates/voelin-media/tests/studio_alloc.rs new file mode 100644 index 0000000..d4b6251 --- /dev/null +++ b/crates/voelin-media/tests/studio_alloc.rs @@ -0,0 +1,195 @@ +//! The studio compositor allocates nothing per composed frame: several +//! sources of different sizes, scaled, cropped, blended and mirrored into a +//! 1080p canvas, counted with a global allocator that counts only on the +//! thread that asks. +//! +//! A scene change, a source that resizes and a new output size each replan +//! (and allocate); a steady composite must not. +#![allow(unsafe_code)] + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; +use std::sync::Arc; +use std::time::Duration; + +use voelin_media::frame::{FrameData, Plane, VideoFrame}; +use voelin_media::studio::compose::{Compositor, Feed, RgbaScaler}; +use voelin_media::studio::scene::{Colour, Crop, Fit, Scene, Source, SourceKind, Transform}; + +thread_local! { + static COUNTING: Cell = const { Cell::new(false) }; + static COUNT: Cell = const { Cell::new(0) }; +} + +fn count() { + // `try_with`: never panics, also while the thread is torn down; const + // thread locals without destructors never allocate. + let _ = COUNTING.try_with(|on| { + if on.get() { + let _ = COUNT.try_with(|n| n.set(n.get() + 1)); + } + }); +} + +struct Counting; + +// SAFETY: every method forwards to `System` with the caller's arguments +// unchanged, so `System`'s guarantees hold; counting touches only +// thread-local cells and never allocates. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + count(); + // SAFETY: forwarded unchanged (see above). + unsafe { System.alloc(layout) } + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + count(); + // SAFETY: forwarded unchanged. + unsafe { System.alloc_zeroed(layout) } + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + count(); + // SAFETY: forwarded unchanged. + unsafe { System.realloc(ptr, layout, new_size) } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + // SAFETY: forwarded unchanged. + unsafe { System.dealloc(ptr, layout) } + } +} + +#[global_allocator] +static ALLOCATOR: Counting = Counting; + +/// Allocations `f` makes on this thread. +fn allocations(f: impl FnOnce()) -> u64 { + COUNT.with(|n| n.set(0)); + COUNTING.with(|on| on.set(true)); + f(); + COUNTING.with(|on| on.set(false)); + COUNT.with(Cell::get) +} + +/// A `width` x `height` frame whose pixel `(x, y)` is a cheap pattern, RGBA or +/// BGRA. +fn frame(width: u32, height: u32, bgra: bool, seed: u8) -> Arc { + let mut data = Vec::with_capacity(width as usize * height as usize * 4); + for y in 0..height { + for x in 0..width { + let v = (x ^ y) as u8 ^ seed; + data.extend_from_slice(&[v, v.wrapping_mul(3), seed, 128 | seed]); + } + } + let plane = Plane::new(data, width as usize * 4); + Arc::new(VideoFrame { + width, + height, + timestamp: Duration::ZERO, + data: if bgra { FrameData::Bgra(plane) } else { FrameData::Rgba(plane) }, + }) +} + +#[test] +fn composing_allocates_nothing_per_frame() { + // The counter works. + assert_eq!(allocations(|| drop(std::hint::black_box(vec![0u8; 16]))), 1); + + let mut scene = Scene::new(1, "alloc"); + scene.background = Colour::rgb(20, 20, 24); + // A 4K screen scaled down to the canvas. + scene.sources.push(Source { + transform: Transform { fit: Fit::Cover, ..Transform::full(1920, 1080) }, + ..Source::new(1, SourceKind::Screen { monitor: 0, backend: None, cursor: true }) + }); + // A camera, cropped, mirrored, in the corner. + scene.sources.push(Source { + transform: Transform::box_at(1520.0, 800.0, 384.0, 216.0), + crop: Crop { left: 40, top: 0, right: 40, bottom: 0 }, + ..Source::new( + 2, + SourceKind::Camera { device: String::new(), size: None, fps: None, mirror: true }, + ) + }); + // A logo with alpha, at 1:1. + scene.sources.push(Source { + transform: Transform::box_at(32.0, 32.0, 128.0, 128.0), + opacity: 0.75, + ..Source::new(3, SourceKind::Image { path: "logo.png".into() }) + }); + // Text, scaled up. + scene.sources.push(Source { + transform: Transform::box_at(32.0, 960.0, 600.0, 80.0), + ..Source::new( + 4, + SourceKind::Text { + text: "LIVE".into(), + font: None, + size_px: 48.0, + colour: Colour::WHITE, + backdrop: Colour::CLEAR, + align: Default::default(), + padding: 0, + }, + ) + }); + let sizes = [(3840u32, 2160u32), (1280, 720), (128, 128), (600, 80)]; + let bgra = [true, true, false, false]; + let feeds: Vec>> = + (0..scene.sources.len()).map(|_| Some(Arc::new(Feed::new()))).collect(); + let frames: Vec> = sizes + .iter() + .zip(bgra) + .enumerate() + .map(|(i, (&(w, h), bgra))| frame(w, h, bgra, i as u8 * 40)) + .collect(); + + let mut compositor = Compositor::new(4); + compositor.set_size(1920, 1080); + let mut preview = RgbaScaler::new(2); + // Every source delivers every frame except the camera (every third). + let step = |compositor: &mut Compositor, preview: &mut RgbaScaler, n: u64| { + for (i, feed) in feeds.iter().enumerate() { + if i != 1 || n.is_multiple_of(3) { + feed.as_ref().unwrap().put(frames[i].clone()); + } + } + let out = + compositor.compose(&scene, 1, &feeds, Duration::from_millis(n * 16)).expect("composed"); + // The preview tap runs on the same thread in this test. + drop(preview.scale(&out, 480, 270).expect("previewed")); + drop(out); + }; + // Warm up: the plan, the filter weights, the canvas pool and the scratch + // rows are all in place after the first frames. + for n in 0..12 { + step(&mut compositor, &mut preview, n); + } + let count = allocations(|| { + for n in 12..112 { + step(&mut compositor, &mut preview, n); + } + }); + assert_eq!(count, 0, "allocations in 100 composed frames"); + let stats = compositor.stats(); + assert_eq!(stats.frames, 112); + assert_eq!(stats.replans, 1, "the plan was made once"); + // One canvas: the previous one is released before the next compose. + assert_eq!(stats.allocated, 1); + assert!(stats.compose_time > Duration::ZERO); + + // A new output size replans, then allocates nothing again. + compositor.set_size(1280, 720); + for n in 112..124 { + step(&mut compositor, &mut preview, n); + } + assert_eq!(compositor.stats().replans, 2); + let count = allocations(|| { + for n in 124..164 { + step(&mut compositor, &mut preview, n); + } + }); + assert_eq!(count, 0, "allocations after a size change"); +} From e0f6404eb91e6b8bd708b98f2d45cc955c997b75 Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 18:34:16 +0300 Subject: [PATCH 3/7] voelin-media: give the studio its sources and cameras A scene needs something behind each of its sources. Colour, text and image are drawn once and put in the feed; screens, windows and the portal run the existing capture backends through a sink that copies into pooled frames; cameras get their own module. One broken source only sets its feed's error, so it never stops the studio. Text is rasterised with ab_glyph and the same Inter the UI bundles (reached across crates rather than copied, and tools without the UI crate need it too); images come from the `image` crate, which the tree already had. Cameras are listed straight from V4L2 -- the card name and every pixel format and resolution the driver reports, no hard-coded list -- but captured through PipeWire, which already owns the devices; the connection comes from the user's daemon or, in a sandbox, from the XDG Camera portal, and both reuse the screen capture's PipeWire thread. Only the three read-only enumeration ioctls are hand-written, so no bindgen build dependency joins the tree. The test pattern is always listed as a camera, which is what the tests use. convert gained a borrowed-frame entry point so a capture buffer becomes RGBA without an owned frame in between. Co-Authored-By: Claude Opus 5 --- Cargo.lock | 2 + Cargo.toml | 18 - crates/voelin-media/Cargo.toml | 6 +- crates/voelin-media/src/capture/mod.rs | 2 +- crates/voelin-media/src/convert.rs | 26 +- crates/voelin-media/src/studio/camera.rs | 915 +++++++++++++++++++++++ crates/voelin-media/src/studio/mod.rs | 5 + crates/voelin-media/src/studio/source.rs | 529 +++++++++++++ 8 files changed, 1473 insertions(+), 30 deletions(-) create mode 100644 crates/voelin-media/src/studio/camera.rs create mode 100644 crates/voelin-media/src/studio/source.rs diff --git a/Cargo.lock b/Cargo.lock index a921c1a..90f3a2a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9169,10 +9169,12 @@ dependencies = [ name = "voelin-media" version = "0.1.0" dependencies = [ + "ab_glyph", "ashpd", "bzip2", "criterion", "dav1d", + "image", "libloading", "libvpx-native-sys", "memmap2", diff --git a/Cargo.toml b/Cargo.toml index d9debe8..8fdf6c8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,16 +69,8 @@ opt-level = 3 # every 10 ms of microphone audio; unoptimized it needs about a third of a core. [profile.dev.package.sonora] opt-level = 3 -[profile.dev.package.sonora-aec3] -opt-level = 3 [profile.dev.package.sonora-agc2] opt-level = 3 -[profile.dev.package.sonora-common-audio] -opt-level = 3 -[profile.dev.package.sonora-fft] -opt-level = 3 -[profile.dev.package.sonora-ns] -opt-level = 3 [profile.dev.package.sonora-simd] opt-level = 3 @@ -91,10 +83,6 @@ opt-level = 3 opt-level = 3 [profile.dev.package.str0m] opt-level = 3 -[profile.dev.package.str0m-proto] -opt-level = 3 -[profile.dev.package.str0m-aws-lc-rs] -opt-level = 3 [profile.dev.package.openh264] opt-level = 3 [profile.dev.package.dav1d] @@ -103,12 +91,6 @@ opt-level = 3 opt-level = 3 [profile.dev.package.pipewire] opt-level = 3 -[profile.dev.package.libspa] -opt-level = 3 -[profile.dev.package.x11rb-protocol] -opt-level = 3 -[profile.dev.package.wayland-backend] -opt-level = 3 [profile.dev.package.wayland-client] opt-level = 3 diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index b11e7be..a871b40 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -33,6 +33,7 @@ pipewire = ["dep:ashpd", "dep:pipewire", "dep:memmap2", "dep:rustix"] wlroots = ["dep:wayland-client", "dep:wayland-protocols", "dep:wayland-protocols-wlr", "dep:memmap2", "dep:rustix"] # Conversion between `Codec` and `str0m::format::Codec`. str0m = ["dep:str0m"] +v4l = [] [dependencies] bzip2 = { version = "0.6.1", optional = true } @@ -45,6 +46,9 @@ reqwest = { version = "0.13.5", default-features = false, features = ["rustls"], rtrb = "0.4.0" # Scene graphs are serialised into the `studio.scenes` setting. serde = { version = "1", features = ["derive"] } +# Studio sources: text rasterising and image files. +ab_glyph = "0.2.32" +image = { version = "0.25.10", default-features = false, features = ["jpeg", "png"] } sha2 = { version = "0.10.9", optional = true } str0m = { version = "0.23.1", default-features = false, optional = true } thiserror = "2.0.21" @@ -53,7 +57,7 @@ tracing = "0.1.44" yuv = "0.8.19" [target.'cfg(target_os = "linux")'.dependencies] -ashpd = { version = "0.13.13", default-features = false, features = ["screencast", "tokio"], optional = true } +ashpd = { version = "0.13.13", default-features = false, features = ["camera", "screencast", "tokio"], optional = true } memmap2 = { version = "0.9.11", optional = true } pipewire = { version = "0.10.1", optional = true } rustix = { version = "1.1.5", features = ["event", "fs"], optional = true } diff --git a/crates/voelin-media/src/capture/mod.rs b/crates/voelin-media/src/capture/mod.rs index b4ccc1a..7f4863e 100644 --- a/crates/voelin-media/src/capture/mod.rs +++ b/crates/voelin-media/src/capture/mod.rs @@ -38,7 +38,7 @@ pub mod playback; #[cfg(all(target_os = "linux", feature = "pipewire"))] pub mod portal; #[cfg(all(target_os = "linux", feature = "pipewire"))] -mod pw; +pub(crate) mod pw; pub mod synthetic; #[cfg(windows)] pub mod windows; diff --git a/crates/voelin-media/src/convert.rs b/crates/voelin-media/src/convert.rs index 5c98f9d..6c96098 100644 --- a/crates/voelin-media/src/convert.rs +++ b/crates/voelin-media/src/convert.rs @@ -37,6 +37,12 @@ fn stride_u32(stride: usize) -> Result { /// Suits a Slint `SharedPixelBuffer`: /// `to_rgba(&frame, buffer.make_mut_bytes(), width as usize * 4)`. pub fn to_rgba(frame: &VideoFrame, out: &mut [u8], out_stride: usize) -> Result<()> { + to_rgba_ref(&frame.view(), out, out_stride) +} + +/// Write a borrowed frame (e.g. a mapped capture buffer) as RGBA (alpha 255) +/// into `out`, `out_stride` bytes per row. Allocates nothing. +pub fn to_rgba_ref(frame: &FrameRef<'_>, out: &mut [u8], out_stride: usize) -> Result<()> { frame.validate()?; let (w, h) = (frame.width, frame.height); let row = w as usize * 4; @@ -48,32 +54,32 @@ pub fn to_rgba(frame: &VideoFrame, out: &mut [u8], out_stride: usize) -> Result< ))); } let out_stride_u32 = stride_u32(out_stride)?; - match &frame.data { - FrameData::I420 { y, u, v } => { + match &frame.pixels { + PixelsRef::I420 { y, u, v } => { let image = YuvPlanarImage { - y_plane: &y.data, + y_plane: y.data, y_stride: stride_u32(y.stride)?, - u_plane: &u.data, + u_plane: u.data, u_stride: stride_u32(u.stride)?, - v_plane: &v.data, + v_plane: v.data, v_stride: stride_u32(v.stride)?, width: w, height: h, }; yuv::yuv420_to_rgba(&image, out, out_stride_u32, RANGE, MATRIX).map_err(error) } - FrameData::Nv12 { y, uv } => { + PixelsRef::Nv12 { y, uv } => { let image = YuvBiPlanarImage { - y_plane: &y.data, + y_plane: y.data, y_stride: stride_u32(y.stride)?, - uv_plane: &uv.data, + uv_plane: uv.data, uv_stride: stride_u32(uv.stride)?, width: w, height: h, }; yuv::yuv_nv12_to_rgba(&image, out, out_stride_u32, RANGE, MATRIX, mode()).map_err(error) } - FrameData::Bgra(p) => { + PixelsRef::Bgra(p) => { for y in 0..h as usize { let src = p.row(y, row); let dst = &mut out[y * out_stride..y * out_stride + row]; @@ -83,7 +89,7 @@ pub fn to_rgba(frame: &VideoFrame, out: &mut [u8], out_stride: usize) -> Result< } Ok(()) } - FrameData::Rgba(p) => { + PixelsRef::Rgba(p) => { for y in 0..h as usize { out[y * out_stride..y * out_stride + row].copy_from_slice(p.row(y, row)); } diff --git a/crates/voelin-media/src/studio/camera.rs b/crates/voelin-media/src/studio/camera.rs new file mode 100644 index 0000000..29d59af --- /dev/null +++ b/crates/voelin-media/src/studio/camera.rs @@ -0,0 +1,915 @@ +//! Cameras for the studio. +//! +//! Linux: cameras are listed straight from V4L2 (`/dev/video*`: the card +//! name, the pixel formats and every resolution the driver reports, no +//! hard-coded list), and captured through PipeWire, which is what already +//! owns the devices on a modern desktop. The PipeWire connection comes from +//! the user's daemon, or — in a sandbox, where that is not allowed — from +//! the XDG Camera portal ([`ashpd`]), which asks the user once; both go +//! through the same stream code and the same [`crate::capture::pw::PwThread`] +//! as screen capture. +//! +//! Every camera pixel format PipeWire can give us (YUY2, UYVY, NV12, I420, +//! and the packed 24- and 32-bit ones) is converted to RGBA or taken as BGRA +//! for the compositor, in one SIMD pass into a pooled frame, so a running +//! camera allocates nothing per frame. Compressed formats (MJPEG) are not +//! offered, so a camera that has both gives us its raw one. +//! +//! [`SYNTHETIC`] is a camera that is always there: the test pattern. Tests +//! and machines without a camera use it. +//! +//! Windows and Android have no camera backend yet ([`list`] returns only the +//! synthetic one). + +use std::sync::Arc; +use std::sync::atomic::AtomicU32; +use tracing::debug; + +use crate::Result; +use crate::capture::synthetic::SyntheticScreen; +use crate::capture::{CaptureOptions, ScreenCapture, SourceId}; +use crate::studio::compose::Feed; +use crate::studio::source::FeedSink; + +/// The id of the camera that is always available: the test pattern. +pub const SYNTHETIC: &str = "synthetic"; + +const BACKEND: &str = "camera"; + +/// A pixel format a camera delivers. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Pixel { + /// 4:2:2, two pixels in `Y0 U Y1 V`. + Yuyv, + /// 4:2:2, two pixels in `U Y0 V Y1`. + Uyvy, + Nv12, + I420, + /// 4 bytes per pixel, B G R x. + Bgrx, + /// 4 bytes per pixel, R G B x. + Rgbx, + /// 3 bytes per pixel. + Rgb24, + Bgr24, + /// Motion JPEG; not offered (see the [module docs](self)). + Mjpeg, +} + +impl Pixel { + /// The format of a V4L2 / DRM four-character code. + pub fn from_fourcc(code: u32) -> Option { + Some(match &code.to_le_bytes() { + b"YUYV" | b"YUY2" => Self::Yuyv, + b"UYVY" => Self::Uyvy, + b"NV12" => Self::Nv12, + b"YU12" | b"I420" => Self::I420, + b"XR24" | b"AR24" | b"BGR4" => Self::Bgrx, + b"XB24" | b"AB24" | b"RGB4" => Self::Rgbx, + b"RGB3" => Self::Rgb24, + b"BGR3" => Self::Bgr24, + b"MJPG" | b"JPEG" => Self::Mjpeg, + _ => return None, + }) + } + + /// The name shown in a picker. + pub fn label(self) -> &'static str { + match self { + Self::Yuyv => "YUYV", + Self::Uyvy => "UYVY", + Self::Nv12 => "NV12", + Self::I420 => "I420", + Self::Bgrx => "BGRx", + Self::Rgbx => "RGBx", + Self::Rgb24 => "RGB", + Self::Bgr24 => "BGR", + Self::Mjpeg => "MJPEG", + } + } +} + +/// One pixel format of a camera, with the sizes the driver reports for it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Format { + pub pixel: Pixel, + /// Every resolution the driver lists, largest first; empty for a driver + /// that only reports a range. + pub sizes: Vec<(u32, u32)>, + /// Highest frame rate of the largest size, or 0 if unknown. + pub max_fps: u32, +} + +/// A camera as shown in a picker. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Camera { + /// What a scene's `SourceKind::Camera { device }` names: the device path + /// on Linux, or [`SYNTHETIC`]. + pub id: String, + pub name: String, + /// Where the list came from (`"v4l2"`, `"synthetic"`). + pub backend: &'static str, + pub formats: Vec, +} + +/// Every camera this session can use. Never fails: a device that cannot be +/// asked is left out, and [`SYNTHETIC`] is always last. +pub fn list() -> Vec { + let mut cameras = Vec::new(); + #[cfg(target_os = "linux")] + cameras.extend(v4l2::list()); + cameras.push(Camera { + id: SYNTHETIC.to_owned(), + name: "Test pattern".to_owned(), + backend: "synthetic", + formats: vec![Format { pixel: Pixel::Bgrx, sizes: vec![(1280, 720)], max_fps: 60 }], + }); + cameras +} + +/// A running camera; stops when dropped. +pub struct Capture { + backend: &'static str, + device: String, + screen: Option>, + #[cfg(all(target_os = "linux", feature = "pipewire"))] + stream: Option, +} + +impl Capture { + /// Open `device` (a [`Camera::id`]; empty: the first camera, else the + /// test pattern) and feed `feed` with up to `fps` frames a second at + /// `size` if the camera has it. + /// + /// Must run on a Tokio runtime: the camera portal talks D-Bus. + pub async fn start( + device: &str, + size: Option<(u32, u32)>, + fps: u32, + feed: Arc, + ) -> Result { + let fps = fps.max(1); + let wanted = match device.trim() { + "" => list() + .into_iter() + .find(|c| c.backend != "synthetic") + .map_or_else(|| SYNTHETIC.to_owned(), |c| c.id), + name => name.to_owned(), + }; + if wanted == SYNTHETIC { + 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?; + return Ok(Self { + backend: "synthetic", + device: wanted, + screen: Some(Box::new(screen)), + #[cfg(all(target_os = "linux", feature = "pipewire"))] + stream: None, + }); + } + #[cfg(all(target_os = "linux", feature = "pipewire"))] + { + let stream = pipewire_camera::Stream::start(&wanted, size, fps, feed).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); + Err(crate::Error::CaptureUnavailable { + backend: BACKEND, + reason: format!("no camera backend for {wanted:?} in this build"), + }) + } + } + + /// Where the frames come from (`"pipewire"`, `"portal"`, `"synthetic"`). + pub fn backend(&self) -> &'static str { + #[cfg(all(target_os = "linux", feature = "pipewire"))] + if let Some(stream) = &self.stream { + return stream.backend(); + } + self.backend + } + + /// The camera that was opened. + pub fn device(&self) -> &str { + &self.device + } +} + +impl Drop for Capture { + fn drop(&mut self) { + if let Some(screen) = &mut self.screen { + screen.stop(); + } + } +} + +/// Listing cameras through V4L2: the card name and every pixel format and +/// resolution the driver reports. +/// +/// Only the three read-only enumeration ioctls are used; frames come through +/// PipeWire. The structures below are the kernel's V4L2 ABI (`videodev2.h`), +/// which is stable and the same on 32- and 64-bit: plain `u8` and `u32` +/// fields, no pointers. +#[cfg(target_os = "linux")] +mod v4l2 { + #![allow(unsafe_code)] + + use std::os::fd::OwnedFd; + + use rustix::ioctl::{Getter, Opcode, Updater, ioctl, opcode}; + + use super::{Camera, Format, Pixel}; + + /// `V4L2_BUF_TYPE_VIDEO_CAPTURE`. + const CAPTURE: u32 = 1; + /// `V4L2_CAP_VIDEO_CAPTURE`. + const CAP_VIDEO_CAPTURE: u32 = 0x0000_0001; + /// `V4L2_CAP_DEVICE_CAPS`. + const CAP_DEVICE_CAPS: u32 = 0x8000_0000; + /// `V4L2_FRMSIZE_TYPE_DISCRETE`. + const FRMSIZE_DISCRETE: u32 = 1; + /// `V4L2_FRMIVAL_TYPE_DISCRETE`. + const FRMIVAL_DISCRETE: u32 = 1; + /// Enumeration stops here even if the driver never says "no more". + const MAX_ENTRIES: u32 = 128; + + /// `struct v4l2_capability`. + #[repr(C)] + #[derive(Clone, Copy)] + struct Capability { + driver: [u8; 16], + card: [u8; 32], + bus_info: [u8; 32], + version: u32, + capabilities: u32, + device_caps: u32, + reserved: [u32; 3], + } + + /// `struct v4l2_fmtdesc`. + #[repr(C)] + #[derive(Clone, Copy)] + struct FmtDesc { + index: u32, + type_: u32, + flags: u32, + description: [u8; 32], + pixelformat: u32, + mbus_code: u32, + reserved: [u32; 3], + } + + /// `struct v4l2_frmsizeenum` (the union as the largest member, + /// `v4l2_frmsize_stepwise`). + #[repr(C)] + #[derive(Clone, Copy)] + struct FrmSizeEnum { + index: u32, + pixel_format: u32, + type_: u32, + /// Discrete: `[width, height]`; stepwise: min, max and step of both. + size: [u32; 6], + reserved: [u32; 2], + } + + /// `struct v4l2_frmivalenum` (the union as `v4l2_frmival_stepwise`). + #[repr(C)] + #[derive(Clone, Copy)] + struct FrmIvalEnum { + index: u32, + pixel_format: u32, + width: u32, + height: u32, + type_: u32, + /// Discrete: `[numerator, denominator]` seconds per frame. + interval: [u32; 6], + reserved: [u32; 2], + } + + const QUERYCAP: Opcode = opcode::read::(b'V', 0); + const ENUM_FMT: Opcode = opcode::read_write::(b'V', 2); + const ENUM_FRAMESIZES: Opcode = opcode::read_write::(b'V', 74); + const ENUM_FRAMEINTERVALS: Opcode = opcode::read_write::(b'V', 75); + + /// The NUL-terminated ASCII of a fixed-size kernel string field. + fn text(bytes: &[u8]) -> String { + let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len()); + String::from_utf8_lossy(&bytes[..end]).trim().to_owned() + } + + fn open(path: &std::path::Path) -> Option { + use rustix::fs::{Mode, OFlags}; + rustix::fs::open(path, OFlags::RDWR | OFlags::CLOEXEC | OFlags::NONBLOCK, Mode::empty()) + .ok() + } + + /// The card name of a capture device, or `None` if it cannot capture + /// video. + fn card(fd: &OwnedFd) -> Option { + // SAFETY: `QUERYCAP` is `_IOR('V', 0, struct v4l2_capability)`, and + // `Capability` is that structure; the kernel only writes into it. + let caps = unsafe { ioctl(fd, Getter::::new()) }.ok()?; + let usable = if caps.capabilities & CAP_DEVICE_CAPS != 0 { + caps.device_caps + } else { + caps.capabilities + }; + (usable & CAP_VIDEO_CAPTURE != 0).then(|| text(&caps.card)) + } + + /// Every resolution the driver lists for `pixelformat`, largest first, + /// and the highest frame rate of the largest one. + fn sizes(fd: &OwnedFd, pixelformat: u32) -> (Vec<(u32, u32)>, u32) { + let mut sizes = Vec::new(); + for index in 0..MAX_ENTRIES { + let mut entry = FrmSizeEnum { + index, + pixel_format: pixelformat, + type_: 0, + size: [0; 6], + reserved: [0; 2], + }; + // SAFETY: `ENUM_FRAMESIZES` is + // `_IOWR('V', 74, struct v4l2_frmsizeenum)` and `entry` is that + // structure, which the kernel reads and writes in place. + if unsafe { ioctl(fd, Updater::::new(&mut entry)) } + .is_err() + { + break; + } + if entry.type_ == FRMSIZE_DISCRETE { + sizes.push((entry.size[0], entry.size[1])); + } else { + // A range: its largest size is all we offer. + sizes.push((entry.size[1], entry.size[4])); + break; + } + } + sizes.sort_unstable_by_key(|&(w, h)| std::cmp::Reverse(u64::from(w) * u64::from(h))); + sizes.dedup(); + let fps = sizes.first().map_or(0, |&(w, h)| max_fps(fd, pixelformat, w, h)); + (sizes, fps) + } + + /// The highest frame rate the driver lists for one size. + fn max_fps(fd: &OwnedFd, pixel_format: u32, width: u32, height: u32) -> u32 { + let mut best = 0; + for index in 0..MAX_ENTRIES { + let mut entry = FrmIvalEnum { + index, + pixel_format, + width, + height, + type_: 0, + interval: [0; 6], + reserved: [0; 2], + }; + // SAFETY: `ENUM_FRAMEINTERVALS` is + // `_IOWR('V', 75, struct v4l2_frmivalenum)` and `entry` is that + // structure, which the kernel reads and writes in place. + if unsafe { ioctl(fd, Updater::::new(&mut entry)) } + .is_err() + { + break; + } + // Seconds per frame; a stepwise range starts with its smallest + // interval, which is the highest rate. + let (num, den) = (entry.interval[0], entry.interval[1]); + if num > 0 { + best = best.max(den / num); + } + if entry.type_ != FRMIVAL_DISCRETE { + break; + } + } + best + } + + /// The pixel formats of a capture device. + fn formats(fd: &OwnedFd) -> Vec { + let mut formats = Vec::new(); + for index in 0..MAX_ENTRIES { + let mut entry = FmtDesc { + index, + type_: CAPTURE, + flags: 0, + description: [0; 32], + pixelformat: 0, + mbus_code: 0, + reserved: [0; 3], + }; + // SAFETY: `ENUM_FMT` is `_IOWR('V', 2, struct v4l2_fmtdesc)` and + // `entry` is that structure, which the kernel reads and writes + // in place. + if unsafe { ioctl(fd, Updater::::new(&mut entry)) }.is_err() { + break; + } + let Some(pixel) = Pixel::from_fourcc(entry.pixelformat) else { continue }; + if formats.iter().any(|f: &Format| f.pixel == pixel) { + continue; + } + let (sizes, max_fps) = sizes(fd, entry.pixelformat); + formats.push(Format { pixel, sizes, max_fps }); + } + formats + } + + /// Every `/dev/video*` that can capture video, by path. + pub fn list() -> Vec { + let Ok(entries) = std::fs::read_dir("/dev") else { return Vec::new() }; + let mut paths: Vec = entries + .flatten() + .map(|e| e.path()) + .filter(|p| { + p.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with("video") && n[5..].parse::().is_ok()) + }) + .collect(); + paths.sort(); + paths + .into_iter() + .filter_map(|path| { + let fd = open(&path)?; + let name = card(&fd)?; + let formats = formats(&fd); + // A device node without a usable format is a metadata or + // output node of the same camera. + (!formats.is_empty()).then(|| Camera { + id: path.to_string_lossy().into_owned(), + name: if name.is_empty() { path.to_string_lossy().into_owned() } else { name }, + backend: "v4l2", + formats, + }) + }) + .collect() + } +} + +/// Camera frames through PipeWire: the user's daemon, or the XDG Camera +/// portal's connection in a sandbox. +#[cfg(all(target_os = "linux", feature = "pipewire"))] +mod pipewire_camera { + use std::os::fd::OwnedFd; + use std::sync::Arc; + use std::time::{Duration, Instant}; + + use pipewire as pw; + use pw::spa::param::format::{FormatProperties, MediaSubtype, MediaType}; + use pw::spa::param::video::{VideoFormat, VideoInfoRaw}; + use pw::spa::pod::{Object, Value, property}; + use pw::spa::utils::{Fraction, Rectangle, SpaTypes}; + use tracing::{debug, warn}; + + use crate::capture::FramePacer; + use crate::capture::pw::{PwThread, pod, serialize}; + use crate::frame::{FrameRef, PixelsRef, PlaneRef}; + use crate::pool::FramePool; + use crate::studio::compose::Feed; + use crate::studio::source::deliver; + use crate::{Error, Result}; + + use super::BACKEND; + + /// The pixel formats we take, in order of preference; all of them the + /// compositor can use after one conversion. + const FORMATS: [VideoFormat; 8] = [ + VideoFormat::NV12, + VideoFormat::I420, + VideoFormat::YUY2, + VideoFormat::UYVY, + VideoFormat::BGRx, + VideoFormat::RGBx, + VideoFormat::BGR, + VideoFormat::RGB, + ]; + + /// A running camera stream; stops when dropped. + pub struct Stream { + backend: &'static str, + _thread: PwThread, + } + + impl Stream { + /// Connect to `device` (a `/dev/video*` path) and feed `feed`. + pub async fn start( + device: &str, + size: Option<(u32, u32)>, + fps: u32, + feed: Arc, + ) -> 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()); + 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)?; + Ok(Self { backend: "portal", _thread: thread }) + } + } + } + + pub fn backend(&self) -> &'static str { + self.backend + } + } + + /// A PipeWire connection with camera access from the XDG Camera portal. + async fn portal_fd() -> Result { + use ashpd::desktop::camera::Camera; + let unavailable = |e: String| Error::CaptureUnavailable { backend: BACKEND, reason: e }; + let proxy = Camera::new() + .await + .map_err(|e| unavailable(format!("the camera portal is not available: {e}")))?; + if !proxy + .is_present() + .await + .map_err(|e| unavailable(format!("the camera portal did not answer: {e}")))? + { + return Err(unavailable("the desktop reports no camera".into())); + } + proxy + .request_access(Default::default()) + .await + .map_err(|e| unavailable(format!("camera access was refused: {e}")))? + .response() + .map_err(|_| Error::Cancelled)?; + proxy + .open_pipe_wire_remote(Default::default()) + .await + .map_err(|e| unavailable(format!("the camera portal gave no connection: {e}"))) + } + + fn connect( + fd: Option, + device: &str, + size: Option<(u32, u32)>, + fps: u32, + feed: Arc, + ) -> 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) + }) + .map_err(|e| Error::Capture { backend: BACKEND, message: e }) + } + + struct State { + feed: Arc, + pool: FramePool, + pacer: FramePacer, + started: Instant, + format: Option<(VideoFormat, u32, u32)>, + mainloop: pw::main_loop::MainLoopWeak, + } + + type Parts = (pw::stream::StreamRc, pw::stream::StreamListener); + + #[allow(clippy::too_many_arguments)] + fn camera_stream( + core: &pw::core::CoreRc, + mainloop: &pw::main_loop::MainLoopRc, + target: Option, + device: &str, + size: Option<(u32, u32)>, + fps: u32, + feed: Arc, + ) -> std::result::Result { + let props = pw::properties::properties! { + *pw::keys::MEDIA_TYPE => "Video", + *pw::keys::MEDIA_CATEGORY => "Capture", + *pw::keys::MEDIA_ROLE => "Camera", + }; + let stream = pw::stream::StreamRc::new(core.clone(), "voelin-camera", props) + .map_err(|e| format!("PipeWire stream: {e}"))?; + let state = State { + feed, + pool: FramePool::new(), + pacer: FramePacer::new(Some(fps)), + started: Instant::now(), + format: None, + mainloop: mainloop.downgrade(), + }; + let listener = stream + .add_local_listener_with_user_data(state) + .state_changed(|_, state, _, new| { + if let pw::stream::StreamState::Error(e) = &new { + warn!("camera stream failed: {e}"); + state.feed.set_error(format!("camera stream failed: {e}")); + } + if matches!( + new, + pw::stream::StreamState::Error(_) | pw::stream::StreamState::Unconnected + ) && let Some(mainloop) = state.mainloop.upgrade() + { + mainloop.quit(); + } + }) + .param_changed(|_, state, id, param| { + let Some(param) = param else { return }; + if id != pw::spa::param::ParamType::Format.as_raw() { + return; + } + let Ok((MediaType::Video, MediaSubtype::Raw)) = + pw::spa::param::format_utils::parse_format(param) + else { + return; + }; + let mut info = VideoInfoRaw::new(); + if let Err(e) = info.parse(param) { + warn!("cannot parse the camera format: {e}"); + return; + } + let size = info.size(); + debug!(format = ?info.format(), size.width, size.height, "camera format"); + state.format = Some((info.format(), size.width, size.height)); + }) + .process(process) + .register() + .map_err(|e| format!("PipeWire listener: {e}"))?; + let formats = enum_formats(size, fps)?; + let mut pods = + formats.iter().map(|f| pod(f)).collect::, _>>()?; + stream + .connect( + pw::spa::utils::Direction::Input, + target, + pw::stream::StreamFlags::AUTOCONNECT | pw::stream::StreamFlags::MAP_BUFFERS, + &mut pods, + ) + .map_err(|e| format!("cannot connect to a camera ({device}): {e}"))?; + Ok((stream, listener)) + } + + /// One offer per pixel format: the wanted size (or any) and up to `fps`. + fn enum_formats( + size: Option<(u32, u32)>, + fps: u32, + ) -> std::result::Result>, String> { + let mut formats = Vec::new(); + for format in FORMATS { + let mut properties = vec![ + property!(FormatProperties::MediaType, Id, MediaType::Video), + property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw), + property!(FormatProperties::VideoFormat, Id, format), + ]; + properties.push(match size { + Some((w, h)) => property!( + FormatProperties::VideoSize, + Choice, + Range, + Rectangle, + Rectangle { width: w.max(2), height: h.max(2) }, + Rectangle { width: 1, height: 1 }, + Rectangle { width: 16384, height: 16384 } + ), + None => property!( + FormatProperties::VideoSize, + Choice, + Range, + Rectangle, + Rectangle { width: 1280, height: 720 }, + Rectangle { width: 1, height: 1 }, + Rectangle { width: 16384, height: 16384 } + ), + }); + properties.push(property!( + FormatProperties::VideoFramerate, + Choice, + Range, + Fraction, + Fraction { num: fps, denom: 1 }, + Fraction { num: 1, denom: 1 }, + Fraction { num: fps.max(1), denom: 1 } + )); + formats.push(serialize(Value::Object(Object { + type_: SpaTypes::ObjectParamFormat.as_raw(), + id: pw::spa::param::ParamType::EnumFormat.as_raw(), + properties, + }))?); + } + Ok(formats) + } + + fn process(stream: &pw::stream::Stream, state: &mut State) { + let Some(mut buffer) = stream.dequeue_buffer() else { return }; + let Some((format, width, height)) = state.format else { return }; + let timestamp = state.started.elapsed(); + if state.feed.is_closed() { + if let Some(mainloop) = state.mainloop.upgrade() { + mainloop.quit(); + } + return; + } + if !state.pacer.take(timestamp) { + return; + } + let Some(data) = buffer.datas_mut().first_mut() else { return }; + let chunk = data.chunk(); + if chunk.size() == 0 || chunk.flags().contains(pw::spa::buffer::ChunkFlags::CORRUPTED) { + return; + } + let (offset, stride) = (chunk.offset() as usize, chunk.stride() as usize); + let Some(bytes) = data.data() else { return }; + let Some(bytes) = bytes.get(offset..) else { return }; + if let Err(e) = take(state, format, width, height, stride, bytes, timestamp) { + warn!("cannot take a camera frame: {e}"); + state.feed.set_error(e); + } + } + + /// Hand one camera buffer to the feed, converted to something the + /// compositor draws. + fn take( + state: &mut State, + format: VideoFormat, + width: u32, + height: u32, + stride: usize, + bytes: &[u8], + timestamp: Duration, + ) -> Result<()> { + let (w, h) = (width as usize, height as usize); + /// The buffer as a plane whose stride is at least one row. + fn plane(bytes: &[u8], stride: usize, row: usize) -> PlaneRef<'_> { + PlaneRef::new(bytes, if stride >= row { stride } else { row }) + } + let pixels = match format { + VideoFormat::BGRx | VideoFormat::BGRA => PixelsRef::Bgra(plane(bytes, stride, w * 4)), + VideoFormat::RGBx | VideoFormat::RGBA => PixelsRef::Rgba(plane(bytes, stride, w * 4)), + VideoFormat::NV12 => { + let y = plane(bytes, stride, w); + let split = y.stride * h; + PixelsRef::Nv12 { + y, + uv: plane(bytes.get(split..).unwrap_or_default(), stride, w.div_ceil(2) * 2), + } + } + VideoFormat::I420 => { + let y = plane(bytes, stride, w); + let (cw, ch) = crate::frame::chroma_size(width, height); + let split = y.stride * h; + let rest = bytes.get(split..).unwrap_or_default(); + PixelsRef::I420 { + y, + u: PlaneRef::new(rest, cw), + v: PlaneRef::new(rest.get(cw * ch..).unwrap_or_default(), cw), + } + } + // 4:2:2 and 24-bit formats: unpacked into the pool's RGBA frame. + other => return packed(state, other, width, height, stride, bytes, timestamp), + }; + let frame = FrameRef { width, height, timestamp, pixels }; + deliver(&mut state.pool, &state.feed, &frame) + } + + /// YUY2 / UYVY / RGB / BGR straight into a pooled RGBA frame. + fn packed( + state: &mut State, + format: VideoFormat, + width: u32, + height: u32, + stride: usize, + bytes: &[u8], + timestamp: Duration, + ) -> Result<()> { + use crate::frame::{FrameData, PixelFormat}; + let (w, h) = (width as usize, height as usize); + let row = match format { + VideoFormat::YUY2 | VideoFormat::UYVY => w * 2, + VideoFormat::RGB | VideoFormat::BGR => w * 3, + other => { + return Err(Error::Convert(format!("camera format {other:?} is not supported"))); + } + }; + let stride = if stride >= row { stride } else { row }; + if bytes.len() < stride * (h - 1) + row { + return Err(Error::InvalidFrame(format!( + "camera buffer of {} bytes is too small for {width}x{height}", + bytes.len() + ))); + } + let slot = state.pool.get_format(width, height, PixelFormat::Rgba); + let target = Arc::get_mut(slot).expect("the pool hands out unshared frames"); + target.timestamp = timestamp; + let FrameData::Rgba(out) = &mut target.data else { + return Err(Error::InvalidFrame("the camera pool is not RGBA".into())); + }; + match format { + VideoFormat::YUY2 | VideoFormat::UYVY => { + let image = yuv::YuvPackedImage { + yuy: bytes, + yuy_stride: u32::try_from(stride) + .map_err(|_| Error::InvalidFrame("camera stride too large".into()))?, + width, + height, + }; + let convert = if format == VideoFormat::YUY2 { + yuv::yuyv422_to_rgba + } else { + yuv::uyvy422_to_rgba + }; + convert( + &image, + &mut out.data, + out.stride as u32, + yuv::YuvRange::Limited, + yuv::YuvStandardMatrix::Bt601, + ) + .map_err(|e| Error::Convert(e.to_string()))?; + } + _ => { + let bgr = format == VideoFormat::BGR; + for y in 0..h { + let src = &bytes[y * stride..][..row]; + let dst = &mut out.data[y * out.stride..][..w * 4]; + for (d, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(3)) { + d.copy_from_slice(&if bgr { + [s[2], s[1], s[0], 255] + } else { + [s[0], s[1], s[2], 255] + }); + } + } + } + } + state.feed.put(slot.clone()); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + #[test] + fn the_test_pattern_camera_is_always_listed() { + let cameras = list(); + let synthetic = cameras.last().expect("at least the test pattern"); + assert_eq!(synthetic.id, SYNTHETIC); + assert_eq!(synthetic.backend, "synthetic"); + assert!(!synthetic.formats.is_empty()); + // Real cameras, if any, have a name and at least one usable format. + for camera in cameras.iter().filter(|c| c.backend != "synthetic") { + assert!(!camera.id.is_empty() && !camera.name.is_empty(), "{camera:?}"); + assert!(!camera.formats.is_empty(), "{camera:?}"); + for format in &camera.formats { + assert!(format.sizes.iter().all(|&(w, h)| w > 0 && h > 0), "{format:?}"); + } + println!( + "camera {} ({}): {}", + camera.id, + camera.name, + camera + .formats + .iter() + .map(|f| format!( + "{} {:?} up to {} fps", + f.pixel.label(), + f.sizes.first(), + f.max_fps + )) + .collect::>() + .join(", ") + ); + } + } + + #[test] + fn four_character_codes() { + assert_eq!(Pixel::from_fourcc(u32::from_le_bytes(*b"YUYV")), Some(Pixel::Yuyv)); + assert_eq!(Pixel::from_fourcc(u32::from_le_bytes(*b"MJPG")), Some(Pixel::Mjpeg)); + assert_eq!(Pixel::from_fourcc(u32::from_le_bytes(*b"XR24")), Some(Pixel::Bgrx)); + assert_eq!(Pixel::from_fourcc(u32::from_le_bytes(*b"ZZZZ")), None); + assert_eq!(Pixel::Nv12.label(), "NV12"); + } + + #[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(); + assert_eq!(capture.backend(), "synthetic"); + assert_eq!(capture.device(), SYNTHETIC); + let started = std::time::Instant::now(); + while feed.delivered() == 0 && started.elapsed() < Duration::from_secs(5) { + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!(feed.delivered() > 0); + assert_eq!(feed.size(), (64, 48)); + assert_eq!(feed.error(), None); + } +} diff --git a/crates/voelin-media/src/studio/mod.rs b/crates/voelin-media/src/studio/mod.rs index 8b1b0bb..80ca8da 100644 --- a/crates/voelin-media/src/studio/mod.rs +++ b/crates/voelin-media/src/studio/mod.rs @@ -5,6 +5,11 @@ //! persisted shape of a studio //! - [`compose`]: the compositor, which draws the live scene into pooled //! frames at the output size +//! - [`source`]: the live input behind each of a scene's sources (colour, +//! text, image, screen, window, camera) +//! - [`camera`]: listing and capturing cameras +pub mod camera; pub mod compose; pub mod scene; +pub mod source; diff --git a/crates/voelin-media/src/studio/source.rs b/crates/voelin-media/src/studio/source.rs new file mode 100644 index 0000000..fe6be97 --- /dev/null +++ b/crates/voelin-media/src/studio/source.rs @@ -0,0 +1,529 @@ +//! The live inputs behind a scene's sources. +//! +//! [`Input`] starts whatever a [`SourceKind`] needs and publishes pictures +//! into a [`Feed`] the compositor reads: +//! +//! - colour, text and image are drawn once (they never change by themselves) +//! and put into the feed; a changed text or colour is drawn again +//! - screen, window, portal and the test pattern run one of the +//! [`crate::capture`] backends, which hands every frame to a [`FeedSink`] +//! on its own thread +//! - camera runs one of the [`crate::studio::camera`] backends +//! +//! Nothing here fails loudly: a camera that is gone or an image that cannot +//! be read leaves [`Feed::error`] set and the source draws nothing, so one +//! broken source never stops the studio. + +use std::path::Path; +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::time::Duration; + +use ab_glyph::{Font, FontRef, Glyph, PxScale, ScaleFont, point}; +use tracing::{debug, warn}; + +use crate::capture::{ + CaptureOptions, FramePacer, FrameSink, ScreenCapture, synthetic::SyntheticScreen, +}; +use crate::frame::{FrameData, FrameRef, PixelFormat, PixelsRef, Plane, VideoFrame}; +use crate::pool::FramePool; +use crate::studio::camera; +use crate::studio::compose::Feed; +use crate::studio::scene::{Align, Colour, SourceKind}; +use crate::{Error, Result}; + +/// The UI's font, for text sources without one of their own. The same file +/// `crates/voelin-ui` bundles (its notice is in `about-assets.md`); reached +/// from here because tools without the UI crate rasterise text too. +const DEFAULT_FONT: &[u8] = include_bytes!("../../../voelin-ui/ui/assets/fonts/Inter-Regular.ttf"); + +/// An RGBA frame of one flat colour. +pub fn colour_frame(colour: Colour, size: (u32, u32)) -> VideoFrame { + let (width, height) = (size.0.max(1), size.1.max(1)); + let rgba = colour.to_rgba(); + 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); + } + VideoFrame { + width, + height, + timestamp: Duration::ZERO, + data: FrameData::Rgba(Plane::new(data, width as usize * 4)), + } +} + +/// An RGBA frame from an image file (PNG, JPEG, ...), alpha kept. +pub fn image_frame(path: &Path) -> Result { + let image = image::open(path) + .map_err(|e| Error::InvalidFrame(format!("cannot read {}: {e}", path.display())))? + .into_rgba8(); + let (width, height) = (image.width(), image.height()); + if width == 0 || height == 0 { + return Err(Error::InvalidFrame(format!("{} is empty", path.display()))); + } + Ok(VideoFrame { + width, + height, + timestamp: Duration::ZERO, + data: FrameData::Rgba(Plane::new(image.into_raw(), width as usize * 4)), + }) +} + +/// Straight-alpha source-over of `src` (with coverage `coverage`) onto `dst`. +fn over(dst: &mut [u8], src: [u8; 4], coverage: f32) { + let sa = f32::from(src[3]) / 255.0 * coverage.clamp(0.0, 1.0); + if sa <= 0.0 { + return; + } + let da = f32::from(dst[3]) / 255.0; + let out = sa + da * (1.0 - sa); + for c in 0..3 { + let s = f32::from(src[c]) * sa; + let d = f32::from(dst[c]) * da * (1.0 - sa); + dst[c] = ((s + d) / out).round().clamp(0.0, 255.0) as u8; + } + dst[3] = (out * 255.0).round().clamp(0.0, 255.0) as u8; +} + +/// An RGBA frame with `text` rasterised: lines split at `\n`, `padding` +/// pixels around them, glyphs in `colour` over `backdrop`. +/// +/// `font`: a TrueType / OpenType file; `None` uses the UI's font. +pub fn text_frame( + text: &str, + font: Option<&Path>, + size_px: f32, + colour: Colour, + backdrop: Colour, + align: Align, + padding: u32, +) -> Result { + let owned = match font { + Some(path) => Some(std::fs::read(path).map_err(|e| { + Error::InvalidFrame(format!("cannot read the font {}: {e}", path.display())) + })?), + None => None, + }; + let bytes = owned.as_deref().unwrap_or(DEFAULT_FONT); + let font = FontRef::try_from_slice(bytes) + .map_err(|e| Error::InvalidFrame(format!("not a usable font: {e}")))?; + let scaled = font.as_scaled(PxScale::from(size_px.clamp(1.0, 4096.0))); + let line_height = scaled.height() + scaled.line_gap(); + // Lay every line out at the origin first, to know how wide it gets. + let mut lines: Vec<(Vec, f32)> = Vec::new(); + for line in text.split('\n') { + let mut glyphs = Vec::new(); + let mut caret = 0.0; + let mut previous = None; + for ch in line.chars() { + if ch.is_control() { + continue; + } + let mut glyph = scaled.scaled_glyph(ch); + if let Some(previous) = previous { + caret += scaled.kern(previous, glyph.id); + } + previous = Some(glyph.id); + glyph.position = point(caret, 0.0); + caret += scaled.h_advance(glyph.id); + glyphs.push(glyph); + } + lines.push((glyphs, caret)); + } + let pad = padding as f32; + let widest = lines.iter().map(|(_, w)| *w).fold(0.0f32, f32::max); + let width = (widest + 2.0 * pad).ceil().max(1.0) as u32; + let height = (lines.len() as f32 * line_height + 2.0 * pad).ceil().max(1.0) as u32; + let mut frame = colour_frame(backdrop, (width, height)); + let FrameData::Rgba(plane) = &mut frame.data else { unreachable!("colour_frame is RGBA") }; + let (stride, rgba) = (plane.stride, colour.to_rgba()); + for (i, (glyphs, line_width)) in lines.iter().enumerate() { + let free = widest - line_width; + let offset = pad + + match align { + Align::Left => 0.0, + Align::Center => free / 2.0, + Align::Right => free, + }; + let baseline = pad + scaled.ascent() + i as f32 * line_height; + for glyph in glyphs { + let mut placed = glyph.clone(); + placed.position = point(glyph.position.x + offset, baseline); + let Some(outline) = scaled.outline_glyph(placed) else { continue }; + let bounds = outline.px_bounds(); + outline.draw(|x, y, coverage| { + let px = bounds.min.x as i64 + i64::from(x); + let py = bounds.min.y as i64 + i64::from(y); + if px < 0 || py < 0 || px >= i64::from(width) || py >= i64::from(height) { + return; + } + let at = py as usize * stride + px as usize * 4; + over(&mut plane.data[at..at + 4], rgba, coverage); + }); + } + } + Ok(frame) +} + +/// Copies every captured frame into a pooled frame for a [`Feed`]: BGRA and +/// RGBA as they are (the compositor takes both), anything else converted to +/// RGBA. Allocates nothing per frame once the pool is warm. +pub struct FeedSink { + feed: Arc, + pool: FramePool, + fps: Arc, + pacer: FramePacer, + rate: u32, +} + +impl FeedSink { + /// `fps` is shared with the studio, so the rate can change while + /// 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 } + } + + fn follow_rate(&mut self) -> u32 { + let rate = self.fps.load(Ordering::Relaxed).max(1); + if rate != self.rate { + self.rate = rate; + self.pacer.set_fps(Some(rate)); + } + rate + } +} + +impl FrameSink for FeedSink { + fn max_fps(&self) -> u32 { + self.fps.load(Ordering::Relaxed).max(1) + } + + fn wants(&mut self, timestamp: Duration) -> bool { + if self.feed.is_closed() { + return false; + } + self.follow_rate(); + self.pacer.due(timestamp) + } + + fn frame(&mut self, frame: FrameRef<'_>) -> bool { + if self.feed.is_closed() { + return false; + } + self.pacer.keep(frame.timestamp); + match deliver(&mut self.pool, &self.feed, &frame) { + Ok(()) => true, + Err(e) => { + warn!("cannot take a studio source frame: {e}"); + self.feed.set_error(e); + true + } + } + } +} + +/// Copy `frame` into a pooled frame and publish it. +pub fn deliver(pool: &mut FramePool, feed: &Feed, frame: &FrameRef<'_>) -> Result<()> { + frame.validate()?; + let (width, height) = (frame.width, frame.height); + let row = width as usize * 4; + let format = match frame.pixels { + PixelsRef::Bgra(_) => PixelFormat::Bgra, + // I420, NV12 and the rest become RGBA. + _ => PixelFormat::Rgba, + }; + let slot = pool.get_format(width, height, format); + let target = Arc::get_mut(slot).expect("the pool hands out unshared frames"); + target.timestamp = frame.timestamp; + let (FrameData::Bgra(plane) | FrameData::Rgba(plane)) = &mut target.data else { + return Err(Error::InvalidFrame("the studio source pool is not packed".into())); + }; + match frame.pixels { + PixelsRef::Bgra(src) | PixelsRef::Rgba(src) => { + 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)?, + } + feed.put(slot.clone()); + Ok(()) +} + +/// The screen capture backend a source asks for by name. +fn screen_backend(name: Option<&str>) -> Result> { + let unavailable = |backend: &'static str| Error::CaptureUnavailable { + backend, + reason: format!("{backend} capture is not in this build"), + }; + match name.map(str::trim).filter(|n| !n.is_empty() && *n != "auto") { + None => crate::capture::default_screen_capture(), + #[cfg(all(target_os = "linux", feature = "pipewire"))] + Some("portal") => Ok(Box::new(crate::capture::portal::PortalCapture::new())), + #[cfg(all(target_os = "linux", feature = "wlroots"))] + Some("wlroots") => Ok(Box::new(crate::capture::wlroots::WlrootsCapture::new())), + #[cfg(all(target_os = "linux", feature = "x11"))] + Some("x11") => Ok(Box::new(crate::capture::x11::X11Capture::new())), + #[cfg(windows)] + Some("windows") => Ok(Box::new(crate::capture::windows::WindowsCapture::new())), + #[cfg(not(all(target_os = "linux", feature = "pipewire")))] + Some("portal") => Err(unavailable("portal")), + #[cfg(not(all(target_os = "linux", feature = "wlroots")))] + Some("wlroots") => Err(unavailable("wlroots")), + #[cfg(not(all(target_os = "linux", feature = "x11")))] + Some("x11") => Err(unavailable("x11")), + #[cfg(not(windows))] + Some("windows") => Err(unavailable("windows")), + Some(other) => Err(Error::CaptureUnavailable { + backend: "screen", + reason: format!("no capture backend named {other:?}"), + }), + } +} + +/// A source's live input: its [`Feed`] and whatever produces the pictures. +pub struct Input { + pub feed: Arc, + kind: SourceKind, + fps: Arc, + /// Stopped when dropped. + screen: Option>, + camera: Option, + /// The portal's token for this choice, to skip its dialog next time. + restore_token: Option, +} + +impl Input { + /// Start the input of `kind` at up to `fps`. Never fails: a source that + /// 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 { + let feed = Arc::new(Feed::new()); + let mut input = Self { + feed: feed.clone(), + fps: Arc::new(AtomicU32::new(fps.max(1))), + kind, + screen: None, + camera: None, + restore_token: None, + }; + if let Err(e) = input.begin().await { + warn!(kind = input.kind.label(), "studio source: {e}"); + feed.set_error(e); + } + input + } + + async fn begin(&mut self) -> Result<()> { + match &self.kind { + SourceKind::Colour { colour, size } => { + self.feed.put(Arc::new(colour_frame(*colour, *size))); + } + SourceKind::Image { path } => { + self.feed.put(Arc::new(image_frame(path)?)); + } + SourceKind::Text { text, font, size_px, colour, backdrop, align, padding } => { + let frame = text_frame( + text, + font.as_deref(), + *size_px, + *colour, + *backdrop, + *align, + *padding, + )?; + self.feed.put(Arc::new(frame)); + } + 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?; + debug!(device = %capture.backend(), "studio camera"); + self.camera = Some(capture); + } + kind => { + let source = kind.capture_source().expect("every other kind captures a screen"); + let (backend, cursor) = match kind { + SourceKind::Screen { backend, cursor, .. } + | SourceKind::Window { backend, cursor, .. } => (backend.as_deref(), *cursor), + SourceKind::Portal { cursor, .. } => (Some("portal"), *cursor), + _ => (None, false), + }; + let options = CaptureOptions { + fps: self.fps.load(Ordering::Relaxed), + cursor, + ..CaptureOptions::default() + }; + let sink = Box::new(FeedSink::new(self.feed.clone(), self.fps.clone())); + match kind { + SourceKind::Pattern { size } => { + let mut screen = SyntheticScreen::new(size.0.max(2), size.1.max(2)); + screen.start_sink(&source, &options, sink).await?; + self.screen = Some(Box::new(screen)); + } + // Its own arm: the token it grants comes off the backend. + #[cfg(all(target_os = "linux", feature = "pipewire"))] + SourceKind::Portal { restore_token, .. } => { + use crate::capture::portal::PortalCapture; + let mut portal = PortalCapture::with_restore_token(restore_token.clone()); + portal.start_sink(&source, &options, sink).await?; + self.restore_token = portal.restore_token().map(str::to_owned); + self.screen = Some(Box::new(portal)); + } + _ => { + let mut screen = screen_backend(backend)?; + screen.start_sink(&source, &options, sink).await?; + self.screen = Some(screen); + } + } + } + } + Ok(()) + } + + pub fn kind(&self) -> &SourceKind { + &self.kind + } + + /// Frame-rate cap; the capture follows without restarting. + pub fn set_fps(&self, fps: u32) { + self.fps.store(fps.max(1), Ordering::Relaxed); + } + + /// The portal's token for this choice, if it granted one. + pub fn restore_token(&self) -> Option<&str> { + self.restore_token.as_deref() + } + + /// The camera device this input actually opened, for the UI. + pub fn camera_id(&self) -> Option<&str> { + self.camera.as_ref().map(camera::Capture::device) + } +} + +impl Drop for Input { + fn drop(&mut self) { + self.feed.close(); + if let Some(screen) = &mut self.screen { + screen.stop(); + } + } +} + +#[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 colour_source_is_flat() { + let frame = colour_frame(Colour::rgba(1, 2, 3, 4), (3, 2)); + assert_eq!((frame.width, frame.height), (3, 2)); + assert_eq!(frame.format(), PixelFormat::Rgba); + frame.validate().unwrap(); + assert_eq!(pixel(&frame, 2, 1), [1, 2, 3, 4]); + // A zero size is rounded up, not an empty frame. + assert_eq!((colour_frame(Colour::BLACK, (0, 0)).width, 1), (1, 1)); + } + + #[test] + fn text_is_rasterised_with_the_bundled_font() { + let frame = + text_frame("Hi", None, 48.0, Colour::WHITE, Colour::CLEAR, Align::Left, 4).unwrap(); + assert!(frame.width > 20 && frame.height > 20, "{}x{}", frame.width, frame.height); + frame.validate().unwrap(); + let FrameData::Rgba(p) = &frame.data else { panic!() }; + // Some glyph pixels are opaque white, the padding is transparent. + let opaque = p.data.chunks_exact(4).filter(|px| px[3] > 200).count(); + assert!(opaque > 20, "only {opaque} glyph pixels"); + assert!(p.data.chunks_exact(4).all(|px| px[3] == 0 || px[0] > 100)); + assert_eq!(pixel(&frame, 0, 0), [0, 0, 0, 0], "the padding is clear"); + + // Two lines are taller, and centring is symmetric. + let two = text_frame("Hi\nHi", None, 48.0, Colour::WHITE, Colour::CLEAR, Align::Center, 0) + .unwrap(); + assert!(two.height > frame.height); + // A backdrop fills everything. + let filled = + text_frame("x", None, 24.0, Colour::WHITE, Colour::rgb(9, 9, 9), Align::Right, 2) + .unwrap(); + assert_eq!(pixel(&filled, 0, 0), [9, 9, 9, 255]); + // An empty text still gives a usable frame. + text_frame("", None, 24.0, Colour::WHITE, Colour::CLEAR, Align::Left, 0) + .unwrap() + .validate() + .unwrap(); + // A font that is not one says so. + assert!( + text_frame( + "x", + Some(Path::new("/nonexistent.ttf")), + 24.0, + Colour::WHITE, + Colour::CLEAR, + Align::Left, + 0 + ) + .is_err() + ); + } + + #[test] + fn images_are_read_with_their_alpha() { + let dir = std::env::temp_dir().join(format!("voelin-studio-image-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("half.png"); + // 2x1 PNG: opaque red, half-transparent green. + let mut image = image::RgbaImage::new(2, 1); + image.put_pixel(0, 0, image::Rgba([255, 0, 0, 255])); + image.put_pixel(1, 0, image::Rgba([0, 255, 0, 128])); + image.save(&path).unwrap(); + let frame = image_frame(&path).unwrap(); + assert_eq!((frame.width, frame.height), (2, 1)); + assert_eq!(pixel(&frame, 0, 0), [255, 0, 0, 255]); + assert_eq!(pixel(&frame, 1, 0), [0, 255, 0, 128]); + assert!(image_frame(&dir.join("missing.png")).is_err()); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn unknown_backends_are_named() { + let Err(e) = screen_backend(Some("nonsense")) else { panic!("a made-up backend started") }; + assert!(e.to_string().contains("nonsense"), "{e}"); + // `auto` and an empty name are the default backend. + assert_eq!(screen_backend(Some("auto")).is_ok(), screen_backend(None).is_ok()); + } + + #[tokio::test] + async fn the_test_pattern_and_static_kinds_feed() { + let input = Input::start(SourceKind::Pattern { size: (64, 48) }, 30).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; + } + assert!(input.feed.delivered() > 0, "the test pattern delivered nothing"); + assert_eq!(input.feed.size(), (64, 48)); + assert_eq!(input.feed.error(), None); + let frame = input.feed.take().expect("a frame"); + 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; + 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; + assert!(broken.feed.error().is_some()); + assert!(broken.feed.take().is_none()); + } +} From 1f8fc4c268db930f7960e84c77b4718ea451ece5 Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 18:37:48 +0300 Subject: [PATCH 4/7] voelin-media: make a real camera negotiate Tried against a real V4L2 camera through PipeWire, three things stopped it. A camera offers fixed frame rates (often only 30), so a rate range capped at the wanted rate never intersects: the offer now takes any rate and the frame pacer brings it down. Camera nodes hand out buffer types the CPU cannot map unless asked otherwise, as screen capture already does. And PipeWire takes the first offer that fits, so a size range alone gave the camera's smallest size: the exact size is offered first, the range second. Co-Authored-By: Claude Opus 5 --- crates/voelin-media/src/studio/camera.rs | 132 ++++++++++++++++------- 1 file changed, 92 insertions(+), 40 deletions(-) diff --git a/crates/voelin-media/src/studio/camera.rs b/crates/voelin-media/src/studio/camera.rs index 29d59af..ba1c210 100644 --- a/crates/voelin-media/src/studio/camera.rs +++ b/crates/voelin-media/src/studio/camera.rs @@ -617,7 +617,7 @@ mod pipewire_camera { mainloop.quit(); } }) - .param_changed(|_, state, id, param| { + .param_changed(|stream, state, id, param| { let Some(param) = param else { return }; if id != pw::spa::param::ParamType::Format.as_raw() { return; @@ -635,6 +635,11 @@ mod pipewire_camera { let size = info.size(); debug!(format = ?info.format(), size.width, size.height, "camera format"); state.format = Some((info.format(), size.width, size.height)); + // Only buffers the CPU can read: a camera node may otherwise + // hand out DMA-BUFs, which this path cannot map. + if let Err(e) = use_memory_buffers(stream) { + warn!("camera buffers: {e}"); + } }) .process(process) .register() @@ -653,52 +658,70 @@ mod pipewire_camera { Ok((stream, listener)) } - /// One offer per pixel format: the wanted size (or any) and up to `fps`. + /// Ask for buffers in memory the CPU can read. + fn use_memory_buffers(stream: &pw::stream::Stream) -> std::result::Result<(), String> { + let types = (1 << pw::spa::sys::SPA_DATA_MemPtr) | (1 << pw::spa::sys::SPA_DATA_MemFd); + let buffers = serialize(Value::Object(Object { + type_: SpaTypes::ObjectParamBuffers.as_raw(), + id: pw::spa::param::ParamType::Buffers.as_raw(), + properties: vec![pw::spa::pod::Property { + key: pw::spa::sys::SPA_PARAM_BUFFERS_dataType, + flags: pw::spa::pod::PropertyFlags::empty(), + value: Value::Int(types), + }], + }))?; + stream.update_params(&mut [pod(&buffers)?]).map_err(|e| e.to_string()) + } + + /// The offers, best first: every pixel format at the wanted size, then + /// every pixel format at any size. A camera has a handful of fixed + /// sizes, and PipeWire takes the first offer that fits, so the exact + /// size has to come before the range or a range's smallest size wins. fn enum_formats( size: Option<(u32, u32)>, fps: u32, ) -> std::result::Result>, String> { + let (w, h) = size.unwrap_or((1280, 720)); + let exact = Rectangle { width: w.max(2), height: h.max(2) }; let mut formats = Vec::new(); - for format in FORMATS { - let mut properties = vec![ - property!(FormatProperties::MediaType, Id, MediaType::Video), - property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw), - property!(FormatProperties::VideoFormat, Id, format), - ]; - properties.push(match size { - Some((w, h)) => property!( - FormatProperties::VideoSize, + for fixed in [true, false] { + for format in FORMATS { + let mut properties = vec![ + property!(FormatProperties::MediaType, Id, MediaType::Video), + property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw), + property!(FormatProperties::VideoFormat, Id, format), + ]; + properties.push(if fixed { + property!(FormatProperties::VideoSize, Rectangle, exact) + } else { + property!( + FormatProperties::VideoSize, + Choice, + Range, + Rectangle, + exact, + Rectangle { width: 1, height: 1 }, + Rectangle { width: 16384, height: 16384 } + ) + }); + // Any rate the camera has, preferring the wanted one: a + // camera offers fixed rates (often only 30), and + // `FramePacer` brings whatever we get down to `fps`. + properties.push(property!( + FormatProperties::VideoFramerate, Choice, Range, - Rectangle, - Rectangle { width: w.max(2), height: h.max(2) }, - Rectangle { width: 1, height: 1 }, - Rectangle { width: 16384, height: 16384 } - ), - None => property!( - FormatProperties::VideoSize, - Choice, - Range, - Rectangle, - Rectangle { width: 1280, height: 720 }, - Rectangle { width: 1, height: 1 }, - Rectangle { width: 16384, height: 16384 } - ), - }); - properties.push(property!( - FormatProperties::VideoFramerate, - Choice, - Range, - Fraction, - Fraction { num: fps, denom: 1 }, - Fraction { num: 1, denom: 1 }, - Fraction { num: fps.max(1), denom: 1 } - )); - formats.push(serialize(Value::Object(Object { - type_: SpaTypes::ObjectParamFormat.as_raw(), - id: pw::spa::param::ParamType::EnumFormat.as_raw(), - properties, - }))?); + Fraction, + Fraction { num: fps, denom: 1 }, + Fraction { num: 0, denom: 1 }, + Fraction { num: 1000, denom: 1 } + )); + formats.push(serialize(Value::Object(Object { + type_: SpaTypes::ObjectParamFormat.as_raw(), + id: pw::spa::param::ParamType::EnumFormat.as_raw(), + properties, + }))?); + } } Ok(formats) } @@ -898,6 +921,35 @@ mod tests { assert_eq!(Pixel::Nv12.label(), "NV12"); } + /// The first real camera, through PipeWire. Needs a camera and a + /// PipeWire daemon, so it is not part of the normal run: + /// `cargo test -p voelin-media --lib real_camera -- --ignored --nocapture`. + #[tokio::test] + #[ignore = "needs a camera and PipeWire"] + async fn a_real_camera_delivers() { + let Some(camera) = list().into_iter().find(|c| c.backend != "synthetic") else { + 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 started = std::time::Instant::now(); + while feed.delivered() < 3 && started.elapsed() < Duration::from_secs(20) { + tokio::time::sleep(Duration::from_millis(50)).await; + } + println!( + "{} through {}: {} frames at {:?}, error {:?}", + camera.name, + capture.backend(), + feed.delivered(), + feed.size(), + feed.error() + ); + assert!(feed.delivered() >= 3, "only {} frames", feed.delivered()); + let frame = feed.take().expect("a frame"); + assert!(frame.width > 0 && frame.height > 0); + frame.validate().unwrap(); + } + #[tokio::test] async fn the_synthetic_camera_delivers() { let feed = Arc::new(Feed::new()); From 73aec78b35c373923996f6e7a997bcb6b4c2ca76 Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 23:32:23 +0300 Subject: [PATCH 5/7] voelin-media: record the studio and keep a replay buffer Recording and the replay buffer must work whether or not a stream is live, and neither may cost a second encode, so both are fed the packets the streamer's encoders already produce. That makes them output sinks over one small trait rather than pipelines of their own. The container is an own EBML writer: Matroska and WebM need so little of the format for this (a header, one Info, one Tracks, clusters of SimpleBlocks) that a dependency would be the larger cost. The segment size stays unknown and there are no cues, so a recording cut short by a crash still plays; only the duration is written back at the end, because a file of unknown length is a poor thing to hand a player. H.264 is stored the way Matroska wants it, length-prefixed with its parameter sets in CodecPrivate, which is why the header waits for the first keyframe. The replay buffer keeps whole keyframe groups so a clip always starts where a decoder can, and a window longer than memory allows spills its oldest packets to a temporary file it drops again once they age out -- the length is a setting with no maximum, so it cannot be bounded by what fits in RAM. RTMP is a seam that says what it is waiting for (the muxing side of the FFmpeg loader) instead of dropping a stream silently. tests/studio_record.rs runs real VP8 frames through both and reads the files back with ffprobe: codecs, size, duration, and every frame of a clip decoded. Co-Authored-By: Claude Opus 5 --- crates/voelin-media/src/studio/mod.rs | 3 + crates/voelin-media/src/studio/output/ebml.rs | 514 ++++++++++++++++++ crates/voelin-media/src/studio/output/mod.rs | 122 +++++ .../voelin-media/src/studio/output/record.rs | 305 +++++++++++ .../voelin-media/src/studio/output/replay.rs | 488 +++++++++++++++++ crates/voelin-media/src/studio/output/rtmp.rs | 71 +++ crates/voelin-media/tests/studio_record.rs | 200 +++++++ 7 files changed, 1703 insertions(+) create mode 100644 crates/voelin-media/src/studio/output/ebml.rs create mode 100644 crates/voelin-media/src/studio/output/mod.rs create mode 100644 crates/voelin-media/src/studio/output/record.rs create mode 100644 crates/voelin-media/src/studio/output/replay.rs create mode 100644 crates/voelin-media/src/studio/output/rtmp.rs create mode 100644 crates/voelin-media/tests/studio_record.rs diff --git a/crates/voelin-media/src/studio/mod.rs b/crates/voelin-media/src/studio/mod.rs index 80ca8da..19fd5de 100644 --- a/crates/voelin-media/src/studio/mod.rs +++ b/crates/voelin-media/src/studio/mod.rs @@ -8,8 +8,11 @@ //! - [`source`]: the live input behind each of a scene's sources (colour, //! text, image, screen, window, camera) //! - [`camera`]: listing and capturing cameras +//! - [`output`]: what the encoded packets go to besides the stream +//! (recording, the replay buffer, WHIP) pub mod camera; pub mod compose; +pub mod output; pub mod scene; pub mod source; diff --git a/crates/voelin-media/src/studio/output/ebml.rs b/crates/voelin-media/src/studio/output/ebml.rs new file mode 100644 index 0000000..46e4577 --- /dev/null +++ b/crates/voelin-media/src/studio/output/ebml.rs @@ -0,0 +1,514 @@ +//! A small Matroska / WebM writer, enough for what the studio records. +//! +//! Only what a recording needs is written: an EBML header, one `Info`, one +//! `Tracks` and a stream of `Cluster`s of `SimpleBlock`s. The `Segment` has +//! an unknown size and there are no `Cues`, so a recording that is cut short +//! (a crash, a full disk) still plays up to the last cluster; players seek by +//! scanning, which is what a live WebM stream needs anyway. The one thing +//! written back is the `Duration`, which is reserved in the header and filled +//! in on [`Writer::finish`] -- without it players show a file of unknown +//! length. +//! +//! Timestamps are milliseconds (`TimecodeScale` 1 ms); each cluster starts at +//! a keyframe, and blocks carry their offset from the cluster as a 16-bit +//! value, so a cluster never spans more than 32 seconds. +//! +//! H.264 has to be stored length-prefixed with its parameter sets in +//! `CodecPrivate` ([`avcc`]), which is why the header is written when the +//! first keyframe arrives rather than at the start. + +use std::io::{Seek, SeekFrom, Write}; + +use crate::codec::Codec; +use crate::{Error, Result}; + +/// `Segment`, `Cluster` and the rest, as their full EBML ids. +mod id { + pub const EBML: u32 = 0x1A45_DFA3; + pub const EBML_VERSION: u32 = 0x4286; + pub const EBML_READ_VERSION: u32 = 0x42F7; + pub const EBML_MAX_ID_LENGTH: u32 = 0x42F2; + pub const EBML_MAX_SIZE_LENGTH: u32 = 0x42F3; + pub const DOC_TYPE: u32 = 0x4282; + pub const DOC_TYPE_VERSION: u32 = 0x4287; + pub const DOC_TYPE_READ_VERSION: u32 = 0x4285; + pub const SEGMENT: u32 = 0x1853_8067; + pub const INFO: u32 = 0x1549_A966; + pub const TIMECODE_SCALE: u32 = 0x002A_D7B1; + pub const DURATION: u32 = 0x4489; + pub const MUXING_APP: u32 = 0x4D80; + pub const WRITING_APP: u32 = 0x5741; + pub const TRACKS: u32 = 0x1654_AE6B; + pub const TRACK_ENTRY: u32 = 0xAE; + pub const TRACK_NUMBER: u32 = 0xD7; + pub const TRACK_UID: u32 = 0x73C5; + pub const TRACK_TYPE: u32 = 0x83; + pub const FLAG_LACING: u32 = 0x9C; + pub const CODEC_ID: u32 = 0x86; + pub const CODEC_PRIVATE: u32 = 0x63A2; + pub const LANGUAGE: u32 = 0x0022_B59C; + pub const VIDEO: u32 = 0xE0; + pub const PIXEL_WIDTH: u32 = 0xB0; + pub const PIXEL_HEIGHT: u32 = 0xBA; + pub const AUDIO: u32 = 0xE1; + pub const SAMPLING_FREQUENCY: u32 = 0xB5; + pub const CHANNELS: u32 = 0x9F; + pub const CLUSTER: u32 = 0x1F43_B675; + pub const TIMECODE: u32 = 0xE7; + pub const SIMPLE_BLOCK: u32 = 0xA3; +} + +/// Append an element id (its bytes already carry their length). +fn put_id(out: &mut Vec, id: u32) { + let bytes = id.to_be_bytes(); + let first = bytes.iter().position(|&b| b != 0).unwrap_or(3); + out.extend_from_slice(&bytes[first..]); +} + +/// Append an EBML unsigned integer of `len` bytes (the length marker is the +/// top bit of the first byte). +fn put_size(out: &mut Vec, size: u64) { + // The shortest length whose value range holds `size` (all-ones is + // reserved for "unknown"). + let mut len = 1; + while len < 8 && size >= (1u64 << (7 * len)) - 1 { + len += 1; + } + let marked = size | 1u64 << (7 * len); + out.extend_from_slice(&marked.to_be_bytes()[8 - len..]); +} + +/// Append an element with `body` as its content. +fn element(out: &mut Vec, id: u32, body: &[u8]) { + put_id(out, id); + put_size(out, body.len() as u64); + out.extend_from_slice(body); +} + +/// An unsigned integer element, in as few bytes as it fits. +fn uint(out: &mut Vec, id: u32, value: u64) { + let bytes = value.to_be_bytes(); + let first = bytes.iter().position(|&b| b != 0).unwrap_or(7); + element(out, id, &bytes[first..]); +} + +/// An IEEE-754 double element (Matroska stores frequencies as floats). +fn float(out: &mut Vec, id: u32, value: f64) { + element(out, id, &value.to_be_bytes()); +} + +fn text(out: &mut Vec, id: u32, value: &str) { + element(out, id, value.as_bytes()); +} + +/// What one track holds. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum TrackKind { + Video { + codec: Codec, + width: u32, + height: u32, + }, + /// Opus at 48 kHz. + Opus { + channels: u16, + }, +} + +/// One track of the file. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Track { + pub kind: TrackKind, + /// `CodecPrivate`: the Opus head, or H.264's `avcC`. + pub private: Vec, +} + +impl TrackKind { + /// The Matroska codec id. + fn codec_id(&self) -> &'static str { + match self { + Self::Video { codec: Codec::Vp8, .. } => "V_VP8", + Self::Video { codec: Codec::Vp9, .. } => "V_VP9", + Self::Video { codec: Codec::Av1, .. } => "V_AV1", + Self::Video { codec: Codec::H264, .. } => "V_MPEG4/ISO/AVC", + Self::Video { codec: Codec::H265, .. } => "V_MPEGH/ISO/HEVC", + Self::Opus { .. } => "A_OPUS", + } + } + + /// Whether WebM allows this codec (Matroska allows everything). + fn in_webm(&self) -> bool { + matches!( + self, + Self::Video { codec: Codec::Vp8 | Codec::Vp9 | Codec::Av1, .. } | Self::Opus { .. } + ) + } +} + +/// The `CodecPrivate` of an Opus track: an `OpusHead` for 48 kHz. +pub fn opus_head(channels: u16) -> Vec { + let mut head = Vec::with_capacity(19); + head.extend_from_slice(b"OpusHead"); + head.push(1); // version + head.push(channels.clamp(1, 255) as u8); + head.extend_from_slice(&312u16.to_le_bytes()); // pre-skip + head.extend_from_slice(&48_000u32.to_le_bytes()); + head.extend_from_slice(&0i16.to_le_bytes()); // output gain + head.push(0); // channel mapping family + head +} + +/// The NAL units of an Annex B stream (start codes stripped). +pub fn annex_b_units(data: &[u8]) -> impl Iterator { + let mut rest = data; + std::iter::from_fn(move || { + // Skip to the first start code. + let start = (0..rest.len().saturating_sub(2)).find(|&i| rest[i..i + 3] == [0, 0, 1])?; + rest = &rest[start + 3..]; + let end = (0..rest.len().saturating_sub(2)) + .find(|&i| rest[i..i + 3] == [0, 0, 1]) + .map_or(rest.len(), |i| if i > 0 && rest[i - 1] == 0 { i - 1 } else { i }); + let (unit, tail) = rest.split_at(end); + rest = tail; + Some(unit) + }) + .filter(|unit| !unit.is_empty()) +} + +/// The `avcC` record of an Annex B keyframe: the parameter sets Matroska +/// needs before any picture. `None` if the frame carries none. +pub fn avcc(keyframe: &[u8]) -> Option> { + let mut sps: Option<&[u8]> = None; + let mut pps: Option<&[u8]> = None; + for unit in annex_b_units(keyframe) { + match unit[0] & 0x1F { + 7 => sps = sps.or(Some(unit)), + 8 => pps = pps.or(Some(unit)), + _ => {} + } + } + let (sps, pps) = (sps?, pps?); + if sps.len() < 4 { + return None; + } + let mut record = vec![1, sps[1], sps[2], sps[3], 0xFF, 0xE1]; + record.extend_from_slice(&(sps.len() as u16).to_be_bytes()); + record.extend_from_slice(sps); + record.push(1); + record.extend_from_slice(&(pps.len() as u16).to_be_bytes()); + record.extend_from_slice(pps); + Some(record) +} + +/// An Annex B frame as the length-prefixed units Matroska stores. +pub fn to_length_prefixed(data: &[u8], out: &mut Vec) { + out.clear(); + for unit in annex_b_units(data) { + // Access unit delimiters say nothing a container does not. + if unit[0] & 0x1F == 9 { + continue; + } + out.extend_from_slice(&(unit.len() as u32).to_be_bytes()); + out.extend_from_slice(unit); + } +} + +/// A cluster is closed at a keyframe, or once it reaches this many bytes or +/// this much time (a block's timestamp is 16 bits from the cluster's). +const CLUSTER_BYTES: usize = 4 << 20; +const CLUSTER_MS: u64 = 5_000; + +/// Writes Matroska or WebM; see the [module docs](self). +pub struct Writer { + out: W, + /// Where the `Duration` value sits, to fill in at the end. + duration_at: u64, + tracks: Vec, + /// Timestamp of the open cluster, and its blocks. + cluster: Option, + buffer: Vec, + /// The first timestamp seen, so the file starts at zero. + origin: Option, + last_ms: u64, + bytes: u64, + blocks: u64, +} + +impl Writer { + /// Start a file with these tracks (track 1 first). `webm` writes the + /// WebM doc type, which only allows VP8, VP9, AV1 and Opus. + pub fn new(mut out: W, webm: bool, tracks: Vec) -> Result { + if tracks.is_empty() { + return Err(Error::InvalidFrame("a recording needs at least one track".into())); + } + if webm && let Some(track) = tracks.iter().find(|t| !t.kind.in_webm()) { + return Err(Error::InvalidFrame(format!( + "{} cannot go into WebM; record Matroska instead", + track.kind.codec_id() + ))); + } + let mut head = Vec::new(); + let mut body = Vec::new(); + uint(&mut body, id::EBML_VERSION, 1); + uint(&mut body, id::EBML_READ_VERSION, 1); + uint(&mut body, id::EBML_MAX_ID_LENGTH, 4); + uint(&mut body, id::EBML_MAX_SIZE_LENGTH, 8); + text(&mut body, id::DOC_TYPE, if webm { "webm" } else { "matroska" }); + uint(&mut body, id::DOC_TYPE_VERSION, 4); + uint(&mut body, id::DOC_TYPE_READ_VERSION, 2); + element(&mut head, id::EBML, &body); + // A segment of unknown size: nothing is ever written back. + put_id(&mut head, id::SEGMENT); + head.extend_from_slice(&[0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]); + + body.clear(); + uint(&mut body, id::TIMECODE_SCALE, 1_000_000); + text(&mut body, id::MUXING_APP, "Voelin Studio"); + text(&mut body, id::WRITING_APP, "Voelin Studio"); + // Reserved: the length is only known when the recording stops. + put_id(&mut body, id::DURATION); + put_size(&mut body, 8); + let duration_in_info = body.len(); + body.extend_from_slice(&0f64.to_be_bytes()); + element(&mut head, id::INFO, &body); + let duration_at = (head.len() - body.len() + duration_in_info) as u64; + + body.clear(); + for (i, track) in tracks.iter().enumerate() { + let mut entry = Vec::new(); + let number = i as u64 + 1; + uint(&mut entry, id::TRACK_NUMBER, number); + uint(&mut entry, id::TRACK_UID, number); + uint( + &mut entry, + id::TRACK_TYPE, + match track.kind { + TrackKind::Video { .. } => 1, + TrackKind::Opus { .. } => 2, + }, + ); + uint(&mut entry, id::FLAG_LACING, 0); + text(&mut entry, id::LANGUAGE, "und"); + text(&mut entry, id::CODEC_ID, track.kind.codec_id()); + if !track.private.is_empty() { + element(&mut entry, id::CODEC_PRIVATE, &track.private); + } + match track.kind { + TrackKind::Video { width, height, .. } => { + let mut video = Vec::new(); + uint(&mut video, id::PIXEL_WIDTH, u64::from(width.max(1))); + uint(&mut video, id::PIXEL_HEIGHT, u64::from(height.max(1))); + element(&mut entry, id::VIDEO, &video); + } + TrackKind::Opus { channels } => { + let mut audio = Vec::new(); + float(&mut audio, id::SAMPLING_FREQUENCY, 48_000.0); + uint(&mut audio, id::CHANNELS, u64::from(channels.max(1))); + element(&mut entry, id::AUDIO, &audio); + } + } + element(&mut body, id::TRACK_ENTRY, &entry); + } + element(&mut head, id::TRACKS, &body); + out.write_all(&head)?; + Ok(Self { + out, + duration_at, + tracks, + cluster: None, + buffer: Vec::with_capacity(CLUSTER_BYTES / 4), + origin: None, + last_ms: 0, + bytes: head.len() as u64, + blocks: 0, + }) + } + + /// The tracks, in the order their numbers follow. + pub fn tracks(&self) -> &[Track] { + &self.tracks + } + + /// Bytes written so far. + pub fn bytes(&self) -> u64 { + self.bytes + self.buffer.len() as u64 + } + + pub fn blocks(&self) -> u64 { + self.blocks + } + + /// Length of the recording so far. + pub fn duration(&self) -> std::time::Duration { + std::time::Duration::from_millis(self.last_ms) + } + + /// Add one frame of `track` (0-based) at `ms` from the start of the + /// stream. The first frame decides where the file's clock starts. + pub fn write(&mut self, track: usize, ms: u64, keyframe: bool, data: &[u8]) -> Result<()> { + if track >= self.tracks.len() { + return Err(Error::InvalidFrame(format!("no track {track} in this recording"))); + } + if data.is_empty() { + return Ok(()); + } + let origin = *self.origin.get_or_insert(ms); + let ms = ms.saturating_sub(origin); + self.last_ms = self.last_ms.max(ms); + let start = match self.cluster { + Some(start) + if !(keyframe && track == 0) + && self.buffer.len() < CLUSTER_BYTES + && ms.saturating_sub(start) < CLUSTER_MS => + { + start + } + _ => { + self.flush_cluster()?; + self.cluster = Some(ms); + let mut head = Vec::new(); + uint(&mut head, id::TIMECODE, ms); + self.buffer.extend_from_slice(&head); + ms + } + }; + let offset = i64::try_from(ms).unwrap_or(i64::MAX) - i64::try_from(start).unwrap_or(0); + let offset = offset.clamp(i64::from(i16::MIN), i64::from(i16::MAX)) as i16; + put_id(&mut self.buffer, id::SIMPLE_BLOCK); + put_size(&mut self.buffer, data.len() as u64 + 4); + // Track number as a one-byte EBML varint (at most 127 tracks). + self.buffer.push(0x80 | (track as u8 + 1)); + self.buffer.extend_from_slice(&offset.to_be_bytes()); + self.buffer.push(if keyframe { 0x80 } else { 0 }); + self.buffer.extend_from_slice(data); + self.blocks += 1; + Ok(()) + } + + fn flush_cluster(&mut self) -> Result<()> { + if self.cluster.take().is_none() || self.buffer.is_empty() { + self.buffer.clear(); + return Ok(()); + } + let mut head = Vec::new(); + put_id(&mut head, id::CLUSTER); + put_size(&mut head, self.buffer.len() as u64); + self.out.write_all(&head)?; + self.out.write_all(&self.buffer)?; + self.bytes += (head.len() + self.buffer.len()) as u64; + self.buffer.clear(); + Ok(()) + } + + /// Write out the open cluster, fill in the duration and return the sink. + pub fn finish(mut self) -> Result { + self.flush_cluster()?; + let end = self.out.stream_position()?; + self.out.seek(SeekFrom::Start(self.duration_at))?; + self.out.write_all(&(self.last_ms as f64).to_be_bytes())?; + self.out.seek(SeekFrom::Start(end))?; + self.out.flush()?; + Ok(self.out) + } +} + +#[cfg(test)] +mod tests { + use std::io::Cursor; + + use super::*; + + fn varint(size: u64) -> Vec { + let mut out = Vec::new(); + put_size(&mut out, size); + out + } + + #[test] + fn sizes_take_the_shortest_form() { + assert_eq!(varint(0), vec![0x80]); + assert_eq!(varint(1), vec![0x81]); + // 127 is the reserved "unknown" value of a one-byte size. + assert_eq!(varint(126), vec![0xFE]); + assert_eq!(varint(127), vec![0x40, 0x7F]); + assert_eq!(varint(0x3FFE), vec![0x7F, 0xFE]); + assert_eq!(varint(0x3FFF), vec![0x20, 0x3F, 0xFF], "the two-byte all-ones is reserved"); + let mut out = Vec::new(); + uint(&mut out, 0x83, 1); + assert_eq!(out, vec![0x83, 0x81, 1]); + out.clear(); + uint(&mut out, 0x2AD7B1, 1_000_000); + assert_eq!(out, vec![0x2A, 0xD7, 0xB1, 0x83, 0x0F, 0x42, 0x40]); + } + + #[test] + fn annex_b_is_split_and_converted() { + // SPS, PPS and an IDR, with three- and four-byte start codes. + let sps = [0x67u8, 0x42, 0x00, 0x1E, 0xAA]; + let pps = [0x68u8, 0xCE, 0x3C, 0x80]; + let idr = [0x65u8, 0x88, 0x84]; + let mut stream = vec![0, 0, 0, 1]; + stream.extend_from_slice(&sps); + stream.extend_from_slice(&[0, 0, 1]); + stream.extend_from_slice(&pps); + stream.extend_from_slice(&[0, 0, 0, 1]); + stream.extend_from_slice(&idr); + let units: Vec<&[u8]> = annex_b_units(&stream).collect(); + assert_eq!(units, vec![&sps[..], &pps[..], &idr[..]]); + + let record = avcc(&stream).expect("parameter sets"); + assert_eq!(&record[..6], &[1, 0x42, 0x00, 0x1E, 0xFF, 0xE1]); + assert_eq!(&record[6..8], &(sps.len() as u16).to_be_bytes()); + assert_eq!(&record[8..8 + sps.len()], &sps); + assert_eq!(record[8 + sps.len()], 1, "one PPS"); + + let mut prefixed = Vec::new(); + to_length_prefixed(&stream, &mut prefixed); + assert_eq!(&prefixed[..4], &(sps.len() as u32).to_be_bytes()); + assert_eq!(prefixed.len(), 12 + sps.len() + pps.len() + idr.len()); + // A frame without parameter sets has no record. + assert!(avcc(&[0, 0, 1, 0x65, 1, 2]).is_none()); + } + + #[test] + fn a_file_has_a_header_tracks_and_clusters() { + let tracks = vec![ + Track { + kind: TrackKind::Video { codec: Codec::Vp8, width: 320, height: 240 }, + private: Vec::new(), + }, + Track { kind: TrackKind::Opus { channels: 2 }, private: opus_head(2) }, + ]; + let mut writer = Writer::new(Cursor::new(Vec::new()), true, tracks).unwrap(); + writer.write(0, 1000, true, &[1, 2, 3]).unwrap(); + writer.write(1, 1000, true, &[4, 5]).unwrap(); + writer.write(0, 1033, false, &[6]).unwrap(); + // A video keyframe opens a new cluster. + writer.write(0, 1066, true, &[7]).unwrap(); + assert_eq!(writer.blocks(), 4); + assert_eq!(writer.duration(), std::time::Duration::from_millis(66)); + let file = writer.finish().unwrap().into_inner(); + // EBML header, "webm", two clusters. + assert_eq!(&file[..4], &[0x1A, 0x45, 0xDF, 0xA3]); + assert!(file.windows(4).any(|w| w == b"webm")); + assert!(file.windows(5).any(|w| w == b"V_VP8")); + assert!(file.windows(6).any(|w| w == b"A_OPUS")); + assert!(file.windows(8).any(|w| w == b"OpusHead")); + let clusters = file.windows(4).filter(|w| *w == [0x1F, 0x43, 0xB6, 0x75]).count(); + assert_eq!(clusters, 2, "a keyframe starts a cluster"); + + // WebM refuses H.264; Matroska takes it. + let h264 = vec![Track { + kind: TrackKind::Video { codec: Codec::H264, width: 16, height: 16 }, + private: vec![1, 2, 3], + }]; + assert!(Writer::new(Cursor::new(Vec::new()), true, h264.clone()).is_err()); + let mut writer = Writer::new(Cursor::new(Vec::new()), false, h264).unwrap(); + writer.write(0, 0, true, &[9]).unwrap(); + assert!(writer.write(1, 0, true, &[9]).is_err(), "no track 1"); + let file = writer.finish().unwrap().into_inner(); + assert!(file.windows(8).any(|w| w == b"matroska")); + assert!(file.windows(15).any(|w| w == b"V_MPEG4/ISO/AVC")); + assert!(Writer::new(Cursor::new(Vec::new()), false, Vec::new()).is_err()); + } +} diff --git a/crates/voelin-media/src/studio/output/mod.rs b/crates/voelin-media/src/studio/output/mod.rs new file mode 100644 index 0000000..5373642 --- /dev/null +++ b/crates/voelin-media/src/studio/output/mod.rs @@ -0,0 +1,122 @@ +//! Where the studio's encoded packets go besides the stream. +//! +//! The streamer already encodes every layer; an [`OutputSink`] is fed the +//! same packets, so recording, the replay buffer and WHIP cost no second +//! encode and work whether or not the stream is live. +//! +//! - [`record`]: a file, WebM or Matroska ([`ebml`]) +//! - [`replay`]: the last few seconds in memory (spilling to disk), written +//! out as a clip without re-encoding +//! - `whip`: WHIP (WebRTC-HTTP ingestion) to a broadcast service +//! - [`rtmp`]: the seam for RTMP, which will go through the FFmpeg loader +//! +//! A sink never stalls the encoder: [`OutputSink::write`] returns an error +//! instead of blocking for long, and the studio drops the sink and reports +//! it. + +use crate::Result; +use crate::codec::Codec; + +pub mod ebml; +pub mod record; +pub mod replay; +pub mod rtmp; + +/// Which stream a packet belongs to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Track { + /// One simulcast layer's video. + Video { codec: Codec, layer: u32 }, + /// The studio's audio: Opus, 48 kHz. + Audio { channels: u16 }, +} + +impl Track { + pub fn is_video(&self) -> bool { + matches!(self, Self::Video { .. }) + } + + pub fn layer(&self) -> u32 { + match self { + Self::Video { layer, .. } => *layer, + Self::Audio { .. } => u32::MAX, + } + } +} + +/// One encoded packet on its way out of the studio. +#[derive(Clone, Copy, Debug)] +pub struct Packet<'a> { + pub track: Track, + /// Presentation time on the 90 kHz clock, as RTP carries it. + pub pts_90khz: u64, + /// Video: a frame that stands alone. Audio: always true. + pub keyframe: bool, + /// Size of the picture this packet belongs to (video only, 0 otherwise). + pub width: u32, + pub height: u32, + pub data: &'a [u8], +} + +impl Packet<'_> { + /// The packet's time in milliseconds. + pub fn ms(&self) -> u64 { + self.pts_90khz * 1000 / 90_000 + } +} + +/// Something fed with the studio's encoded packets. +/// +/// Every method runs on the encoder's thread, so none of them may block for +/// long; work that can wait belongs on the sink's own thread. +pub trait OutputSink: Send { + /// For logs, stats and the controller's events. + fn name(&self) -> &str; + + /// Whether this sink wants `track` at all. A recording takes one layer; + /// WHIP may take another. + fn wants(&self, track: Track) -> bool { + let _ = track; + true + } + + /// Whether the sink needs a keyframe now (it has just started, or it + /// dropped packets). + fn needs_keyframe(&mut self) -> bool { + false + } + + /// Take one packet. + fn write(&mut self, packet: &Packet<'_>) -> Result<()>; + + /// Close the file, tear the session down. Called once. + fn finish(&mut self) -> Result<()> { + Ok(()) + } + + /// Bytes written so far, for the stats. + fn bytes(&self) -> u64 { + 0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn packet_times_and_tracks() { + let packet = Packet { + track: Track::Video { codec: Codec::Vp8, layer: 2 }, + pts_90khz: 90_000 * 3 / 2, + keyframe: true, + width: 8, + height: 6, + data: &[1], + }; + assert_eq!(packet.ms(), 1500); + assert!(packet.track.is_video()); + assert_eq!(packet.track.layer(), 2); + assert!(!Track::Audio { channels: 2 }.is_video()); + } +} diff --git a/crates/voelin-media/src/studio/output/record.rs b/crates/voelin-media/src/studio/output/record.rs new file mode 100644 index 0000000..1237273 --- /dev/null +++ b/crates/voelin-media/src/studio/output/record.rs @@ -0,0 +1,305 @@ +//! Recording the studio to a file, without re-encoding. +//! +//! The recorder waits for the first keyframe of the layer it records (a file +//! that starts mid-picture is useless), then writes an [`ebml`] file and +//! every packet after it. The audio track is declared from the start, so +//! audio that arrives before the first keyframe is simply dropped rather +//! than shifting the file's clock. + +use std::fs::File; +use std::io::BufWriter; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use tracing::debug; + +use crate::codec::Codec; +use crate::studio::output::ebml::{self, Track as MkvTrack, TrackKind, Writer}; +use crate::studio::output::{OutputSink, Packet, Track}; +use crate::{Error, Result}; + +/// The container a recording is written in. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Format { + /// VP8, VP9, AV1 and Opus. + #[default] + WebM, + /// Also H.264 and H.265. + Matroska, +} + +impl Format { + /// The format a file name asks for: `.webm`, or `.mkv` / `.mka`. + pub fn of_path(path: &Path) -> Result { + match path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() { + Some("webm") => Ok(Self::WebM), + Some("mkv" | "mka" | "matroska") => Ok(Self::Matroska), + _ => Err(Error::InvalidFrame(format!( + "cannot tell the recording format of {}: use .webm or .mkv", + path.display() + ))), + } + } + + /// The format that can hold `codec`, preferring what `wanted` asks for. + pub fn for_codec(wanted: Self, codec: Codec) -> Self { + match codec { + Codec::Vp8 | Codec::Vp9 | Codec::Av1 => wanted, + // WebM has no place for these. + Codec::H264 | Codec::H265 => Self::Matroska, + } + } +} + +/// Writes the studio's packets to a file; see the [module docs](self). +pub struct Recorder { + path: PathBuf, + name: String, + format: Format, + /// The layer recorded; other layers are ignored. + layer: u32, + channels: u16, + writer: Option>>, + /// Set until the first keyframe opened the file. + waiting: bool, + /// H.264 frames are rewritten length-prefixed. + scratch: Vec, + video: Option, +} + +impl Recorder { + /// Start recording `layer` to `path`. The container comes from the file + /// name; a codec WebM cannot hold moves the recording to Matroska (and + /// the file keeps the name it was given). + pub fn start(path: impl Into, layer: u32, channels: u16) -> Result { + let path = path.into(); + let format = Format::of_path(&path)?; + if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { + std::fs::create_dir_all(parent)?; + } + // Fail now rather than at the first keyframe if the path is bad. + File::create(&path)?; + let name = path.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); + Ok(Self { + path, + name, + format, + layer, + channels: channels.clamp(1, 8), + writer: None, + waiting: true, + scratch: Vec::new(), + video: None, + }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// What the file actually holds (a codec WebM cannot hold moved it). + pub fn format(&self) -> Format { + self.format + } + + /// Whether the first keyframe arrived and the file is being written. + pub fn started(&self) -> bool { + self.writer.is_some() + } + + /// Length of the recording so far. + pub fn duration(&self) -> Duration { + self.writer.as_ref().map_or(Duration::ZERO, Writer::duration) + } + + /// Open the file on the first keyframe of the recorded layer. + fn open(&mut self, packet: &Packet<'_>, codec: Codec) -> Result<()> { + let private = if codec == Codec::H264 { + ebml::avcc(packet.data).ok_or_else(|| Error::Encoder { + codec, + message: "the keyframe carries no parameter sets to record".into(), + })? + } else { + Vec::new() + }; + self.format = Format::for_codec(self.format, codec); + let tracks = vec![ + MkvTrack { + kind: TrackKind::Video { + codec, + width: packet.width.max(2), + height: packet.height.max(2), + }, + private, + }, + MkvTrack { + kind: TrackKind::Opus { channels: self.channels }, + private: ebml::opus_head(self.channels), + }, + ]; + let file = BufWriter::new(File::create(&self.path)?); + let writer = Writer::new(file, self.format == Format::WebM, tracks)?; + debug!(path = %self.path.display(), %codec, format = ?self.format, "recording"); + self.writer = Some(writer); + self.waiting = false; + self.video = Some(codec); + Ok(()) + } +} + +impl OutputSink for Recorder { + fn name(&self) -> &str { + &self.name + } + + fn wants(&self, track: Track) -> bool { + match track { + Track::Video { layer, .. } => layer == self.layer, + Track::Audio { .. } => true, + } + } + + fn needs_keyframe(&mut self) -> bool { + self.waiting + } + + fn write(&mut self, packet: &Packet<'_>) -> Result<()> { + let (index, codec) = match packet.track { + Track::Video { codec, layer } if layer == self.layer => (0, Some(codec)), + Track::Video { .. } => return Ok(()), + Track::Audio { .. } => (1, None), + }; + if self.writer.is_none() { + // Nothing before the first keyframe of the recorded layer. + let Some(codec) = codec.filter(|_| packet.keyframe) else { return Ok(()) }; + self.open(packet, codec)?; + } + let Some(writer) = &mut self.writer else { return Ok(()) }; + // A codec change mid-recording would need a new file. + if let Some(codec) = codec + && self.video != Some(codec) + { + return Err(Error::Encoder { + codec, + message: "the codec changed while recording; stop and start again".into(), + }); + } + if codec == Some(Codec::H264) { + ebml::to_length_prefixed(packet.data, &mut self.scratch); + let scratch = std::mem::take(&mut self.scratch); + let result = writer.write(index, packet.ms(), packet.keyframe, &scratch); + self.scratch = scratch; + return result; + } + writer.write(index, packet.ms(), packet.keyframe, packet.data) + } + + fn finish(&mut self) -> Result<()> { + let Some(writer) = self.writer.take() else { return Ok(()) }; + let blocks = writer.blocks(); + let file = writer.finish()?; + drop(file); + debug!(path = %self.path.display(), blocks, "recording finished"); + Ok(()) + } + + fn bytes(&self) -> u64 { + self.writer.as_ref().map_or(0, Writer::bytes) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "voelin-studio-{name}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn video(layer: u32, ms: u64, keyframe: bool, data: &[u8]) -> Packet<'_> { + Packet { + track: Track::Video { codec: Codec::Vp8, layer }, + pts_90khz: ms * 90, + keyframe, + width: 320, + height: 240, + data, + } + } + + #[test] + fn formats_come_from_the_name_and_the_codec() { + assert_eq!(Format::of_path(Path::new("a.webm")).unwrap(), Format::WebM); + assert_eq!(Format::of_path(Path::new("a.MKV")).unwrap(), Format::Matroska); + assert!(Format::of_path(Path::new("a.mp4")).is_err()); + assert!(Format::of_path(Path::new("a")).is_err()); + assert_eq!(Format::for_codec(Format::WebM, Codec::Vp9), Format::WebM); + assert_eq!(Format::for_codec(Format::WebM, Codec::H264), Format::Matroska); + } + + #[test] + fn recording_starts_at_a_keyframe() { + let dir = dir("record"); + let path = dir.join("clip.webm"); + let mut recorder = Recorder::start(&path, 0, 2).unwrap(); + assert!(recorder.needs_keyframe()); + // Before the first keyframe nothing is written. + recorder.write(&video(0, 0, false, &[1, 2])).unwrap(); + recorder + .write(&Packet { track: Track::Audio { channels: 2 }, ..video(0, 0, true, &[9]) }) + .unwrap(); + assert!(!recorder.started()); + // Another layer is ignored even when it is a keyframe. + assert!(!recorder.wants(Track::Video { codec: Codec::Vp8, layer: 1 })); + recorder.write(&video(1, 10, true, &[3])).unwrap(); + assert!(!recorder.started()); + + recorder.write(&video(0, 100, true, &[1, 2, 3])).unwrap(); + assert!(recorder.started() && !recorder.needs_keyframe()); + for ms in (133..1000).step_by(33) { + recorder.write(&video(0, ms, false, &[4, 5])).unwrap(); + recorder + .write(&Packet { + track: Track::Audio { channels: 2 }, + pts_90khz: ms * 90, + keyframe: true, + width: 0, + height: 0, + data: &[7, 7, 7], + }) + .unwrap(); + } + // The file's clock starts at the first keyframe, not at zero. + assert!(recorder.duration() >= Duration::from_millis(800)); + recorder.finish().unwrap(); + let written = std::fs::read(&path).unwrap(); + assert!(written.len() > 100, "{} bytes", written.len()); + assert!(written.windows(4).any(|w| w == b"webm")); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn a_codec_change_stops_the_recording() { + let dir = dir("codec-change"); + let path = dir.join("clip.mkv"); + let mut recorder = Recorder::start(&path, 0, 2).unwrap(); + recorder.write(&video(0, 0, true, &[1])).unwrap(); + let mut other = video(0, 33, false, &[2]); + other.track = Track::Video { codec: Codec::Vp9, layer: 0 }; + assert!(recorder.write(&other).is_err()); + recorder.finish().unwrap(); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn an_unwritable_path_fails_at_once() { + assert!(Recorder::start("/nonexistent-root-dir/x/clip.webm", 0, 2).is_err()); + assert!(Recorder::start("clip.mp4", 0, 2).is_err()); + } +} diff --git a/crates/voelin-media/src/studio/output/replay.rs b/crates/voelin-media/src/studio/output/replay.rs new file mode 100644 index 0000000..d5c1a35 --- /dev/null +++ b/crates/voelin-media/src/studio/output/replay.rs @@ -0,0 +1,488 @@ +//! The replay buffer: the last few seconds, kept encoded. +//! +//! Every packet is kept until it falls out of the window +//! (`studio.replay_seconds`, no maximum), and the window always reaches back +//! to a keyframe, so [`ReplayBuffer::save_clip`] can write a playable file +//! without re-encoding anything. +//! +//! Long windows do not have to fit in memory: past +//! `studio.replay_memory_mb` the oldest packets are moved to a temporary +//! file and only their offsets stay in memory. The file is emptied again +//! whenever every packet in it has aged out, so a buffer that briefly +//! overflowed does not keep the disk space. + +use std::collections::VecDeque; +use std::fs::File; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use tracing::debug; + +use crate::codec::Codec; +use crate::studio::output::record::Recorder; +use crate::studio::output::{OutputSink, Packet, Track}; +use crate::{Error, Result}; + +/// Where a kept packet's bytes are. +enum Data { + Memory(Vec), + Spilled { offset: u64, len: u32 }, +} + +/// One kept packet. +struct Entry { + track: Track, + pts_90khz: u64, + keyframe: bool, + width: u32, + height: u32, + data: Data, +} + +/// The temporary file holding packets that no longer fit in memory. +struct Spill { + path: PathBuf, + file: File, + /// Bytes written so far (the next offset). + end: u64, + /// Packets still in it. + entries: usize, +} + +impl Drop for Spill { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.path); + } +} + +/// What the buffer holds right now. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ReplayStats { + pub packets: u64, + /// How far back the buffer reaches. + pub duration: Duration, + pub memory_bytes: u64, + pub spilled_bytes: u64, + /// Clips written. + pub clips: u64, +} + +/// The rolling buffer of encoded packets; see the [module docs](self). +pub struct ReplayBuffer { + length: Duration, + memory_limit: u64, + layer: u32, + channels: u16, + entries: VecDeque, + memory: u64, + spill: Option, + /// Where the temporary file goes. + spill_dir: PathBuf, + codec: Option, + clips: u64, + needs_keyframe: bool, +} + +impl ReplayBuffer { + /// A buffer holding `length` of `layer` (0 turns it off) with at most + /// `memory_mb` megabytes in memory before it spills to disk. + pub fn new(length: Duration, memory_mb: u64, layer: u32, channels: u16) -> Self { + Self { + length, + memory_limit: memory_mb.saturating_mul(1 << 20), + layer, + channels: channels.clamp(1, 8), + entries: VecDeque::new(), + memory: 0, + spill: None, + spill_dir: std::env::temp_dir(), + codec: None, + clips: 0, + needs_keyframe: true, + } + } + + /// Where the spill file goes (the system's temporary directory by + /// default). + pub fn with_spill_dir(mut self, dir: impl Into) -> Self { + self.spill_dir = dir.into(); + self + } + + /// How far back the buffer keeps packets; 0 turns it off and frees what + /// it holds. There is no maximum. + pub fn set_length(&mut self, length: Duration) { + self.length = length; + if length.is_zero() { + self.clear(); + } else { + self.trim(); + } + } + + pub fn length(&self) -> Duration { + self.length + } + + /// Megabytes kept in memory before older packets go to disk. + pub fn set_memory_mb(&mut self, memory_mb: u64) { + self.memory_limit = memory_mb.saturating_mul(1 << 20); + let _ = self.spill_over_limit(); + } + + pub fn is_on(&self) -> bool { + !self.length.is_zero() + } + + pub fn clear(&mut self) { + self.entries.clear(); + self.memory = 0; + self.spill = None; + self.needs_keyframe = true; + } + + pub fn stats(&self) -> ReplayStats { + let first = self.entries.front().map_or(0, |e| e.pts_90khz); + let last = self.entries.back().map_or(0, |e| e.pts_90khz); + ReplayStats { + packets: self.entries.len() as u64, + duration: Duration::from_micros(last.saturating_sub(first) * 1_000_000 / 90_000), + memory_bytes: self.memory, + spilled_bytes: self.spill.as_ref().map_or(0, |s| s.end), + clips: self.clips, + } + } + + /// Drop packets older than the window, never past the keyframe the + /// window starts in. + fn trim(&mut self) { + let Some(newest) = self.entries.back().map(|e| e.pts_90khz) else { return }; + let window = (self.length.as_micros() as u64).saturating_mul(90_000) / 1_000_000; + let cutoff = newest.saturating_sub(window); + // The last video keyframe at or before the cutoff: everything before + // it can go. + let keep = self + .entries + .iter() + .enumerate() + .rfind(|(_, e)| e.keyframe && e.track.is_video() && e.pts_90khz <= cutoff) + .map(|(i, _)| i); + let Some(keep) = keep else { return }; + let dropped: Vec = self.entries.drain(..keep).map(|e| e.data).collect(); + for data in &dropped { + self.release(data); + } + self.reset_spill(); + } + + /// Account for an entry that is gone. + fn release(&mut self, data: &Data) { + match data { + Data::Memory(bytes) => self.memory = self.memory.saturating_sub(bytes.len() as u64), + Data::Spilled { .. } => { + if let Some(spill) = &mut self.spill { + spill.entries -= 1; + } + } + } + } + + /// Throw the spill file away once nothing in it is kept any more. + fn reset_spill(&mut self) { + if self.spill.as_ref().is_some_and(|s| s.entries == 0) { + self.spill = None; + } + } + + /// Move the oldest in-memory packets to disk until memory is within the + /// limit. + fn spill_over_limit(&mut self) -> Result<()> { + if self.memory <= self.memory_limit { + return Ok(()); + } + for index in 0..self.entries.len() { + if self.memory <= self.memory_limit { + break; + } + let Data::Memory(bytes) = &self.entries[index].data else { continue }; + let len = bytes.len(); + let spill = match &mut self.spill { + Some(spill) => spill, + None => { + let path = self.spill_dir.join(format!( + "voelin-replay-{}-{:?}.bin", + std::process::id(), + std::thread::current().id() + )); + let file = File::options() + .create(true) + .truncate(true) + .read(true) + .write(true) + .open(&path)?; + debug!(path = %path.display(), "replay buffer spilling to disk"); + self.spill.insert(Spill { path, file, end: 0, entries: 0 }) + } + }; + let offset = spill.end; + // Take the bytes out before writing, so a failed write drops the + // packet rather than leaving it counted twice. + let Data::Memory(bytes) = std::mem::replace( + &mut self.entries[index].data, + Data::Spilled { offset, len: len as u32 }, + ) else { + unreachable!("checked above") + }; + spill.file.seek(SeekFrom::Start(offset))?; + spill.file.write_all(&bytes)?; + spill.end += len as u64; + spill.entries += 1; + self.memory -= len as u64; + } + Ok(()) + } + + /// The bytes of one kept packet, into `out`. + fn read(&mut self, index: usize, out: &mut Vec) -> Result<()> { + out.clear(); + match &self.entries[index].data { + Data::Memory(bytes) => out.extend_from_slice(bytes), + Data::Spilled { offset, len } => { + let (offset, len) = (*offset, *len as usize); + let Some(spill) = &mut self.spill else { + return Err(Error::InvalidFrame("the replay spill file is gone".into())); + }; + out.resize(len, 0); + spill.file.seek(SeekFrom::Start(offset))?; + spill.file.read_exact(out)?; + } + } + Ok(()) + } + + /// Write everything the buffer holds, from its first keyframe, to + /// `path`; the container comes from the file name. Returns how long the + /// clip is. + /// + /// The buffer keeps its packets, so several clips can be saved from one + /// window. + pub fn save_clip(&mut self, path: impl AsRef) -> Result { + let path = path.as_ref(); + if !self.is_on() { + return Err(Error::InvalidFrame( + "the replay buffer is off (studio.replay_seconds is 0)".into(), + )); + } + let start = + self.entries.iter().position(|e| e.keyframe && e.track.is_video()).ok_or_else( + || Error::InvalidFrame("the replay buffer holds no keyframe yet".into()), + )?; + let mut recorder = Recorder::start(path, self.layer, self.channels)?; + let mut bytes = Vec::new(); + for index in start..self.entries.len() { + self.read(index, &mut bytes)?; + let entry = &self.entries[index]; + recorder.write(&Packet { + track: entry.track, + pts_90khz: entry.pts_90khz, + keyframe: entry.keyframe, + width: entry.width, + height: entry.height, + data: &bytes, + })?; + } + let length = recorder.duration(); + recorder.finish()?; + self.clips += 1; + debug!(path = %path.display(), ?length, "replay clip saved"); + Ok(length) + } +} + +impl OutputSink for ReplayBuffer { + fn name(&self) -> &str { + "replay" + } + + fn wants(&self, track: Track) -> bool { + match track { + Track::Video { layer, .. } => layer == self.layer, + Track::Audio { .. } => true, + } + } + + fn needs_keyframe(&mut self) -> bool { + self.is_on() && self.needs_keyframe + } + + fn write(&mut self, packet: &Packet<'_>) -> Result<()> { + if !self.is_on() || !self.wants(packet.track) { + return Ok(()); + } + if let Track::Video { codec, .. } = packet.track { + // A codec change makes everything before it unplayable. + if self.codec.is_some_and(|c| c != codec) { + self.clear(); + } + self.codec = Some(codec); + if packet.keyframe { + self.needs_keyframe = false; + } + } + // Nothing before the first keyframe: a clip has to start at one. + if self.entries.is_empty() && !(packet.keyframe && packet.track.is_video()) { + return Ok(()); + } + self.entries.push_back(Entry { + track: packet.track, + pts_90khz: packet.pts_90khz, + keyframe: packet.keyframe, + width: packet.width, + height: packet.height, + data: Data::Memory(packet.data.to_vec()), + }); + self.memory += packet.data.len() as u64; + self.trim(); + self.spill_over_limit() + } + + fn bytes(&self) -> u64 { + self.memory + self.spill.as_ref().map_or(0, |s| s.end) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn video(ms: u64, keyframe: bool, len: usize) -> (Vec, u64, bool) { + (vec![(ms % 251) as u8; len], ms, keyframe) + } + + fn push(buffer: &mut ReplayBuffer, ms: u64, keyframe: bool, len: usize) { + let (data, ms, keyframe) = video(ms, keyframe, len); + buffer + .write(&Packet { + track: Track::Video { codec: Codec::Vp8, layer: 0 }, + pts_90khz: ms * 90, + keyframe, + width: 320, + height: 240, + data: &data, + }) + .unwrap(); + } + + fn dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "voelin-replay-{name}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn it_starts_at_a_keyframe_and_keeps_the_window() { + let mut buffer = ReplayBuffer::new(Duration::from_secs(2), 64, 0, 2); + assert!(buffer.is_on() && buffer.needs_keyframe()); + // Nothing before the first keyframe. + for ms in [0, 33, 66] { + push(&mut buffer, ms, false, 10); + } + assert_eq!(buffer.stats().packets, 0); + push(&mut buffer, 100, true, 100); + assert!(!buffer.needs_keyframe()); + // Five seconds at 30 fps with a keyframe every second. + for n in 1..150u64 { + let ms = 100 + n * 33; + push(&mut buffer, ms, n.is_multiple_of(30), 10); + } + let stats = buffer.stats(); + // The window reaches back to the keyframe that covers it: at most a + // keyframe interval more than the two seconds asked for. + assert!( + stats.duration >= Duration::from_secs(2) && stats.duration <= Duration::from_secs(3), + "{stats:?}" + ); + assert_eq!(stats.spilled_bytes, 0, "everything fits in memory"); + } + + #[test] + fn it_spills_to_disk_and_comes_back() { + let dir = dir("spill"); + // A tiny memory limit: almost everything goes to the file. + let mut buffer = ReplayBuffer::new(Duration::from_secs(4), 0, 0, 2).with_spill_dir(&dir); + push(&mut buffer, 0, true, 4096); + for n in 1..120u64 { + push(&mut buffer, n * 33, n.is_multiple_of(30), 4096); + } + let stats = buffer.stats(); + assert!(stats.spilled_bytes > 0, "{stats:?}"); + assert!(stats.memory_bytes < stats.spilled_bytes, "{stats:?}"); + assert_eq!(buffer.bytes(), stats.memory_bytes + stats.spilled_bytes); + + // The clip reads the spilled packets back. + let clip = dir.join("clip.webm"); + let length = buffer.save_clip(&clip).unwrap(); + assert!(length >= Duration::from_secs(3), "{length:?}"); + let written = std::fs::read(&clip).unwrap(); + assert!(written.len() > 4096 * 50, "{} bytes", written.len()); + assert!(written.windows(4).any(|w| w == b"webm")); + // The buffer still holds everything. + assert_eq!(buffer.stats().packets, stats.packets); + assert_eq!(buffer.stats().clips, 1); + + // Turning it off frees everything, including the file. + buffer.set_length(Duration::ZERO); + assert_eq!(buffer.stats(), ReplayStats { clips: 1, ..ReplayStats::default() }); + assert!(buffer.save_clip(&clip).is_err(), "a buffer that is off saves nothing"); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn a_window_that_shrinks_drops_the_old_packets() { + let mut buffer = ReplayBuffer::new(Duration::from_secs(10), 64, 0, 2); + push(&mut buffer, 0, true, 100); + for n in 1..300u64 { + push(&mut buffer, n * 33, n.is_multiple_of(30), 100); + } + let before = buffer.stats().packets; + buffer.set_length(Duration::from_secs(1)); + let after = buffer.stats().packets; + assert!(after < before / 4, "{before} -> {after}"); + assert!(buffer.stats().duration <= Duration::from_secs(2)); + // The first packet kept is still a keyframe. + assert!(buffer.entries.front().is_some_and(|e| e.keyframe)); + } + + #[test] + fn a_codec_change_starts_over() { + let mut buffer = ReplayBuffer::new(Duration::from_secs(5), 64, 0, 2); + push(&mut buffer, 0, true, 100); + push(&mut buffer, 33, false, 100); + assert_eq!(buffer.stats().packets, 2); + buffer + .write(&Packet { + track: Track::Video { codec: Codec::Vp9, layer: 0 }, + pts_90khz: 66 * 90, + keyframe: true, + width: 320, + height: 240, + data: &[1, 2, 3], + }) + .unwrap(); + assert_eq!(buffer.stats().packets, 1, "the VP8 packets were dropped"); + } + + #[test] + fn other_layers_are_left_alone() { + let buffer = ReplayBuffer::new(Duration::from_secs(1), 64, 1, 2); + assert!(!buffer.wants(Track::Video { codec: Codec::Vp8, layer: 0 })); + assert!(buffer.wants(Track::Video { codec: Codec::Vp8, layer: 1 })); + assert!(buffer.wants(Track::Audio { channels: 2 })); + assert_eq!(buffer.name(), "replay"); + } +} diff --git a/crates/voelin-media/src/studio/output/rtmp.rs b/crates/voelin-media/src/studio/output/rtmp.rs new file mode 100644 index 0000000..8c8e888 --- /dev/null +++ b/crates/voelin-media/src/studio/output/rtmp.rs @@ -0,0 +1,71 @@ +//! RTMP: the seam only. +//! +//! RTMP will go out through the FFmpeg libraries the crate already loads at +//! runtime ([`crate::ffmpeg`]): `libavformat` speaks `rtmp://` and +//! `rtmps://`, so the studio will hand it the same encoded packets it hands +//! every other output and never link or ship an RTMP stack of its own. +//! +//! What is missing is the muxer side of that loader (`avformat_alloc_output_ +//! context2`, `av_interleaved_write_frame` and the bitstream filters H.264 +//! and AAC need in FLV). Until then [`Rtmp::connect`] says so rather than +//! pretending, so a scene file or a `voelinctl` command that names an RTMP +//! output fails with a reason instead of silently dropping the stream. + +use crate::studio::output::{OutputSink, Packet, Track}; +use crate::{Error, Result}; + +/// An RTMP output. Not implemented yet; see the [module docs](self). +#[derive(Debug)] +pub struct Rtmp { + url: String, +} + +impl Rtmp { + /// Whether `url` is one this output would take. + pub fn handles(url: &str) -> bool { + url.starts_with("rtmp://") || url.starts_with("rtmps://") + } + + /// Always fails for now, with what is missing. + pub fn connect(url: &str, _key: Option<&str>) -> Result { + Err(Error::CodecUnavailable { + codec: crate::codec::Codec::H264, + reason: format!( + "RTMP ({url}) needs the muxing side of the FFmpeg loader, which is not \ + written yet; record to a file or use WHIP" + ), + }) + } + + pub fn url(&self) -> &str { + &self.url + } +} + +impl OutputSink for Rtmp { + fn name(&self) -> &str { + &self.url + } + + fn wants(&self, _track: Track) -> bool { + true + } + + fn write(&mut self, _packet: &Packet<'_>) -> Result<()> { + Err(Error::Capture { backend: "rtmp", message: "RTMP is not implemented".into() }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rtmp_urls_are_recognised_but_refused() { + assert!(Rtmp::handles("rtmp://live.example/app")); + assert!(Rtmp::handles("rtmps://live.example/app")); + assert!(!Rtmp::handles("https://example/whip")); + let e = Rtmp::connect("rtmp://live.example/app", Some("key")).unwrap_err().to_string(); + assert!(e.contains("FFmpeg"), "{e}"); + } +} diff --git a/crates/voelin-media/tests/studio_record.rs b/crates/voelin-media/tests/studio_record.rs new file mode 100644 index 0000000..8a071e7 --- /dev/null +++ b/crates/voelin-media/tests/studio_record.rs @@ -0,0 +1,200 @@ +//! The studio's recording and replay outputs against a real encoder and a +//! real demuxer: frames the test pattern produces are encoded, written to +//! WebM and read back with `ffprobe` (skipped where it is not installed). + +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::Duration; + +use voelin_media::codec::{Codec, Codecs, EncoderConfig}; +use voelin_media::frame::VideoFrame; +use voelin_media::studio::output::record::Recorder; +use voelin_media::studio::output::replay::ReplayBuffer; +use voelin_media::studio::output::{OutputSink, Packet, Track}; + +const WIDTH: u32 = 320; +const HEIGHT: u32 = 240; +const FPS: u64 = 30; + +fn dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("voelin-studio-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A moving picture, so the encoder has something to encode. +fn frame(n: u64) -> VideoFrame { + let mut frame = VideoFrame::black_i420(WIDTH, HEIGHT); + let voelin_media::frame::FrameData::I420 { y, .. } = &mut frame.data else { unreachable!() }; + let x0 = (n * 4 % u64::from(WIDTH - 40)) as usize; + for row in 40..120 { + y.data[row * y.stride + x0..][..40].fill(200); + } + frame.timestamp = Duration::from_micros(n * 1_000_000 / FPS); + frame +} + +/// Encode `frames` pictures with `codec` and hand every packet to `sink`. +/// Returns how many keyframes came out. +fn encode_into(codec: Codec, frames: u64, sink: &mut dyn OutputSink) -> u64 { + let codecs = Codecs::new(); + let mut encoder = codecs + .new_encoder( + codec, + EncoderConfig { fps: FPS as u32, bitrate_bps: 800_000, ..EncoderConfig::default() }, + ) + .expect("an encoder for the test codec"); + let mut keyframes = 0; + for n in 0..frames { + let picture = frame(n); + // A keyframe every second, as a stream would have. + let force = n.is_multiple_of(FPS); + encoder + .encode_with(&picture, force, &mut |chunk| { + keyframes += u64::from(chunk.keyframe); + sink.write(&Packet { + track: Track::Video { codec, layer: 0 }, + pts_90khz: chunk.pts_90khz, + keyframe: chunk.keyframe, + width: WIDTH, + height: HEIGHT, + data: chunk.data, + }) + .expect("the sink took the packet"); + }) + .expect("encoded"); + // 20 ms of "Opus" per two pictures, so the audio track is used too. + if n.is_multiple_of(2) { + sink.write(&Packet { + track: Track::Audio { channels: 2 }, + pts_90khz: n * 90_000 / FPS, + keyframe: true, + width: 0, + height: 0, + data: &[0xFC, 0xFF, 0xFE], + }) + .expect("the sink took the audio packet"); + } + } + keyframes +} + +/// `ffprobe -show_streams` of `path`, or `None` if ffprobe is not installed. +fn ffprobe(path: &Path) -> Option { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-show_entries", + "stream=codec_name,codec_type,width,height:format=format_name,duration", + "-of", + "default=noprint_wrappers=1", + ]) + .arg(path) + .output() + .ok()?; + assert!( + out.status.success(), + "ffprobe rejected {}: {}", + path.display(), + String::from_utf8_lossy(&out.stderr) + ); + assert!( + out.stderr.is_empty(), + "ffprobe complained about {}: {}", + path.display(), + String::from_utf8_lossy(&out.stderr) + ); + Some(String::from_utf8_lossy(&out.stdout).into_owned()) +} + +#[test] +fn a_recording_is_a_webm_ffprobe_reads() { + let codec = Codec::Vp8; + if Codecs::new().new_encoder(codec, EncoderConfig::default()).is_err() { + eprintln!("skipped: no VP8 encoder in this build"); + return; + } + let dir = dir("record"); + let path = dir.join("recording.webm"); + let mut recorder = Recorder::start(&path, 0, 2).unwrap(); + let keyframes = encode_into(codec, 90, &mut recorder); + assert!(keyframes >= 3, "only {keyframes} keyframes"); + assert!(recorder.duration() >= Duration::from_millis(2800), "{:?}", recorder.duration()); + assert!(recorder.bytes() > 1000); + recorder.finish().unwrap(); + + let Some(probe) = ffprobe(&path) else { + eprintln!("skipped the ffprobe check: ffprobe is not installed"); + std::fs::remove_dir_all(&dir).ok(); + return; + }; + println!("{probe}"); + assert!(probe.contains("codec_name=vp8"), "{probe}"); + assert!(probe.contains("codec_type=video"), "{probe}"); + assert!(probe.contains("codec_name=opus"), "{probe}"); + assert!(probe.contains(&format!("width={WIDTH}")), "{probe}"); + assert!(probe.contains(&format!("height={HEIGHT}")), "{probe}"); + assert!(probe.contains("format_name=matroska,webm"), "{probe}"); + let duration: f64 = probe + .lines() + .find_map(|l| l.strip_prefix("duration=")) + .and_then(|d| d.parse().ok()) + .unwrap_or(0.0); + assert!(duration > 2.5, "the file says it is {duration} s long"); + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn a_replay_clip_starts_at_a_keyframe_and_plays() { + let codec = Codec::Vp8; + if Codecs::new().new_encoder(codec, EncoderConfig::default()).is_err() { + eprintln!("skipped: no VP8 encoder in this build"); + return; + } + let dir = dir("replay"); + // Two seconds kept out of five encoded, spilling at once (0 MB memory). + let mut buffer = ReplayBuffer::new(Duration::from_secs(2), 0, 0, 2).with_spill_dir(&dir); + encode_into(codec, 150, &mut buffer); + let stats = buffer.stats(); + assert!(stats.spilled_bytes > 0, "{stats:?}"); + assert!(stats.duration >= Duration::from_secs(2), "{stats:?}"); + // Five seconds went in, at most three come out (two plus the keyframe + // interval the window starts in). + assert!(stats.duration <= Duration::from_secs(3), "{stats:?}"); + + let clip = dir.join("clip.webm"); + let length = buffer.save_clip(&clip).unwrap(); + assert!(length >= Duration::from_secs(2), "{length:?}"); + // Saving does not empty the buffer. + assert_eq!(buffer.stats().packets, stats.packets); + + let Some(probe) = ffprobe(&clip) else { + eprintln!("skipped the ffprobe check: ffprobe is not installed"); + std::fs::remove_dir_all(&dir).ok(); + return; + }; + println!("{probe}"); + assert!(probe.contains("codec_name=vp8"), "{probe}"); + // The clip decodes from its first frame: ffmpeg would report errors on + // stderr (which `ffprobe` asserts is empty) if it started mid-picture. + let frames = Command::new("ffprobe") + .args([ + "-v", + "error", + "-count_frames", + "-select_streams", + "v:0", + "-show_entries", + "stream=nb_read_frames", + "-of", + "default=noprint_wrappers=1:nokey=1", + ]) + .arg(&clip) + .output() + .expect("ffprobe ran"); + assert!(frames.stderr.is_empty(), "{}", String::from_utf8_lossy(&frames.stderr)); + let decoded: u64 = String::from_utf8_lossy(&frames.stdout).trim().parse().unwrap_or_default(); + assert!(decoded >= 60, "only {decoded} frames decoded from the clip"); + std::fs::remove_dir_all(&dir).ok(); +} From b625c38d7fc624097c9b3bf7a823b3587c635ecd Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 23:39:11 +0300 Subject: [PATCH 6/7] voelin-media: push the studio to a WHIP service Going live to a broadcast service is the one output that is not a file, and WHIP is the standard that makes it one HTTP request: post the offer, apply the answer, delete the location to stop. str0m already drives WebRTC here, so the session is a thread of its own fed through a bounded channel -- a slow or dead upload drops its own packets instead of stalling an encoder. The session offers only the codec the studio already encodes plus Opus, so the service can never negotiate its way into a second encode. Candidates are one host candidate on the interface that routes to the service, found by connecting a throwaway socket: enough for a service with a public address and for a server on this machine, not enough behind a NAT the service cannot reach back through. STUN and TURN are not here yet. tests/studio_whip.rs is a WHIP server built on str0m in the test: the offer is posted, ICE and DTLS come up, real VP8 and Opus packets arrive, a refusal is reported with the service's own words, and stopping deletes the resource. Co-Authored-By: Claude Opus 5 --- crates/voelin-core/Cargo.toml | 2 +- crates/voelin-media/Cargo.toml | 3 + crates/voelin-media/src/studio/output/mod.rs | 5 +- crates/voelin-media/src/studio/output/whip.rs | 480 ++++++++++++++++++ crates/voelin-media/tests/studio_whip.rs | 305 +++++++++++ 5 files changed, 793 insertions(+), 2 deletions(-) create mode 100644 crates/voelin-media/src/studio/output/whip.rs create mode 100644 crates/voelin-media/tests/studio_whip.rs diff --git a/crates/voelin-core/Cargo.toml b/crates/voelin-core/Cargo.toml index 8ef9568..b659708 100644 --- a/crates/voelin-core/Cargo.toml +++ b/crates/voelin-core/Cargo.toml @@ -35,7 +35,7 @@ toml = "1.1.6" tracing = "0.1" voelin-audio = { path = "../voelin-audio", default-features = false } voelin-gateway-proto = { path = "../voelin-gateway-proto", features = ["client"] } -voelin-media = { path = "../voelin-media", default-features = false, features = ["str0m"], optional = true } +voelin-media = { path = "../voelin-media", default-features = false, features = ["str0m", "whip"], optional = true } voelin-model = { path = "../voelin-model" } voelin-observer = { path = "../voelin-observer" } # Paths only (the cache directory). diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index a871b40..8f1c3ad 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -33,6 +33,9 @@ pipewire = ["dep:ashpd", "dep:pipewire", "dep:memmap2", "dep:rustix"] wlroots = ["dep:wayland-client", "dep:wayland-protocols", "dep:wayland-protocols-wlr", "dep:memmap2", "dep:rustix"] # Conversion between `Codec` and `str0m::format::Codec`. str0m = ["dep:str0m"] +# The studio's WHIP output: a WebRTC session (str0m) set up over HTTP. Needs +# str0m's crypto provider, the same one voelin-stream uses. +whip = ["str0m", "str0m/aws-lc-rs", "dep:reqwest"] v4l = [] [dependencies] diff --git a/crates/voelin-media/src/studio/output/mod.rs b/crates/voelin-media/src/studio/output/mod.rs index 5373642..f9f6472 100644 --- a/crates/voelin-media/src/studio/output/mod.rs +++ b/crates/voelin-media/src/studio/output/mod.rs @@ -7,7 +7,8 @@ //! - [`record`]: a file, WebM or Matroska ([`ebml`]) //! - [`replay`]: the last few seconds in memory (spilling to disk), written //! out as a clip without re-encoding -//! - `whip`: WHIP (WebRTC-HTTP ingestion) to a broadcast service +//! - [`whip`]: WHIP (WebRTC-HTTP ingestion) to a broadcast service (feature +//! `whip`) //! - [`rtmp`]: the seam for RTMP, which will go through the FFmpeg loader //! //! A sink never stalls the encoder: [`OutputSink::write`] returns an error @@ -21,6 +22,8 @@ pub mod ebml; pub mod record; pub mod replay; pub mod rtmp; +#[cfg(feature = "whip")] +pub mod whip; /// Which stream a packet belongs to. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] diff --git a/crates/voelin-media/src/studio/output/whip.rs b/crates/voelin-media/src/studio/output/whip.rs new file mode 100644 index 0000000..3277921 --- /dev/null +++ b/crates/voelin-media/src/studio/output/whip.rs @@ -0,0 +1,480 @@ +//! WHIP: pushing the studio to a broadcast service over WebRTC. +//! +//! WHIP (WebRTC-HTTP ingestion, RFC 9725) is one HTTP request: `POST` the SDP +//! offer, get the answer and a `Location` back, and `DELETE` that location to +//! stop. Everything after that is an ordinary WebRTC session, which `str0m` +//! drives on a thread of its own; the studio's encoded packets go in through +//! a channel, so an output that is slow or gone never holds up an encoder. +//! +//! The session offers exactly one video codec — the one the studio already +//! encodes — and Opus, both send-only, so the service never asks for a codec +//! that would mean a second encode. +//! +//! Candidates: one host candidate on the interface that reaches the service. +//! That is enough for a service with a public address, which is what WHIP is +//! for, and for a server on this machine (the tests). There is no STUN or +//! TURN here yet, so a studio behind a NAT that the service cannot reach back +//! through will not connect. + +use std::io::ErrorKind; +use std::net::{SocketAddr, UdpSocket}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::mpsc::{Receiver, SyncSender, TrySendError, sync_channel}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use str0m::change::SdpAnswer; +use str0m::media::{Direction, Frequency, MediaKind, MediaTime, Mid, Pt}; +use str0m::net::{Protocol, Receive}; +use str0m::{Candidate, Event, Input, Output, Rtc, RtcConfig}; +use tracing::{debug, trace, warn}; + +use crate::codec::Codec; +use crate::studio::output::{OutputSink, Packet, Track}; +use crate::{Error, Result}; + +/// Packets waiting for the session thread; a full queue drops the oldest, +/// because a stalled upload must not stall an encoder. +const QUEUE: usize = 256; + +fn error(message: impl Into) -> Error { + Error::Capture { backend: "whip", message: message.into() } +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// One packet on its way to the session thread. +struct Queued { + video: bool, + pts_90khz: u64, + data: Vec, +} + +/// What a WHIP output is doing. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct WhipStats { + pub connected: bool, + pub packets: u64, + pub bytes: u64, + /// Packets dropped because the session could not keep up. + pub dropped: u64, + pub error: Option, +} + +/// A WHIP session; stops and deletes its resource when dropped. +pub struct Whip { + name: String, + /// The `Location` the service gave us, to `DELETE` on stop. + resource: Option, + token: Option, + layer: u32, + codec: Codec, + queue: Option>, + thread: Option>, + stop: Arc, + shared: Arc, +} + +#[derive(Default)] +struct Shared { + connected: AtomicBool, + packets: AtomicU64, + bytes: AtomicU64, + dropped: AtomicU64, + error: Mutex>, +} + +impl Whip { + /// Whether `url` is one this output takes. + pub fn handles(url: &str) -> bool { + url.starts_with("http://") || url.starts_with("https://") + } + + /// Offer `codec` (the layer the studio encodes) and Opus to the WHIP + /// endpoint at `url`, with `token` as the bearer token if the service + /// wants one. + /// + /// Must run on a Tokio runtime: the HTTP request does. + pub async fn start( + url: &str, + token: Option<&str>, + codec: Codec, + layer: u32, + audio: bool, + ) -> Result { + let endpoint = reqwest::Url::parse(url).map_err(|e| error(format!("bad WHIP url: {e}")))?; + let host = endpoint + .socket_addrs(|| match endpoint.scheme() { + "https" => Some(443), + _ => Some(80), + }) + .map_err(|e| error(format!("cannot resolve {url}: {e}")))? + .into_iter() + .next() + .ok_or_else(|| error(format!("{url} resolves to nothing")))?; + + let (socket, local) = bind_towards(host)?; + let mut rtc = build_rtc(codec, audio); + let candidate = Candidate::host(local, Protocol::Udp) + .map_err(|e| error(format!("cannot offer {local}: {e}")))?; + rtc.add_local_candidate(candidate); + let mut api = rtc.sdp_api(); + let msid = Some("voelin-studio".to_owned()); + let video = api.add_media(MediaKind::Video, Direction::SendOnly, msid.clone(), None, None); + let audio_mid = + audio.then(|| api.add_media(MediaKind::Audio, Direction::SendOnly, msid, None, None)); + let (offer, pending) = api.apply().ok_or_else(|| error("nothing to offer"))?; + + let mut request = reqwest::Client::new() + .post(endpoint.clone()) + .header("content-type", "application/sdp") + .body(offer.to_sdp_string()); + if let Some(token) = token { + request = request.bearer_auth(token); + } + let response = + request.send().await.map_err(|e| error(format!("the WHIP request failed: {e}")))?; + let status = response.status(); + let resource = response + .headers() + .get(reqwest::header::LOCATION) + .and_then(|l| l.to_str().ok()) + .and_then(|l| endpoint.join(l).ok()) + .map(|u| u.to_string()); + let body = response.text().await.unwrap_or_default(); + if !status.is_success() { + return Err(error(format!("the service answered {status}: {}", body.trim()))); + } + let answer = SdpAnswer::from_sdp_string(&body) + .map_err(|e| error(format!("the service's answer is not SDP: {e}")))?; + rtc.sdp_api() + .accept_answer(pending, answer) + .map_err(|e| error(format!("the service's answer was refused: {e}")))?; + debug!(url, resource = resource.as_deref().unwrap_or("-"), %codec, "WHIP session"); + + let (queue, packets) = sync_channel(QUEUE); + let stop = Arc::new(AtomicBool::new(false)); + let shared = Arc::new(Shared::default()); + let session = Session { + rtc, + socket, + packets, + stop: stop.clone(), + shared: shared.clone(), + video, + audio: audio_mid, + writers: [None, None], + }; + let thread = std::thread::Builder::new() + .name("voelin-whip".into()) + .spawn(move || session.run()) + .map_err(|e| error(e.to_string()))?; + Ok(Self { + name: url.to_owned(), + resource, + token: token.map(str::to_owned), + layer, + codec, + queue: Some(queue), + thread: Some(thread), + stop, + shared, + }) + } + + /// The resource the service gave us, which stops the stream when deleted. + pub fn resource(&self) -> Option<&str> { + self.resource.as_deref() + } + + pub fn stats(&self) -> WhipStats { + WhipStats { + connected: self.shared.connected.load(Ordering::Relaxed), + packets: self.shared.packets.load(Ordering::Relaxed), + bytes: self.shared.bytes.load(Ordering::Relaxed), + dropped: self.shared.dropped.load(Ordering::Relaxed), + error: lock(&self.shared.error).clone(), + } + } + + /// Stop the session and tell the service, if there is a runtime to do it + /// on (the request needs one). + fn teardown(&mut self) { + self.stop.store(true, Ordering::Relaxed); + self.queue = None; + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + let Some(resource) = self.resource.take() else { return }; + let token = self.token.clone(); + let logged = resource.clone(); + let delete = async move { + let mut request = reqwest::Client::new().delete(&resource); + if let Some(token) = token { + request = request.bearer_auth(token); + } + match request.send().await { + Ok(response) => debug!(%resource, status = %response.status(), "WHIP deleted"), + Err(e) => debug!(%resource, "cannot delete the WHIP resource: {e}"), + } + }; + match tokio::runtime::Handle::try_current() { + Ok(handle) => { + let _ = logged; + handle.spawn(delete); + } + // No runtime: the service times the session out instead. + Err(_) => debug!(resource = %logged, "no runtime to delete the WHIP resource on"), + } + } +} + +impl Drop for Whip { + fn drop(&mut self) { + self.teardown(); + } +} + +impl OutputSink for Whip { + fn name(&self) -> &str { + &self.name + } + + fn wants(&self, track: Track) -> bool { + match track { + Track::Video { codec, layer } => layer == self.layer && codec == self.codec, + Track::Audio { .. } => true, + } + } + + fn needs_keyframe(&mut self) -> bool { + // Until the session is up there is nobody to send a keyframe to. + !self.shared.connected.load(Ordering::Relaxed) + } + + fn write(&mut self, packet: &Packet<'_>) -> Result<()> { + let Some(queue) = &self.queue else { return Ok(()) }; + if !self.wants(packet.track) { + return Ok(()); + } + let queued = Queued { + video: packet.track.is_video(), + pts_90khz: packet.pts_90khz, + data: packet.data.to_vec(), + }; + match queue.try_send(queued) { + Ok(()) => Ok(()), + Err(TrySendError::Full(_)) => { + self.shared.dropped.fetch_add(1, Ordering::Relaxed); + Ok(()) + } + Err(TrySendError::Disconnected(_)) => Err(error( + lock(&self.shared.error).clone().unwrap_or_else(|| "session ended".into()), + )), + } + } + + fn finish(&mut self) -> Result<()> { + self.teardown(); + Ok(()) + } + + fn bytes(&self) -> u64 { + self.shared.bytes.load(Ordering::Relaxed) + } +} + +/// An RTC that offers exactly `codec` and, if `audio`, Opus. +fn build_rtc(codec: Codec, audio: bool) -> Rtc { + let config = RtcConfig::new().clear_codecs().enable_opus(audio); + let config = match codec { + Codec::Vp8 => config.enable_vp8(true), + Codec::Vp9 => config.enable_vp9(true), + Codec::Av1 => config.enable_av1(true), + Codec::H264 => config.enable_h264(true), + Codec::H265 => config.enable_h265(true), + }; + config.build(Instant::now()) +} + +/// A UDP socket on the interface that reaches `peer`, and its address. +/// +/// Connecting a socket makes the kernel pick the route, so its local address +/// is the one the peer can send back to; the socket that is kept is then +/// bound to that address but left unconnected, so it takes the service's +/// candidates as well. +fn bind_towards(peer: SocketAddr) -> Result<(UdpSocket, SocketAddr)> { + let any = if peer.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" }; + let probe = UdpSocket::bind(any)?; + probe.connect(peer)?; + let local = probe.local_addr()?; + drop(probe); + let socket = UdpSocket::bind(SocketAddr::new(local.ip(), 0))?; + let local = socket.local_addr()?; + Ok((socket, local)) +} + +/// The session's thread: str0m's I/O and the studio's packets. +struct Session { + rtc: Rtc, + socket: UdpSocket, + packets: Receiver, + stop: Arc, + shared: Arc, + video: Mid, + audio: Option, + /// The payload type for video and for audio, once negotiated. + writers: [Option<(Mid, Pt)>; 2], +} + +impl Session { + fn run(mut self) { + let mut buf = vec![0u8; 2000]; + let local = match self.socket.local_addr() { + Ok(addr) => addr, + Err(e) => { + self.fail(format!("the WHIP socket has no address: {e}")); + return; + } + }; + while !self.stop.load(Ordering::Relaxed) { + if let Err(e) = self.rtc.handle_input(Input::Timeout(Instant::now())) { + self.fail(format!("WHIP session failed: {e}")); + return; + } + let deadline = loop { + if !self.rtc.is_alive() { + self.fail("the WHIP session closed"); + return; + } + match self.rtc.poll_output() { + Ok(Output::Timeout(t)) => break t, + Ok(Output::Transmit(t)) => { + if let Err(e) = self.socket.send_to(&t.contents, t.destination) { + trace!("WHIP send to {} failed: {e}", t.destination); + } + } + Ok(Output::Event(event)) => { + if let Event::IceConnectionStateChange(state) = event { + let up = state == str0m::IceConnectionState::Connected + || state == str0m::IceConnectionState::Completed; + self.shared.connected.store(up, Ordering::Relaxed); + debug!(?state, "WHIP ICE"); + } + } + Err(e) => { + self.fail(format!("WHIP session failed: {e}")); + return; + } + } + }; + // Feed what the studio queued, then wait for the socket until + // str0m's deadline (never longer than a tick, so the queue is + // drained promptly). + while let Ok(queued) = self.packets.try_recv() { + self.send(queued); + } + let now = Instant::now(); + let wait = deadline.saturating_duration_since(now).min(Duration::from_millis(5)); + if self.socket.set_read_timeout(Some(wait.max(Duration::from_millis(1)))).is_err() { + return; + } + match self.socket.recv_from(&mut buf) { + Ok((n, source)) => { + let Ok(contents) = buf[..n].try_into() else { continue }; + let input = Input::Receive( + Instant::now(), + Receive { proto: Protocol::Udp, source, destination: local, contents }, + ); + if self.rtc.accepts(&input) + && let Err(e) = self.rtc.handle_input(input) + { + self.fail(format!("WHIP session failed: {e}")); + return; + } + } + Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {} + Err(e) => trace!("WHIP receive failed: {e}"), + } + } + } + + /// One studio packet into the session. + fn send(&mut self, queued: Queued) { + let slot = usize::from(!queued.video); + let kind = if queued.video { MediaKind::Video } else { MediaKind::Audio }; + if self.writers[slot].is_none() { + let Some(mid) = (if queued.video { Some(self.video) } else { self.audio }) else { + return; + }; + let Some(writer) = self.rtc.writer(mid) else { return }; + let Some(pt) = + writer.payload_params().find(|p| p.spec().codec.kind() == kind).map(|p| p.pt()) + else { + return; + }; + self.writers[slot] = Some((mid, pt)); + } + let Some((mid, pt)) = self.writers[slot] else { return }; + // Video keeps the 90 kHz clock; Opus counts samples at 48 kHz. + let time = if queued.video { + MediaTime::from_90khz(queued.pts_90khz) + } else { + MediaTime::new(queued.pts_90khz * 48_000 / 90_000, Frequency::FORTY_EIGHT_KHZ) + }; + let bytes = queued.data.len() as u64; + let Some(writer) = self.rtc.writer(mid) else { return }; + match writer.write(pt, Instant::now(), time, queued.data) { + Ok(()) => { + self.shared.packets.fetch_add(1, Ordering::Relaxed); + self.shared.bytes.fetch_add(bytes, Ordering::Relaxed); + } + Err(e) => trace!(?kind, "WHIP packet not sent: {e}"), + } + } + + fn fail(&self, message: impl Into) { + let message = message.into(); + warn!("{message}"); + *lock(&self.shared.error) = Some(message); + self.shared.connected.store(false, Ordering::Relaxed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn urls_and_codecs() { + assert!(Whip::handles("https://live.example/whip")); + assert!(Whip::handles("http://127.0.0.1:8080/whip")); + assert!(!Whip::handles("rtmp://live.example/app")); + // Every codec the studio can encode has an str0m codec to offer. + for codec in [Codec::Vp8, Codec::Vp9, Codec::Av1, Codec::H264, Codec::H265] { + assert!(build_rtc(codec, true).is_alive(), "{codec}"); + } + } + + #[test] + fn a_socket_binds_towards_the_peer() { + let (socket, local) = bind_towards("127.0.0.1:9".parse().unwrap()).unwrap(); + assert!(local.ip().is_loopback(), "{local}"); + assert_ne!(local.port(), 0); + assert_eq!(socket.local_addr().unwrap(), local); + } + + #[tokio::test] + async fn an_endpoint_that_is_not_there_fails() { + // Port 1 on loopback: nothing listens. + let Err(e) = Whip::start("http://127.0.0.1:1/whip", Some("t"), Codec::Vp8, 0, true).await + else { + panic!("a session started against nothing"); + }; + assert!(e.to_string().contains("WHIP request failed"), "{e}"); + assert!(Whip::start("not a url", None, Codec::Vp8, 0, true).await.is_err()); + } +} diff --git a/crates/voelin-media/tests/studio_whip.rs b/crates/voelin-media/tests/studio_whip.rs new file mode 100644 index 0000000..743c537 --- /dev/null +++ b/crates/voelin-media/tests/studio_whip.rs @@ -0,0 +1,305 @@ +//! The studio's WHIP output against a WHIP server built on str0m here in the +//! test: the offer is posted, the answer applied, ICE and DTLS come up, real +//! VP8 frames arrive at the server, and stopping deletes the resource. +//! +//! The server is the smallest thing that is still WHIP: a TCP listener that +//! answers one `POST` with `201 Created`, a `Location` and the SDP answer, and +//! one `DELETE` with `200`. +#![cfg(feature = "whip")] + +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{SocketAddr, TcpListener, TcpStream, UdpSocket}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use str0m::change::SdpOffer; +use str0m::media::MediaKind; +use str0m::net::{Protocol, Receive}; +use str0m::{Candidate, Event, Input, Output, Rtc, RtcConfig}; +use voelin_media::codec::{Codec, Codecs, EncoderConfig}; +use voelin_media::frame::{FrameData, VideoFrame}; +use voelin_media::studio::output::whip::Whip; +use voelin_media::studio::output::{OutputSink, Packet, Track}; + +const WIDTH: u32 = 160; +const HEIGHT: u32 = 120; + +/// What the test server saw. +#[derive(Default)] +struct Seen { + video: AtomicU64, + audio: AtomicU64, + keyframes: AtomicU64, + connected: AtomicBool, + deleted: AtomicBool, + resource: Mutex>, +} + +/// Read one HTTP request: its start line and body. +fn read_request(stream: &mut TcpStream) -> Option<(String, String)> { + let mut reader = BufReader::new(stream.try_clone().ok()?); + let mut start = String::new(); + reader.read_line(&mut start).ok()?; + let mut length = 0usize; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).ok()? == 0 { + break; + } + if line.trim().is_empty() { + break; + } + if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") { + length = value.trim().parse().unwrap_or(0); + } + } + let mut body = vec![0u8; length]; + if length > 0 { + reader.read_exact(&mut body).ok()?; + } + Some((start.trim().to_owned(), String::from_utf8_lossy(&body).into_owned())) +} + +/// A WHIP server on a loopback port; returns its URL and what it saw. +fn spawn_server() -> (String, Arc) { + let listener = TcpListener::bind("127.0.0.1:0").expect("a port"); + let port = listener.local_addr().unwrap().port(); + let url = format!("http://127.0.0.1:{port}/whip"); + let seen = Arc::new(Seen::default()); + let shared = seen.clone(); + std::thread::Builder::new() + .name("whip-test-server".into()) + .spawn(move || { + for stream in listener.incoming().take(2) { + let Ok(mut stream) = stream else { continue }; + let Some((start, body)) = read_request(&mut stream) else { continue }; + if start.starts_with("DELETE") { + shared.deleted.store(true, Ordering::Relaxed); + let _ = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + continue; + } + assert!(start.starts_with("POST"), "{start}"); + let answer = match accept(&body, &shared) { + Ok(answer) => answer, + Err(e) => { + let _ = stream.write_all( + format!( + "HTTP/1.1 400 Bad Request\r\nContent-Length: {}\r\n\r\n{e}", + e.len() + ) + .as_bytes(), + ); + continue; + } + }; + *shared.resource.lock().unwrap() = Some(format!("/whip/{port}")); + let response = format!( + "HTTP/1.1 201 Created\r\nContent-Type: application/sdp\r\n\ + Location: /whip/{port}\r\nContent-Length: {}\r\n\r\n{answer}", + answer.len() + ); + let _ = stream.write_all(response.as_bytes()); + let _ = stream.flush(); + } + }) + .expect("the server thread"); + (url, seen) +} + +/// Accept an offer, start the session's thread and return the SDP answer. +fn accept(offer: &str, seen: &Arc) -> Result { + let offer = SdpOffer::from_sdp_string(offer).map_err(|e| e.to_string())?; + let mut rtc = + RtcConfig::new().clear_codecs().enable_opus(true).enable_vp8(true).build(Instant::now()); + let socket = UdpSocket::bind("127.0.0.1:0").map_err(|e| e.to_string())?; + let local = socket.local_addr().map_err(|e| e.to_string())?; + rtc.add_local_candidate(Candidate::host(local, Protocol::Udp).map_err(|e| e.to_string())?); + let answer = rtc.sdp_api().accept_offer(offer).map_err(|e| e.to_string())?; + let seen = seen.clone(); + std::thread::Builder::new() + .name("whip-test-session".into()) + .spawn(move || run_session(rtc, socket, local, seen)) + .map_err(|e| e.to_string())?; + Ok(answer.to_sdp_string()) +} + +fn run_session(mut rtc: Rtc, socket: UdpSocket, local: SocketAddr, seen: Arc) { + let mut buf = vec![0u8; 2000]; + let deadline = Instant::now() + Duration::from_secs(30); + while rtc.is_alive() && Instant::now() < deadline { + if rtc.handle_input(Input::Timeout(Instant::now())).is_err() { + return; + } + let timeout = loop { + match rtc.poll_output() { + Ok(Output::Timeout(t)) => break t, + Ok(Output::Transmit(t)) => { + let _ = socket.send_to(&t.contents, t.destination); + } + Ok(Output::Event(Event::IceConnectionStateChange(state))) => { + if matches!( + state, + str0m::IceConnectionState::Connected | str0m::IceConnectionState::Completed + ) { + seen.connected.store(true, Ordering::Relaxed); + } + } + Ok(Output::Event(Event::MediaData(data))) => { + if data.params.spec().codec.kind() == MediaKind::Video { + seen.video.fetch_add(1, Ordering::Relaxed); + seen.keyframes.fetch_add( + u64::from(data.contiguous && is_vp8_key(&data.data)), + Ordering::Relaxed, + ); + } else { + seen.audio.fetch_add(1, Ordering::Relaxed); + } + } + Ok(Output::Event(_)) => {} + Err(_) => return, + } + }; + let wait = timeout + .saturating_duration_since(Instant::now()) + .clamp(Duration::from_millis(1), Duration::from_millis(20)); + if socket.set_read_timeout(Some(wait)).is_err() { + return; + } + match socket.recv_from(&mut buf) { + Ok((n, source)) => { + let Ok(contents) = buf[..n].try_into() else { continue }; + let input = Input::Receive( + Instant::now(), + Receive { proto: Protocol::Udp, source, destination: local, contents }, + ); + if rtc.accepts(&input) { + let _ = rtc.handle_input(input); + } + } + Err(_) => continue, + } + } +} + +/// VP8's keyframe bit (the inverse of `P` in the payload header). +fn is_vp8_key(data: &[u8]) -> bool { + data.first().is_some_and(|b| b & 1 == 0) +} + +fn frame(n: u64) -> VideoFrame { + let mut frame = VideoFrame::black_i420(WIDTH, HEIGHT); + let FrameData::I420 { y, .. } = &mut frame.data else { unreachable!() }; + let x0 = (n * 3 % u64::from(WIDTH - 20)) as usize; + for row in 20..60 { + y.data[row * y.stride + x0..][..20].fill(220); + } + frame.timestamp = Duration::from_micros(n * 1_000_000 / 30); + frame +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_whip_session_carries_the_studios_packets() { + let codecs = Codecs::new(); + let Ok(mut encoder) = codecs.new_encoder( + Codec::Vp8, + EncoderConfig { fps: 30, bitrate_bps: 400_000, ..EncoderConfig::default() }, + ) else { + eprintln!("skipped: no VP8 encoder in this build"); + return; + }; + let (url, seen) = spawn_server(); + let mut whip = Whip::start(&url, Some("test-token"), Codec::Vp8, 0, true) + .await + .expect("the WHIP session started"); + assert!(whip.resource().is_some_and(|r| r.contains("/whip/")), "{:?}", whip.resource()); + // Until ICE is up there is nobody to send a keyframe to. + assert!(whip.needs_keyframe()); + assert!(whip.wants(Track::Video { codec: Codec::Vp8, layer: 0 })); + assert!(!whip.wants(Track::Video { codec: Codec::Vp9, layer: 0 })); + assert!(!whip.wants(Track::Video { codec: Codec::Vp8, layer: 1 })); + + // Push frames until the server has seen enough, or give up. + let started = Instant::now(); + let mut n = 0u64; + while started.elapsed() < Duration::from_secs(20) + && (seen.video.load(Ordering::Relaxed) < 20 || seen.audio.load(Ordering::Relaxed) < 10) + { + let picture = frame(n); + encoder + .encode_with(&picture, n == 0, &mut |chunk| { + whip.write(&Packet { + track: Track::Video { codec: Codec::Vp8, layer: 0 }, + pts_90khz: chunk.pts_90khz, + keyframe: chunk.keyframe, + width: WIDTH, + height: HEIGHT, + data: chunk.data, + }) + .expect("the session took the packet"); + }) + .expect("encoded"); + if n.is_multiple_of(2) { + // Opus silence: a valid frame the server can count. + whip.write(&Packet { + track: Track::Audio { channels: 2 }, + pts_90khz: n * 90_000 / 30, + keyframe: true, + width: 0, + height: 0, + data: &[0xF8, 0xFF, 0xFE], + }) + .expect("the session took the audio packet"); + } + n += 1; + tokio::time::sleep(Duration::from_millis(33)).await; + } + + let stats = whip.stats(); + assert!(seen.connected.load(Ordering::Relaxed), "ICE never came up: {stats:?}"); + assert!(stats.connected, "the output does not think it is connected: {stats:?}"); + assert!(whip.bytes() > 0, "{stats:?}"); + assert_eq!(stats.error, None); + let (video, audio) = (seen.video.load(Ordering::Relaxed), seen.audio.load(Ordering::Relaxed)); + assert!(video >= 20, "only {video} video frames reached the server ({stats:?})"); + assert!(audio >= 10, "only {audio} audio frames reached the server ({stats:?})"); + assert!(seen.keyframes.load(Ordering::Relaxed) >= 1, "no keyframe arrived"); + + // Stopping deletes the resource the service handed out. + whip.finish().unwrap(); + let waited = Instant::now(); + while !seen.deleted.load(Ordering::Relaxed) && waited.elapsed() < Duration::from_secs(5) { + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert!(seen.deleted.load(Ordering::Relaxed), "the resource was not deleted"); +} + +#[tokio::test] +async fn a_service_that_refuses_says_why() { + let (url, _seen) = spawn_server(); + // An offer the server cannot parse: it answers 400 with a reason. + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + std::thread::spawn(move || { + for stream in listener.incoming().take(1) { + let Ok(mut stream) = stream else { continue }; + let _ = read_request(&mut stream); + let body = "no capacity"; + let _ = stream.write_all( + format!( + "HTTP/1.1 503 Service Unavailable\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ) + .as_bytes(), + ); + } + }); + let Err(e) = + Whip::start(&format!("http://127.0.0.1:{port}/whip"), None, Codec::Vp8, 0, true).await + else { + panic!("a service that refuses 503 still started a session"); + }; + let e = e.to_string(); + assert!(e.contains("503") && e.contains("no capacity"), "{e}"); + let _ = url; +} From 312e5b2036735940b043cc5c3e1a695d92a899cb Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 23:51:03 +0300 Subject: [PATCH 7/7] voelin-media: give the studio a controller and background blur The UI needs one place to drive: a Command per thing a person can do, a stream of Events back, and a preview it reads at its own size and rate without ever holding up the composite. Studio is that place. It keeps the scene graph, starts and stops the inputs the live scene needs, runs one compose thread at the output rate, and tees encoded packets to the outputs. Making the composite a ScreenCapture backend (StudioCapture, SourceId::Studio) is what keeps the rest untouched: the streamer's conversion, simulcast, encoders and peers see an ordinary screen source, and recording and the replay buffer need no stream at all. A source is restarted only when its input really changed -- a portal token written back into the scene is not a reason to ask the user again -- so a drag or an opacity change costs nothing but a replan. Background replacement runs the segmenter on its own thread at a tenth of the video rate and takes its newest mask latest-wins, because a mask a few frames old is still right and segmentation costs far more than a frame. The blur is a three-pass box blur, separable and with a running sum, so its cost is flat in the radius; it is split into bands of rows on the worker pool over pooled buffers. The vertical pass restarts its sum per band, which costs a few reads and keeps the pass free of unsafe. What segments is a centred oval, not a person: no ONNX model is loaded in this build. The Segmenter trait is the seam for one, and segment.rs says so plainly rather than implying the blur follows a person. Co-Authored-By: Claude Opus 5 --- crates/voelin-media/src/capture/mod.rs | 2 + crates/voelin-media/src/studio/camera.rs | 43 +- crates/voelin-media/src/studio/mod.rs | 1256 +++++++++++++++++++++ crates/voelin-media/src/studio/segment.rs | 741 ++++++++++++ crates/voelin-media/src/studio/source.rs | 95 +- 5 files changed, 2111 insertions(+), 26 deletions(-) create mode 100644 crates/voelin-media/src/studio/segment.rs 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()); }