From a35d3b67844197981fa80427abeabb29464f398a Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 18:34:16 +0300 Subject: [PATCH] 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()); + } +}