diff --git a/Cargo.lock b/Cargo.lock index ea31997..f795171 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9204,6 +9204,8 @@ dependencies = [ "windows-capture", "x11rb", "yuv", + "zune-core", + "zune-jpeg", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index d9debe8..0b87ede 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -111,6 +111,9 @@ opt-level = 3 opt-level = 3 [profile.dev.package.wayland-client] opt-level = 3 +# MJPEG cameras: unoptimized, a 1440p picture takes most of a second. +[profile.dev.package.zune-jpeg] +opt-level = 3 [profile.dev] # Line tables (for backtraces) for workspace crates, no debug info for diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index 97d80ca..0d1a352 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -27,7 +27,9 @@ av1 = ["dep:dav1d"] x11 = ["dep:x11rb", "dep:memmap2", "dep:rustix"] # Wayland screen capture (ScreenCast portal + PipeWire, shared memory or # LINEAR DMA-BUFs) and PipeWire system audio (Linux). -pipewire = ["dep:ashpd", "dep:pipewire", "dep:memmap2", "dep:rustix"] +# MJPEG cameras are decoded with zune-jpeg (already in the tree through +# `image`). +pipewire = ["dep:ashpd", "dep:pipewire", "dep:memmap2", "dep:rustix", "dep:zune-core", "dep:zune-jpeg"] # Screen capture on wlroots compositors (Sway, Hyprland, river, ...) without # the portal: ext-image-copy-capture-v1 or wlr-screencopy-unstable-v1 (Linux). wlroots = ["dep:wayland-client", "dep:wayland-protocols", "dep:wayland-protocols-wlr", "dep:memmap2", "dep:rustix"] @@ -67,6 +69,8 @@ wayland-client = { version = "0.31.15", optional = true } wayland-protocols = { version = "0.32.13", features = ["client", "staging"], optional = true } wayland-protocols-wlr = { version = "0.3.12", features = ["client"], optional = true } x11rb = { version = "0.13.2", features = ["randr", "shm", "xfixes"], optional = true } +zune-core = { version = "0.5.3", default-features = false, optional = true } +zune-jpeg = { version = "0.5.15", optional = true } [target.'cfg(target_os = "android")'.dependencies] ndk = { version = "0.9.0", default-features = false, features = ["media", "api-level-29"] } diff --git a/crates/voelin-media/src/studio/camera.rs b/crates/voelin-media/src/studio/camera.rs index a4bad62..7c45bbd 100644 --- a/crates/voelin-media/src/studio/camera.rs +++ b/crates/voelin-media/src/studio/camera.rs @@ -12,8 +12,12 @@ //! 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. +//! camera allocates nothing per frame. MJPEG, which many USB cameras offer +//! for their large sizes only (1080p and up at full rate), is decoded with +//! `zune-jpeg` straight into pooled RGBA frames on a thread of its own: +//! the newest picture wins, so a decode that falls behind drops pictures +//! instead of holding up the camera. A raw format is preferred where it +//! gives the wanted size at the wanted rate (no decoding at all). //! //! [`SYNTHETIC`] is a camera that is always there: the test pattern. Tests //! and machines without a camera use it. @@ -53,7 +57,8 @@ pub enum Pixel { /// 3 bytes per pixel. Rgb24, Bgr24, - /// Motion JPEG; not offered (see the [module docs](self)). + /// Motion JPEG, decoded on a thread of its own (see the + /// [module docs](self)). Mjpeg, } @@ -180,8 +185,14 @@ impl Capture { } #[cfg(all(target_os = "linux", feature = "pipewire"))] { + let formats = v4l2::list() + .into_iter() + .find(|c| c.id == wanted) + .map(|c| c.formats) + .unwrap_or_default(); let stream = - pipewire_camera::Stream::start(&wanted, size, fps, feed, background).await?; + pipewire_camera::Stream::start(&wanted, size, fps, formats, feed, background) + .await?; tracing::debug!(device = %wanted, "camera through PipeWire"); Ok(Self { backend: "pipewire", device: wanted, screen: None, stream: Some(stream) }) } @@ -472,8 +483,8 @@ mod pipewire_camera { 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 pw::spa::pod::{ChoiceValue, Object, Property, PropertyFlags, Value, property}; + use pw::spa::utils::{Choice, ChoiceEnum, ChoiceFlags, Fraction, Rectangle, SpaTypes}; use tracing::{debug, warn}; use crate::capture::FramePacer; @@ -486,7 +497,7 @@ mod pipewire_camera { use crate::studio::source::deliver; use crate::{Error, Result}; - use super::BACKEND; + use super::{BACKEND, Format, Pixel, mjpeg}; /// The pixel formats we take, in order of preference; all of them the /// compositor can use after one conversion. @@ -509,22 +520,27 @@ mod pipewire_camera { impl Stream { /// Connect to `device` (a `/dev/video*` path) and feed `feed`. + /// `formats` are what V4L2 lists for it (empty if unknown). pub async fn start( device: &str, size: Option<(u32, u32)>, fps: u32, + formats: Vec, 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(), background.clone()); + let offers = enum_formats(size, fps, &formats) + .map_err(|e| Error::Capture { backend: BACKEND, message: e })?; + let direct = + connect(None, device, offers.clone(), 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, background)?; + let thread = connect(Some(fd), device, offers, fps, feed, background)?; Ok(Self { backend: "portal", _thread: thread }) } } @@ -564,7 +580,7 @@ mod pipewire_camera { fn connect( fd: Option, device: &str, - size: Option<(u32, u32)>, + offers: Vec>, fps: u32, feed: Arc, background: Background, @@ -574,7 +590,7 @@ mod pipewire_camera { // 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, background) + camera_stream(core, mainloop, None, &device, &offers, fps, feed, background) }) .map_err(|e| Error::Capture { backend: BACKEND, message: e }) } @@ -585,10 +601,20 @@ mod pipewire_camera { pool: FramePool, pacer: FramePacer, started: Instant, - format: Option<(VideoFormat, u32, u32)>, + format: Option, + /// The MJPEG decoder, once MJPEG was negotiated. + mjpeg: Option, mainloop: pw::main_loop::MainLoopWeak, } + /// What the camera and we agreed on. + #[derive(Clone, Copy, Debug)] + enum Negotiated { + Raw(VideoFormat, u32, u32), + /// The size comes with each picture. + Mjpeg, + } + type Parts = (pw::stream::StreamRc, pw::stream::StreamListener); #[allow(clippy::too_many_arguments)] @@ -597,7 +623,7 @@ mod pipewire_camera { mainloop: &pw::main_loop::MainLoopRc, target: Option, device: &str, - size: Option<(u32, u32)>, + offers: &[Vec], fps: u32, feed: Arc, background: Background, @@ -618,6 +644,7 @@ mod pipewire_camera { pacer: FramePacer::new(Some(fps)), started: Instant::now(), format: None, + mjpeg: None, mainloop: mainloop.downgrade(), }; let listener = stream @@ -640,19 +667,24 @@ mod pipewire_camera { 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; + match pw::spa::param::format_utils::parse_format(param) { + Ok((MediaType::Video, MediaSubtype::Raw)) => { + 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(Negotiated::Raw(info.format(), size.width, size.height)); + } + Ok((MediaType::Video, MediaSubtype::Mjpg)) => { + debug!("camera format MJPEG"); + state.format = Some(Negotiated::Mjpeg); + } + _ => return, } - 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) { @@ -662,9 +694,7 @@ mod pipewire_camera { .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::, _>>()?; + let mut pods = offers.iter().map(|f| pod(f)).collect::, _>>()?; stream .connect( pw::spa::utils::Direction::Input, @@ -691,62 +721,137 @@ mod pipewire_camera { 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. + type Sizes = Vec<(u32, u32)>; + + /// The PipeWire format of a camera pixel format: `None` for MJPEG. + fn spa_format(pixel: Pixel) -> Option { + Some(match pixel { + Pixel::Nv12 => VideoFormat::NV12, + Pixel::I420 => VideoFormat::I420, + Pixel::Yuyv => VideoFormat::YUY2, + Pixel::Uyvy => VideoFormat::UYVY, + Pixel::Bgrx => VideoFormat::BGRx, + Pixel::Rgbx => VideoFormat::RGBx, + Pixel::Bgr24 => VideoFormat::BGR, + Pixel::Rgb24 => VideoFormat::RGB, + Pixel::Mjpeg => return None, + }) + } + + /// The offers, best first, from what the driver lists for the camera + /// (`formats`, from V4L2): + /// + /// 1. the wanted size at least at the wanted rate, raw formats first + /// (nothing to decode); + /// 2. the wanted size at any rate, MJPEG first: cameras give their large + /// sizes at full rate only compressed (a raw 1080p over USB 2 is a few + /// frames a second); + /// 3. every format at the sizes it lists (the one nearest the wanted + /// size first), raw formats first. + /// + /// Every offer names sizes the driver lists for its format: PipeWire's + /// V4L2 source does not always check (it took a fixed size on trust, and + /// a range too, and then failed to set NV12 at 2560x1440 on a camera + /// that has that size only as MJPEG). PipeWire takes the first offer + /// that fits. Without a list (a camera only the portal can see), every + /// format at the wanted size, then at any. fn enum_formats( size: Option<(u32, u32)>, fps: u32, + formats: &[Format], ) -> 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 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, - 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, - }))?); + let exact = (w.max(2), h.max(2)); + let rect = |(width, height): (u32, u32)| Rectangle { width, height }; + // Our order of preference among raw formats, then MJPEG. + let rank = |f: Option| match f { + Some(f) => FORMATS.iter().position(|x| *x == f).unwrap_or(FORMATS.len()), + None => FORMATS.len() + 1, + }; + let mut known: Vec<(Option, Sizes)> = formats + .iter() + .map(|f| (spa_format(f.pixel), f.sizes.clone())) + .filter(|(_, sizes)| !sizes.is_empty()) + .collect(); + known.sort_by_key(|(f, _)| rank(*f)); + // Format (`None`: MJPEG), sizes (empty: any), lowest rate. + let mut offers: Vec<(Option, Sizes, u32)> = Vec::new(); + if known.is_empty() { + let all: Vec> = + FORMATS.iter().copied().map(Some).chain([None]).collect(); + offers.extend(all.iter().map(|f| (*f, vec![exact], fps))); + offers.extend(all.iter().map(|f| (*f, Vec::new(), 0))); + } else { + let at_size: Vec> = + known.iter().filter(|(_, sizes)| sizes.contains(&exact)).map(|(f, _)| *f).collect(); + offers.extend(at_size.iter().map(|f| (*f, vec![exact], fps))); + let mjpeg_first = at_size + .iter() + .filter(|f| f.is_none()) + .chain(at_size.iter().filter(|f| f.is_some())); + offers.extend(mjpeg_first.map(|f| (*f, vec![exact], 0))); + let area = |(w, h): (u32, u32)| i64::from(w) * i64::from(h); + for (format, sizes) in &known { + let mut sizes = sizes.clone(); + sizes.sort_by_key(|s| (area(*s) - area(exact)).abs()); + offers.push((*format, sizes, 0)); } } - Ok(formats) + let mut params = Vec::with_capacity(offers.len()); + for (format, sizes, min_fps) in offers { + let mut properties = vec![ + property!(FormatProperties::MediaType, Id, MediaType::Video), + property!( + FormatProperties::MediaSubtype, + Id, + if format.is_some() { MediaSubtype::Raw } else { MediaSubtype::Mjpg } + ), + ]; + if let Some(format) = format { + properties.push(property!(FormatProperties::VideoFormat, Id, format)); + } + // A list (also of one size): the source checks each against + // what the driver lists. No list: any size, the wanted first. + let choice = match sizes.split_first() { + Some((first, _)) => ChoiceEnum::Enum { + default: rect(*first), + alternatives: sizes.iter().copied().map(rect).collect(), + }, + None => ChoiceEnum::Range { + default: rect(exact), + min: Rectangle { width: 1, height: 1 }, + max: Rectangle { width: 16384, height: 16384 }, + }, + }; + properties.push(Property { + key: FormatProperties::VideoSize.as_raw(), + flags: PropertyFlags::empty(), + value: Value::Choice(ChoiceValue::Rectangle(Choice(ChoiceFlags::empty(), choice))), + }); + // The wanted rate or any above it (any at all in the later + // passes): a camera offers fixed rates (often only 30), and + // `FramePacer` brings whatever we get down to `fps`. + properties.push(property!( + FormatProperties::VideoFramerate, + Choice, + Range, + Fraction, + Fraction { num: fps, denom: 1 }, + Fraction { num: min_fps, denom: 1 }, + Fraction { num: 1000, denom: 1 } + )); + params.push(serialize(Value::Object(Object { + type_: SpaTypes::ObjectParamFormat.as_raw(), + id: pw::spa::param::ParamType::EnumFormat.as_raw(), + properties, + }))?); + } + Ok(params) } 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 Some(negotiated) = state.format else { return }; let timestamp = state.started.elapsed(); if state.feed.is_closed() { if let Some(mainloop) = state.mainloop.upgrade() { @@ -763,9 +868,34 @@ mod pipewire_camera { return; } let (offset, stride) = (chunk.offset() as usize, chunk.stride() as usize); + let size = chunk.size() 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) { + let result = match negotiated { + Negotiated::Raw(format, width, height) => { + take(state, format, width, height, stride, bytes, timestamp) + } + Negotiated::Mjpeg => { + let jpeg = &bytes[..size.min(bytes.len())]; + // The decoder starts with the first picture; the background + // filter moves to its thread. + let decoder = match &mut state.mjpeg { + Some(decoder) => decoder, + slot @ None => { + match mjpeg::Decoder::start(state.feed.clone(), state.filter.take()) { + Ok(decoder) => slot.insert(decoder), + Err(e) => { + state.feed.set_error(e.to_string()); + return; + } + } + } + }; + decoder.put(jpeg, timestamp); + Ok(()) + } + }; + if let Err(e) = result { warn!("cannot take a camera frame: {e}"); state.feed.set_error(e); } @@ -894,6 +1024,209 @@ mod pipewire_camera { } } +/// MJPEG pictures decoded on a thread of their own, the newest first: the +/// camera's thread copies each picture into a recycled buffer and hands it +/// over latest-wins, so a decode that falls behind skips pictures instead +/// of holding up the camera. Each picture is decoded by `zune-jpeg` +/// straight into a pooled RGBA frame (its SIMD paths do the colour +/// conversion on the way), and the background filter, if any, runs there +/// too. +/// +/// ponytail: one decoder thread. A camera-like 1440p picture (400 KB) takes +/// about 30 ms here, so 1440p at 30 fps is about all one thread does; +/// decode alternate pictures on a second thread (dropping any that come out +/// late) if larger MJPEG cameras need it. +#[cfg(all(target_os = "linux", feature = "pipewire"))] +mod mjpeg { + use std::sync::Arc; + use std::thread::JoinHandle; + use std::time::Duration; + + use tracing::debug; + use zune_core::bytestream::ZCursor; + use zune_core::colorspace::ColorSpace; + use zune_core::options::DecoderOptions; + use zune_jpeg::JpegDecoder; + + use crate::frame::{FrameData, PixelFormat}; + use crate::handoff::Handoff; + use crate::pool::FramePool; + use crate::studio::compose::Feed; + use crate::studio::segment::BackgroundFilter; + use crate::{Error, Result}; + + /// Pictures in a row that do not decode before the source reports an + /// error: a camera sends a broken picture now and then. + const FAILURES: u32 = 30; + /// How often the decoder checks whether to stop. + const POLL: Duration = Duration::from_millis(100); + + /// One compressed picture. + pub struct Jpeg { + pub data: Vec, + pub timestamp: Duration, + } + + /// The decoder thread; stops when dropped. + pub struct Decoder { + input: Arc>, + /// Buffers handed over, reused once the decoder let go of them. + spare: Vec>, + thread: Option>, + } + + impl Decoder { + /// Decode into `feed`, through `filter` if given. + pub fn start(feed: Arc, filter: Option) -> Result { + let input = Arc::new(Handoff::new()); + let thread = std::thread::Builder::new() + .name("voelin-mjpeg".into()) + .spawn({ + let input = input.clone(); + move || run(&input, &feed, filter) + }) + .map_err(Error::Io)?; + Ok(Self { input, spare: Vec::new(), thread: Some(thread) }) + } + + /// Hand over a picture (copied); one the decoder has not taken yet + /// is replaced. + pub fn put(&mut self, data: &[u8], timestamp: Duration) { + let free = self.spare.iter().position(|j| Arc::strong_count(j) == 1); + let slot = match free { + Some(i) => &mut self.spare[i], + None => { + self.spare.push(Arc::new(Jpeg { data: Vec::new(), timestamp })); + self.spare.last_mut().expect("just pushed") + } + }; + let jpeg = Arc::get_mut(slot).expect("nobody else holds a spare buffer"); + jpeg.data.clear(); + jpeg.data.extend_from_slice(data); + jpeg.timestamp = timestamp; + self.input.put(slot.clone()); + } + } + + impl Drop for Decoder { + fn drop(&mut self) { + self.input.close(); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } + } + + fn run(input: &Handoff, feed: &Feed, mut filter: Option) { + let mut pool = FramePool::new(); + let mut failures = 0; + while !input.is_closed() && !feed.is_closed() { + let Some(jpeg) = input.wait_timeout(POLL) else { continue }; + match decode(&jpeg, &mut pool, feed, filter.as_mut()) { + Ok(()) => failures = 0, + Err(e) => { + failures += 1; + debug!("an MJPEG picture did not decode: {e}"); + if failures == FAILURES { + feed.set_error(format!("the camera's MJPEG does not decode: {e}")); + } + } + } + } + } + + /// Decode `jpeg` into a pooled RGBA frame and hand it to `feed`. + pub fn decode( + jpeg: &Jpeg, + pool: &mut FramePool, + feed: &Feed, + filter: Option<&mut BackgroundFilter>, + ) -> Result<()> { + let convert = |e: zune_jpeg::errors::DecodeErrors| Error::Convert(format!("MJPEG: {e}")); + let options = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGBA); + let mut decoder = JpegDecoder::new_with_options(ZCursor::new(&jpeg.data[..]), options); + decoder.decode_headers().map_err(convert)?; + let (w, h) = decoder + .dimensions() + .ok_or_else(|| Error::Convert("MJPEG: a picture without a size".into()))?; + let (width, height) = ( + u32::try_from(w).map_err(|_| Error::Convert("MJPEG: too wide".into()))?, + u32::try_from(h).map_err(|_| Error::Convert("MJPEG: too high".into()))?, + ); + let slot = pool.get_format(width, height, PixelFormat::Rgba); + let target = Arc::get_mut(slot).expect("the pool hands out unshared frames"); + target.timestamp = jpeg.timestamp; + let FrameData::Rgba(plane) = &mut target.data else { + return Err(Error::InvalidFrame("the camera pool is not RGBA".into())); + }; + // Pooled planes are tightly packed: exactly what the decoder writes. + decoder.decode_into(&mut plane.data).map_err(convert)?; + if let Some(filter) = filter { + filter.apply(target)?; + } + feed.put(slot.clone()); + Ok(()) + } + + #[cfg(test)] + mod tests { + use super::*; + + /// A JPEG of `width` x `height`: red on the left half, blue on the + /// right (made with the `image` crate's encoder). + fn picture(width: u32, height: u32) -> Vec { + let image = image::RgbImage::from_fn(width, height, |x, _| { + if x < width / 2 { image::Rgb([220, 30, 30]) } else { image::Rgb([30, 30, 220]) } + }); + let mut out = std::io::Cursor::new(Vec::new()); + image.write_to(&mut out, image::ImageFormat::Jpeg).unwrap(); + out.into_inner() + } + + #[test] + fn pictures_decode_into_pooled_frames() { + let feed = Feed::new(); + let mut pool = FramePool::new(); + for n in 0..3u64 { + let jpeg = Jpeg { data: picture(64, 36), timestamp: Duration::from_millis(n * 33) }; + decode(&jpeg, &mut pool, &feed, None).unwrap(); + let frame = feed.take().expect("a frame"); + assert_eq!((frame.width, frame.height), (64, 36)); + assert_eq!(frame.timestamp, Duration::from_millis(n * 33)); + let FrameData::Rgba(plane) = &frame.data else { panic!("not RGBA") }; + let pixel = |x: usize| &plane.data[(18 * 64 + x) * 4..][..4]; + let near = |p: &[u8], c: [u8; 3]| p.iter().zip(c).all(|(a, b)| a.abs_diff(b) < 24); + assert!(near(pixel(8), [220, 30, 30]), "{:?}", pixel(8)); + assert!(near(pixel(56), [30, 30, 220]), "{:?}", pixel(56)); + assert_eq!(pixel(8)[3], 255); + } + // The same frame came back each time. + assert_eq!(pool.allocated(), 1); + let broken = Jpeg { data: vec![0xFF, 0xD8, 1, 2, 3], timestamp: Duration::ZERO }; + assert!(decode(&broken, &mut pool, &feed, None).is_err()); + } + + #[test] + fn the_thread_takes_the_newest_picture() { + let feed = Arc::new(Feed::new()); + let mut decoder = Decoder::start(feed.clone(), None).unwrap(); + let jpeg = picture(32, 18); + for n in 0..5u64 { + decoder.put(&jpeg, Duration::from_millis(n)); + } + let started = std::time::Instant::now(); + while feed.delivered() == 0 && started.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(5)); + } + assert!(feed.delivered() >= 1); + assert_eq!(feed.size(), (32, 18)); + // Buffers are reused, not one per picture. + assert!(decoder.spare.len() <= 3, "{}", decoder.spare.len()); + drop(decoder); + } + } +} + #[cfg(test)] mod tests { use std::time::Duration; @@ -972,6 +1305,50 @@ mod tests { frame.validate().unwrap(); } + /// The first real camera at its largest MJPEG size (decoded on our + /// thread), for three seconds: prints the size and the rate that + /// arrived. Needs a camera with MJPEG and PipeWire: + /// `cargo test -p voelin-media --lib largest_mjpeg -- --ignored --nocapture`. + #[tokio::test] + #[ignore = "needs a camera with MJPEG and PipeWire"] + async fn a_real_camera_delivers_its_largest_mjpeg_size() { + let Some((camera, (w, h), fps)) = list().into_iter().find_map(|c| { + let mjpeg = c.formats.iter().find(|f| f.pixel == Pixel::Mjpeg)?; + // `VOELIN_CAMERA_SIZE=1920x1080` picks another of its sizes. + let wanted = std::env::var("VOELIN_CAMERA_SIZE").ok().and_then(|s| { + let (w, h) = s.split_once('x')?; + Some((w.parse().ok()?, h.parse().ok()?)) + }); + let size = wanted.unwrap_or(*mjpeg.sizes.first()?); + Some((c.clone(), size, mjpeg.max_fps.max(1))) + }) else { + panic!("no camera with MJPEG on this machine"); + }; + let feed = Arc::new(Feed::new()); + let capture = Capture::start(&camera.id, Some((w, h)), fps, feed.clone(), Background::Keep) + .await + .unwrap(); + let started = std::time::Instant::now(); + while feed.delivered() < 2 && started.elapsed() < Duration::from_secs(20) { + tokio::time::sleep(Duration::from_millis(20)).await; + } + let (first, at) = (feed.delivered(), std::time::Instant::now()); + tokio::time::sleep(Duration::from_secs(3)).await; + let rate = (feed.delivered() - first) as f64 / at.elapsed().as_secs_f64(); + println!( + "{} through {}: asked {w}x{h} at {fps} fps, got {:?} at {rate:.1} fps, error {:?}", + camera.name, + capture.backend(), + feed.size(), + feed.error() + ); + drop(capture); + assert_eq!(feed.size(), (w, h)); + // Not `fps`: in low light a camera's auto exposure lowers its rate + // (the Fifine K420 gives 10 fps at 1440p then, also to `v4l2-ctl`). + assert!(rate >= 1.0, "{rate:.1} fps"); + } + #[tokio::test] async fn the_synthetic_camera_delivers() { let feed = Arc::new(Feed::new()); diff --git a/docs/studio.md b/docs/studio.md index b74ef81..8446e10 100644 --- a/docs/studio.md +++ b/docs/studio.md @@ -104,9 +104,22 @@ only three read-only enumeration ioctls are written by hand. Capture goes through PipeWire, which owns the devices on a current desktop: from the user's daemon, or in a sandbox from the XDG Camera portal (`ashpd`), both on the same PipeWire thread as screen capture. Raw formats (YUYV, UYVY, NV12, -I420, packed RGB) are converted into pooled frames; MJPEG is not offered, so -a camera that has both gives its raw format (often at a lower size at the -highest rates). `camera::SYNTHETIC` is always listed: the test pattern, for +I420, packed RGB) are converted into pooled frames. MJPEG, which many USB +cameras offer for their large sizes only (the Fifine K420: 2560x1440 and +1920x1080 only as MJPEG, raw up to 1280x720), is decoded by `zune-jpeg` +straight into pooled RGBA frames on a thread of its own, latest-wins, so a +decode that falls behind drops pictures rather than holding up the camera; +the background filter then runs on that thread. A camera-like 1440p +picture takes about 30 ms to decode (one core), so 1440p at 30 fps is about +what that thread does. + +What PipeWire is offered comes from the V4L2 list, best first: the wanted +size at the wanted rate in a raw format (nothing to decode), then the +wanted size at any rate with MJPEG first, then every format at the sizes it +lists, nearest the wanted size first. Every offer names sizes the driver +lists for that format: PipeWire's V4L2 source takes a size on trust and +then fails to set it (NV12 at 2560x1440 on a camera that has that size only +as MJPEG). `camera::SYNTHETIC` is always listed: the test pattern, for tests and machines without a camera. `voelinctl studio cameras` prints the list. @@ -314,6 +327,8 @@ two threads) takes about 3 ms at its own rate (15 fps by default). | Settings ⇄ studio in both directions | `voelin-core` `studio::tests` | tested | | WHIP: offer, answer, ICE, DTLS, VP8 and Opus arriving, refusal with the service's reason, `DELETE` on stop | `tests/studio_whip.rs` against a WHIP server built on str0m in the test (`--features whip`) | tested; no public WHIP service tried | | Real camera through the user's PipeWire (Fifine K420, 1280x720) | `camera::tests::a_real_camera_delivers` (`--ignored`) | tested on one webcam | +| MJPEG: decoded into pooled frames (one frame reused), broken pictures refused, the decoder thread takes the newest | `camera::mjpeg::tests` | tested | +| MJPEG from a real camera (Fifine K420) at 2560x1440, 1920x1080 and 1280x720 | `camera::tests::a_real_camera_delivers_its_largest_mjpeg_size` (`--ignored`, `VOELIN_CAMERA_SIZE` picks a size) | tested on one webcam: each size arrived at 10 fps, which is what the camera sent in that light (`v4l2-ctl` measured the same 10 fps) | | Camera through the XDG Camera portal (sandboxes) | – | compiles only | | Screen, window and portal sources | the existing capture backends ([media.md](media.md#capture)) | as tested there; not run inside the studio here | | Background blur, image and colour backdrops on the oval mask | `segment::tests` | tested; **no person segmentation model** (see above) |