diff --git a/Cargo.lock b/Cargo.lock index 4776873..a7e39ff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9167,6 +9167,7 @@ version = "0.1.0" dependencies = [ "ashpd", "bzip2", + "criterion", "dav1d", "libvpx-native-sys", "memmap2", @@ -9181,6 +9182,9 @@ dependencies = [ "tokio", "tracing", "wasapi", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", "windows-capture", "x11rb", "yuv", diff --git a/Cargo.toml b/Cargo.toml index 12f7812..d9debe8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -82,6 +82,36 @@ opt-level = 3 [profile.dev.package.sonora-simd] opt-level = 3 +# Screen sharing runs pixel conversion, codecs and RTP for every frame; +# unoptimized, a debug build manages a few frames per second at 1080p. +# (libvpx, dav1d and libopus are system / release-built C libraries.) +[profile.dev.package.yuv] +opt-level = 3 +[profile.dev.package.voelin-media] +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] +opt-level = 3 +[profile.dev.package.opus2] +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 + [profile.dev] # Line tables (for backtraces) for workspace crates, no debug info for # dependencies: keeps target/ several times smaller. Override locally for @@ -95,3 +125,12 @@ debug = false # third_party/dimpl/VOELIN-PATCH.md. [patch.crates-io] dimpl = { path = "third_party/dimpl" } + +[profile.release] +# One optimisation unit across all crates: inlining across crate boundaries +# matters for the per-pixel and per-packet code of streams. Panics still +# unwind (no `panic = "abort"`): a panic in one tokio task or media thread +# must not end the app (tasks and threads report it, mutexes recover from +# poisoning), and the crash reporter's hook runs either way. +lto = "fat" +codegen-units = 1 diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index f3712b8..3d338d1 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -3,11 +3,15 @@ //! //! - [`Streamer`] captures a screen or window (and optionally system audio), //! encodes the video with the codec our offer carries ([`stream_codec`], -//! VP8 by default) at the bitrate of the stream setup, and the audio with -//! Opus (48 kHz stereo, 20 ms). It hands the frames to a [`MediaSink`]: -//! the [`StreamSink`] of a live stream, or an [`EncodedSource`] for code -//! that drives `voelin_stream::Streams` itself. Keyframe requests of viewers -//! are honoured. +//! VP8 by default) in one or more simulcast layers ([`LayerSpec`]), and +//! the audio with Opus (48 kHz stereo, 20 ms). Capture, conversion and +//! each layer's encoder run on threads of their own, connected by +//! latest-wins handoffs. It hands the frames to a [`MediaSink`]: the +//! [`StreamSink`] of a live stream, or an [`EncodedSource`] for code that +//! drives `voelin_stream::Streams` itself. Keyframe requests of viewers +//! are honoured per layer, and each layer's encoder follows the bitrate +//! the sink allows. [`Streamer::reconfigure`] changes frame rate, +//! bitrate, codec and layers while streaming. //! - [`VideoPipeline`] decodes the video of a watched stream on its own //! thread and hands every picture to a callback. After lost frames or //! decoder errors it skips to the next keyframe and asks for one. @@ -23,7 +27,7 @@ //! MediaCodec on Android). use std::collections::VecDeque; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use std::sync::mpsc as std_mpsc; use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; use std::thread::JoinHandle; @@ -32,12 +36,17 @@ use std::time::{Duration, Instant}; use tracing::{debug, warn}; use voelin_audio::{VoiceCodec, VoiceEncoder}; pub use voelin_media; +pub use voelin_media::capture::synthetic::Pattern; use voelin_media::capture::synthetic::{SineSource, SyntheticScreen}; use voelin_media::capture::{ - self, AudioCapture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, + self, AudioCapture, CaptureOptions, CaptureSource, FramePacer, FrameSink, ScreenCapture, + SourceId, }; +use voelin_media::handoff::Handoff; +use voelin_media::scale::Pyramid; use voelin_media::{ - AudioBuffer, Codec, Codecs, ContentHint, EncoderConfig, FrameReceiver, VideoEncoder, VideoFrame, + AudioBuffer, Codec, Codecs, ContentHint, EncoderConfig, FrameReceiver, FrameRef, VideoEncoder, + VideoFrame, }; use voelin_stream::{ EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind, @@ -64,6 +73,8 @@ pub enum MediaError { Media(#[from] voelin_media::Error), #[error("Opus: {0}")] Opus(#[from] voelin_audio::Error), + #[error("stream settings: {0}")] + Config(String), } fn lock(m: &Mutex) -> MutexGuard<'_, T> { @@ -178,11 +189,48 @@ impl MediaSink for StreamSink { /// Which backend captures monitors and windows. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub enum CaptureBackend { - /// The one for this desktop session (`capture::default_screen_capture`). + /// The one for this desktop session (`capture::default_screen_capture`: + /// the ScreenCast portal on Wayland, X11, Windows Graphics Capture). #[default] Auto, + /// The xdg-desktop-portal ScreenCast dialog (Wayland; also X11 desktops + /// that run the portal). Monitor and window ids are ignored: the + /// dialog picks. + Portal, /// X11, also under Wayland through XWayland (Linux). X11, + /// wlroots compositors (Sway, Hyprland, river, ...) directly, without + /// the portal: `ext-image-copy-capture-v1`, or `wlr-screencopy-unstable-v1` + /// where that is missing (Linux). + Wlroots, +} + +impl CaptureBackend { + /// Names as in settings: `auto`, `portal`, `x11`, `wlroots`. + pub fn name(&self) -> &'static str { + match self { + CaptureBackend::Auto => "auto", + CaptureBackend::Portal => "portal", + CaptureBackend::X11 => "x11", + CaptureBackend::Wlroots => "wlroots", + } + } +} + +impl std::str::FromStr for CaptureBackend { + type Err = MediaError; + + fn from_str(s: &str) -> Result { + match s.trim().to_ascii_lowercase().as_str() { + "auto" | "" => Ok(CaptureBackend::Auto), + "portal" => Ok(CaptureBackend::Portal), + "x11" => Ok(CaptureBackend::X11), + "wlroots" | "wlr" => Ok(CaptureBackend::Wlroots), + other => Err(MediaError::Config(format!( + "unknown capture backend {other:?}: auto, portal, x11 or wlroots" + ))), + } + } } /// What and how to stream. @@ -191,9 +239,11 @@ pub struct StreamerConfig { pub source: SourceId, /// For monitors and windows. pub backend: CaptureBackend, - /// Frames per second (1 to 60). + /// Frame-rate cap (at least 1). The capture delivers what the source + /// gives up to this rate; layers may cap lower. pub fps: u32, - /// Video bitrate in kbit/s, as in `StreamSetup::bitrate`. + /// Video bitrate in kbit/s, as in `StreamSetup::bitrate`, for the single + /// layer when `layers` is empty. pub bitrate_kbps: u32, /// The codec of our offer, see [`stream_codec`]. pub codec: Codec, @@ -202,10 +252,13 @@ pub struct StreamerConfig { pub cursor: bool, /// Size of the test pattern ([`SourceId::Synthetic`]). pub synthetic_size: (u32, u32), + /// What the test pattern shows. + pub synthetic_pattern: Pattern, /// Portal restore token from an earlier share: the desktop may skip its /// dialog. The new one is [`Streamer::restore_token`]. pub restore_token: Option, - /// Simulcast layers to encode. Empty: one layer at `bitrate_kbps`. + /// Simulcast layers to encode, each with its own encoder. Empty: one + /// layer (id 0) at the source's size and `bitrate_kbps`. pub layers: Vec, } @@ -220,16 +273,69 @@ impl Default for StreamerConfig { audio: true, cursor: true, synthetic_size: (1280, 720), + synthetic_pattern: Pattern::Simple, restore_token: None, layers: Vec::new(), } } } -/// What a [`Streamer`] has done so far. +impl StreamerConfig { + /// The layers that are encoded: [`layers`](Self::layers), or one layer at + /// `bitrate_kbps`. + pub fn effective_layers(&self) -> Vec { + if self.layers.is_empty() { + vec![LayerSpec::single(u64::from(self.bitrate_kbps.max(1)) * 1000)] + } else { + self.layers.clone() + } + } +} + +/// Changes for a running [`Streamer`] ([`Streamer::reconfigure`]); `None` +/// keeps the current value. #[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct StreamerStats { +pub struct StreamerConfigUpdate { + /// Frame-rate cap; the capture follows without restarting. + pub fps: Option, + /// Bitrate of the single layer (used while `layers` is empty). + pub bitrate_kbps: Option, + /// Another codec: new encoders, starting with keyframes. + pub codec: Option, + /// Another set of layers (`Some(vec![])`: back to a single layer). Layers + /// keep their encoder when their id stays; new ids get new encoders. + pub layers: Option>, +} + +/// One simulcast layer in [`StreamerStats`]. Rates are over the last second. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct LayerStats { + pub id: LayerId, + /// Size of the last encoded frame. + pub width: u32, + pub height: u32, /// Frames handed to the sink. + pub frames: u64, + pub keyframes: u64, + /// Frames the layer's encoder was too busy for (replaced by a newer one + /// before it got to them). + pub dropped: u64, + pub fps: f64, + pub kbps: f64, + /// Mean time to encode a frame. + pub encode_time: Duration, + /// The encoder's target bitrate (bit/s): the layer's, or what the + /// viewers' bandwidth estimates allow. + pub bitrate: u64, + pub threads: u32, + /// The encoder's speed setting (libvpx `cpu-used`), if it has one. + pub speed: Option, +} + +/// What a [`Streamer`] has done so far. Rates are over the last second. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StreamerStats { + /// Frames handed to the sink (all layers). pub video_frames: u64, pub audio_frames: u64, /// Size of the last captured frame. @@ -240,6 +346,120 @@ pub struct StreamerStats { pub capture_ended: bool, /// The last encoder error. pub error: Option, + /// Frames the capture delivered (within the frame-rate cap). + pub captured_frames: u64, + pub capture_fps: f64, + /// Mean time to convert a captured frame to I420 and scale it for every + /// layer that is due. + pub convert_time: Duration, + /// Frames dropped between conversion and the encoders, all layers. + pub dropped_frames: u64, + /// Threads converting and scaling. + pub convert_threads: usize, + pub codec: Option, + pub layers: Vec, +} + +/// One simulcast layer while streaming: its encoder thread's inbox and +/// counters (written by the pipeline threads, read lock-free by stats). +struct Layer { + id: LayerId, + /// Size, scale and frame-rate cap, read by the capture thread when the + /// layer set changes. + spec: Mutex, + /// Newest converted frame for the encoder. + inbox: Handoff, + /// A keyframe was asked for. + keyframe: AtomicBool, + stop: AtomicBool, + /// Configured bitrate and cap (0: none), bit/s. + bitrate: AtomicU64, + max_bitrate: AtomicU64, + /// Frame rate the encoder plans for. + fps: AtomicU32, + /// An encoder to switch to (codec change). + next_encoder: Mutex>>, + threads: u32, + // Counters. + frames: AtomicU64, + keyframes: AtomicU64, + bytes: AtomicU64, + encoded: AtomicU64, + encode_ns: AtomicU64, + /// `width << 32 | height` of the last encoded frame. + size: AtomicU64, + target: AtomicU64, + /// `cpu-used`, or `i64::MIN`. + speed: AtomicI64, +} + +impl Layer { + fn new(spec: &LayerSpec, fps: u32, threads: u32) -> Self { + Self { + id: spec.id, + spec: Mutex::new(spec.clone()), + inbox: Handoff::new(), + keyframe: AtomicBool::new(false), + stop: AtomicBool::new(false), + bitrate: AtomicU64::new(spec.bitrate.max(1)), + max_bitrate: AtomicU64::new(spec.max_bitrate.unwrap_or(0)), + fps: AtomicU32::new(layer_fps(spec, fps)), + next_encoder: Mutex::new(None), + threads, + frames: AtomicU64::new(0), + keyframes: AtomicU64::new(0), + bytes: AtomicU64::new(0), + encoded: AtomicU64::new(0), + encode_ns: AtomicU64::new(0), + size: AtomicU64::new(0), + target: AtomicU64::new(spec.bitrate), + speed: AtomicI64::new(i64::MIN), + } + } + + fn update(&self, spec: &LayerSpec, fps: u32) { + *lock(&self.spec) = spec.clone(); + self.bitrate.store(spec.bitrate.max(1), Ordering::Relaxed); + self.max_bitrate.store(spec.max_bitrate.unwrap_or(0), Ordering::Relaxed); + self.fps.store(layer_fps(spec, fps), Ordering::Relaxed); + } + + fn stopped(&self) -> bool { + self.stop.load(Ordering::Relaxed) + } +} + +/// The frame rate a layer encodes at: its cap, within the capture's. +fn layer_fps(spec: &LayerSpec, fps: u32) -> u32 { + spec.max_fps.map_or(fps, |cap| cap.min(fps)).max(1) +} + +/// What [`Streamer::reconfigure`] changes. +struct Settings { + fps: u32, + bitrate_kbps: u32, + codec: Codec, + layers: Vec, +} + +impl Settings { + fn effective_layers(&self) -> Vec { + StreamerConfig { + bitrate_kbps: self.bitrate_kbps, + layers: self.layers.clone(), + ..StreamerConfig::default() + } + .effective_layers() + } +} + +/// Rates the stats thread computes once a second. +#[derive(Default)] +struct Rates { + capture_fps: f64, + convert_time: Duration, + /// Per layer: id, fps, kbit/s, encode time. + layers: Vec<(LayerId, f64, f64, Duration)>, } #[derive(Default)] @@ -252,6 +472,20 @@ struct Shared { size: AtomicU64, capture_ended: AtomicBool, error: Mutex>, + /// Frame-rate cap of the capture. + fps: AtomicU32, + captured: AtomicU64, + converted: AtomicU64, + convert_ns: AtomicU64, + convert_threads: AtomicUsize, + /// The layers being encoded, in configuration order. + layers: Mutex>>, + /// Bumped whenever `layers` or a layer's spec changes. + generation: AtomicU64, + /// Scratch set for the sink's keyframe requests. + keyframes: Mutex, + settings: Mutex>, + rates: Mutex, } impl Shared { @@ -262,16 +496,80 @@ impl Shared { fn stopped(&self) -> bool { self.stop.load(Ordering::Relaxed) } + + fn set_error(&self, e: impl ToString) { + *lock(&self.error) = Some(e.to_string()); + } + + /// Move the sink's keyframe requests to the layers they are for. Any + /// encoder thread may call it; one at a time does the work. + fn poll_keyframes(&self, sink: &dyn MediaSink) { + let Ok(mut requested) = self.keyframes.try_lock() else { return }; + sink.take_layer_keyframes(&mut requested); + if requested.is_empty() { + return; + } + for layer in lock(&self.layers).iter() { + if requested.contains(layer.id) { + layer.keyframe.store(true, Ordering::Relaxed); + } + } + requested.clear(); + } +} + +/// Split `cores` encoder threads over layers by their share of the pixels +/// (source size unknown yet: layers with a fixed size count against +/// 1920x1080). +fn thread_split(layers: &[LayerSpec], cores: u32) -> Vec { + let area = |l: &LayerSpec| { + let (w, h) = l.output_size(1920, 1080); + f64::from(w) * f64::from(h) + }; + let total: f64 = layers.iter().map(area).sum::().max(1.0); + layers.iter().map(|l| ((f64::from(cores) * area(l) / total).round() as u32).max(1)).collect() +} + +/// CPUs split between the layers' encoders (all but one, see +/// `voelin_media::codec::encoder_cpus`). +fn cores() -> u32 { + voelin_media::codec::encoder_cpus() +} + +fn new_encoder( + codecs: &Codecs, + codec: Codec, + spec: &LayerSpec, + fps: u32, + threads: u32, +) -> Result, MediaError> { + let config = EncoderConfig { + fps: layer_fps(spec, fps), + bitrate_bps: spec.bitrate.clamp(1, u64::from(u32::MAX)) as u32, + content: ContentHint::Screen, + threads, + ..EncoderConfig::default() + }; + Ok(codecs.new_encoder(codec, config)?) } /// Capture and encoding for our stream. Frames are captured from the start -/// (the portal asks the user then), but only encoded once a sink is -/// [attached](Streamer::attach). Stops when dropped. +/// (the portal asks the user then), but only converted and encoded once a +/// sink is [attached](Streamer::attach). Stops when dropped. +/// +/// The capture backend hands each frame, still in its capture buffer, to +/// the conversion on its own thread: one pass converts it to I420 on all +/// cores and derives every layer's size from it (a pyramid, recycled +/// buffers). Each layer's newest frame goes through a one-slot handoff to +/// that layer's encoder thread; a frame an encoder was too busy for is +/// replaced, not queued. pub struct Streamer { shared: Arc, screen: Option>, audio: Option>, threads: Vec>, + /// Encoder threads, by layer. + encoders: Mutex)>>, backend: &'static str, restore_token: Option, audio_error: Option, @@ -281,67 +579,69 @@ impl Streamer { /// Start capturing. Must run on a Tokio runtime (the portal talks D-Bus /// on it); may wait for the user in the portal's dialog. pub async fn start(codecs: &Codecs, config: StreamerConfig) -> Result { - let fps = config.fps.clamp(1, 60); - let encoder = codecs.new_encoder( - config.codec, - EncoderConfig { - fps, - bitrate_bps: config.bitrate_kbps.clamp(100, 10_000) * 1000, - content: ContentHint::Screen, - ..EncoderConfig::default() - }, - )?; - let options = CaptureOptions { fps, cursor: config.cursor, ..CaptureOptions::default() }; - // The portal's token for this choice comes with the capture. - let (screen, frames, restore_token): (Box, _, _) = match &config.source { - SourceId::Synthetic => { - let (w, h) = config.synthetic_size; - let mut screen = SyntheticScreen::new(w, h); - let frames = screen.start(&SourceId::Synthetic, &options).await?; - (Box::new(screen), frames, None) - } - #[cfg(all(target_os = "linux", feature = "media-desktop"))] - SourceId::Portal => { - use voelin_media::capture::portal::PortalCapture; - let mut portal = PortalCapture::with_restore_token(config.restore_token.clone()); - let frames = portal.start(&SourceId::Portal, &options).await?; - let token = portal.restore_token().map(str::to_owned); - (Box::new(portal), frames, token) - } - source => { - let mut screen = match config.backend { - CaptureBackend::Auto => capture::default_screen_capture()?, - #[cfg(all(target_os = "linux", feature = "media-desktop"))] - CaptureBackend::X11 => Box::new(voelin_media::capture::x11::X11Capture::new()), - #[cfg(not(all(target_os = "linux", feature = "media-desktop")))] - CaptureBackend::X11 => { - return Err(voelin_media::Error::CaptureUnavailable { - backend: "x11", - reason: "X11 capture is only in Linux desktop builds".into(), - } - .into()); - } - }; - let frames = screen.start(source, &options).await?; - (screen, frames, None) - } - }; - let backend = screen.backend(); - + let fps = config.fps.max(1); + let layers = config.effective_layers(); + check_layers(&layers)?; let shared = Arc::new(Shared::default()); + shared.fps.store(fps, Ordering::Relaxed); let mut streamer = Self { shared: shared.clone(), - screen: Some(screen), + screen: None, audio: None, threads: Vec::new(), - backend, - restore_token, + encoders: Mutex::new(Vec::new()), + backend: "", + restore_token: None, audio_error: None, }; - streamer.threads.push(spawn("voelin-stream-video", { + // Encoders first: an unavailable codec fails before any dialog. + let split = thread_split(&layers, cores()); + let mut ready = Vec::new(); + for (spec, threads) in layers.iter().zip(split) { + let encoder = new_encoder(codecs, config.codec, spec, fps, threads)?; + ready.push((Arc::new(Layer::new(spec, fps, threads)), encoder)); + } + for (layer, encoder) in ready { + streamer.spawn_encoder(layer, encoder)?; + } + *lock(&shared.settings) = Some(Settings { + fps, + bitrate_kbps: config.bitrate_kbps, + codec: config.codec, + layers: config.layers.clone(), + }); + streamer.threads.push(spawn("voelin-stream-stats", { let shared = shared.clone(); - move || video_loop(&shared, frames, encoder) + move || stats_loop(&shared) })?); + + let ingest = Box::new(Ingest::new(shared.clone())); + let options = CaptureOptions { fps, cursor: config.cursor, ..CaptureOptions::default() }; + // The portal's token for this choice comes with the capture. + let (screen, restore_token): (Box, _) = match &config.source { + SourceId::Synthetic => { + let (w, h) = config.synthetic_size; + let mut screen = SyntheticScreen::with_pattern(w, h, config.synthetic_pattern); + screen.start_sink(&SourceId::Synthetic, &options, ingest).await?; + (Box::new(screen), None) + } + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + _ if config.source == SourceId::Portal || config.backend == CaptureBackend::Portal => { + use voelin_media::capture::portal::PortalCapture; + let mut portal = PortalCapture::with_restore_token(config.restore_token.clone()); + portal.start_sink(&SourceId::Portal, &options, ingest).await?; + let token = portal.restore_token().map(str::to_owned); + (Box::new(portal), token) + } + source => { + let mut screen = screen_backend(&config.backend)?; + screen.start_sink(source, &options, ingest).await?; + (screen, None) + } + }; + streamer.backend = screen.backend(); + streamer.screen = Some(screen); + streamer.restore_token = restore_token; if config.audio { match start_audio(&config.source) { Ok((capture, buffers, encoder)) => { @@ -359,6 +659,103 @@ impl Streamer { Ok(streamer) } + fn spawn_encoder( + &self, + layer: Arc, + encoder: Box, + ) -> Result<(), MediaError> { + let id = layer.id; + lock(&self.shared.layers).push(layer.clone()); + self.shared.generation.fetch_add(1, Ordering::Relaxed); + let shared = self.shared.clone(); + let thread = + spawn(&format!("voelin-encode-{id}"), move || encode_loop(&shared, &layer, encoder))?; + lock(&self.encoders).push((id, thread)); + Ok(()) + } + + /// Change frame rate, bitrate, codec or layers while streaming, without + /// restarting the capture; applies from the next frame. A new codec + /// gets new encoders, which start with a keyframe; new layers get new + /// encoders; removed layers stop. Fails without changing anything if an + /// encoder cannot be created. + pub fn reconfigure( + &self, + codecs: &Codecs, + update: StreamerConfigUpdate, + ) -> Result<(), MediaError> { + let mut guard = lock(&self.shared.settings); + let Some(settings) = guard.as_mut() else { return Ok(()) }; + let old_codec = settings.codec; + let next = Settings { + fps: update.fps.unwrap_or(settings.fps).max(1), + bitrate_kbps: update.bitrate_kbps.unwrap_or(settings.bitrate_kbps), + codec: update.codec.unwrap_or(settings.codec), + layers: update.layers.unwrap_or_else(|| settings.layers.clone()), + }; + let specs = next.effective_layers(); + check_layers(&specs)?; + let codec_changed = next.codec != old_codec; + let current: Vec> = lock(&self.shared.layers).clone(); + // Create every encoder before changing anything. + let split = thread_split(&specs, cores()); + let mut created = Vec::new(); + for (spec, &threads) in specs.iter().zip(&split) { + let existing = current.iter().any(|l| l.id == spec.id); + if !existing || codec_changed { + created.push((spec.id, new_encoder(codecs, next.codec, spec, next.fps, threads)?)); + } + } + self.shared.fps.store(next.fps, Ordering::Relaxed); + let mut layers = Vec::with_capacity(specs.len()); + for (spec, &threads) in specs.iter().zip(&split) { + let encoder = + created.iter().position(|(id, _)| *id == spec.id).map(|i| created.swap_remove(i).1); + match current.iter().find(|l| l.id == spec.id) { + Some(layer) => { + layer.update(spec, next.fps); + if let Some(encoder) = encoder { + *lock(&layer.next_encoder) = Some(encoder); + } + layers.push(layer.clone()); + } + None => { + let layer = Arc::new(Layer::new(spec, next.fps, threads)); + let encoder = encoder.expect("created above"); + let shared = self.shared.clone(); + let thread = spawn(&format!("voelin-encode-{}", spec.id), { + let layer = layer.clone(); + move || encode_loop(&shared, &layer, encoder) + })?; + lock(&self.encoders).push((spec.id, thread)); + layers.push(layer); + } + } + } + // Stop removed layers. + let removed: Vec = + current.iter().filter(|l| !specs.iter().any(|s| s.id == l.id)).map(|l| l.id).collect(); + for layer in current.iter().filter(|l| removed.contains(&l.id)) { + layer.stop.store(true, Ordering::Relaxed); + layer.inbox.close(); + } + *lock(&self.shared.layers) = layers; + self.shared.generation.fetch_add(1, Ordering::Relaxed); + *settings = next; + drop(guard); + let finished: Vec> = { + let mut encoders = lock(&self.encoders); + let (done, keep) = encoders.drain(..).partition(|(id, _)| removed.contains(id)); + *encoders = keep; + done.into_iter().map(|(_, t)| t).collect() + }; + for thread in finished { + let _ = thread.join(); + } + debug!(?removed, codec_changed, "stream reconfigured"); + Ok(()) + } + /// Start encoding into `sink` (replacing an earlier one). pub fn attach(&self, sink: Arc) { *lock(&self.shared.sink) = Some(sink); @@ -389,15 +786,56 @@ impl Streamer { self.audio.is_some() } + /// The ids of the layers being encoded. + pub fn layer_ids(&self) -> Vec { + lock(&self.shared.layers).iter().map(|l| l.id).collect() + } + pub fn stats(&self) -> StreamerStats { - let size = self.shared.size.load(Ordering::Relaxed); + let shared = &self.shared; + let size = shared.size.load(Ordering::Relaxed); + let codec = lock(&shared.settings).as_ref().map(|s| s.codec); + let rates = lock(&shared.rates); + let layers: Vec = lock(&shared.layers) + .iter() + .map(|l| { + let size = l.size.load(Ordering::Relaxed); + let (fps, kbps, encode_time) = rates + .layers + .iter() + .find(|r| r.0 == l.id) + .map_or((0.0, 0.0, Duration::ZERO), |r| (r.1, r.2, r.3)); + let speed = l.speed.load(Ordering::Relaxed); + LayerStats { + id: l.id, + width: (size >> 32) as u32, + height: size as u32, + frames: l.frames.load(Ordering::Relaxed), + keyframes: l.keyframes.load(Ordering::Relaxed), + dropped: l.inbox.replaced(), + fps, + kbps, + encode_time, + bitrate: l.target.load(Ordering::Relaxed), + threads: l.threads, + speed: (speed != i64::MIN).then_some(speed as i32), + } + }) + .collect(); StreamerStats { - video_frames: self.shared.video_frames.load(Ordering::Relaxed), - audio_frames: self.shared.audio_frames.load(Ordering::Relaxed), + video_frames: shared.video_frames.load(Ordering::Relaxed), + audio_frames: shared.audio_frames.load(Ordering::Relaxed), width: (size >> 32) as u32, height: size as u32, - capture_ended: self.shared.capture_ended.load(Ordering::Relaxed), - error: lock(&self.shared.error).clone(), + capture_ended: shared.capture_ended.load(Ordering::Relaxed), + error: lock(&shared.error).clone(), + captured_frames: shared.captured.load(Ordering::Relaxed), + capture_fps: rates.capture_fps, + convert_time: rates.convert_time, + dropped_frames: layers.iter().map(|l| l.dropped).sum(), + convert_threads: shared.convert_threads.load(Ordering::Relaxed), + codec, + layers, } } @@ -411,7 +849,15 @@ impl Streamer { if let Some(mut audio) = self.audio.take() { audio.stop(); } + for layer in lock(&self.shared.layers).iter() { + layer.inbox.close(); + } + let encoders: Vec<_> = lock(&self.encoders).drain(..).collect(); + for (_, thread) in encoders { + let _ = thread.join(); + } for thread in self.threads.drain(..) { + thread.thread().unpark(); let _ = thread.join(); } } @@ -423,6 +869,50 @@ impl Drop for Streamer { } } +/// Layer ids must be unique. +fn check_layers(layers: &[LayerSpec]) -> Result<(), MediaError> { + for (i, layer) in layers.iter().enumerate() { + if layers[..i].iter().any(|l| l.id == layer.id) { + return Err(MediaError::Config(format!("layer {} is listed twice", layer.id))); + } + } + Ok(()) +} + +/// The capture backend for monitors and windows. +fn screen_backend(backend: &CaptureBackend) -> Result, MediaError> { + // Unused where every backend is built in. + #[allow(unused_variables)] + let unavailable = |backend: &'static str, reason: &str| { + MediaError::Media(voelin_media::Error::CaptureUnavailable { + backend, + reason: reason.into(), + }) + }; + Ok(match backend { + CaptureBackend::Auto => capture::default_screen_capture()?, + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + CaptureBackend::X11 => Box::new(voelin_media::capture::x11::X11Capture::new()), + #[cfg(not(all(target_os = "linux", feature = "media-desktop")))] + CaptureBackend::X11 => { + return Err(unavailable("x11", "X11 capture is only in Linux desktop builds")); + } + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + CaptureBackend::Wlroots => Box::new(voelin_media::capture::wlroots::WlrootsCapture::new()), + #[cfg(not(all(target_os = "linux", feature = "media-desktop")))] + CaptureBackend::Wlroots => { + return Err(unavailable("wlroots", "wlroots capture is only in Linux desktop builds")); + } + // Only reached where the portal is not built in. + CaptureBackend::Portal => { + return Err(unavailable( + "portal", + "the ScreenCast portal is only in Linux desktop builds", + )); + } + }) +} + type AudioStart = (Box, FrameReceiver, VoiceEncoder); fn start_audio(source: &SourceId) -> Result { @@ -436,52 +926,331 @@ fn start_audio(source: &SourceId) -> Result { Ok((capture, buffers, encoder)) } -fn video_loop( - shared: &Shared, - mut frames: FrameReceiver, - mut encoder: Box, -) { +/// A layer as the capture thread sees it. +struct IngestLayer { + layer: Arc, + spec: LayerSpec, + pacer: FramePacer, +} + +/// The conversion stage, on the capture backend's thread: paces frames, +/// converts and scales them for every layer that is due, and hands each +/// layer's frame to its encoder. Allocates nothing per frame once the +/// frame pools are warm. +struct Ingest { + shared: Arc, + pyramid: Pyramid, + pacer: FramePacer, + fps: u32, + generation: u64, + layers: Vec, + sizes: Vec<(u32, u32)>, + due: Vec, + out: Vec>>, +} + +impl Ingest { + fn new(shared: Arc) -> Self { + let pyramid = Pyramid::new(0); + shared.convert_threads.store(pyramid.threads(), Ordering::Relaxed); + let fps = shared.fps.load(Ordering::Relaxed); + Self { + shared, + pyramid, + pacer: FramePacer::new(Some(fps)), + fps, + generation: u64::MAX, + layers: Vec::new(), + sizes: Vec::new(), + due: Vec::new(), + out: Vec::new(), + } + } + + /// Pick up layer and frame-rate changes. + fn refresh(&mut self) { + let fps = self.shared.fps.load(Ordering::Relaxed); + if fps != self.fps { + self.fps = fps; + self.pacer.set_fps(Some(fps)); + } + let generation = self.shared.generation.load(Ordering::Relaxed); + if generation == self.generation { + return; + } + self.generation = generation; + let layers = lock(&self.shared.layers).clone(); + let old = std::mem::take(&mut self.layers); + for layer in layers { + let spec = lock(&layer.spec).clone(); + let fps = spec.max_fps.map(|cap| cap.min(self.fps)); + // Keep a layer's pacing across changes. + let pacer = match old.iter().find(|l| l.layer.id == layer.id) { + Some(l) => { + let mut pacer = l.pacer.clone(); + pacer.set_fps(fps); + pacer + } + None => FramePacer::new(fps), + }; + self.layers.push(IngestLayer { layer, spec, pacer }); + } + self.sizes.resize(self.layers.len(), (0, 0)); + self.due.resize(self.layers.len(), false); + self.out.resize(self.layers.len(), None); + } +} + +impl FrameSink for Ingest { + fn max_fps(&self) -> u32 { + self.shared.fps.load(Ordering::Relaxed).max(1) + } + + fn wants(&mut self, timestamp: Duration) -> bool { + if self.shared.stopped() { + return false; + } + let fps = self.shared.fps.load(Ordering::Relaxed); + if fps != self.fps { + self.fps = fps; + self.pacer.set_fps(Some(fps)); + } + self.pacer.due(timestamp) + } + + fn frame(&mut self, frame: FrameRef<'_>) -> bool { + if self.shared.stopped() { + return false; + } + self.pacer.keep(frame.timestamp); + self.refresh(); + let shared = &self.shared; + shared.captured.fetch_add(1, Ordering::Relaxed); + shared + .size + .store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed); + if lock(&shared.sink).is_none() { + return true; + } + let mut any = false; + for (i, l) in self.layers.iter_mut().enumerate() { + self.sizes[i] = l.spec.output_size(frame.width, frame.height); + self.due[i] = !l.layer.stopped() && l.pacer.take(frame.timestamp); + any |= self.due[i]; + } + if !any { + return true; + } + let started = Instant::now(); + if let Err(e) = self.pyramid.process(&frame, &self.sizes, &self.due, &mut self.out) { + warn!("cannot convert a captured frame: {e}"); + shared.set_error(e); + return true; + } + shared.convert_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + shared.converted.fetch_add(1, Ordering::Relaxed); + for (l, out) in self.layers.iter().zip(&mut self.out) { + if let Some(frame) = out.take() { + l.layer.inbox.put(frame); + } + } + true + } +} + +impl Drop for Ingest { + fn drop(&mut self) { + if !self.shared.stopped() { + debug!("screen capture ended"); + self.shared.capture_ended.store(true, Ordering::Relaxed); + } + } +} + +/// One layer's encoder thread. +fn encode_loop(shared: &Shared, layer: &Layer, mut encoder: Box) { // A requested keyframe the encoder has not produced yet (rate control // may skip a frame). let mut keyframe_due = false; - while !shared.stopped() { - let Some(frame) = frames.recv_timeout(POLL) else { - if frames.is_closed() { - debug!("screen capture ended"); - shared.capture_ended.store(true, Ordering::Relaxed); - break; - } - continue; - }; - let size = u64::from(frame.width) << 32 | u64::from(frame.height); - shared.size.store(size, Ordering::Relaxed); + // The last picture, and when it came: a static screen sends no frames, + // so keyframe requests are answered by encoding it again. + let mut last: Option<(Arc, Instant)> = None; + let mut bitrate = layer.bitrate.load(Ordering::Relaxed); + let mut fps = layer.fps.load(Ordering::Relaxed); + layer.speed.store(encoder.speed().map_or(i64::MIN, i64::from), Ordering::Relaxed); + while !shared.stopped() && !layer.stopped() { + let frame = layer.inbox.wait_timeout(POLL); + if let Some(next) = lock(&layer.next_encoder).take() { + // Another codec: its first frame is a keyframe anyway. + encoder = next; + bitrate = 0; + keyframe_due = true; + } let Some(sink) = shared.sink() else { continue }; - let keyframe = sink.take_keyframe_request() || keyframe_due; - match encoder.encode(&frame, keyframe) { - Ok(encoded) => { - keyframe_due = keyframe && !encoded.iter().any(|f| f.keyframe); - for f in encoded { - let frame = EncodedFrame { - kind: MediaKind::Video, - time: MediaTime::from_90khz(f.pts_90khz), - data: f.data.into(), - layer: 0, - keyframe: f.keyframe, - }; - if sink.send(frame) { - shared.video_frames.fetch_add(1, Ordering::Relaxed); - } + shared.poll_keyframes(&*sink); + let requested = layer.keyframe.swap(false, Ordering::Relaxed); + let force = requested || keyframe_due; + let frame = match frame { + Some(frame) => { + last = Some((frame.clone(), Instant::now())); + frame + } + None if force => { + let Some((frame, at)) = &last else { + layer.keyframe.store(requested, Ordering::Relaxed); + continue; + }; + // Same picture, later timestamp (rare: copies the frame). + Arc::new((**frame).clone().with_timestamp(frame.timestamp + at.elapsed())) + } + None => continue, + }; + // Follow the layer's bitrate, or what the viewers' estimates allow. + let configured = layer.bitrate.load(Ordering::Relaxed); + let cap = match layer.max_bitrate.load(Ordering::Relaxed) { + 0 => u64::MAX, + max => max, + }; + let target = sink.layer_bitrate(layer.id).unwrap_or(configured).clamp(1, cap); + if target.abs_diff(bitrate) * 100 > bitrate { + match encoder.set_bitrate(target.min(u64::from(u32::MAX)) as u32) { + Ok(()) => { + bitrate = target; + layer.target.store(target, Ordering::Relaxed); } + Err(e) => warn!(layer = layer.id, "cannot change the bitrate: {e}"), } + } + let want_fps = layer.fps.load(Ordering::Relaxed); + if want_fps != fps && encoder.set_fps(want_fps).is_ok() { + fps = want_fps; + } + let started = Instant::now(); + let mut produced_keyframe = false; + let result = encoder.encode_with(&frame, force, &mut |chunk| { + produced_keyframe |= chunk.keyframe; + let encoded = EncodedFrame { + kind: MediaKind::Video, + time: MediaTime::from_90khz(chunk.pts_90khz), + // The one allocation per encoded frame. + data: Arc::from(chunk.data), + layer: layer.id, + keyframe: chunk.keyframe, + }; + if sink.send(encoded) { + layer.frames.fetch_add(1, Ordering::Relaxed); + layer.keyframes.fetch_add(u64::from(chunk.keyframe), Ordering::Relaxed); + layer.bytes.fetch_add(chunk.data.len() as u64, Ordering::Relaxed); + shared.video_frames.fetch_add(1, Ordering::Relaxed); + } + }); + layer.encode_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + layer.encoded.fetch_add(1, Ordering::Relaxed); + layer.size.store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed); + layer.speed.store(encoder.speed().map_or(i64::MIN, i64::from), Ordering::Relaxed); + match result { + Ok(()) => keyframe_due = force && !produced_keyframe, Err(e) => { - warn!("video encoding failed: {e}"); - keyframe_due = keyframe; - *lock(&shared.error) = Some(e.to_string()); + warn!(layer = layer.id, "video encoding failed: {e}"); + keyframe_due = force; + shared.set_error(e); } } } } +/// Counter values at the last stats sample. +#[derive(Clone, Copy, Default)] +struct Sample { + captured: u64, + converted: u64, + convert_ns: u64, +} + +/// Once a second: rates for [`Streamer::stats`]; every five seconds a +/// summary at debug level. +fn stats_loop(shared: &Shared) { + const PERIOD: Duration = Duration::from_secs(1); + let mut last = Sample::default(); + // Per layer: id, frames, bytes, encoded, encode_ns. + let mut last_layers: Vec<(LayerId, u64, u64, u64, u64)> = Vec::new(); + let mut at = Instant::now(); + let mut ticks = 0u32; + while !shared.stopped() { + std::thread::park_timeout(PERIOD.saturating_sub(at.elapsed())); + if shared.stopped() { + break; + } + let elapsed = at.elapsed(); + if elapsed < PERIOD { + continue; + } + at = Instant::now(); + let secs = elapsed.as_secs_f64(); + let now = Sample { + captured: shared.captured.load(Ordering::Relaxed), + converted: shared.converted.load(Ordering::Relaxed), + convert_ns: shared.convert_ns.load(Ordering::Relaxed), + }; + let mean = |ns: u64, n: u64| Duration::from_nanos(ns.checked_div(n).unwrap_or(0)); + let mut rates = lock(&shared.rates); + rates.capture_fps = (now.captured - last.captured) as f64 / secs; + rates.convert_time = mean(now.convert_ns - last.convert_ns, now.converted - last.converted); + rates.layers.clear(); + let layers = lock(&shared.layers); + for layer in layers.iter() { + let current = ( + layer.id, + layer.frames.load(Ordering::Relaxed), + layer.bytes.load(Ordering::Relaxed), + layer.encoded.load(Ordering::Relaxed), + layer.encode_ns.load(Ordering::Relaxed), + ); + let before = last_layers + .iter() + .find(|l| l.0 == layer.id) + .copied() + .unwrap_or((layer.id, 0, 0, 0, 0)); + rates.layers.push(( + layer.id, + (current.1 - before.1) as f64 / secs, + (current.2 - before.2) as f64 * 8.0 / secs / 1000.0, + mean(current.4 - before.4, current.3 - before.3), + )); + } + last_layers.clear(); + last_layers.extend(layers.iter().map(|l| { + ( + l.id, + l.frames.load(Ordering::Relaxed), + l.bytes.load(Ordering::Relaxed), + l.encoded.load(Ordering::Relaxed), + l.encode_ns.load(Ordering::Relaxed), + ) + })); + last = now; + ticks += 1; + if ticks.is_multiple_of(5) && tracing::enabled!(tracing::Level::DEBUG) { + let summary: Vec = rates + .layers + .iter() + .map(|(id, fps, kbps, encode)| { + format!( + "L{id} {fps:.1} fps {kbps:.0} kbit/s enc {:.1} ms", + encode.as_secs_f64() * 1e3 + ) + }) + .collect(); + debug!( + "stream: capture {:.1} fps, convert {:.1} ms, {}", + rates.capture_fps, + rates.convert_time.as_secs_f64() * 1e3, + summary.join(", ") + ); + } + } +} + /// Interleaved stereo from any channel count (extra channels are dropped). fn append_stereo(buffer: &AudioBuffer, out: &mut Vec) { match buffer.channels { @@ -549,7 +1318,13 @@ fn audio_loop(shared: &Shared, mut buffers: FrameReceiver, mut enco /// Collects a [`Streamer`]'s frames for [`EncodedSource`]. struct ChannelSink { tx: std_mpsc::Sender, + /// A keyframe on every layer was asked for. keyframe: AtomicBool, + /// Layers a keyframe was asked for. + layers: Mutex, + /// What the viewers' bandwidth estimates allow, per layer. + bitrates: Mutex>, + shared: Arc, } impl MediaSink for ChannelSink { @@ -560,6 +1335,21 @@ impl MediaSink for ChannelSink { fn take_keyframe_request(&self) -> bool { self.keyframe.swap(false, Ordering::Relaxed) } + + fn take_layer_keyframes(&self, layers: &mut LayerSet) { + if self.keyframe.swap(false, Ordering::Relaxed) { + for layer in lock(&self.shared.layers).iter() { + layers.insert(layer.id); + } + } + let mut requested = lock(&self.layers); + layers.union_with(&requested); + requested.clear(); + } + + fn layer_bitrate(&self, layer: LayerId) -> Option { + lock(&self.bitrates).iter().find(|(id, _)| *id == layer).map(|(_, bps)| *bps) + } } /// A [`Streamer`] as a [`FrameSource`], for code that runs @@ -573,7 +1363,13 @@ pub struct EncodedSource { impl EncodedSource { pub fn new(streamer: Streamer) -> Self { let (tx, frames) = std_mpsc::channel(); - let sink = Arc::new(ChannelSink { tx, keyframe: AtomicBool::new(true) }); + let sink = Arc::new(ChannelSink { + tx, + keyframe: AtomicBool::new(true), + layers: Mutex::new(LayerSet::new()), + bitrates: Mutex::new(Vec::new()), + shared: streamer.shared.clone(), + }); streamer.attach(sink.clone()); Self { streamer, frames, sink } } @@ -591,6 +1387,18 @@ impl FrameSource for EncodedSource { fn request_keyframe(&mut self) { self.sink.keyframe.store(true, Ordering::Relaxed); } + + fn request_layer_keyframe(&mut self, layer: LayerId) { + lock(&self.sink.layers).insert(layer); + } + + fn set_layer_bitrate(&mut self, layer: LayerId, bitrate: u64) { + let mut bitrates = lock(&self.sink.bitrates); + match bitrates.iter_mut().find(|(id, _)| *id == layer) { + Some(entry) => entry.1 = bitrate, + None => bitrates.push((layer, bitrate)), + } + } } /// Whether `data` (one depacketized frame) starts a picture that decodes on @@ -941,15 +1749,20 @@ impl Latest { } } -/// Feeds a [`Streamer`]'s video straight into a [`VideoPipeline`]. +/// Feeds one layer of a [`Streamer`]'s video straight into a +/// [`VideoPipeline`]. struct PipelineSink { input: FrameInput, codec: voelin_stream::Codec, + layer: LayerId, keyframe: Arc, } impl MediaSink for PipelineSink { fn send(&self, frame: EncodedFrame) -> bool { + if frame.kind != MediaKind::Video || frame.layer != self.layer { + return true; + } self.input.push(MediaFrame { kind: frame.kind, codec: self.codec, @@ -964,6 +1777,12 @@ impl MediaSink for PipelineSink { fn take_keyframe_request(&self) -> bool { self.keyframe.swap(false, Ordering::Relaxed) } + + fn take_layer_keyframes(&self, layers: &mut LayerSet) { + if self.take_keyframe_request() { + layers.insert(self.layer); + } + } } /// Capture → encoder → decoder without a server, e.g. to preview a share or @@ -983,6 +1802,8 @@ impl LocalPreview { // The audio would go nowhere. config.audio = false; let codec = config.codec; + // The first (usually the largest) layer is shown. + let layer = config.effective_layers()[0].id; let streamer = Streamer::start(&codecs, config).await?; let keyframe = Arc::new(AtomicBool::new(true)); let pipeline = VideoPipeline::new(codecs, on_frame, { @@ -990,7 +1811,7 @@ impl LocalPreview { move || keyframe.store(true, Ordering::Relaxed) }); let input = pipeline.input(); - streamer.attach(Arc::new(PipelineSink { input, codec: codec.into(), keyframe })); + streamer.attach(Arc::new(PipelineSink { input, codec: codec.into(), layer, keyframe })); Ok(Self { streamer, pipeline }) } @@ -1110,6 +1931,124 @@ mod tests { assert_eq!(preview.streamer().backend(), "synthetic"); } + fn layer(id: LayerId, scale: f32, max_fps: Option, bitrate: u64) -> LayerSpec { + LayerSpec { id, scale, max_fps, ..LayerSpec::single(bitrate) } + } + + /// Poll `source` until `done` holds for the frames collected since the + /// last call (at most 10 s). + async fn collect( + source: &mut EncodedSource, + done: impl Fn(&[EncodedFrame]) -> bool, + ) -> Vec { + let mut frames = Vec::new(); + let deadline = Instant::now() + Duration::from_secs(10); + while !done(&frames) { + assert!(Instant::now() < deadline, "timed out with {} frames", frames.len()); + tokio::time::sleep(Duration::from_millis(20)).await; + source.poll_frames(Instant::now(), &mut frames); + } + frames + } + + /// Size of the last picture of `layer`, and whether the first frame that + /// decoded was a keyframe. Frames before it (another codec) are skipped. + fn decoded_size(codec: Codec, frames: &[EncodedFrame], layer: LayerId) -> ((u32, u32), bool) { + let mut decoder = Codecs::new().new_decoder(codec).unwrap(); + let (mut size, mut first_keyframe) = ((0, 0), None); + for f in frames.iter().filter(|f| f.layer == layer) { + match decoder.decode(&f.data) { + Ok(Some(p)) => { + size = (p.width, p.height); + first_keyframe.get_or_insert(f.keyframe); + } + Ok(None) => {} + Err(e) => assert!(first_keyframe.is_none(), "layer {layer}: {e}"), + } + } + (size, first_keyframe == Some(true)) + } + + /// Two layers at their own sizes and frame rates, keyframes per layer, + /// then a new codec and another layer set while streaming. + #[cfg(feature = "media-desktop")] + #[tokio::test(flavor = "multi_thread")] + async fn simulcast_layers_and_reconfigure() { + let codecs = Codecs::new(); + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (320, 240), + fps: 30, + audio: false, + layers: vec![layer(0, 1.0, None, 800_000), layer(5, 0.5, Some(10), 300_000)], + ..StreamerConfig::default() + }; + let streamer = Streamer::start(&codecs, config).await.unwrap(); + assert_eq!(streamer.layer_ids(), [0, 5]); + let mut source = EncodedSource::new(streamer); + let count = |frames: &[EncodedFrame], id| frames.iter().filter(|f| f.layer == id).count(); + let started = Instant::now(); + let frames = collect(&mut source, |f| count(f, 0) >= 30).await; + let seconds = started.elapsed().as_secs_f64(); + // Both start with a keyframe (the source asks for one on every layer). + for id in [0, 5] { + assert!(frames.iter().find(|f| f.layer == id).unwrap().keyframe, "layer {id}"); + } + assert_eq!(decoded_size(Codec::Vp8, &frames, 0), ((320, 240), true)); + assert_eq!(decoded_size(Codec::Vp8, &frames, 5), ((160, 120), true)); + // Layer 5 is capped at 10 fps (layer 0 may fall behind its 30 under + // load, dropping stale frames). + let small = count(&frames, 5) as f64; + assert!(small >= 3.0 && small <= seconds * 10.0 * 1.2 + 2.0, "{small} in {seconds:.2} s"); + + // A keyframe on layer 5 only. + source.request_layer_keyframe(5); + let frames = collect(&mut source, |f| f.iter().any(|f| f.layer == 5 && f.keyframe)).await; + assert!(!frames.iter().any(|f| f.layer == 0 && f.keyframe), "layer 0 got a keyframe"); + + // A viewer's estimate lowers layer 5's encoder bitrate only. + source.set_layer_bitrate(5, 150_000); + let target = |id| { + let stats = source.streamer().stats(); + stats.layers.iter().find(|l| l.id == id).map(|l| l.bitrate) + }; + let deadline = Instant::now() + Duration::from_secs(5); + while target(5) != Some(150_000) { + assert!(Instant::now() < deadline, "layer 5 at {:?}", target(5)); + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert_eq!(target(0), Some(800_000)); + + // VP9, layer 5 gone, a new layer 7 at a fixed size. + let fixed = LayerSpec { size: Some((96, 64)), ..layer(7, 1.0, None, 200_000) }; + let update = StreamerConfigUpdate { + codec: Some(Codec::Vp9), + layers: Some(vec![layer(0, 1.0, None, 600_000), fixed]), + fps: Some(20), + ..StreamerConfigUpdate::default() + }; + source.streamer().reconfigure(&codecs, update).unwrap(); + assert_eq!(source.streamer().layer_ids(), [0, 7]); + // VP8 frames encoded before the switch may still come first; the + // first VP9 picture of each layer is a keyframe. + let frames = collect(&mut source, |f| count(f, 7) >= 10 && count(f, 0) >= 10).await; + assert_eq!(decoded_size(Codec::Vp9, &frames, 0), ((320, 240), true)); + assert_eq!(decoded_size(Codec::Vp9, &frames, 7), ((96, 64), true)); + let stats = source.streamer().stats(); + assert_eq!(stats.codec, Some(Codec::Vp9)); + assert_eq!(stats.layers.iter().map(|l| l.id).collect::>(), [0, 7]); + assert!(stats.error.is_none(), "{stats:?}"); + assert!(stats.captured_frames > 0 && stats.convert_threads >= 1, "{stats:?}"); + + // Duplicate ids are refused and change nothing. + let bad = StreamerConfigUpdate { + layers: Some(vec![layer(1, 1.0, None, 1), layer(1, 0.5, None, 1)]), + ..StreamerConfigUpdate::default() + }; + assert!(source.streamer().reconfigure(&codecs, bad).is_err()); + assert_eq!(source.streamer().layer_ids(), [0, 7]); + } + /// Audio of the test pattern: 20 ms Opus frames on a 48 kHz clock. #[cfg(feature = "media-desktop")] #[tokio::test(flavor = "multi_thread")] diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index 103ffbb..1dccab6 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -9,7 +9,7 @@ repository.workspace = true publish.workspace = true [features] -default = ["vpx", "openh264", "openh264-download", "x11", "pipewire"] +default = ["vpx", "openh264", "openh264-download", "x11", "pipewire", "wlroots"] # VP8 and VP9 through the system libvpx (pkg-config `vpx`). vpx = ["dep:libvpx-native-sys"] # H.264 through Cisco's prebuilt OpenH264 library, loaded at runtime. The @@ -21,9 +21,12 @@ openh264-download = ["openh264", "dep:reqwest", "dep:bzip2", "dep:sha2"] av1 = ["dep:dav1d"] # X11 screen capture (Linux). x11 = ["dep:x11rb", "dep:memmap2", "dep:rustix"] -# Wayland screen capture (ScreenCast portal + PipeWire) and PipeWire system -# audio (Linux). -pipewire = ["dep:ashpd", "dep:pipewire"] +# 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"] +# 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"] # Conversion between `Codec` and `str0m::format::Codec`. str0m = ["dep:str0m"] @@ -44,7 +47,10 @@ yuv = "0.8.19" ashpd = { version = "0.13.13", default-features = false, features = ["screencast", "tokio"], optional = true } memmap2 = { version = "0.9.11", optional = true } pipewire = { version = "0.10.1", optional = true } -rustix = { version = "1.1.5", features = ["fs"], optional = true } +rustix = { version = "1.1.5", features = ["event", "fs"], optional = true } +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 } [target.'cfg(target_os = "android")'.dependencies] @@ -55,7 +61,12 @@ wasapi = "0.24.0" windows-capture = "2.0.1" [dev-dependencies] +criterion = "0.8" tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread", "time"] } +[[bench]] +name = "convert" +harness = false + [lints] workspace = true diff --git a/crates/voelin-media/benches/convert.rs b/crates/voelin-media/benches/convert.rs new file mode 100644 index 0000000..926ad29 --- /dev/null +++ b/crates/voelin-media/benches/convert.rs @@ -0,0 +1,79 @@ +//! Pixel conversion and scaling of screen-sized frames: +//! `cargo bench -p voelin-media --bench convert`. +//! +//! - `to_i420`: the allocating one-thread conversion streams used before +//! - `converter/`: [`Converter`] into a pooled frame on n threads (0: all) +//! - `pyramid`: conversion plus a half and a quarter size layer +//! - `scale/half`, `scale/2-3`: one luma plane, 2x2 box and area averaging + +use std::hint::black_box; +use std::sync::Arc; +use std::time::Duration; + +use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; +use voelin_media::capture::synthetic::{Pattern, SyntheticScreen}; +use voelin_media::convert::{self, Converter}; +use voelin_media::pool::FramePool; +use voelin_media::scale::{PlaneScaler, Pyramid}; +use voelin_media::workers::Workers; +use voelin_media::{FrameData, VideoFrame}; + +const SIZES: [(u32, u32); 3] = [(1280, 720), (1920, 1080), (2560, 1440)]; + +fn source(w: u32, h: u32) -> VideoFrame { + SyntheticScreen::with_pattern(w, h, Pattern::Desktop).frame(1, 30) +} + +fn conversion(c: &mut Criterion) { + let mut group = c.benchmark_group("convert"); + group.sample_size(30).measurement_time(Duration::from_secs(3)); + for (w, h) in SIZES { + let src = source(w, h); + let size = format!("{w}x{h}"); + group.throughput(Throughput::Elements(u64::from(w) * u64::from(h))); + group.bench_with_input(BenchmarkId::new("to_i420", &size), &src, |b, src| { + b.iter(|| black_box(convert::to_i420(src).unwrap())); + }); + for threads in [1, 0] { + let mut converter = Converter::new(threads); + let mut pool = FramePool::new(); + let id = BenchmarkId::new(format!("converter/{}", converter.threads()), &size); + group.bench_with_input(id, &src, |b, src| { + b.iter(|| { + let target = Arc::get_mut(pool.get(w, h)).unwrap(); + converter.to_i420_into(&src.view(), target).unwrap(); + }); + }); + } + let mut pyramid = Pyramid::new(0); + let sizes = [(w, h), (w / 2, h / 2), (w / 4, h / 4)]; + let mut out = vec![None; 3]; + group.bench_with_input(BenchmarkId::new("pyramid/1+1/2+1/4", &size), &src, |b, src| { + b.iter(|| { + pyramid.process(&src.view(), &sizes, &[true; 3], &mut out).unwrap(); + out.iter_mut().for_each(|f| drop(f.take())); + }); + }); + } + group.finish(); +} + +fn scaling(c: &mut Criterion) { + let mut group = c.benchmark_group("scale"); + group.sample_size(30).measurement_time(Duration::from_secs(3)); + let mut workers = Workers::new("bench-scale", 0); + let i420 = convert::to_i420(&source(1920, 1080)).unwrap().into_owned(); + let FrameData::I420 { y, .. } = &i420.data else { unreachable!() }; + for (name, (dw, dh)) in [("half", (960, 540)), ("2-3", (1280, 720))] { + let mut scaler = PlaneScaler::new((1920, 1080), (dw, dh)); + let mut out = vec![0; dw * dh]; + group.throughput(Throughput::Elements((dw * dh) as u64)); + group.bench_function(format!("{name}/1920x1080-luma"), |b| { + b.iter(|| scaler.scale(&mut workers, y.view(), &mut out, dw).unwrap()); + }); + } + group.finish(); +} + +criterion_group!(benches, conversion, scaling); +criterion_main!(benches); diff --git a/crates/voelin-media/src/capture/dmabuf.rs b/crates/voelin-media/src/capture/dmabuf.rs new file mode 100644 index 0000000..a82aa74 --- /dev/null +++ b/crates/voelin-media/src/capture/dmabuf.rs @@ -0,0 +1,101 @@ +//! CPU access to LINEAR DMA-BUFs (screen capture buffers a compositor +//! shares): a read-only mapping, and `DMA_BUF_IOCTL_SYNC` around each read +//! so caches are coherent with what the GPU wrote. Tiled buffers cannot be +//! read like this; they need a GPU import (not done here). +#![allow(unsafe_code)] + +use std::io; +use std::os::fd::{BorrowedFd, RawFd}; + +use memmap2::{Mmap, MmapOptions}; + +/// `struct dma_buf_sync` of ``. +#[repr(C)] +struct DmaBufSync { + flags: u64, +} + +const DMA_BUF_SYNC_READ: u64 = 1 << 0; +const DMA_BUF_SYNC_START: u64 = 0 << 2; +const DMA_BUF_SYNC_END: u64 = 1 << 2; +/// `DMA_BUF_IOCTL_SYNC`: `_IOW('b', 0, struct dma_buf_sync)`. +const SYNC: rustix::ioctl::Opcode = rustix::ioctl::opcode::write::(b'b', 0); + +/// A read-only mapping of a DMA-BUF. +pub(crate) struct DmaBufMap { + fd: RawFd, + map: Mmap, +} + +impl DmaBufMap { + /// Map the first `len` bytes of the DMA-BUF `fd`. The caller keeps `fd` + /// open while the mapping is used (the mapping itself keeps the buffer + /// alive, but [`DmaBufMap::read`] syncs through the descriptor). + pub fn new(fd: RawFd, len: usize) -> io::Result { + if fd < 0 || len == 0 { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "no DMA-BUF to map")); + } + // SAFETY: memmap2 requires that the mapped object is not truncated + // or changed by others while Rust reads it. A DMA-BUF cannot be + // truncated; the compositor writes into a buffer only while it is + // not handed to us (PipeWire queues it back after our callback), and + // `read` brackets every access with DMA_BUF_IOCTL_SYNC so the CPU + // sees the GPU's writes. We only read. + let map = unsafe { MmapOptions::new().len(len).map(fd) }?; + Ok(Self { fd, map }) + } + + pub fn fd(&self) -> RawFd { + self.fd + } + + pub fn len(&self) -> usize { + self.map.len() + } + + /// Run `f` on the mapped bytes between the start and end of a read + /// access. + pub fn read(&self, f: impl FnOnce(&[u8]) -> R) -> R { + self.sync(DMA_BUF_SYNC_START); + let result = f(&self.map); + self.sync(DMA_BUF_SYNC_END); + result + } + + fn sync(&self, when: u64) { + // SAFETY: `fd` is the open DMA-BUF this mapping was made from (see + // `new`); borrowing it for the call does not close it. + let fd = unsafe { BorrowedFd::borrow_raw(self.fd) }; + let sync = DmaBufSync { flags: DMA_BUF_SYNC_READ | when }; + // SAFETY: DMA_BUF_IOCTL_SYNC takes a pointer to a `dma_buf_sync`, + // which is what `Setter` passes; it only reads it. A failure (e.g. a + // kernel without the ioctl) leaves the data as coherent as the + // mapping is anyway, so it is ignored. + let _ = unsafe { + rustix::ioctl::ioctl(fd, rustix::ioctl::Setter::::new(sync)) + }; + } +} + +#[cfg(test)] +mod tests { + use std::io::Write; + use std::os::fd::AsRawFd; + + use super::*; + + /// A memfd maps like a DMA-BUF; the sync ioctl fails on it and is + /// ignored. + #[test] + fn maps_and_reads() { + let fd = rustix::fs::memfd_create("voelin-dmabuf-test", rustix::fs::MemfdFlags::CLOEXEC) + .unwrap(); + let mut file = std::fs::File::from(fd); + file.write_all(&[7; 8192]).unwrap(); + let map = DmaBufMap::new(file.as_raw_fd(), 8192).unwrap(); + assert_eq!(map.len(), 8192); + assert_eq!(map.fd(), file.as_raw_fd()); + assert_eq!(map.read(|b| b.iter().map(|&x| u64::from(x)).sum::()), 7 * 8192); + assert!(DmaBufMap::new(-1, 10).is_err()); + } +} diff --git a/crates/voelin-media/src/capture/mod.rs b/crates/voelin-media/src/capture/mod.rs index 2717fb9..4bfaf85 100644 --- a/crates/voelin-media/src/capture/mod.rs +++ b/crates/voelin-media/src/capture/mod.rs @@ -1,7 +1,12 @@ //! Screen and system-audio capture. //! -//! Backends deliver frames on a [`FrameReceiver`] from their own thread; the -//! queue drops the oldest frame when the consumer falls behind. +//! Screen backends hand each frame to a [`FrameSink`] on their own thread, +//! with the pixels still in the capture buffer (a PipeWire buffer, the X11 +//! shared-memory segment, a Windows staging texture), so the sink converts +//! straight from it ([`ScreenCapture::start_sink`]). [`ScreenCapture::start`] +//! instead copies frames into a [`FrameReceiver`]; the queue drops the oldest +//! frame when the consumer falls behind. Audio backends use a +//! [`FrameReceiver`]. //! //! | Backend | Screen | System audio | //! |---|---|---| @@ -18,10 +23,12 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::thread::JoinHandle; use std::time::{Duration, Instant}; -use crate::frame::{AudioBuffer, VideoFrame}; -use crate::queue::FrameReceiver; +use crate::frame::{AudioBuffer, FrameRef, VideoFrame}; +use crate::queue::{FrameReceiver, FrameSender, frame_channel}; use crate::{Error, Result}; +#[cfg(all(target_os = "linux", feature = "pipewire"))] +mod dmabuf; pub mod external; #[cfg(all(target_os = "linux", feature = "pipewire"))] pub mod pipewire_audio; @@ -32,6 +39,8 @@ mod pw; pub mod synthetic; #[cfg(windows)] pub mod windows; +#[cfg(all(target_os = "linux", feature = "wlroots"))] +pub mod wlroots; #[cfg(all(target_os = "linux", feature = "x11"))] pub mod x11; @@ -64,7 +73,8 @@ pub struct CaptureSource { #[derive(Clone, Debug, PartialEq, Eq)] pub struct CaptureOptions { - /// Maximum frame rate. + /// Maximum frame rate for [`ScreenCapture::start`] (with + /// [`ScreenCapture::start_sink`], [`FrameSink::max_fps`] decides). pub fps: u32, /// Draw the mouse cursor into the frames. pub cursor: bool, @@ -78,6 +88,133 @@ impl Default for CaptureOptions { } } +/// Receives captured frames on the capture backend's thread; see +/// [`ScreenCapture::start_sink`]. +pub trait FrameSink: Send { + /// The highest frame rate wanted now. Backends that pace themselves + /// (X11, the test pattern) capture at this rate; it may change while + /// capturing. + fn max_fps(&self) -> u32; + + /// Whether a frame captured at `timestamp` would be used. Backends that + /// get frames pushed (PipeWire, Windows, wlroots) ask before they map or + /// copy anything, and give unwanted buffers straight back. + fn wants(&mut self, timestamp: Duration) -> bool { + let _ = timestamp; + true + } + + /// One frame. Its pixels are only valid during the call. Returns + /// `false` when no more frames are wanted; the backend then stops. + fn frame(&mut self, frame: FrameRef<'_>) -> bool; +} + +/// Keeps frames of a source for a frame-rate cap, by their timestamps, so +/// the kept frames are evenly spaced at the cap (or at the source's rate if +/// that is lower). +#[derive(Clone, Debug)] +pub struct FramePacer { + interval: Duration, + next: Option, +} + +impl FramePacer { + /// At most `fps` frames per second; `None` (or 0) keeps every frame. + pub fn new(fps: Option) -> Self { + let mut pacer = Self { interval: Duration::ZERO, next: None }; + pacer.set_fps(fps); + pacer + } + + pub fn set_fps(&mut self, fps: Option) { + self.interval = match fps { + Some(fps) if fps > 0 => Duration::from_secs(1) / fps, + _ => Duration::ZERO, + }; + } + + /// Whether a frame at `timestamp` is due. A frame up to an eighth of + /// the interval early still counts, so jitter does not halve the rate; + /// a timestamp far before the expected one means the clock started + /// over. + pub fn due(&self, timestamp: Duration) -> bool { + self.next.is_none_or(|next| { + timestamp + self.interval / 8 >= next || timestamp + 2 * self.interval <= next + }) + } + + /// Record that the frame at `timestamp` was kept. + pub fn keep(&mut self, timestamp: Duration) { + let iv = self.interval; + self.next = Some(match self.next { + // On time: keep the average rate exact. + Some(next) if timestamp < next + iv && timestamp + 2 * iv > next => next + iv, + // Late (or the clock jumped): start over from this frame. + _ => timestamp + iv, + }); + } + + /// [`due`](Self::due), and [`keep`](Self::keep) if so. + pub fn take(&mut self, timestamp: Duration) -> bool { + let due = self.due(timestamp); + if due { + self.keep(timestamp); + } + due + } +} + +/// Copies frames into a queue: [`ScreenCapture::start`] of backends that +/// deliver into a [`FrameSink`]. +pub(crate) struct QueueSink { + tx: FrameSender, + fps: u32, + pacer: FramePacer, +} + +impl QueueSink { + pub fn new(options: &CaptureOptions) -> (Self, FrameReceiver) { + let (tx, rx) = frame_channel(options.queue); + let fps = options.fps.max(1); + (Self { tx, fps, pacer: FramePacer::new(Some(fps)) }, rx) + } +} + +impl FrameSink for QueueSink { + fn max_fps(&self) -> u32 { + self.fps + } + + fn wants(&mut self, timestamp: Duration) -> bool { + !self.tx.is_closed() && self.pacer.due(timestamp) + } + + fn frame(&mut self, frame: FrameRef<'_>) -> bool { + self.pacer.keep(frame.timestamp); + self.tx.send(frame.to_frame()) + } +} + +/// Hand frames of `frames` to `sink` on a thread of their own, until either +/// side stops ([`ScreenCapture::start_sink`] of backends that only have +/// [`ScreenCapture::start`]). +pub fn forward(mut frames: FrameReceiver, mut sink: Box) -> Result<()> { + std::thread::Builder::new().name("voelin-capture-forward".into()).spawn(move || { + loop { + match frames.recv_timeout(Duration::from_millis(100)) { + Some(frame) => { + if sink.wants(frame.timestamp) && !sink.frame(frame.view()) { + break; + } + } + None if frames.is_closed() => break, + None => {} + } + } + })?; + Ok(()) +} + /// A screen / window capture backend. pub trait ScreenCapture: Send { /// Short name for logs (`"x11"`, `"portal"`, ...). @@ -87,15 +224,38 @@ pub trait ScreenCapture: Send { /// returns a single [`SourceId::Portal`] entry: its dialog picks. fn sources(&mut self) -> Result>; - /// Start capturing (stopping a previous capture). Async because the - /// portal asks the user. Frames stop when [`ScreenCapture::stop`] is - /// called, the backend is dropped, or the receiver is dropped. + /// Start capturing (stopping a previous capture), copying every frame + /// into a queue. Async because the portal asks the user. Frames stop + /// when [`ScreenCapture::stop`] is called, the backend is dropped, or the + /// receiver is dropped. fn start( &mut self, source: &SourceId, options: &CaptureOptions, ) -> BoxFuture<'_, Result>>; + /// Start capturing into `sink` (stopping a previous capture): the + /// backend calls it on its own thread with the pixels still in the + /// capture buffer, and drops it when the capture ends (stopped, the + /// source went away, or the sink returned `false`). `options.fps` is + /// ignored in favour of [`FrameSink::max_fps`]. + /// + /// The default forwards the frames of [`ScreenCapture::start`] from a + /// thread of its own. + fn start_sink( + &mut self, + source: &SourceId, + options: &CaptureOptions, + sink: Box, + ) -> BoxFuture<'_, Result<()>> { + let source = source.clone(); + let options = CaptureOptions { fps: sink.max_fps(), ..options.clone() }; + Box::pin(async move { + let frames = self.start(&source, &options).await?; + forward(frames, sink) + }) + } + fn stop(&mut self); } @@ -196,6 +356,11 @@ impl Ticker { Self { interval: Duration::from_secs(1) / fps.max(1), next: Instant::now() } } + /// Change the rate from the next tick on. + pub fn set_fps(&mut self, fps: u32) { + self.interval = Duration::from_secs(1) / fps.max(1); + } + /// Sleep until the next tick. Returns `false` if `stop` got set. pub fn wait(&mut self, stop: &AtomicBool) -> bool { self.next += self.interval; @@ -232,4 +397,32 @@ mod tests { worker.stop(); assert!(started.elapsed() < Duration::from_millis(900)); } + + fn kept(pacer: &mut FramePacer, source_fps: f64, jitter_ms: f64, seconds: u32) -> usize { + let frames = (source_fps * f64::from(seconds)) as usize; + (0..frames) + .filter(|&n| { + let jitter = if n % 2 == 0 { jitter_ms } else { -jitter_ms }; + let t = (n as f64 * 1000.0 / source_fps + jitter).max(0.0); + pacer.take(Duration::from_secs_f64(t / 1000.0)) + }) + .count() + } + + #[test] + fn pacer_caps_the_rate() { + // 60 Hz source, 30 fps cap: every other frame, even with jitter. + assert_eq!(kept(&mut FramePacer::new(Some(30)), 60.0, 1.5, 10), 300); + // 144 Hz to 60: close to 60. + let n = kept(&mut FramePacer::new(Some(60)), 144.0, 0.5, 10); + assert!((580..=610).contains(&n), "{n}"); + // A cap above the source rate keeps everything. + assert_eq!(kept(&mut FramePacer::new(Some(120)), 30.0, 2.0, 10), 300); + assert_eq!(kept(&mut FramePacer::new(None), 60.0, 0.0, 1), 60); + // A clock that jumps back starts over. + let mut pacer = FramePacer::new(Some(10)); + assert!(pacer.take(Duration::from_secs(100))); + assert!(!pacer.take(Duration::from_millis(100_050))); + assert!(pacer.take(Duration::from_secs(1))); + } } diff --git a/crates/voelin-media/src/capture/portal.rs b/crates/voelin-media/src/capture/portal.rs index c4f19ba..ea42eab 100644 --- a/crates/voelin-media/src/capture/portal.rs +++ b/crates/voelin-media/src/capture/portal.rs @@ -4,24 +4,40 @@ //! //! The portal can remember the user's choice: pass the token from //! [`PortalCapture::restore_token`] to [`PortalCapture::with_restore_token`] -//! next time (it persists until the user revokes it). Only shared-memory -//! buffers (`BGRx` / `RGBx` family) are negotiated; DMA-BUF import is a TODO. +//! next time (it persists until the user revokes it). +//! +//! Buffers: LINEAR DMA-BUFs (mapped and read by the CPU, with +//! `DMA_BUF_IOCTL_SYNC` around each read) are offered first, shared memory +//! (`BGRx` / `BGRA` / `RGBx` / `RGBA`) second, so compositors without +//! DMA-BUF support use shared memory. When reading DMA-BUFs turns out slow +//! (buffers in memory the CPU reads uncached, e.g. a discrete GPU's VRAM), +//! the stream switches to shared memory. Tiled DMA-BUFs would need a GPU +//! import and are not offered. Frames go to the [`FrameSink`] while the +//! buffer is dequeued; nothing is copied before conversion. The frame rate +//! follows the sink's cap: the compositor is asked for up to that rate and +//! sends frames when the screen changes. use std::time::{Duration, Instant}; use ashpd::desktop::PersistMode; use ashpd::desktop::screencast::{CursorMode, Screencast, SelectSourcesOptions, SourceType}; use pipewire as pw; +use pw::spa::buffer::DataType; use pw::spa::param::format::{FormatProperties, MediaSubtype, MediaType}; use pw::spa::param::video::{VideoFormat, VideoInfoRaw}; -use pw::spa::pod::{Value, object, property}; -use pw::spa::utils::{Fraction, Rectangle, SpaTypes}; +use pw::spa::pod::{ + ChoiceValue, Object, Pod, PodPropFlags, Property, PropertyFlags, Value, property, +}; +use pw::spa::utils::{Choice, ChoiceEnum, ChoiceFlags, Fraction, Id, Rectangle, SpaTypes}; use tracing::{debug, warn}; +use crate::capture::dmabuf::DmaBufMap; use crate::capture::pw::{PwThread, pod, serialize}; -use crate::capture::{BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId}; -use crate::frame::VideoFrame; -use crate::queue::{FrameReceiver, FrameSender, frame_channel}; +use crate::capture::{ + BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture, SourceId, +}; +use crate::frame::{FrameRef, PixelsRef, PlaneRef, VideoFrame}; +use crate::queue::FrameReceiver; use crate::{Error, Result}; const BACKEND: &str = "portal"; @@ -49,13 +65,21 @@ struct Session { /// ScreenCast portal + PipeWire backend (Wayland, also works on X11 desktops /// that run xdg-desktop-portal). -#[derive(Default)] pub struct PortalCapture { restore_token: Option, + dmabuf: bool, session: Option, thread: Option, } +impl Default for PortalCapture { + fn default() -> Self { + // VOELIN_PORTAL_DMABUF=0 offers shared memory only. + let dmabuf = std::env::var("VOELIN_PORTAL_DMABUF").map_or(true, |v| v != "0"); + Self { restore_token: None, dmabuf, session: None, thread: None } + } +} + impl PortalCapture { pub fn new() -> Self { Self::default() @@ -64,7 +88,16 @@ impl PortalCapture { /// Reuse an earlier choice without asking (a token from /// [`PortalCapture::restore_token`]). pub fn with_restore_token(token: Option) -> Self { - Self { restore_token: token, session: None, thread: None } + let mut capture = Self::default(); + capture.restore_token = token; + capture + } + + /// Offer LINEAR DMA-BUFs (default, unless `VOELIN_PORTAL_DMABUF=0`), or + /// shared memory only. + pub fn with_dmabuf(mut self, enabled: bool) -> Self { + self.dmabuf = enabled; + self } /// Token to persist after a successful start; `None` before that or if @@ -149,6 +182,22 @@ impl ScreenCapture for PortalCapture { source: &SourceId, options: &CaptureOptions, ) -> BoxFuture<'_, Result>> { + let (sink, rx) = QueueSink::new(options); + let started = self.start_sink(source, options, Box::new(sink)); + Box::pin(async move { + started.await?; + Ok(rx) + }) + } + + /// The sink reads the PipeWire buffer itself (shared memory, or a + /// LINEAR DMA-BUF mapped for reading) while the buffer is dequeued. + fn start_sink( + &mut self, + source: &SourceId, + options: &CaptureOptions, + sink: Box, + ) -> BoxFuture<'_, Result<()>> { let source = source.clone(); let options = options.clone(); Box::pin(async move { @@ -157,15 +206,14 @@ impl ScreenCapture for PortalCapture { } self.stop(); let (fd, node) = self.open(&options).await?; - let (tx, rx) = frame_channel(options.queue); - let fps = options.fps.max(1); + let dmabuf = self.dmabuf; let thread = PwThread::spawn("voelin-portal-capture", Some(fd), move |core, mainloop| { - video_stream(core, mainloop, node, fps, tx) + video_stream(core, mainloop, node, dmabuf, sink) }) .map_err(|e| Error::Capture { backend: BACKEND, message: e })?; self.thread = Some(thread); - Ok(rx) + Ok(()) }) } @@ -190,12 +238,43 @@ impl Drop for PortalCapture { } } +/// Pixel formats we take, in order of preference (all 4 bytes per pixel; +/// `x` and `A` are ignored). +const FORMATS: [VideoFormat; 4] = + [VideoFormat::BGRx, VideoFormat::BGRA, VideoFormat::RGBx, VideoFormat::RGBA]; +/// DRM_FORMAT_MOD_LINEAR: rows of pixels, readable by the CPU once mapped. +const MODIFIER_LINEAR: i64 = 0; +/// Reading DMA-BUFs slower than this (per pixel, conversion included) means +/// the buffers live in memory the CPU reads uncached (e.g. a discrete GPU's +/// VRAM); shared memory is faster then. +const SLOW_DMABUF_NS_PER_PIXEL: f64 = 6.0; +/// DMA-BUF frames timed before deciding. +const DMABUF_PROBE_FRAMES: u32 = 30; + +/// What was negotiated. +#[derive(Clone, Copy, Debug)] +struct Negotiated { + format: VideoFormat, + width: u32, + height: u32, + /// DMA-BUF modifier; `None`: shared memory. + modifier: Option, +} + struct VideoState { - tx: FrameSender, - format: Option<(VideoFormat, u32, u32)>, + sink: Box, + format: Option, started: Instant, - interval: Duration, - last: Option, + /// Frame rate the offered formats ask for. + fps: u32, + /// Offer DMA-BUFs. + dmabuf: bool, + /// Mappings of the DMA-BUFs PipeWire cycles through. + maps: Vec, + /// Time spent handing DMA-BUF frames to the sink, and how many. + dmabuf_time: Duration, + dmabuf_frames: u32, + logged: Option, mainloop: pw::main_loop::MainLoopWeak, } @@ -203,8 +282,8 @@ fn video_stream( core: &pw::core::CoreRc, mainloop: &pw::main_loop::MainLoopRc, node: u32, - fps: u32, - tx: FrameSender, + dmabuf: bool, + sink: Box, ) -> std::result::Result<(pw::stream::StreamRc, pw::stream::StreamListener), String> { let props = pw::properties::properties! { *pw::keys::MEDIA_TYPE => "Video", @@ -213,13 +292,17 @@ fn video_stream( }; let stream = pw::stream::StreamRc::new(core.clone(), "voelin-screen-capture", props) .map_err(|e| format!("PipeWire stream: {e}"))?; + let fps = sink.max_fps().max(1); let state = VideoState { - tx, + sink, format: None, started: Instant::now(), - // Accept frames slightly early so rounding does not halve the rate. - interval: Duration::from_secs(1) / fps * 9 / 10, - last: None, + fps, + dmabuf, + maps: Vec::new(), + dmabuf_time: Duration::ZERO, + dmabuf_frames: 0, + logged: None, mainloop: mainloop.downgrade(), }; let listener = stream @@ -236,125 +319,319 @@ fn video_stream( 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; } - let Ok((MediaType::Video, MediaSubtype::Raw)) = - pw::spa::param::format_utils::parse_format(param) - else { - return; - }; - let mut info = VideoInfoRaw::new(); - if info.parse(param).is_ok() { - let size = info.size(); - debug!(format = ?info.format(), size.width, size.height, "screen capture format"); - state.format = Some((info.format(), size.width, size.height)); + if let Err(e) = format_changed(stream, state, param) { + warn!("screen capture format: {e}"); } }) - .process(|stream, state| { - let Some(mut buffer) = stream.dequeue_buffer() else { return }; - let Some((format, width, height)) = state.format else { return }; - let now = Instant::now(); - if state.last.is_some_and(|last| now - last < state.interval) { - return; - } - let Some(data) = buffer.datas_mut().first_mut() else { return }; - let Some(frame) = copy_frame(data, format, width, height) else { return }; - state.last = Some(now); - if !state.tx.send(frame.with_timestamp(now - state.started)) - && let Some(mainloop) = state.mainloop.upgrade() - { - // Nobody receives frames anymore. - mainloop.quit(); - } + .remove_buffer(|_, state, _| { + // PipeWire is replacing its buffers: map the new ones. + state.maps.clear(); }) + .process(process) .register() .map_err(|e| format!("PipeWire listener: {e}"))?; - let format = serialize(Value::Object(object!( - SpaTypes::ObjectParamFormat, - pw::spa::param::ParamType::EnumFormat, - property!(FormatProperties::MediaType, Id, MediaType::Video), - property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw), - property!( - FormatProperties::VideoFormat, - Choice, - Enum, - Id, - VideoFormat::BGRx, - VideoFormat::BGRx, - VideoFormat::BGRA, - VideoFormat::RGBx, - VideoFormat::RGBA - ), - property!( - FormatProperties::VideoSize, - Choice, - Range, - Rectangle, - Rectangle { width: 1920, height: 1080 }, - Rectangle { width: 1, height: 1 }, - Rectangle { width: 8192, height: 8192 } - ), - property!( - FormatProperties::VideoFramerate, - Choice, - Range, - Fraction, - Fraction { num: fps, denom: 1 }, - Fraction { num: 0, denom: 1 }, - Fraction { num: fps, denom: 1 } - ), - )))?; + let formats = enum_formats(fps, dmabuf)?; + let mut pods = formats.iter().map(|f| pod(f)).collect::, _>>()?; stream .connect( pw::spa::utils::Direction::Input, Some(node), pw::stream::StreamFlags::AUTOCONNECT | pw::stream::StreamFlags::MAP_BUFFERS, - &mut [pod(&format)?], + &mut pods, ) .map_err(|e| format!("cannot connect to the screen cast node {node}: {e}"))?; Ok((stream, listener)) } -/// Copy one shared-memory buffer into a frame. `None` for buffers without -/// mapped data (DMA-BUF), empty or corrupted chunks, and unknown formats. -fn copy_frame( - data: &mut pw::spa::buffer::Data, - format: VideoFormat, - width: u32, - height: u32, -) -> Option { - let bgra = match format { +fn size_range() -> Property { + property!( + FormatProperties::VideoSize, + Choice, + Range, + Rectangle, + Rectangle { width: 1920, height: 1080 }, + Rectangle { width: 1, height: 1 }, + Rectangle { width: 16384, height: 16384 } + ) +} + +/// Up to `fps`, as the compositor can (it sends frames on damage only). +fn framerate_range(fps: u32) -> Property { + property!( + FormatProperties::VideoFramerate, + Choice, + Range, + Fraction, + Fraction { num: fps, denom: 1 }, + Fraction { num: 0, denom: 1 }, + Fraction { num: fps, denom: 1 } + ) +} + +fn modifier_property(fixed: bool) -> Property { + let flags = pw::spa::sys::SPA_POD_PROP_FLAG_MANDATORY + | if fixed { 0 } else { pw::spa::sys::SPA_POD_PROP_FLAG_DONT_FIXATE }; + let value = if fixed { + Value::Long(MODIFIER_LINEAR) + } else { + Value::Choice(ChoiceValue::Long(Choice( + ChoiceFlags::empty(), + ChoiceEnum::Enum { default: MODIFIER_LINEAR, alternatives: vec![MODIFIER_LINEAR] }, + ))) + }; + Property { + key: FormatProperties::VideoModifier.as_raw(), + flags: PropertyFlags::from_bits_retain(flags), + value, + } +} + +fn format_object(properties: Vec) -> Value { + Value::Object(Object { + type_: SpaTypes::ObjectParamFormat.as_raw(), + id: pw::spa::param::ParamType::EnumFormat.as_raw(), + properties, + }) +} + +/// The formats we offer: each pixel format as a LINEAR DMA-BUF (if +/// `dmabuf`), then all of them in shared memory. +fn enum_formats(fps: u32, dmabuf: bool) -> std::result::Result>, String> { + let mut formats = Vec::new(); + let base = || { + vec![ + property!(FormatProperties::MediaType, Id, MediaType::Video), + property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw), + ] + }; + if dmabuf { + for format in FORMATS { + let mut properties = base(); + properties.push(property!(FormatProperties::VideoFormat, Id, format)); + properties.push(modifier_property(false)); + properties.push(size_range()); + properties.push(framerate_range(fps)); + formats.push(serialize(format_object(properties))?); + } + } + let mut properties = base(); + properties.push(property!( + FormatProperties::VideoFormat, + Choice, + Enum, + Id, + FORMATS[0], + FORMATS[0], + FORMATS[1], + FORMATS[2], + FORMATS[3] + )); + properties.push(size_range()); + properties.push(framerate_range(fps)); + formats.push(serialize(format_object(properties))?); + Ok(formats) +} + +/// Offer formats again (another frame rate, or no DMA-BUFs); PipeWire +/// renegotiates. +fn renegotiate(stream: &pw::stream::Stream, fps: u32, dmabuf: bool) { + let result = enum_formats(fps, dmabuf).and_then(|formats| { + let mut pods = + formats.iter().map(|f| pod(f)).collect::, _>>()?; + stream.update_params(&mut pods).map_err(|e| e.to_string()) + }); + if let Err(e) = result { + warn!("cannot renegotiate the screen capture format: {e}"); + } +} + +fn format_changed( + stream: &pw::stream::Stream, + state: &mut VideoState, + param: &Pod, +) -> std::result::Result<(), String> { + let Ok((MediaType::Video, MediaSubtype::Raw)) = + pw::spa::param::format_utils::parse_format(param) + else { + return Ok(()); + }; + let mut info = VideoInfoRaw::new(); + info.parse(param).map_err(|e| format!("cannot parse the video format: {e}"))?; + let size = info.size(); + state.maps.clear(); + let modifier = param + .as_object() + .ok() + .and_then(|o| o.find_prop(Id(FormatProperties::VideoModifier.as_raw()))); + let modifier = match modifier { + Some(prop) if prop.flags().contains(PodPropFlags::DONT_FIXATE) => { + // The producer left the choice to us; we only take LINEAR. + let mut properties = vec![ + property!(FormatProperties::MediaType, Id, MediaType::Video), + property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw), + property!(FormatProperties::VideoFormat, Id, info.format()), + modifier_property(true), + property!( + FormatProperties::VideoSize, + Rectangle, + Rectangle { width: size.width, height: size.height } + ), + ]; + properties.push(framerate_range(state.fps)); + let fixed = serialize(format_object(properties))?; + stream.update_params(&mut [pod(&fixed)?]).map_err(|e| e.to_string())?; + return Ok(()); + } + Some(prop) => Some(prop.value().get_long().unwrap_or(MODIFIER_LINEAR)), + None => None, + }; + debug!(format = ?info.format(), size.width, size.height, ?modifier, "screen capture format"); + state.format = Some(Negotiated { + format: info.format(), + width: size.width, + height: size.height, + modifier, + }); + let types = if modifier.is_some() { + 1 << pw::spa::sys::SPA_DATA_DmaBuf + } else { + (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![Property { + key: pw::spa::sys::SPA_PARAM_BUFFERS_dataType, + flags: PropertyFlags::empty(), + value: Value::Int(types as i32), + }], + }))?; + stream.update_params(&mut [pod(&buffers)?]).map_err(|e| e.to_string()) +} + +fn process(stream: &pw::stream::Stream, state: &mut VideoState) { + // Follow the sink's frame rate: ask the compositor for another rate. + let fps = state.sink.max_fps().max(1); + if fps != state.fps { + state.fps = fps; + renegotiate(stream, fps, state.dmabuf); + } + let Some(mut buffer) = stream.dequeue_buffer() else { return }; + let Some(format) = state.format else { return }; + if format.modifier.is_some_and(|m| m != MODIFIER_LINEAR) { + // Tiled: the CPU cannot read it (we never offer that). + return; + } + let timestamp = state.started.elapsed(); + if !state.sink.wants(timestamp) { + // Dropping the buffer queues it back. + return; + } + let Some(data) = buffer.datas_mut().first_mut() else { return }; + let bgra = match format.format { VideoFormat::BGRx | VideoFormat::BGRA => true, VideoFormat::RGBx | VideoFormat::RGBA => false, - _ => return None, + _ => return, }; let chunk = data.chunk(); if chunk.size() == 0 || chunk.flags().contains(pw::spa::buffer::ChunkFlags::CORRUPTED) { - return None; + return; } let offset = chunk.offset() as usize; - let row = width as usize * 4; + let row = format.width as usize * 4; let stride = usize::try_from(chunk.stride()).ok().filter(|&s| s >= row).unwrap_or(row); - let bytes = data.data()?; - let bytes = bytes.get(offset..)?; - let needed = stride * (height as usize).checked_sub(1)? + row; - if bytes.len() < needed { - return None; + let needed = offset + stride * (format.height as usize).saturating_sub(1) + row; + fn view( + bytes: &[u8], + at: (usize, usize, bool), + format: Negotiated, + t: Duration, + ) -> Option> { + let (offset, stride, bgra) = at; + let plane = PlaneRef::new(bytes.get(offset..)?, stride); + let pixels = if bgra { PixelsRef::Bgra(plane) } else { PixelsRef::Rgba(plane) }; + Some(FrameRef { width: format.width, height: format.height, timestamp: t, pixels }) } - let mut pixels = Vec::with_capacity(row * height as usize); - for y in 0..height as usize { - pixels.extend_from_slice(&bytes[y * stride..y * stride + row]); + let at = (offset, stride, bgra); + let is_dmabuf = data.type_() == DataType::DmaBuf; + if state.logged != Some(is_dmabuf) { + state.logged = Some(is_dmabuf); + debug!(dmabuf = is_dmabuf, "screen capture buffers"); } - let frame = if bgra { - VideoFrame::from_bgra(width, height, row, pixels) + let started = Instant::now(); + let more = if is_dmabuf { + let raw = data.as_raw(); + let len = (raw.mapoffset + raw.maxsize) as usize; + let fd = data.fd(); + if !state.maps.iter().any(|m| m.fd() == fd && m.len() >= len) { + state.maps.retain(|m| m.fd() != fd); + match DmaBufMap::new(fd, len) { + Ok(map) => state.maps.push(map), + Err(e) => { + warn!("cannot map a screen capture DMA-BUF: {e}"); + return; + } + } + } + let map = state.maps.iter().find(|m| m.fd() == fd).expect("mapped above"); + let base = raw.mapoffset as usize; + map.read(|bytes| { + match bytes + .get(base..) + .filter(|b| b.len() >= needed) + .and_then(|b| view(b, at, format, timestamp)) + { + Some(frame) => state.sink.frame(frame), + None => true, + } + }) } else { - VideoFrame::from_rgba(width, height, row, pixels) + match data.data().filter(|b| b.len() >= needed).and_then(|b| view(b, at, format, timestamp)) + { + Some(frame) => state.sink.frame(frame), + None => true, + } }; - frame.ok() + if is_dmabuf && state.dmabuf { + probe_dmabuf(stream, state, started.elapsed(), format); + } + if !more && let Some(mainloop) = state.mainloop.upgrade() { + // Nobody takes frames any more. + mainloop.quit(); + } +} + +/// Time the first DMA-BUF frames; if reading them is slow, offer shared +/// memory only. +fn probe_dmabuf( + stream: &pw::stream::Stream, + state: &mut VideoState, + took: Duration, + format: Negotiated, +) { + if state.dmabuf_frames >= DMABUF_PROBE_FRAMES { + return; + } + state.dmabuf_frames += 1; + state.dmabuf_time += took; + if state.dmabuf_frames < DMABUF_PROBE_FRAMES { + return; + } + let pixels = f64::from(format.width) * f64::from(format.height); + let per_pixel = state.dmabuf_time.as_secs_f64() * 1e9 / f64::from(DMABUF_PROBE_FRAMES) / pixels; + if per_pixel > SLOW_DMABUF_NS_PER_PIXEL { + tracing::info!( + "reading DMA-BUFs takes {per_pixel:.1} ns per pixel; switching screen capture to shared memory" + ); + state.dmabuf = false; + renegotiate(stream, state.fps, false); + } } #[cfg(test)] @@ -378,4 +655,28 @@ mod tests { assert!(!PortalCapture::is_available().await); assert!(capture.restore_token().is_none()); } + + /// The offered formats parse back: DMA-BUF (mandatory LINEAR modifier, + /// left to us to fixate) per pixel format, then shared memory. + #[test] + fn offered_formats() { + let formats = enum_formats(60, true).unwrap(); + assert_eq!(formats.len(), FORMATS.len() + 1); + for (i, bytes) in formats.iter().enumerate() { + let object = pod(bytes).unwrap().as_object().unwrap(); + let modifier = object.find_prop(Id(FormatProperties::VideoModifier.as_raw())); + if i < FORMATS.len() { + let flags = modifier.expect("a modifier").flags(); + assert!(flags.contains(PodPropFlags::MANDATORY | PodPropFlags::DONT_FIXATE)); + } else { + assert!(modifier.is_none(), "shared memory has no modifier"); + } + } + assert_eq!(enum_formats(30, false).unwrap().len(), 1); + let fixed = serialize(format_object(vec![modifier_property(true)])).unwrap(); + let object = pod(&fixed).unwrap().as_object().unwrap(); + let prop = object.find_prop(Id(FormatProperties::VideoModifier.as_raw())).unwrap(); + assert_eq!(prop.value().get_long().unwrap(), MODIFIER_LINEAR); + assert!(!prop.flags().contains(PodPropFlags::DONT_FIXATE)); + } } diff --git a/crates/voelin-media/src/capture/synthetic.rs b/crates/voelin-media/src/capture/synthetic.rs index 63f8618..c9b71b5 100644 --- a/crates/voelin-media/src/capture/synthetic.rs +++ b/crates/voelin-media/src/capture/synthetic.rs @@ -1,13 +1,15 @@ -//! Synthetic sources for tests and `--synthetic` streaming: an animated test -//! pattern (a rectangle moving over a flat background, plus a frame counter) -//! and a sine tone. +//! Synthetic sources for tests, benchmarks and `--synthetic` streaming: an +//! animated test pattern (a rectangle moving over a flat background, or over +//! a desktop-like picture, plus a frame counter) and a sine tone. -use std::time::Duration; +use std::sync::Arc; +use std::time::{Duration, Instant}; use crate::capture::{ - AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, Ticker, Worker, + AudioCapture, BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture, + SourceId, Ticker, Worker, }; -use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, VideoFrame}; +use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, FrameRef, PixelsRef, PlaneRef, VideoFrame}; use crate::queue::{FrameReceiver, frame_channel}; use crate::{Error, Result}; @@ -32,16 +34,224 @@ const DIGITS: [[u8; 5]; 10] = [ [7, 5, 7, 1, 7], ]; +/// What the test pattern shows. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Pattern { + /// A flat background, the moving rectangle and a frame counter: cheap to + /// encode and easy to check after decoding. + #[default] + Simple, + /// Like a desktop with a code editor: a title bar with a gradient, a side + /// bar, lines of coloured text in a document that scrolls three pixels + /// per frame, a status bar, and the moving rectangle and frame counter on + /// top. Costs an encoder about as much as real screen content (for + /// benchmarks). + Desktop, +} + +/// A rectangle: `(x, y, width, height)`. +type Rect = (usize, usize, usize, usize); + +fn bgra(c: [u8; 3]) -> [u8; 4] { + [c[2], c[1], c[0], 255] +} + +/// Fill a rectangle of a BGRA image (`width` pixels per row), clipped. +fn fill(data: &mut [u8], width: usize, rect: Rect, color: [u8; 3]) { + let rows = data.len() / (width * 4).max(1); + let (x0, y0, w, h) = rect; + let x1 = (x0 + w).min(width); + if x0 >= x1 { + return; + } + let px = bgra(color); + for y in y0..(y0 + h).min(rows) { + for d in data[(y * width + x0) * 4..(y * width + x1) * 4].chunks_exact_mut(4) { + d.copy_from_slice(&px); + } + } +} + +/// Draw one 3x5 glyph at `scale` pixels per dot. +fn glyph( + data: &mut [u8], + width: usize, + at: (usize, usize), + scale: usize, + bitmap: [u8; 5], + color: [u8; 3], +) { + for (row, bits) in bitmap.iter().enumerate() { + for col in 0..3 { + if bits & (4 >> col) != 0 { + fill(data, width, (at.0 + col * scale, at.1 + row * scale, scale, scale), color); + } + } + } +} + +/// Draw the decimal digits of `n`. +fn number(data: &mut [u8], width: usize, at: (usize, usize), scale: usize, n: u64, color: [u8; 3]) { + let mut digits = [0u8; 20]; + let (mut rest, mut len) = (n, 0); + loop { + digits[len] = (rest % 10) as u8; + len += 1; + rest /= 10; + if rest == 0 { + break; + } + } + for i in 0..len { + let bitmap = DIGITS[usize::from(digits[len - 1 - i])]; + glyph(data, width, (at.0 + i * 4 * scale, at.1), scale, bitmap, color); + } +} + +/// A small deterministic generator (xorshift64). +struct Rng(u64); + +impl Rng { + fn below(&mut self, n: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 % n.max(1) as u64) as usize + } +} + +/// Lines of "code" in `area`: words of glyphs in the palette's colours, +/// indented, some lines empty. +fn text_lines( + data: &mut [u8], + width: usize, + area: Rect, + scale: usize, + palette: &[[u8; 3]], + rng: &mut Rng, +) { + let (ax, ay, aw, ah) = area; + let (advance, pitch) = (4 * scale, 8 * scale); + let columns = aw.saturating_sub(2 * advance) / advance; + let mut y = ay + 2 * scale; + while columns > 0 && y + pitch <= ay + ah { + let indent = rng.below(4) * 2; + let end = if rng.below(6) == 0 { 0 } else { indent + 4 + rng.below(columns) }; + let mut col = indent; + while col < end.min(columns) { + let word = 2 + rng.below(8); + let color = palette[rng.below(palette.len())]; + for _ in 0..word.min(columns - col) { + let x = ax + advance + col * advance; + glyph(data, width, (x, y), scale, DIGITS[rng.below(10)], color); + col += 1; + } + col += 1; + } + y += pitch; + } +} + +/// The parts of [`Pattern::Desktop`] that do not change, rendered once: the +/// page, and the document that scrolls through the editor area. +struct Desktop { + page: Vec, + editor: Rect, + /// `editor.2` pixels wide, twice the editor's height (it wraps around). + document: Vec, + document_rows: usize, +} + +impl Desktop { + fn render(width: usize, height: usize) -> Self { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let scale = (height / 540).max(1); + let mut page = vec![0; width * height * 4]; + let title = (height / 20).max(4); + let status = (height / 40).max(2); + let side = width / 5; + // Title bar: a vertical gradient with tabs. + for y in 0..title { + let t = y * 255 / title; + let c = [(40 + t / 8) as u8, (60 + t / 6) as u8, (110 + t / 4) as u8]; + fill(&mut page, width, (0, y, width, 1), c); + } + for tab in 0..6 { + let tab = (side + tab * width / 8, title / 3, width / 9, title - title / 3); + fill(&mut page, width, tab, [30, 30, 30]); + text_lines(&mut page, width, tab, scale, &[[200, 200, 200]], &mut rng); + } + // Side bar with a file list, status bar. + let sidebar = (0, title, side, height - title - status); + fill(&mut page, width, sidebar, [37, 37, 38]); + let palette = [[204, 204, 204], [150, 150, 150], [230, 200, 120]]; + text_lines(&mut page, width, sidebar, scale, &palette, &mut rng); + fill(&mut page, width, (0, height - status, width, status), [0, 122, 204]); + // The editor's document. + let editor = (side, title, width - side, height - title - status); + let document_rows = editor.3 * 2; + let mut document = vec![0; editor.2 * document_rows * 4]; + fill(&mut document, editor.2, (0, 0, editor.2, document_rows), [30, 30, 30]); + let palette = + [[212, 212, 212], [86, 156, 214], [206, 145, 120], [106, 153, 85], [197, 134, 192]]; + text_lines( + &mut document, + editor.2, + (0, 0, editor.2, document_rows), + scale, + &palette, + &mut rng, + ); + Self { page, editor, document, document_rows } + } + + /// The page with the document scrolled by `offset` rows. + fn draw(&self, out: &mut [u8], width: usize, offset: usize) { + out[..self.page.len()].copy_from_slice(&self.page); + let (ex, ey, ew, eh) = self.editor; + for row in 0..eh { + let src = (offset + row) % self.document_rows * ew * 4; + let dst = ((ey + row) * width + ex) * 4; + out[dst..dst + ew * 4].copy_from_slice(&self.document[src..src + ew * 4]); + } + } +} + /// The test pattern as a [`ScreenCapture`] backend. pub struct SyntheticScreen { width: u32, height: u32, + pattern: Pattern, + desktop: Option>, worker: Option, } impl SyntheticScreen { pub fn new(width: u32, height: u32) -> Self { - Self { width: width.max(16), height: height.max(16), worker: None } + Self::with_pattern(width, height, Pattern::Simple) + } + + /// A test pattern of another kind. + pub fn with_pattern(width: u32, height: u32, pattern: Pattern) -> Self { + let (width, height) = (width.max(16), height.max(16)); + let desktop = (pattern == Pattern::Desktop) + .then(|| Arc::new(Desktop::render(width as usize, height as usize))); + Self { width, height, pattern, desktop, worker: None } + } + + pub fn pattern(&self) -> Pattern { + self.pattern + } + + /// Another source drawing the same pattern. + fn same_pattern(&self) -> Self { + Self { + width: self.width, + height: self.height, + pattern: self.pattern, + desktop: self.desktop.clone(), + worker: None, + } } /// The moving rectangle in frame `n`: `(x, y, width, height)`. @@ -55,40 +265,38 @@ impl SyntheticScreen { (x as u32, (self.height - rh) / 2, rw, rh) } - /// Frame `n` as BGRA, stamped `n / fps` seconds. - pub fn frame(&self, n: u64, fps: u32) -> VideoFrame { + /// Draw frame `n` as BGRA (`width * 4` bytes per row) into `out`, reusing + /// its memory. + pub fn render(&self, n: u64, out: &mut Vec) { let (w, h) = (self.width as usize, self.height as usize); - let mut data = vec![0; w * h * 4]; - let bgra = |c: [u8; 3]| [c[2], c[1], c[0], 255]; - for px in data.chunks_exact_mut(4) { - px.copy_from_slice(&bgra(BACKGROUND)); - } - let mut fill = |x0: usize, y0: usize, rw: usize, rh: usize, c: [u8; 3]| { - for y in y0..(y0 + rh).min(h) { - for x in x0..(x0 + rw).min(w) { - data[(y * w + x) * 4..][..4].copy_from_slice(&bgra(c)); + out.resize(w * h * 4, 0); + match &self.desktop { + Some(desktop) => desktop.draw(out, w, n as usize * 3), + None => { + // One row, then copies of it. + let px = bgra(BACKGROUND); + for d in out[..w * 4].chunks_exact_mut(4) { + d.copy_from_slice(&px); + } + let (first, rest) = out.split_at_mut(w * 4); + for row in rest.chunks_exact_mut(w * 4) { + row.copy_from_slice(first); } } - }; + } let (rx, ry, rw, rh) = self.rect(n); - fill(rx as usize, ry as usize, rw as usize, rh as usize, RECT_COLOR); - + fill(out, w, (rx as usize, ry as usize, rw as usize, rh as usize), RECT_COLOR); // Frame counter in the top-left corner. let scale = (h / 48).max(1); - for (i, digit) in n.to_string().bytes().enumerate() { - let bitmap = DIGITS[usize::from(digit - b'0')]; - let x0 = scale * 2 + i * 4 * scale; - for (row, bits) in bitmap.iter().enumerate() { - for col in 0..3 { - if bits & (4 >> col) != 0 { - let (x, y) = (x0 + col * scale, scale * 2 + row * scale); - fill(x, y, scale, scale, TEXT_COLOR); - } - } - } - } + number(out, w, (scale * 2, scale * 2), scale, n, TEXT_COLOR); + } + + /// Frame `n` as BGRA, stamped `n / fps` seconds. + pub fn frame(&self, n: u64, fps: u32) -> VideoFrame { + let mut data = Vec::new(); + self.render(n, &mut data); let timestamp = Duration::from_secs(n) / fps.max(1); - VideoFrame::from_bgra(self.width, self.height, w * 4, data) + VideoFrame::from_bgra(self.width, self.height, self.width as usize * 4, data) .expect("pattern buffer matches its size") .with_timestamp(timestamp) } @@ -114,24 +322,58 @@ impl ScreenCapture for SyntheticScreen { source: &SourceId, options: &CaptureOptions, ) -> BoxFuture<'_, Result>> { + let (sink, rx) = QueueSink::new(options); + let started = self.start_sink(source, options, Box::new(sink)); + Box::pin(async move { + started.await?; + Ok(rx) + }) + } + + /// Draws frame after frame into one buffer, at [`FrameSink::max_fps`]; + /// timestamps are the time since the start. + fn start_sink( + &mut self, + source: &SourceId, + _options: &CaptureOptions, + mut sink: Box, + ) -> BoxFuture<'_, Result<()>> { let source = source.clone(); - let options = options.clone(); Box::pin(async move { if source != SourceId::Synthetic { return Err(Error::SourceNotFound(source)); } self.stop(); - let (tx, rx) = frame_channel(options.queue); - let pattern = SyntheticScreen::new(self.width, self.height); - let fps = options.fps; + let pattern = self.same_pattern(); self.worker = Some(Worker::spawn("voelin-synthetic-video", move |stop| { + let (width, height) = (pattern.width, pattern.height); + let mut fps = sink.max_fps(); let mut ticker = Ticker::new(fps); + let mut buffer = Vec::new(); + let started = Instant::now(); let mut n = 0; - while tx.send(pattern.frame(n, fps)) && ticker.wait(&stop) { - n += 1; + loop { + let timestamp = started.elapsed(); + if sink.wants(timestamp) { + pattern.render(n, &mut buffer); + let plane = PlaneRef::new(&buffer, width as usize * 4); + let frame = + FrameRef { width, height, timestamp, pixels: PixelsRef::Bgra(plane) }; + if !sink.frame(frame) { + break; + } + n += 1; + } + if sink.max_fps() != fps { + fps = sink.max_fps(); + ticker.set_fps(fps); + } + if !ticker.wait(&stop) { + break; + } } })?); - Ok(rx) + Ok(()) }) } @@ -225,6 +467,29 @@ mod tests { } } + #[test] + fn desktop_pattern_scrolls() { + let screen = SyntheticScreen::with_pattern(640, 360, Pattern::Desktop); + assert_eq!(screen.pattern(), Pattern::Desktop); + let (mut a, mut b) = (Vec::new(), Vec::new()); + screen.render(1, &mut a); + screen.render(2, &mut b); + assert_eq!(a.len(), 640 * 360 * 4); + // The editor (right of the side bar, below the title bar) scrolled. + let row = |data: &[u8], y: usize| data[(y * 640 + 200) * 4..(y * 640 + 600) * 4].to_vec(); + let differs = (40..340).any(|y| row(&a, y) != row(&b, y)); + assert!(differs); + // Lots of detail: many distinct colours in the editor. + let mut colours: Vec<&[u8]> = a.chunks_exact(4).collect(); + colours.sort_unstable(); + colours.dedup(); + assert!(colours.len() >= 8, "{} colours", colours.len()); + // Rendering reuses the buffer. + let capacity = a.capacity(); + screen.render(3, &mut a); + assert_eq!(a.capacity(), capacity); + } + #[test] fn sine_is_continuous() { let tone = SineSource::new(1000.0, 0.5); diff --git a/crates/voelin-media/src/capture/windows.rs b/crates/voelin-media/src/capture/windows.rs index 1940b34..75fcc9f 100644 --- a/crates/voelin-media/src/capture/windows.rs +++ b/crates/voelin-media/src/capture/windows.rs @@ -10,7 +10,7 @@ use std::collections::VecDeque; use std::sync::atomic::Ordering; -use std::time::{Duration, Instant}; +use std::time::Instant; use tracing::warn; use windows_capture::capture::{CaptureControl, Context, GraphicsCaptureApiHandler}; @@ -24,9 +24,10 @@ use windows_capture::settings::{ use windows_capture::window::Window; use crate::capture::{ - AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, Worker, + AudioCapture, BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture, + SourceId, Worker, }; -use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, VideoFrame}; +use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, FrameRef, PixelsRef, PlaneRef, VideoFrame}; use crate::queue::{FrameReceiver, FrameSender, frame_channel}; use crate::{Error, Result}; @@ -36,20 +37,20 @@ fn failed(e: impl std::fmt::Display) -> Error { Error::Capture { backend: BACKEND, message: e.to_string() } } -/// Receives frames on the capture thread. +/// Receives frames on the capture thread and hands the mapped staging +/// texture (with its row pitch) to the sink. struct Handler { - tx: FrameSender, + sink: Box, started: Instant, - scratch: Vec, } impl GraphicsCaptureApiHandler for Handler { - type Flags = (FrameSender, Instant); + type Flags = (Box, Instant); type Error = String; fn new(ctx: Context) -> std::result::Result { - let (tx, started) = ctx.flags; - Ok(Self { tx, started, scratch: Vec::new() }) + let (sink, started) = ctx.flags; + Ok(Self { sink, started }) } fn on_frame_arrived( @@ -57,12 +58,18 @@ impl GraphicsCaptureApiHandler for Handler { frame: &mut Frame, control: InternalCaptureControl, ) -> std::result::Result<(), Self::Error> { - let buffer = frame.buffer().map_err(|e| e.to_string())?; - let (w, h) = (buffer.width(), buffer.height()); - let pixels = buffer.as_nopadding_buffer(&mut self.scratch).to_vec(); - let frame = - VideoFrame::from_bgra(w, h, w as usize * 4, pixels).map_err(|e| e.to_string())?; - if !self.tx.send(frame.with_timestamp(self.started.elapsed())) { + let timestamp = self.started.elapsed(); + // Frames come as the screen changes, up to its refresh rate; the + // sink's cap decides before anything is copied off the GPU. + if !self.sink.wants(timestamp) { + return Ok(()); + } + let mut buffer = frame.buffer().map_err(|e| e.to_string())?; + let (width, height) = (buffer.width(), buffer.height()); + let pitch = buffer.row_pitch() as usize; + let plane = PlaneRef::new(buffer.as_raw_buffer(), pitch); + let frame = FrameRef { width, height, timestamp, pixels: PixelsRef::Bgra(plane) }; + if !self.sink.frame(frame) { control.stop(); } Ok(()) @@ -84,11 +91,11 @@ impl WindowsCapture { fn start_item( item: T, options: &CaptureOptions, -) -> Result<(CaptureControl, FrameReceiver)> + sink: Box, +) -> Result> where T: TryInto + Send + 'static, { - let (tx, rx) = frame_channel(options.queue); let cursor = if options.cursor { CursorCaptureSettings::WithCursor } else { @@ -99,13 +106,13 @@ where cursor, DrawBorderSettings::WithoutBorder, SecondaryWindowSettings::Default, - MinimumUpdateIntervalSettings::Custom(Duration::from_secs(1) / options.fps.max(1)), + // No minimum: the frame rate can change while capturing. + MinimumUpdateIntervalSettings::Default, DirtyRegionSettings::Default, ColorFormat::Bgra8, - (tx, Instant::now()), + (sink, Instant::now()), ); - let control = Handler::start_free_threaded(settings).map_err(failed)?; - Ok((control, rx)) + Handler::start_free_threaded(settings).map_err(failed) } impl ScreenCapture for WindowsCapture { @@ -147,27 +154,41 @@ impl ScreenCapture for WindowsCapture { source: &SourceId, options: &CaptureOptions, ) -> BoxFuture<'_, Result>> { + let (sink, rx) = QueueSink::new(options); + let started = self.start_sink(source, options, Box::new(sink)); + Box::pin(async move { + started.await?; + Ok(rx) + }) + } + + fn start_sink( + &mut self, + source: &SourceId, + options: &CaptureOptions, + sink: Box, + ) -> BoxFuture<'_, Result<()>> { let source = source.clone(); let options = options.clone(); Box::pin(async move { self.stop(); let not_found = || Error::SourceNotFound(source.clone()); - let (control, rx) = match source { + let control = match source { SourceId::Monitor(index) => { let monitor = Monitor::from_index(index as usize).map_err(|_| not_found())?; - start_item(monitor, &options)? + start_item(monitor, &options, sink)? } SourceId::Window(hwnd) => { let window = Window::from_raw_hwnd(hwnd as usize as *mut std::ffi::c_void); if !window.is_valid() { return Err(not_found()); } - start_item(window, &options)? + start_item(window, &options, sink)? } _ => return Err(not_found()), }; self.control = Some(control); - Ok(rx) + Ok(()) }) } diff --git a/crates/voelin-media/src/capture/wlroots.rs b/crates/voelin-media/src/capture/wlroots.rs new file mode 100644 index 0000000..00fd467 --- /dev/null +++ b/crates/voelin-media/src/capture/wlroots.rs @@ -0,0 +1,679 @@ +//! Screen capture on wlroots compositors (Sway, Hyprland, river, labwc, ...) +//! straight through Wayland, without the portal: `ext-image-copy-capture-v1` +//! with `ext-output-image-capture-source-v1` where the compositor has it, +//! else `wlr-screencopy-unstable-v1`. +//! +//! Frames are copied by the compositor into shared-memory buffers we +//! allocate once (a memfd per buffer size) and handed to the +//! [`FrameSink`] straight from that mapping. Both protocols wait for the +//! screen to change before they complete a frame (`copy_with_damage`), so a +//! still screen costs nothing; the frame rate is capped by +//! [`FrameSink::max_fps`]. Monitors only (window capture needs +//! `ext-foreign-toplevel-list`, not done). DMA-BUF capture is not done: +//! frames are always in shared memory. + +use std::os::fd::AsFd; +use std::os::unix::net::UnixStream; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +use memmap2::MmapMut; +use tracing::{debug, warn}; +use wayland_client::globals::{GlobalList, GlobalListContents, registry_queue_init}; +use wayland_client::protocol::{wl_buffer, wl_output, wl_registry, wl_shm, wl_shm_pool}; +use wayland_client::{Connection, Dispatch, EventQueue, Proxy, QueueHandle, WEnum, delegate_noop}; +use wayland_protocols::ext::image_capture_source::v1::client::{ + ext_image_capture_source_v1, ext_output_image_capture_source_manager_v1, +}; +use wayland_protocols::ext::image_copy_capture::v1::client::{ + ext_image_copy_capture_frame_v1, ext_image_copy_capture_manager_v1, + ext_image_copy_capture_session_v1, +}; +use wayland_protocols_wlr::screencopy::v1::client::{ + zwlr_screencopy_frame_v1, zwlr_screencopy_manager_v1, +}; + +use crate::capture::{ + BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture, SourceId, Worker, +}; +use crate::frame::{FrameRef, PixelsRef, PlaneRef, VideoFrame}; +use crate::queue::FrameReceiver; +use crate::{Error, Result}; + +const BACKEND: &str = "wlroots"; +/// How long the compositor may take to describe buffers. +const SETUP_TIMEOUT: Duration = Duration::from_secs(5); +/// How often waits check whether to stop. +const POLL: Duration = Duration::from_millis(100); +/// Failed frames in a row before the capture gives up. +const MAX_FAILURES: u32 = 20; + +fn unavailable(e: impl std::fmt::Display) -> Error { + Error::CaptureUnavailable { backend: BACKEND, reason: e.to_string() } +} + +fn failed(e: impl std::fmt::Display) -> Error { + Error::Capture { backend: BACKEND, message: e.to_string() } +} + +/// A monitor as the compositor describes it. +#[derive(Clone, Debug, Default)] +struct Output { + name: Option, + description: Option, + mode: (i32, i32), +} + +/// What the compositor said about the frame being captured. +#[derive(Debug, Default)] +struct Frame { + /// Offered shared-memory formats we can read. + formats: Vec, + size: (u32, u32), + /// wlr-screencopy tells the stride; ext-image-copy-capture leaves it to + /// us. + stride: u32, + /// The buffer description is complete. + described: bool, + y_invert: bool, + ready: bool, + failed: Option, + /// The capture session ended (ext): the output went away. + stopped: bool, +} + +#[derive(Default)] +struct State { + outputs: Vec<(wl_output::WlOutput, Output)>, + frame: Frame, +} + +impl Dispatch for State { + fn event( + _: &mut Self, + _: &wl_registry::WlRegistry, + _: wl_registry::Event, + _: &GlobalListContents, + _: &Connection, + _: &QueueHandle, + ) { + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _: &wl_output::WlOutput, + event: wl_output::Event, + index: &usize, + _: &Connection, + _: &QueueHandle, + ) { + let Some((_, output)) = state.outputs.get_mut(*index) else { return }; + match event { + wl_output::Event::Mode { flags: WEnum::Value(flags), width, height, .. } + if flags.contains(wl_output::Mode::Current) => + { + output.mode = (width, height); + } + wl_output::Event::Name { name } => output.name = Some(name), + wl_output::Event::Description { description } => { + output.description = Some(description); + } + _ => {} + } + } +} + +delegate_noop!(State: ignore wl_shm::WlShm); +delegate_noop!(State: ignore wl_shm_pool::WlShmPool); +delegate_noop!(State: ignore wl_buffer::WlBuffer); +delegate_noop!(State: ignore zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1); +delegate_noop!(State: ignore ext_image_copy_capture_manager_v1::ExtImageCopyCaptureManagerV1); +delegate_noop!(State: ignore ext_output_image_capture_source_manager_v1::ExtOutputImageCaptureSourceManagerV1); +delegate_noop!(State: ignore ext_image_capture_source_v1::ExtImageCaptureSourceV1); + +/// Shared-memory formats we read, best first, and whether they are BGRA in +/// memory (else RGBA). +const FORMATS: [(wl_shm::Format, bool); 4] = [ + (wl_shm::Format::Xrgb8888, true), + (wl_shm::Format::Argb8888, true), + (wl_shm::Format::Xbgr8888, false), + (wl_shm::Format::Abgr8888, false), +]; + +fn supported(format: WEnum) -> Option { + match format { + WEnum::Value(f) if FORMATS.iter().any(|(s, _)| *s == f) => Some(f), + _ => None, + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + frame: &zwlr_screencopy_frame_v1::ZwlrScreencopyFrameV1, + event: zwlr_screencopy_frame_v1::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + use zwlr_screencopy_frame_v1::Event; + let f = &mut state.frame; + match event { + Event::Buffer { format, width, height, stride } => { + if let Some(format) = supported(format) { + f.formats.push(format); + f.size = (width, height); + f.stride = stride; + } + // Before version 3 there is exactly one buffer event. + if frame.version() < 3 { + f.described = true; + } + } + Event::BufferDone => f.described = true, + Event::Flags { flags } => { + f.y_invert = matches!(flags, WEnum::Value(v) if v.contains(zwlr_screencopy_frame_v1::Flags::YInvert)); + } + Event::Ready { .. } => f.ready = true, + Event::Failed => f.failed = Some("the compositor could not copy the frame".into()), + _ => {} + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _: &ext_image_copy_capture_session_v1::ExtImageCopyCaptureSessionV1, + event: ext_image_copy_capture_session_v1::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + use ext_image_copy_capture_session_v1::Event; + let f = &mut state.frame; + match event { + Event::BufferSize { width, height } => { + // A new description starts (e.g. the output was resized). + f.described = false; + f.formats.clear(); + f.size = (width, height); + f.stride = width * 4; + } + Event::ShmFormat { format } => { + if let Some(format) = supported(format) { + f.formats.push(format); + } + } + Event::Done => f.described = true, + Event::Stopped => f.stopped = true, + _ => {} + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _: &ext_image_copy_capture_frame_v1::ExtImageCopyCaptureFrameV1, + event: ext_image_copy_capture_frame_v1::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + use ext_image_copy_capture_frame_v1::{Event, FailureReason}; + let f = &mut state.frame; + match event { + Event::Ready => f.ready = true, + Event::Failed { reason } => { + f.failed = Some(match reason { + WEnum::Value(FailureReason::BufferConstraints) => "buffer constraints".into(), + WEnum::Value(FailureReason::Stopped) => { + f.stopped = true; + "the session stopped".into() + } + _ => "the compositor could not copy the frame".into(), + }); + } + _ => {} + } + } +} + +/// A shared-memory buffer the compositor copies frames into. +struct ShmBuffer { + map: MmapMut, + pool: wl_shm_pool::WlShmPool, + buffer: wl_buffer::WlBuffer, + key: (wl_shm::Format, u32, u32, u32), +} + +impl ShmBuffer { + fn new( + shm: &wl_shm::WlShm, + qh: &QueueHandle, + format: wl_shm::Format, + (width, height): (u32, u32), + stride: u32, + ) -> Result { + let size = stride as usize * height as usize; + let fd = + rustix::fs::memfd_create("voelin-wlroots-capture", rustix::fs::MemfdFlags::CLOEXEC) + .map_err(|e| failed(format!("memfd_create: {e}")))?; + let file = std::fs::File::from(fd); + file.set_len(size as u64)?; + let map = map_shared(&file)?; + let len = i32::try_from(size).map_err(|_| failed("frame too large"))?; + let pool = shm.create_pool(file.as_fd(), len, qh, ()); + let buffer = + pool.create_buffer(0, width as i32, height as i32, stride as i32, format, qh, ()); + Ok(Self { map, pool, buffer, key: (format, width, height, stride) }) + } +} + +impl Drop for ShmBuffer { + fn drop(&mut self) { + self.buffer.destroy(); + self.pool.destroy(); + } +} + +/// Map our memfd. +#[allow(unsafe_code)] +fn map_shared(file: &std::fs::File) -> Result { + // SAFETY: memmap2 needs the file not to be truncated, and not to be + // written by others while Rust reads the mapping. The file is an + // anonymous memfd we created and never resize after mapping; the only + // other party is the compositor, which writes into it only between our + // copy request and its `ready` / `failed` event. The capture loop reads + // the mapping only after `ready`, and requests the next copy only after + // reading. + Ok(unsafe { MmapMut::map_mut(file) }?) +} + +/// The protocol the compositor offers. +enum Capturer { + Ext { + manager: ext_image_copy_capture_manager_v1::ExtImageCopyCaptureManagerV1, + sources: ext_output_image_capture_source_manager_v1::ExtOutputImageCaptureSourceManagerV1, + }, + Wlr(zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1), +} + +/// A connection with the globals we need. +struct Display { + conn: Connection, + queue: EventQueue, + state: State, + shm: wl_shm::WlShm, + capturer: Capturer, +} + +impl Display { + fn connect(socket: Option<&PathBuf>) -> Result { + let conn = match socket { + Some(path) => { + let stream = UnixStream::connect(path) + .map_err(|e| unavailable(format!("{}: {e}", path.display())))?; + Connection::from_socket(stream).map_err(unavailable)? + } + None => Connection::connect_to_env().map_err(unavailable)?, + }; + let (globals, mut queue) = registry_queue_init::(&conn).map_err(unavailable)?; + let qh = queue.handle(); + let shm: wl_shm::WlShm = globals.bind(&qh, 1..=1, ()).map_err(unavailable)?; + let capturer = match (globals.bind(&qh, 1..=1, ()), globals.bind(&qh, 1..=1, ())) { + (Ok(manager), Ok(sources)) => Capturer::Ext { manager, sources }, + _ => Capturer::Wlr(globals.bind(&qh, 1..=3, ()).map_err(|_| { + unavailable( + "the compositor has neither ext-image-copy-capture-v1 nor \ + wlr-screencopy-unstable-v1", + ) + })?), + }; + let mut state = State::default(); + bind_outputs(&globals, &qh, &mut state); + // Outputs describe themselves after binding. + queue.roundtrip(&mut state).map_err(unavailable)?; + Ok(Self { conn, queue, state, shm, capturer }) + } + + fn protocol(&self) -> &'static str { + match self.capturer { + Capturer::Ext { .. } => "ext-image-copy-capture-v1", + Capturer::Wlr(_) => "wlr-screencopy-unstable-v1", + } + } + + /// Dispatch events for up to `timeout`. + fn dispatch(&mut self, timeout: Duration) -> Result<()> { + self.queue.dispatch_pending(&mut self.state).map_err(failed)?; + self.queue.flush().map_err(failed)?; + if let Some(guard) = self.queue.prepare_read() { + let readable = { + let fd = guard.connection_fd(); + let mut fds = [rustix::event::PollFd::new(&fd, rustix::event::PollFlags::IN)]; + let timeout = rustix::event::Timespec { + tv_sec: timeout.as_secs() as _, + tv_nsec: timeout.subsec_nanos() as _, + }; + match rustix::event::poll(&mut fds, Some(&timeout)) { + Ok(n) => n > 0, + Err(rustix::io::Errno::INTR) => false, + Err(e) => return Err(failed(format!("poll: {e}"))), + } + }; + if readable { + guard.read().map_err(failed)?; + } + } + self.queue.dispatch_pending(&mut self.state).map_err(failed)?; + Ok(()) + } + + /// Dispatch until `done` holds; `false` if `stop` got set or `timeout` + /// passed first. + fn wait( + &mut self, + stop: &AtomicBool, + timeout: Option, + done: impl Fn(&Frame) -> bool, + ) -> Result { + let deadline = timeout.map(|t| Instant::now() + t); + while !done(&self.state.frame) { + if stop.load(Ordering::Relaxed) || deadline.is_some_and(|d| Instant::now() >= d) { + return Ok(false); + } + self.dispatch(POLL)?; + } + Ok(true) + } +} + +fn bind_outputs(globals: &GlobalList, qh: &QueueHandle, state: &mut State) { + let outputs: Vec<(u32, u32)> = globals.contents().with_list(|list| { + list.iter().filter(|g| g.interface == "wl_output").map(|g| (g.name, g.version)).collect() + }); + for (name, version) in outputs { + let index = state.outputs.len(); + let output: wl_output::WlOutput = globals.registry().bind(name, version.min(4), qh, index); + state.outputs.push((output, Output::default())); + } +} + +/// wlroots capture backend. Sources are the compositor's outputs, as +/// [`SourceId::Monitor`] by their order. +#[derive(Default)] +pub struct WlrootsCapture { + socket: Option, + worker: Option, +} + +impl WlrootsCapture { + /// Capture from `$WAYLAND_DISPLAY`. + pub fn new() -> Self { + Self::default() + } + + /// Capture from another Wayland display: a socket name in + /// `$XDG_RUNTIME_DIR` (`"wayland-1"`) or a path. + pub fn with_display(display: impl Into) -> Self { + let display = display.into(); + let socket = if display.is_absolute() { + display + } else { + std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).unwrap_or_default().join(display) + }; + Self { socket: Some(socket), worker: None } + } + + /// Whether the compositor offers one of the capture protocols. + pub fn is_available(&self) -> bool { + Display::connect(self.socket.as_ref()).is_ok() + } +} + +impl ScreenCapture for WlrootsCapture { + fn backend(&self) -> &'static str { + BACKEND + } + + fn sources(&mut self) -> Result> { + let display = Display::connect(self.socket.as_ref())?; + Ok(display + .state + .outputs + .iter() + .enumerate() + .map(|(i, (_, o))| CaptureSource { + id: SourceId::Monitor(i as u32), + name: o + .description + .clone() + .or_else(|| o.name.clone()) + .unwrap_or_else(|| format!("Output {}", i + 1)), + width: o.mode.0.max(0) as u32, + height: o.mode.1.max(0) as u32, + primary: i == 0, + }) + .collect()) + } + + fn start( + &mut self, + source: &SourceId, + options: &CaptureOptions, + ) -> BoxFuture<'_, Result>> { + let (sink, rx) = QueueSink::new(options); + let started = self.start_sink(source, options, Box::new(sink)); + Box::pin(async move { + started.await?; + Ok(rx) + }) + } + + fn start_sink( + &mut self, + source: &SourceId, + options: &CaptureOptions, + sink: Box, + ) -> BoxFuture<'_, Result<()>> { + let source = source.clone(); + let cursor = options.cursor; + Box::pin(async move { + self.stop(); + let SourceId::Monitor(index) = source else { + return Err(Error::SourceNotFound(source)); + }; + let socket = self.socket.clone(); + let (init_tx, init_rx) = mpsc::channel(); + self.worker = Some(Worker::spawn("voelin-wlroots-capture", move |stop| { + let display = Display::connect(socket.as_ref()).and_then(|d| { + if (index as usize) < d.state.outputs.len() { + Ok(d) + } else { + Err(Error::SourceNotFound(SourceId::Monitor(index))) + } + }); + let mut display = match display { + Ok(d) => d, + Err(e) => { + let _ = init_tx.send(Err(e)); + return; + } + }; + let protocol = display.protocol(); + debug!(protocol, output = index, "wlroots capture"); + let _ = init_tx.send(Ok(())); + if let Err(e) = capture_loop(&mut display, index as usize, cursor, sink, &stop) { + warn!("wlroots capture stopped: {e}"); + } + })?); + match init_rx.recv() { + Ok(result) => result, + Err(_) => Err(failed("the capture thread ended during setup")), + } + }) + } + + fn stop(&mut self) { + self.worker = None; + } +} + +/// Sleep until `until`, or until `stop` is set. `false` if stopped. +fn sleep_until(until: Instant, stop: &AtomicBool) -> bool { + while !stop.load(Ordering::Relaxed) { + let now = Instant::now(); + if now >= until { + return true; + } + // Woken early by `Worker::stop`. + std::thread::park_timeout(until - now); + } + false +} + +fn capture_loop( + display: &mut Display, + output: usize, + cursor: bool, + mut sink: Box, + stop: &AtomicBool, +) -> Result<()> { + let qh = display.queue.handle(); + let wl_output = display.state.outputs[output].0.clone(); + let session = match &display.capturer { + Capturer::Ext { manager, sources } => { + let source = sources.create_source(&wl_output, &qh, ()); + let options = if cursor { + ext_image_copy_capture_manager_v1::Options::PaintCursors + } else { + ext_image_copy_capture_manager_v1::Options::empty() + }; + Some((manager.create_session(&source, options, &qh, ()), source)) + } + Capturer::Wlr(_) => None, + }; + let started = Instant::now(); + let mut buffer: Option = None; + // Rows of a y-inverted frame, flipped. + let mut flipped: Vec = Vec::new(); + let mut next_due = Instant::now(); + let mut failures = 0; + loop { + if !sleep_until(next_due, stop) { + break; + } + // Describe the buffer: per frame (wlr), or per session (ext). + let frame = &mut display.state.frame; + frame.ready = false; + frame.failed = None; + frame.y_invert = false; + let wlr_frame = match &display.capturer { + Capturer::Wlr(manager) => { + frame.formats.clear(); + frame.described = false; + Some(manager.capture_output(i32::from(cursor), &wl_output, &qh, ())) + } + Capturer::Ext { .. } => None, + }; + let described = display.wait(stop, Some(SETUP_TIMEOUT), |f| f.described || f.stopped)?; + if !described || display.state.frame.stopped { + if let Some(f) = wlr_frame { + f.destroy(); + } + if stop.load(Ordering::Relaxed) || display.state.frame.stopped { + break; + } + return Err(failed("the compositor did not describe the frame buffer")); + } + let frame = &display.state.frame; + let Some(format) = FORMATS.iter().map(|(f, _)| *f).find(|f| frame.formats.contains(f)) + else { + return Err(failed(format!("no readable shared-memory format in {:?}", frame.formats))); + }; + let key = (format, frame.size.0, frame.size.1, frame.stride); + if buffer.as_ref().is_none_or(|b| b.key != key) { + // The old buffer goes before the new one is allocated. + drop(buffer.take()); + buffer = Some(ShmBuffer::new(&display.shm, &qh, format, frame.size, frame.stride)?); + } + let shm = buffer.as_ref().expect("created above"); + let ext_frame = match (&wlr_frame, &session) { + (Some(f), _) => { + if f.version() >= 2 { + f.copy_with_damage(&shm.buffer); + } else { + f.copy(&shm.buffer); + } + None + } + (None, Some((session, _))) => { + let f = session.create_frame(&qh, ()); + f.attach_buffer(&shm.buffer); + // Everything may have changed since the buffer was used. + f.damage_buffer(0, 0, i32::MAX, i32::MAX); + f.capture(); + Some(f) + } + (None, None) => unreachable!("one of the protocols is bound"), + }; + let done = display.wait(stop, None, |f| f.ready || f.failed.is_some())?; + if let Some(f) = wlr_frame { + f.destroy(); + } + if let Some(f) = ext_frame { + f.destroy(); + } + if !done { + break; + } + if let Some(reason) = display.state.frame.failed.take() { + if display.state.frame.stopped { + break; + } + failures += 1; + if failures > MAX_FAILURES { + return Err(failed(reason)); + } + // Buffer constraints changed (ext): the session describes the + // new ones. + buffer = None; + continue; + } + failures = 0; + let timestamp = started.elapsed(); + let fps = sink.max_fps().max(1); + next_due = Instant::now() + Duration::from_secs(1) / fps * 7 / 8; + if !sink.wants(timestamp) { + continue; + } + let (width, height, stride) = (key.1, key.2, key.3 as usize); + let bgra = FORMATS.iter().any(|(f, bgra)| *f == format && *bgra); + let mut bytes: &[u8] = &shm.map; + if display.state.frame.y_invert { + // Rare (some renderers read back bottom-up): flip into a buffer. + flipped.clear(); + for row in shm.map.chunks_exact(stride).take(height as usize).rev() { + flipped.extend_from_slice(row); + } + bytes = &flipped; + } + let plane = PlaneRef::new(bytes, stride); + let pixels = if bgra { PixelsRef::Bgra(plane) } else { PixelsRef::Rgba(plane) }; + if !sink.frame(FrameRef { width, height, timestamp, pixels }) { + break; + } + } + if let Some((session, source)) = session { + session.destroy(); + source.destroy(); + } + let _ = display.conn.flush(); + Ok(()) +} diff --git a/crates/voelin-media/src/capture/x11.rs b/crates/voelin-media/src/capture/x11.rs index 66aea30..8d10406 100644 --- a/crates/voelin-media/src/capture/x11.rs +++ b/crates/voelin-media/src/capture/x11.rs @@ -12,7 +12,7 @@ mod shm; use std::fmt::Display; use std::os::fd::OwnedFd; -use std::time::Instant; +use std::time::{Duration, Instant}; use memmap2::MmapMut; use tracing::{debug, warn}; @@ -26,13 +26,16 @@ use x11rb::protocol::xproto::{ use x11rb::rust_connection::RustConnection; use crate::capture::{ - BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, Ticker, Worker, + BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture, SourceId, + Ticker, Worker, }; -use crate::frame::VideoFrame; -use crate::queue::{FrameReceiver, frame_channel}; +use crate::frame::{FrameRef, PixelsRef, PlaneRef, VideoFrame}; +use crate::queue::FrameReceiver; use crate::{Error, Result}; const BACKEND: &str = "x11"; +/// How often the monitor or window position is looked up again. +const REGION_REFRESH: Duration = Duration::from_secs(1); fn unavailable(e: impl Display) -> Error { Error::CaptureUnavailable { backend: BACKEND, reason: e.to_string() } @@ -102,39 +105,88 @@ impl ScreenCapture for X11Capture { source: &SourceId, options: &CaptureOptions, ) -> BoxFuture<'_, Result>> { + let (sink, rx) = QueueSink::new(options); + let started = self.start_sink(source, options, Box::new(sink)); + Box::pin(async move { + started.await?; + Ok(rx) + }) + } + + /// The sink reads the MIT-SHM segment itself (or the GetImage reply); + /// the cursor is blended into it first. + fn start_sink( + &mut self, + source: &SourceId, + options: &CaptureOptions, + mut sink: Box, + ) -> BoxFuture<'_, Result<()>> { let source = source.clone(); let options = options.clone(); Box::pin(async move { self.stop(); let x = Display11::connect(self.display.as_deref())?; // Fail here, not in the thread, if the source does not exist. - x.region(&source)?; - let (tx, rx) = frame_channel(options.queue); + let mut region = x.region(&source)?; let use_shm = self.use_shm; self.worker = Some(Worker::spawn("voelin-x11-capture", move |stop| { let mut grabber = Grabber::new(&x, use_shm); let cursor = options.cursor && x.xfixes; let started = Instant::now(); - let mut ticker = Ticker::new(options.fps); + let mut fps = sink.max_fps(); + let mut ticker = Ticker::new(fps); + let mut region_at = Instant::now(); loop { - match capture(&x, &source, &mut grabber, cursor) { - Ok(frame) => { - if !tx.send(frame.with_timestamp(started.elapsed())) { - break; + let timestamp = started.elapsed(); + if sink.wants(timestamp) { + // Monitors and windows move rarely: look them up once a + // second, and again when a grab fails (e.g. a window + // shrank). + if region_at.elapsed() >= REGION_REFRESH { + region_at = Instant::now(); + match x.region(&source) { + Ok(r) => region = r, + Err(e) => { + warn!("X11 capture stopped: {e}"); + break; + } } } - Err(e) => { + let mut result = capture(&x, ®ion, &mut grabber, cursor); + if result.is_err() { + region_at = Instant::now(); + if let Ok(r) = x.region(&source) { + region = r; + result = capture(&x, ®ion, &mut grabber, cursor); + } + } + if let Err(e) = result { // E.g. the window was closed: end the stream. warn!("X11 capture stopped: {e}"); break; } + let (width, height) = (region.rect.width, region.rect.height); + let plane = PlaneRef::new(grabber.pixels(), usize::from(width) * 4); + let frame = FrameRef { + width: width.into(), + height: height.into(), + timestamp, + pixels: PixelsRef::Bgra(plane), + }; + if !sink.frame(frame) { + break; + } + } + if sink.max_fps() != fps { + fps = sink.max_fps(); + ticker.set_fps(fps); } if !ticker.wait(&stop) { break; } } })?); - Ok(rx) + Ok(()) }) } @@ -408,19 +460,28 @@ struct Segment { struct Grabber { shm: bool, segment: Option, + /// The last GetImage reply. + image: Vec, + /// Where the last grab is: the segment (`true`) or `image`, and its + /// length. + last: (bool, usize), } impl Grabber { fn new(x: &Display11, want_shm: bool) -> Self { - Self { shm: want_shm && x.shm, segment: None } + Self { shm: want_shm && x.shm, segment: None, image: Vec::new(), last: (false, 0) } } - /// Tightly packed BGRx pixels of the region. - fn grab(&mut self, x: &Display11, r: &Region) -> Result> { + /// Read the region's pixels (tightly packed BGRx) into the shared memory + /// segment, or with GetImage; [`Grabber::pixels`] has them. + fn grab(&mut self, x: &Display11, r: &Region) -> Result<()> { let size = usize::from(r.rect.width) * usize::from(r.rect.height) * 4; if self.shm { match self.grab_shm(x, r, size) { - Ok(pixels) => return Ok(pixels), + Ok(()) => { + self.last = (true, size); + return Ok(()); + } Err(e) => { debug!("MIT-SHM capture failed, using GetImage: {e}"); self.shm = false; @@ -442,15 +503,29 @@ impl Grabber { .map_err(failed)? .reply() .map_err(failed)?; - let mut data = reply.data; - if data.len() < size { - return Err(failed(format!("GetImage returned {} bytes, expected {size}", data.len()))); + self.image = reply.data; + if self.image.len() < size { + return Err(failed(format!( + "GetImage returned {} bytes, expected {size}", + self.image.len() + ))); } - data.truncate(size); - Ok(data) + self.last = (false, size); + Ok(()) } - fn grab_shm(&mut self, x: &Display11, r: &Region, size: usize) -> Result> { + /// The pixels of the last grab. + fn pixels(&mut self) -> &mut [u8] { + match (self.last, &mut self.segment) { + ((true, size), Some(segment)) => &mut segment.map[..size], + ((_, size), _) => { + let len = size.min(self.image.len()); + &mut self.image[..len] + } + } + } + + fn grab_shm(&mut self, x: &Display11, r: &Region, size: usize) -> Result<()> { if self.segment.as_ref().is_none_or(|s| s.map.len() < size) { self.release(x); self.segment = Some(Self::attach(x, size)?); @@ -471,7 +546,7 @@ impl Grabber { .map_err(failed)? .reply() .map_err(failed)?; - Ok(segment.map[..size].to_vec()) + Ok(()) } fn attach(x: &Display11, size: usize) -> Result { @@ -533,14 +608,10 @@ fn blend_cursor(bgrx: &mut [u8], width: usize, height: usize, cursor: &Cursor<'_ } } -fn capture( - x: &Display11, - source: &SourceId, - grabber: &mut Grabber, - cursor: bool, -) -> Result { - let region = x.region(source)?; - let mut pixels = grabber.grab(x, ®ion)?; +/// Grab the region and blend the cursor into it; the pixels are then in +/// [`Grabber::pixels`]. +fn capture(x: &Display11, region: &Region, grabber: &mut Grabber, cursor: bool) -> Result<()> { + grabber.grab(x, region)?; let (w, h) = (usize::from(region.rect.width), usize::from(region.rect.height)); if cursor && let Ok(image) = x.conn.xfixes_get_cursor_image().map_err(failed)?.reply() { let cursor = Cursor { @@ -551,10 +622,10 @@ fn capture( argb: &image.cursor_image, }; if cursor.argb.len() >= cursor.width * cursor.height { - blend_cursor(&mut pixels, w, h, &cursor); + blend_cursor(grabber.pixels(), w, h, &cursor); } } - VideoFrame::from_bgra(region.rect.width.into(), region.rect.height.into(), w * 4, pixels) + Ok(()) } #[cfg(test)] diff --git a/crates/voelin-media/src/codec/h264.rs b/crates/voelin-media/src/codec/h264.rs index d9fd168..d1a8a4c 100644 --- a/crates/voelin-media/src/codec/h264.rs +++ b/crates/voelin-media/src/codec/h264.rs @@ -21,7 +21,8 @@ use openh264::encoder::{ use openh264::formats::{YUVSlices, YUVSource}; use crate::codec::{ - Codec, ContentHint, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder, + Codec, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, + VideoEncoder, }; use crate::convert; use crate::frame::{FrameData, Plane, VideoFrame}; @@ -187,11 +188,19 @@ pub struct OpenH264Encoder { config: EncoderConfig, profile: H264Profile, encoder: Option, + /// The last frame's bitstream (reused). + output: Vec, } impl OpenH264Encoder { fn new(library: OpenH264, config: EncoderConfig) -> Result { - let mut encoder = Self { library, config, profile: H264Profile::default(), encoder: None }; + let mut encoder = Self { + library, + config, + profile: H264Profile::default(), + encoder: None, + output: Vec::new(), + }; encoder.encoder = Some(encoder.create()?); Ok(encoder) } @@ -244,6 +253,24 @@ impl VideoEncoder for OpenH264Encoder { } fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result> { + let mut frames = Vec::new(); + self.encode_with(frame, force_keyframe, &mut |f| { + frames.push(EncodedFrame { + data: f.data.to_vec(), + keyframe: f.keyframe, + pts_90khz: f.pts_90khz, + }); + })?; + Ok(frames) + } + + /// Writes the NAL units into a buffer kept across frames. + fn encode_with( + &mut self, + frame: &VideoFrame, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { let i420 = convert::to_i420(frame)?; let FrameData::I420 { y, u, v } = &i420.data else { unreachable!("to_i420 returns I420"); @@ -263,11 +290,15 @@ impl VideoEncoder for OpenH264Encoder { Err(e) => return Err(Error::Encoder { codec: Codec::H264, message: e.to_string() }), }; let keyframe = matches!(bitstream.frame_type(), FrameType::IDR | FrameType::I); - let data = bitstream.to_vec(); - if data.is_empty() || matches!(bitstream.frame_type(), FrameType::Skip) { - return Ok(Vec::new()); + if matches!(bitstream.frame_type(), FrameType::Skip) { + return Ok(()); } - Ok(vec![EncodedFrame { data, keyframe, pts_90khz: i420.pts_90khz() }]) + self.output.clear(); + bitstream.write_vec(&mut self.output); + if !self.output.is_empty() { + out(EncodedChunk { data: &self.output, keyframe, pts_90khz: i420.pts_90khz() }); + } + Ok(()) } /// The `openh264` crate has no safe way to change the bitrate of a diff --git a/crates/voelin-media/src/codec/mod.rs b/crates/voelin-media/src/codec/mod.rs index 488c590..e407a1c 100644 --- a/crates/voelin-media/src/codec/mod.rs +++ b/crates/voelin-media/src/codec/mod.rs @@ -126,8 +126,13 @@ pub struct EncoderConfig { /// start and on request (PLI), like WebRTC. pub keyframe_interval: Option, pub content: ContentHint, - /// Encoder threads; 0 picks a number from the resolution and CPU count. + /// Most encoder threads (still no more than the frame size can use); 0: + /// all CPUs but one ([`encoder_cpus`]). pub threads: u32, + /// A fixed speed / quality trade-off in the backend's own terms (libvpx + /// `cpu-used`); `None` lets the encoder adapt it to how long frames take + /// to encode compared to the frame interval. + pub speed: Option, } impl Default for EncoderConfig { @@ -138,30 +143,46 @@ impl Default for EncoderConfig { keyframe_interval: None, content: ContentHint::Screen, threads: 0, + speed: None, } } } +/// CPUs encoders use by default: all but one (at least one). libvpx's +/// threads wait on each other by spinning, so an encode that wants every +/// core slows down many times over as soon as anything else runs (the +/// capture and conversion of the next frame, another layer, the desktop); +/// measured on a 4-core machine: 130-290 ms per 1080p frame with 4 threads +/// under load, against 9-17 ms with 3. +pub fn encoder_cpus() -> u32 { + let cpus = std::thread::available_parallelism().map_or(1, |n| n.get() as u32); + cpus.saturating_sub(1).max(1) +} + impl EncoderConfig { - /// Threads for a `width` x `height` encode (libwebrtc's heuristic). + /// Threads for a `width` x `height` encode: [`threads`](Self::threads) + /// (or [`encoder_cpus`]), but no more than one per 320x240 pixels: more + /// would idle on small frames and cost quality (VP8 token partitions). pub fn threads_for(&self, width: u32, height: u32) -> u32 { - if self.threads > 0 { - return self.threads; - } - let cpus = std::thread::available_parallelism().map_or(1, |n| n.get() as u32); - let pixels = width * height; - if pixels >= 1920 * 1080 && cpus > 8 { - 8 - } else if pixels >= 1280 * 720 && cpus > 3 { - 4 - } else if pixels >= 640 * 480 && cpus > 2 { - 2 - } else { - 1 - } + let cpus = match self.threads { + 0 => encoder_cpus(), + n => n, + }; + let useful = (u64::from(width) * u64::from(height) / (320 * 240)).clamp(1, 64) as u32; + cpus.min(useful) } } +/// An encoded frame borrowed from the encoder (see +/// [`VideoEncoder::encode_with`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct EncodedChunk<'a> { + pub data: &'a [u8], + pub keyframe: bool, + /// Presentation time on the 90 kHz RTP clock. + pub pts_90khz: u64, +} + /// One encoded frame, ready for `voelin_stream::Peer::write`. #[derive(Clone, Debug, PartialEq, Eq)] pub struct EncodedFrame { @@ -183,8 +204,35 @@ pub trait VideoEncoder: Send { /// encoder skipped it (rate control), usually one. fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result>; + /// Like [`encode`](Self::encode), but hands each encoded frame to `out` + /// borrowed from the encoder's own buffer, so nothing is allocated or + /// copied here (libvpx does this; the default goes through `encode`). + fn encode_with( + &mut self, + frame: &VideoFrame, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + for f in self.encode(frame, force_keyframe)? { + out(EncodedChunk { data: &f.data, keyframe: f.keyframe, pts_90khz: f.pts_90khz }); + } + Ok(()) + } + /// Change the target bitrate (bits per second). fn set_bitrate(&mut self, bps: u32) -> Result<()>; + + /// Change the expected frame rate (rate control and speed decisions); + /// ignored by encoders that follow the frame timestamps anyway. + fn set_fps(&mut self, fps: u32) -> Result<()> { + let _ = fps; + Ok(()) + } + + /// The current speed setting, for statistics (libvpx `cpu-used`). + fn speed(&self) -> Option { + None + } } /// A video decoder. @@ -461,6 +509,7 @@ mod tests { fn thread_heuristic() { let config = EncoderConfig { threads: 3, ..EncoderConfig::default() }; assert_eq!(config.threads_for(1920, 1080), 3); + assert_eq!(config.threads_for(320, 240), 1, "capped by the frame size"); assert_eq!(EncoderConfig::default().threads_for(320, 240), 1); } } diff --git a/crates/voelin-media/src/codec/vpx.rs b/crates/voelin-media/src/codec/vpx.rs index 63798f9..27c27fc 100644 --- a/crates/voelin-media/src/codec/vpx.rs +++ b/crates/voelin-media/src/codec/vpx.rs @@ -1,13 +1,20 @@ //! VP8 and VP9 through the system libvpx. //! //! Encoder settings follow libwebrtc's realtime configuration: one pass CBR, -//! no lag, error resilient, fixed high speed (`cpu-used` 8), keyframes on -//! request, and screen-content tuning for [`ContentHint::Screen`]. +//! no lag (`VPX_DL_REALTIME`), error resilient, keyframes only on request, +//! and screen-content tuning for [`ContentHint::Screen`] +//! (`VP8E_SET_SCREEN_CONTENT_MODE`, `VP9E_SET_TUNE_CONTENT`, static +//! threshold). Threads default to the CPUs the frame size can use; VP8 gets +//! as many token partitions, VP9 row multithreading and tile columns by +//! width. `cpu-used` adapts to the measured encode time (see +//! [`SpeedControl`]) unless [`EncoderConfig::speed`] fixes it. Bitrate +//! changes apply to the running encoder, without a keyframe. -use std::time::Duration; +use std::time::{Duration, Instant}; use crate::codec::{ - Codec, ContentHint, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder, + Codec, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, + VideoEncoder, }; use crate::convert; use crate::frame::{FrameData, Plane, VIDEO_CLOCK_RATE, VideoFrame}; @@ -38,18 +45,117 @@ pub fn libvpx_version() -> String { raw::version() } +/// Speed levels (bigger is faster): VP8 `cpu-used` is minus the level (a +/// fixed speed), VP9's is the level (realtime mode). +struct Levels { + slowest: i32, + fastest: i32, + /// Where adapting starts: fast, so the first seconds do not fall behind. + start: i32, +} + +// On screen content (a probe with the desktop test pattern), VP8 levels +// above 10 were no faster, only about 3 dB worse, and levels below 6 about +// ten times slower for under 1 dB. +const VP8_LEVELS: Levels = Levels { slowest: 6, fastest: 10, start: 10 }; +const VP9_LEVELS: Levels = Levels { slowest: 5, fastest: 9, start: 8 }; + +/// Adapts the speed level to how long frames take to encode compared to +/// the frame interval (keyframes excluded: they are always slow): +/// - faster at once when a single frame took more than the whole interval, +/// and when the running mean is above 75 % of it; +/// - slower (better quality) only when the mean stayed below 35 % for a +/// while: 15 frames, doubling (up to 16x) each time a slower level had to +/// be undone, so it does not oscillate around a level that is too slow. +pub struct SpeedControl { + level: i32, + slowest: i32, + fastest: i32, + /// Mean encode time in seconds. + mean: f64, + frames: u32, + /// Frames the mean must stay low before going slower. + patience: u32, + /// The last change went slower. + slowed: bool, +} + +impl SpeedControl { + const WINDOW: u32 = 15; + const TOO_SLOW: f64 = 0.75; + const TOO_FAST: f64 = 0.35; + + fn new(levels: &Levels) -> Self { + Self { + level: levels.start, + slowest: levels.slowest, + fastest: levels.fastest, + mean: 0.0, + frames: 0, + patience: Self::WINDOW, + slowed: false, + } + } + + pub fn level(&self) -> i32 { + self.level + } + + /// Account one encode; returns the new level if it changed. + pub fn update(&mut self, took: Duration, interval: Duration) -> Option { + if interval.is_zero() { + return None; + } + let took = took.as_secs_f64(); + self.mean = if self.frames == 0 { took } else { self.mean * 0.8 + took * 0.2 }; + self.frames += 1; + let budget = interval.as_secs_f64(); + let load = self.mean / budget; + let faster = took > budget || (self.frames >= Self::WINDOW && load > Self::TOO_SLOW); + let level = if faster { + if self.slowed { + // Going slower was a mistake: wait longer next time. + self.patience = (self.patience * 2).min(Self::WINDOW * 16); + } + (self.level + 1).min(self.fastest) + } else if self.frames >= self.patience && load < Self::TOO_FAST { + (self.level - 1).max(self.slowest) + } else { + self.level + }; + if level == self.level { + return None; + } + self.slowed = level < self.level; + self.level = level; + self.frames = 0; + Some(level) + } +} + /// libvpx VP8 / VP9 encoder. pub struct VpxEncoder { codec: Codec, config: EncoderConfig, encoder: Option, last_pts: Option, + speed: SpeedControl, } impl VpxEncoder { pub fn new(codec: Codec, config: EncoderConfig) -> Result { check(codec, true)?; - Ok(Self { codec, config, encoder: None, last_pts: None }) + let levels = if codec == Codec::Vp9 { &VP9_LEVELS } else { &VP8_LEVELS }; + Ok(Self { codec, config, encoder: None, last_pts: None, speed: SpeedControl::new(levels) }) + } + + /// The libvpx `cpu-used` value in use. + pub fn cpu_used(&self) -> i32 { + match (self.config.speed, self.codec) { + (Some(speed), _) => speed, + (None, Codec::Vp9) => self.speed.level(), + (None, _) => -self.speed.level(), + } } fn error(&self, message: String) -> Error { @@ -69,6 +175,7 @@ impl VpxEncoder { keyframe_interval: self.config.keyframe_interval, screen: self.config.content == ContentHint::Screen, threads: self.config.threads_for(width, height), + speed: self.cpu_used(), }; let encoder = raw::Encoder::new(¶ms).map_err(|e| self.error(e))?; self.encoder = Some(encoder); @@ -87,19 +194,47 @@ impl VideoEncoder for VpxEncoder { } fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result> { + let mut frames = Vec::new(); + self.encode_with(frame, force_keyframe, &mut |f| { + frames.push(EncodedFrame { + data: f.data.to_vec(), + keyframe: f.keyframe, + pts_90khz: f.pts_90khz, + }); + })?; + Ok(frames) + } + + /// Encodes straight from the frame's planes (I420 frames are not + /// copied) and hands out libvpx's own output buffer. + fn encode_with( + &mut self, + frame: &VideoFrame, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { let i420 = convert::to_i420(frame)?; let FrameData::I420 { y, u, v } = &i420.data else { unreachable!("to_i420 returns I420"); }; - // libvpx needs strictly increasing timestamps. + // libvpx needs strictly increasing timestamps. The duration of a + // frame, from which CBR rate control budgets its bits, is the time + // since the previous one (a variable frame rate), but at least 3/4 + // of the nominal interval: a frame whose timestamp had to be bumped + // (e.g. after a keyframe re-sent while the screen was still) would + // otherwise get almost no bits and come out as a smear. + let interval = VIDEO_CLOCK_RATE / u64::from(self.config.fps.max(1)); let mut pts = i420.pts_90khz() as i64; - if let Some(last) = self.last_pts - && pts <= last - { - pts = last + 1; - } + let elapsed = match self.last_pts { + Some(last) if pts <= last => { + pts = last + 1; + 0 + } + Some(last) => (pts - last) as u64, + None => interval, + }; + let duration = elapsed.clamp(interval * 3 / 4, VIDEO_CLOCK_RATE); self.last_pts = Some(pts); - let duration = VIDEO_CLOCK_RATE / u64::from(self.config.fps.max(1)); let image = raw::I420 { width: i420.width, height: i420.height, @@ -110,15 +245,40 @@ impl VideoEncoder for VpxEncoder { uv_stride: u.stride, }; let codec = self.codec; - let encoder = self.ensure_encoder(i420.width, i420.height)?; - let packets = encoder - .encode(&image, pts, duration, force_keyframe) + self.ensure_encoder(i420.width, i420.height)?; + let encoder = self.encoder.as_mut().expect("created above"); + let started = Instant::now(); + let mut keyframe = force_keyframe; + encoder + .encode(&image, pts, duration, force_keyframe, &mut |p| { + keyframe |= p.keyframe; + if !p.data.is_empty() { + out(EncodedChunk { + data: p.data, + keyframe: p.keyframe, + pts_90khz: p.pts as u64, + }); + } + }) .map_err(|message| Error::Encoder { codec, message })?; - Ok(packets - .into_iter() - .filter(|p| !p.data.is_empty()) - .map(|p| EncodedFrame { data: p.data, keyframe: p.keyframe, pts_90khz: p.pts as u64 }) - .collect()) + if self.config.speed.is_none() && !keyframe { + let budget = Duration::from_secs(1) / self.config.fps.max(1); + if let Some(level) = self.speed.update(started.elapsed(), budget) { + let cpu_used = if codec == Codec::Vp9 { level } else { -level }; + tracing::debug!(%codec, cpu_used, "encoder speed"); + encoder.set_speed(cpu_used).map_err(|message| Error::Encoder { codec, message })?; + } + } + Ok(()) + } + + fn set_fps(&mut self, fps: u32) -> Result<()> { + self.config.fps = fps.max(1); + Ok(()) + } + + fn speed(&self) -> Option { + Some(self.cpu_used()) } fn set_bitrate(&mut self, bps: u32) -> Result<()> { @@ -243,6 +403,66 @@ mod tests { assert!(!encoder.encode(&frame(3, 97, 55), false).unwrap()[0].keyframe); } + #[test] + fn speed_follows_the_encode_time() { + let mut control = SpeedControl::new(&VP8_LEVELS); + let interval = Duration::from_millis(33); + // Fast encodes: slower levels (better quality) down to the slowest. + let mut changes = Vec::new(); + for _ in 0..500 { + changes.extend(control.update(Duration::from_millis(2), interval)); + } + assert_eq!(control.level(), VP8_LEVELS.slowest); + assert!(changes.windows(2).all(|w| w[1] == w[0] - 1), "{changes:?}"); + // Slow encodes: faster again. + for _ in 0..500 { + control.update(Duration::from_millis(30), interval); + } + assert_eq!(control.level(), VP8_LEVELS.fastest); + // One frame over the budget: faster at once. + let mut control = SpeedControl::new(&VP9_LEVELS); + assert_eq!(control.update(Duration::from_millis(40), interval), Some(9)); + // A slower level that turns out too slow makes the next try wait. + let mut control = SpeedControl::new(&VP8_LEVELS); + let mut n = 0; + while control.update(Duration::from_millis(2), interval).is_none() { + n += 1; + } + assert_eq!((n, control.level()), (14, 9)); + assert_eq!(control.update(Duration::from_millis(40), interval), Some(10)); + let mut n = 0; + while control.update(Duration::from_millis(2), interval).is_none() { + n += 1; + } + assert_eq!(n, 29, "patience doubled"); + // In between: stays. + let level = control.level(); + for _ in 0..100 { + assert!( + control.update(Duration::from_millis(18), interval).is_none() + || level != control.level() + ); + } + } + + #[test] + fn borrowed_output_and_fixed_speed() { + let config = EncoderConfig { speed: Some(-6), ..EncoderConfig::default() }; + let mut encoder = VpxEncoder::new(Codec::Vp8, config).unwrap(); + assert_eq!(encoder.speed(), Some(-6)); + let mut sizes = Vec::new(); + for n in 0..3 { + encoder + .encode_with(&frame(n, 64, 48), false, &mut |f| { + sizes.push((f.data.len(), f.keyframe)) + }) + .unwrap(); + } + assert_eq!(sizes.len(), 3); + assert!(sizes[0].1 && !sizes[1].1); + assert_eq!(VpxEncoder::new(Codec::Vp9, EncoderConfig::default()).unwrap().speed(), Some(8)); + } + #[test] fn garbage_is_an_error() { let mut decoder = VpxDecoder::new(Codec::Vp8).unwrap(); diff --git a/crates/voelin-media/src/codec/vpx/raw.rs b/crates/voelin-media/src/codec/vpx/raw.rs index e3369eb..358cbeb 100644 --- a/crates/voelin-media/src/codec/vpx/raw.rs +++ b/crates/voelin-media/src/codec/vpx/raw.rs @@ -15,11 +15,6 @@ use vpx_sys as ffi; pub(super) type RawResult = std::result::Result; -/// Speed for realtime encoding. VP8: negative means a fixed speed (a -/// positive value would let libvpx pick one from a CPU budget). -const VP8_CPU_USED: c_int = -8; -const VP9_CPU_USED: c_int = 8; - fn iface(vp9: bool, encoder: bool) -> *const ffi::vpx_codec_iface { // SAFETY: these return pointers to static interface tables (or NULL if // libvpx was built without that codec); no arguments. @@ -109,14 +104,21 @@ pub(super) struct EncoderParams { pub keyframe_interval: Option, pub screen: bool, pub threads: u32, + /// `cpu-used`: VP8 -16 (fastest) to -4 as a fixed speed (negative), VP9 + /// 5 to 9 in realtime mode. + pub speed: i32, } -pub(super) struct Packet { - pub data: Vec, +/// An encoded frame, borrowed from libvpx until the next call. +pub(super) struct Packet<'a> { + pub data: &'a [u8], pub keyframe: bool, pub pts: i64, } +/// Longest keyframe distance libvpx is given with keyframes on request only. +const NO_KEYFRAMES: u32 = 1 << 30; + /// An initialised encoder context. pub(super) struct Encoder { // Boxed: libvpx keeps pointers to the context and the configuration. @@ -164,7 +166,11 @@ impl Encoder { cfg.kf_min_dist = 0; cfg.kf_max_dist = n.max(1); } - None => cfg.kf_mode = ffi::vpx_kf_mode::VPX_KF_DISABLED, + None => { + // Keyframes only when forced (a viewer asks for one). + cfg.kf_mode = ffi::vpx_kf_mode::VPX_KF_DISABLED; + cfg.kf_max_dist = NO_KEYFRAMES; + } } // SAFETY: zeroed context as libvpx expects before init. @@ -184,10 +190,14 @@ impl Encoder { })?; let mut encoder = Self { ctx, cfg }; + encoder.set_speed(p.speed)?; + // log2 of the thread count, for splitting the frame. + let log2_threads = 31 - p.threads.max(1).leading_zeros(); if p.vp9 { - encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_CPUUSED, VP9_CPU_USED)?; encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_ROW_MT, 1)?; - let tiles = (31 - p.threads.max(1).leading_zeros()) as c_int; + // Tiles are at least 256 pixels wide. + let max_tiles = 31 - (p.width / 256).max(1).leading_zeros(); + let tiles = log2_threads.min(max_tiles) as c_int; encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_TILE_COLUMNS, tiles)?; // Cyclic refresh: realtime adaptive quantisation. encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_AQ_MODE, 3)?; @@ -197,7 +207,9 @@ impl Encoder { encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_TUNE_CONTENT, screen)?; } } else { - encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_CPUUSED, VP8_CPU_USED)?; + // Token partitions (1, 2, 4 or 8) let decoders use threads too. + let partitions = log2_threads.min(3) as c_int; + encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_TOKEN_PARTITIONS, partitions)?; encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_NOISE_SENSITIVITY, 0)?; if p.screen { encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_SCREEN_CONTENT_MODE, 1)?; @@ -220,6 +232,11 @@ impl Encoder { check(Some(&self.ctx), err).map_err(|e| format!("control {id:?}: {e}")) } + /// Change `cpu-used` of the running encoder (see [`EncoderParams::speed`]). + pub fn set_speed(&mut self, speed: i32) -> RawResult<()> { + self.control(ffi::vp8e_enc_control_id::VP8E_SET_CPUUSED, speed as c_int) + } + /// Change the target bitrate of the running encoder. pub fn set_bitrate(&mut self, kbps: u32) -> RawResult<()> { self.cfg.rc_target_bitrate = kbps.max(1); @@ -233,14 +250,16 @@ impl Encoder { (self.cfg.g_w, self.cfg.g_h) } - /// Encode one frame (pts and duration in 1/90000 s). + /// Encode one frame (pts and duration in 1/90000 s); `out` gets the + /// encoded frames, borrowed from libvpx. pub fn encode( &mut self, img: &I420<'_>, pts: i64, duration: u64, keyframe: bool, - ) -> RawResult> { + out: &mut dyn FnMut(Packet<'_>), + ) -> RawResult<()> { img.check()?; if (img.width, img.height) != self.size() { return Err("frame size differs from the encoder size".into()); @@ -287,16 +306,16 @@ impl Encoder { ) }; check(Some(&self.ctx), err)?; - Ok(self.drain()) + self.drain(out); + Ok(()) } - fn drain(&mut self) -> Vec { - let mut packets = Vec::new(); + fn drain(&mut self, out: &mut dyn FnMut(Packet<'_>)) { let mut iter: ffi::vpx_codec_iter_t = ptr::null(); loop { // SAFETY: iterates the packets of the last encode call; each // packet and its buffer stay valid until the next libvpx call on - // this context, and are copied before that. + // this context, which `out` cannot make (it has no access to it). let pkt = unsafe { ffi::vpx_codec_get_cx_data(&mut *self.ctx, &mut iter) }; if pkt.is_null() { break; @@ -307,18 +326,17 @@ impl Encoder { } // SAFETY: `frame` is the active union member for frame packets. let frame = unsafe { pkt.data.frame }; - let data = if frame.buf.is_null() || frame.sz == 0 { - Vec::new() + let data: &[u8] = if frame.buf.is_null() || frame.sz == 0 { + &[] } else { - unsafe { std::slice::from_raw_parts(frame.buf.cast::(), frame.sz) }.to_vec() + unsafe { std::slice::from_raw_parts(frame.buf.cast::(), frame.sz) } }; - packets.push(Packet { + out(Packet { data, keyframe: frame.flags & ffi::VPX_FRAME_IS_KEY != 0, pts: frame.pts, }); } - packets } } diff --git a/crates/voelin-media/src/convert.rs b/crates/voelin-media/src/convert.rs index 583c396..5c98f9d 100644 --- a/crates/voelin-media/src/convert.rs +++ b/crates/voelin-media/src/convert.rs @@ -1,17 +1,24 @@ -//! Pixel format conversion through `yuv` (yuvutils-rs). +//! Pixel format conversion through `yuv` (yuvutils-rs, SIMD: AVX2 / SSE4.1 +//! / NEON picked at runtime). //! //! All YUV data uses BT.601 limited range: WebRTC endpoints assume it for VP8, //! VP9 and H.264 unless the stream signals something else, and libwebrtc's //! capture pipeline produces it. +//! +//! [`Converter`] is the streaming path: it converts a borrowed frame (e.g. a +//! mapped capture buffer, any stride) straight into a preallocated I420 +//! frame, in bands of rows on all cores, without allocating. use std::borrow::Cow; +use std::sync::{Mutex, PoisonError}; use yuv::{ BufferStoreMut, YuvBiPlanarImage, YuvConversionMode, YuvPlanarImage, YuvPlanarImageMut, YuvRange, YuvStandardMatrix, }; -use crate::frame::{FrameData, Plane, VideoFrame, chroma_size}; +use crate::frame::{FrameData, FrameRef, PixelsRef, Plane, VideoFrame, chroma_size}; +use crate::workers::{Slots, Workers}; use crate::{Error, Result}; const RANGE: YuvRange = YuvRange::Limited; @@ -164,6 +171,186 @@ fn repack(plane: &Plane, width: usize, rows: usize) -> Plane { out } +/// Rows `r0 .. r0 + rows` of an I420 destination (`r0` even). +struct Band<'a> { + y: &'a mut [u8], + u: &'a mut [u8], + v: &'a mut [u8], + y_stride: usize, + u_stride: usize, + v_stride: usize, + width: usize, + r0: usize, + rows: usize, +} + +impl Band<'_> { + /// Rows `from ..` of this band (`from` even). + fn skip(&mut self, from: usize) -> Band<'_> { + Band { + y: &mut self.y[from * self.y_stride..], + u: &mut self.u[from / 2 * self.u_stride..], + v: &mut self.v[from / 2 * self.v_stride..], + y_stride: self.y_stride, + u_stride: self.u_stride, + v_stride: self.v_stride, + width: self.width, + r0: self.r0 + from, + rows: self.rows - from, + } + } + + /// Convert `rows` rows of packed pixels (`src` starts at the band's + /// first row) with yuv's SIMD code. + fn packed(&mut self, bgra: bool, src: &[u8], stride: usize, rows: usize) -> Result<()> { + let mut image = YuvPlanarImageMut { + y_plane: BufferStoreMut::Borrowed(&mut *self.y), + y_stride: stride_u32(self.y_stride)?, + u_plane: BufferStoreMut::Borrowed(&mut *self.u), + u_stride: stride_u32(self.u_stride)?, + v_plane: BufferStoreMut::Borrowed(&mut *self.v), + v_stride: stride_u32(self.v_stride)?, + width: self.width as u32, + height: rows as u32, + }; + let convert = if bgra { yuv::bgra_to_yuv420 } else { yuv::rgba_to_yuv420 }; + convert(&mut image, src, stride_u32(stride)?, RANGE, MATRIX, mode()).map_err(error) + } +} + +/// Convert one band of `src` into `band`. `tail` is scratch memory for a +/// last row pair that is not padded to the stride. +fn convert_band(src: &PixelsRef<'_>, mut band: Band<'_>, tail: &Mutex>) -> Result<()> { + let (w, r0, rows) = (band.width, band.r0, band.rows); + let (c0, crows) = (r0 / 2, rows.div_ceil(2)); + let cw = w.div_ceil(2); + match *src { + PixelsRef::Bgra(p) | PixelsRef::Rgba(p) => { + let bgra = matches!(src, PixelsRef::Bgra(_)); + let data = &p.data[r0 * p.stride..]; + let padded = rows * p.stride; + // yuv converts pairs of rows in `2 * stride` chunks, so it would + // skip a final pair whose last row ends before the stride does + // (a buffer without padding after the last row). An odd last + // row is converted on its own and needs no padding. + if data.len() >= padded || rows % 2 == 1 { + band.packed(bgra, &data[..data.len().min(padded)], p.stride, rows) + } else { + let head = rows - 2; + if head > 0 { + band.packed(bgra, &data[..head * p.stride], p.stride, head)?; + } + let mut copy = tail.lock().unwrap_or_else(PoisonError::into_inner); + copy.clear(); + copy.extend_from_slice(&data[head * p.stride..][..w * 4]); + copy.extend_from_slice(&data[(head + 1) * p.stride..][..w * 4]); + band.skip(head).packed(bgra, ©, w * 4, 2) + } + } + PixelsRef::I420 { y, u, v } => { + for r in 0..rows { + band.y[r * band.y_stride..][..w].copy_from_slice(y.row(r0 + r, w)); + } + for r in 0..crows { + band.u[r * band.u_stride..][..cw].copy_from_slice(u.row(c0 + r, cw)); + band.v[r * band.v_stride..][..cw].copy_from_slice(v.row(c0 + r, cw)); + } + Ok(()) + } + PixelsRef::Nv12 { y, uv } => { + for r in 0..rows { + band.y[r * band.y_stride..][..w].copy_from_slice(y.row(r0 + r, w)); + } + for r in 0..crows { + let src = uv.row(c0 + r, cw * 2); + let u_row = &mut band.u[r * band.u_stride..][..cw]; + let v_row = &mut band.v[r * band.v_stride..][..cw]; + for ((pair, u), v) in src.chunks_exact(2).zip(u_row).zip(v_row) { + *u = pair[0]; + *v = pair[1]; + } + } + Ok(()) + } + } +} + +/// Converts borrowed frames of any format (any stride) into I420 frames the +/// caller provides, in bands of rows on a [`Workers`] pool. Allocates nothing +/// per frame. +pub struct Converter { + workers: Workers, + tail: Mutex>, +} + +impl Converter { + /// `threads` as in [`Workers::new`] (0: one per CPU). + pub fn new(threads: usize) -> Self { + Self { workers: Workers::new("voelin-convert", threads), tail: Mutex::new(Vec::new()) } + } + + /// The thread pool, for other per-frame work (e.g. scaling). + pub fn workers(&mut self) -> &mut Workers { + &mut self.workers + } + + /// Threads that convert, the caller included. + pub fn threads(&self) -> usize { + self.workers.threads() + } + + /// Convert `src` into `dst`, an I420 frame of the same size whose planes + /// hold `stride * rows` bytes each (e.g. from a + /// [`FramePool`](crate::pool::FramePool)). Takes the timestamp too. + pub fn to_i420_into(&mut self, src: &FrameRef<'_>, dst: &mut VideoFrame) -> Result<()> { + src.validate()?; + if (dst.width, dst.height) != (src.width, src.height) { + return Err(Error::InvalidFrame(format!( + "destination is {}x{}, source {}x{}", + dst.width, dst.height, src.width, src.height + ))); + } + let (w, h) = (src.width as usize, src.height as usize); + let (_, ch) = chroma_size(src.width, src.height); + let FrameData::I420 { y, u, v } = &mut dst.data else { + return Err(Error::InvalidFrame("the destination is not I420".into())); + }; + let padded = |p: &Plane, width: usize, rows: usize| { + p.stride >= width && p.data.len() >= p.stride * rows + }; + if !padded(y, w, h) || !padded(u, w.div_ceil(2), ch) || !padded(v, w.div_ceil(2), ch) { + return Err(Error::InvalidFrame("destination planes are too small".into())); + } + dst.timestamp = src.timestamp; + let tasks = self.workers.tasks(ch); + let band_pairs = ch.div_ceil(tasks); + let band_rows = band_pairs * 2; + let (y_stride, u_stride, v_stride) = (y.stride, u.stride, v.stride); + let bands = y + .data + .chunks_mut(band_rows * y_stride) + .zip(u.data.chunks_mut(band_pairs * u_stride)) + .zip(v.data.chunks_mut(band_pairs * v_stride)) + .take(ch.div_ceil(band_pairs)); + let slots = Slots::new(bands.enumerate()); + let failed = Mutex::new(None); + let tail = &self.tail; + self.workers.run(slots.len(), &|task| { + let Some((i, ((y, u), v))) = slots.take(task) else { return }; + let r0 = i * band_rows; + let rows = band_rows.min(h - r0); + let band = Band { y, u, v, y_stride, u_stride, v_stride, width: w, r0, rows }; + if let Err(e) = convert_band(&src.pixels, band, tail) { + failed.lock().unwrap_or_else(PoisonError::into_inner).get_or_insert(e); + } + }); + match failed.into_inner().unwrap_or_else(PoisonError::into_inner) { + Some(e) => Err(e), + None => Ok(()), + } + } +} + /// Peak signal-to-noise ratio in dB between two frames of the same size, /// over the RGB channels (for tests and quality checks). pub fn psnr(a: &VideoFrame, b: &VideoFrame) -> Result { diff --git a/crates/voelin-media/src/frame.rs b/crates/voelin-media/src/frame.rs index 427ca69..4727851 100644 --- a/crates/voelin-media/src/frame.rs +++ b/crates/voelin-media/src/frame.rs @@ -46,6 +46,29 @@ impl Plane { &self.data[y * self.stride..y * self.stride + width] } + /// The plane borrowed. + pub fn view(&self) -> PlaneRef<'_> { + PlaneRef { data: &self.data, stride: self.stride } + } +} + +/// A borrowed image plane: `stride` bytes per row. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PlaneRef<'a> { + pub data: &'a [u8], + pub stride: usize, +} + +impl<'a> PlaneRef<'a> { + pub fn new(data: &'a [u8], stride: usize) -> Self { + Self { data, stride } + } + + /// Row `y`, `width` bytes long. + pub fn row(&self, y: usize, width: usize) -> &'a [u8] { + &self.data[y * self.stride..y * self.stride + width] + } + fn check(&self, name: &str, width: usize, rows: usize) -> Result<()> { if self.stride < width { return Err(Error::InvalidFrame(format!( @@ -63,6 +86,99 @@ impl Plane { } Ok(()) } + + /// A tightly packed copy of `width` x `rows` bytes. + fn to_plane(self, width: usize, rows: usize) -> Plane { + let mut data = Vec::with_capacity(width * rows); + for y in 0..rows { + data.extend_from_slice(self.row(y, width)); + } + Plane::new(data, width) + } +} + +/// The pixels of a [`FrameRef`], borrowed (e.g. from a mapped capture +/// buffer). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PixelsRef<'a> { + I420 { + y: PlaneRef<'a>, + u: PlaneRef<'a>, + v: PlaneRef<'a>, + }, + Nv12 { + y: PlaneRef<'a>, + uv: PlaneRef<'a>, + }, + /// BGRA or BGRx. + Bgra(PlaneRef<'a>), + /// RGBA or RGBx. + Rgba(PlaneRef<'a>), +} + +/// A video frame whose pixels are borrowed, e.g. a capture buffer that is +/// mapped only while a callback runs. Capture backends hand these to a +/// [`FrameSink`](crate::capture::FrameSink), which converts straight from +/// them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FrameRef<'a> { + pub width: u32, + pub height: u32, + /// As [`VideoFrame::timestamp`]. + pub timestamp: Duration, + pub pixels: PixelsRef<'a>, +} + +impl FrameRef<'_> { + pub fn format(&self) -> PixelFormat { + match self.pixels { + PixelsRef::I420 { .. } => PixelFormat::I420, + PixelsRef::Nv12 { .. } => PixelFormat::Nv12, + PixelsRef::Bgra(_) => PixelFormat::Bgra, + PixelsRef::Rgba(_) => PixelFormat::Rgba, + } + } + + /// Check that the planes are large enough for the frame size. + pub fn validate(&self) -> Result<()> { + if self.width == 0 || self.height == 0 { + return Err(Error::InvalidFrame(format!("empty frame {}x{}", self.width, self.height))); + } + let (w, h) = (self.width as usize, self.height as usize); + let (cw, ch) = chroma_size(self.width, self.height); + match &self.pixels { + PixelsRef::I420 { y, u, v } => { + y.check("Y", w, h)?; + u.check("U", cw, ch)?; + v.check("V", cw, ch) + } + PixelsRef::Nv12 { y, uv } => { + y.check("Y", w, h)?; + uv.check("UV", cw * 2, ch) + } + PixelsRef::Bgra(p) => p.check("BGRA", w * 4, h), + PixelsRef::Rgba(p) => p.check("RGBA", w * 4, h), + } + } + + /// An owned copy with tightly packed planes. + pub fn to_frame(&self) -> VideoFrame { + let (w, h) = (self.width as usize, self.height as usize); + let (cw, ch) = chroma_size(self.width, self.height); + let data = match self.pixels { + PixelsRef::I420 { y, u, v } => FrameData::I420 { + y: y.to_plane(w, h), + u: u.to_plane(cw, ch), + v: v.to_plane(cw, ch), + }, + PixelsRef::Nv12 { y, uv } => { + FrameData::Nv12 { y: y.to_plane(w, h), uv: uv.to_plane(cw * 2, ch) } + } + PixelsRef::Bgra(p) => FrameData::Bgra(p.to_plane(w * 4, h)), + PixelsRef::Rgba(p) => FrameData::Rgba(p.to_plane(w * 4, h)), + }; + VideoFrame { width: self.width, height: self.height, timestamp: self.timestamp, data } + } } /// The pixels of a [`VideoFrame`]. @@ -144,6 +260,19 @@ impl VideoFrame { } } + /// The frame with its pixels borrowed. + pub fn view(&self) -> FrameRef<'_> { + let pixels = match &self.data { + FrameData::I420 { y, u, v } => { + PixelsRef::I420 { y: y.view(), u: u.view(), v: v.view() } + } + FrameData::Nv12 { y, uv } => PixelsRef::Nv12 { y: y.view(), uv: uv.view() }, + FrameData::Bgra(p) => PixelsRef::Bgra(p.view()), + FrameData::Rgba(p) => PixelsRef::Rgba(p.view()), + }; + FrameRef { width: self.width, height: self.height, timestamp: self.timestamp, pixels } + } + /// The timestamp on the 90 kHz RTP video clock. pub fn pts_90khz(&self) -> u64 { (self.timestamp.as_micros() * u128::from(VIDEO_CLOCK_RATE) / 1_000_000) as u64 @@ -151,24 +280,7 @@ impl VideoFrame { /// Check that the planes are large enough for the frame size. pub fn validate(&self) -> Result<()> { - if self.width == 0 || self.height == 0 { - return Err(Error::InvalidFrame(format!("empty frame {}x{}", self.width, self.height))); - } - let (w, h) = (self.width as usize, self.height as usize); - let (cw, ch) = chroma_size(self.width, self.height); - match &self.data { - FrameData::I420 { y, u, v } => { - y.check("Y", w, h)?; - u.check("U", cw, ch)?; - v.check("V", cw, ch) - } - FrameData::Nv12 { y, uv } => { - y.check("Y", w, h)?; - uv.check("UV", cw * 2, ch) - } - FrameData::Bgra(p) => p.check("BGRA", w * 4, h), - FrameData::Rgba(p) => p.check("RGBA", w * 4, h), - } + self.view().validate() } } @@ -218,4 +330,28 @@ mod tests { assert_eq!(audio.frames(), 480); assert_eq!(audio.duration(), Duration::from_millis(10)); } + + #[test] + fn borrowed_frames() { + // 3x2 BGRA with 4 bytes of padding per row, last row unpadded. + let data: Vec = (0..16 + 12).collect(); + let frame = FrameRef { + width: 3, + height: 2, + timestamp: Duration::from_millis(5), + pixels: PixelsRef::Bgra(PlaneRef::new(&data, 16)), + }; + frame.validate().unwrap(); + assert_eq!(frame.format(), PixelFormat::Bgra); + let owned = frame.to_frame(); + let FrameData::Bgra(p) = &owned.data else { panic!("not BGRA") }; + assert_eq!(p.stride, 12); + assert_eq!(p.data[..12], data[..12]); + assert_eq!(p.data[12..], data[16..]); + assert_eq!(owned.timestamp, Duration::from_millis(5)); + assert_eq!(owned.view().to_frame(), owned); + let short = FrameRef { pixels: PixelsRef::Bgra(PlaneRef::new(&data[..27], 16)), ..frame }; + assert!(short.validate().is_err()); + assert_eq!(VideoFrame::black_i420(5, 3).view().format(), PixelFormat::I420); + } } diff --git a/crates/voelin-media/src/handoff.rs b/crates/voelin-media/src/handoff.rs new file mode 100644 index 0000000..145373f --- /dev/null +++ b/crates/voelin-media/src/handoff.rs @@ -0,0 +1,185 @@ +//! A one-slot, latest-wins handoff between two threads. +//! +//! The producer [`put`](Handoff::put)s shared items (`Arc`), replacing one +//! the consumer has not taken yet (a stale frame is worth nothing to an +//! encoder); the consumer [`take`](Handoff::take)s the newest. The slot is a +//! single atomic pointer, so neither side ever blocks the other or +//! allocates; a waiting consumer is parked and unparked. +#![allow(unsafe_code)] + +use std::ptr; +use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU64, Ordering}; +use std::sync::{Arc, OnceLock}; +use std::thread::Thread; +use std::time::{Duration, Instant}; + +/// See the [module docs](self). +pub struct Handoff { + /// Null, or an `Arc` turned into a raw pointer. + slot: AtomicPtr, + consumer: OnceLock, + closed: AtomicBool, + replaced: AtomicU64, +} + +// SAFETY: the slot owns an `Arc`, which moves between the threads; that +// is what `Arc: Send + Sync` allows. +unsafe impl Send for Handoff {} +// SAFETY: as above; all shared access goes through atomics. +unsafe impl Sync for Handoff {} + +impl Default for Handoff { + fn default() -> Self { + Self { + slot: AtomicPtr::new(ptr::null_mut()), + consumer: OnceLock::new(), + closed: AtomicBool::new(false), + replaced: AtomicU64::new(0), + } + } +} + +impl Handoff { + pub fn new() -> Self { + Self::default() + } + + /// Offer `item`. Returns `true` if it replaced an item the consumer had + /// not taken (counted in [`Handoff::replaced`]). + pub fn put(&self, item: Arc) -> bool { + let new = Arc::into_raw(item).cast_mut(); + let old = self.slot.swap(new, Ordering::AcqRel); + if let Some(consumer) = self.consumer.get() { + consumer.unpark(); + } + if old.is_null() { + return false; + } + // SAFETY: a non-null slot value always comes from `Arc::into_raw` + // in `put`, and the swap moved its ownership to us. + drop(unsafe { Arc::from_raw(old) }); + self.replaced.fetch_add(1, Ordering::Relaxed); + true + } + + /// The newest item, if one was put since the last take. + pub fn take(&self) -> Option> { + let item = self.slot.swap(ptr::null_mut(), Ordering::AcqRel); + // SAFETY: as in `put`: the swap moved the `Arc` out of the slot. + (!item.is_null()).then(|| unsafe { Arc::from_raw(item) }) + } + + /// Wait up to `timeout` for an item. The first thread that waits becomes + /// the consumer that `put` wakes; there should be only one. + pub fn wait_timeout(&self, timeout: Duration) -> Option> { + if let Some(item) = self.take() { + return Some(item); + } + let current = std::thread::current(); + let parks = self.consumer.get_or_init(|| current.clone()).id() == current.id(); + let deadline = Instant::now() + timeout; + loop { + if let Some(item) = self.take() { + return Some(item); + } + let now = Instant::now(); + if now >= deadline || self.is_closed() { + return None; + } + if parks { + std::thread::park_timeout(deadline - now); + } else { + // Not the registered consumer: poll. + std::thread::sleep((deadline - now).min(Duration::from_millis(1))); + } + } + } + + /// Wake the consumer and make waits return at once (items can still be + /// taken). + pub fn close(&self) { + self.closed.store(true, Ordering::Release); + if let Some(consumer) = self.consumer.get() { + consumer.unpark(); + } + } + + pub fn is_closed(&self) -> bool { + self.closed.load(Ordering::Acquire) + } + + /// Items dropped because a newer one replaced them before the consumer + /// took them. + pub fn replaced(&self) -> u64 { + self.replaced.load(Ordering::Relaxed) + } +} + +impl Drop for Handoff { + fn drop(&mut self) { + drop(self.take()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn newest_wins() { + let handoff = Handoff::new(); + assert!(handoff.take().is_none()); + assert!(!handoff.put(Arc::new(1))); + assert!(handoff.put(Arc::new(2))); + assert_eq!(handoff.replaced(), 1); + assert_eq!(handoff.take().as_deref(), Some(&2)); + assert!(handoff.take().is_none()); + // Items left in the slot are dropped with it. + let item = Arc::new(3); + handoff.put(item.clone()); + drop(handoff); + assert_eq!(Arc::strong_count(&item), 1); + } + + #[test] + fn wakes_the_consumer() { + let handoff = Arc::new(Handoff::new()); + let consumer = std::thread::spawn({ + let handoff = handoff.clone(); + move || { + let mut got = Vec::new(); + while let Some(item) = handoff.wait_timeout(Duration::from_secs(5)) { + got.push(*item); + if *item == 99 { + break; + } + } + got + } + }); + for i in 0..100 { + handoff.put(Arc::new(i)); + if i % 10 == 0 { + std::thread::sleep(Duration::from_millis(1)); + } + } + let got = consumer.join().unwrap(); + assert_eq!(got.last(), Some(&99)); + assert!(got.windows(2).all(|w| w[0] < w[1]), "in order: {got:?}"); + assert_eq!(got.len() as u64 + handoff.replaced(), 100); + } + + #[test] + fn close_ends_waits() { + let handoff = Arc::new(Handoff::::new()); + let waiter = std::thread::spawn({ + let handoff = handoff.clone(); + move || handoff.wait_timeout(Duration::from_secs(10)) + }); + std::thread::sleep(Duration::from_millis(20)); + let started = Instant::now(); + handoff.close(); + assert!(waiter.join().unwrap().is_none()); + assert!(started.elapsed() < Duration::from_secs(5)); + } +} diff --git a/crates/voelin-media/src/lib.rs b/crates/voelin-media/src/lib.rs index 9577a2e..538625b 100644 --- a/crates/voelin-media/src/lib.rs +++ b/crates/voelin-media/src/lib.rs @@ -14,6 +14,11 @@ //! PipeWire system audio (feature `pipewire`), and Windows Graphics Capture //! plus WASAPI loopback on Windows //! - [`queue`]: the bounded, drop-oldest channel capture backends deliver on +//! - the streaming path: [`workers`] (a fork-join pool that allocates +//! nothing per job), [`pool`] (recycled I420 frames), [`handoff`] +//! (one-slot latest-wins handoff between threads), [`scale`] (plane +//! scaling and the [`scale::Pyramid`] of simulcast sizes), and +//! [`convert::Converter`] (borrowed capture buffers straight to I420) //! //! Encoded frames go to `voelin_stream::Peer::write` with an RTP time of //! [`EncodedFrame::pts_90khz`] (90 kHz clock); received `MediaFrame`s go to @@ -23,14 +28,20 @@ pub mod capture; pub mod codec; pub mod convert; pub mod frame; +pub mod handoff; +pub mod pool; pub mod queue; +pub mod scale; +pub mod workers; pub use capture::{AudioCapture, CaptureOptions, CaptureSource, ScreenCapture, SourceId}; pub use codec::{ - Codec, Codecs, ContentHint, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, - VideoEncoder, + Codec, Codecs, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, + VideoDecoder, VideoEncoder, +}; +pub use frame::{ + AudioBuffer, FrameData, FrameRef, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame, }; -pub use frame::{AudioBuffer, FrameData, PixelFormat, Plane, VideoFrame}; pub use queue::{FrameReceiver, FrameSender, frame_channel}; /// Errors of this crate. diff --git a/crates/voelin-media/src/pool.rs b/crates/voelin-media/src/pool.rs new file mode 100644 index 0000000..34b8c5f --- /dev/null +++ b/crates/voelin-media/src/pool.rs @@ -0,0 +1,100 @@ +//! 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 +//! `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. + +use std::sync::Arc; +use std::time::Duration; + +use crate::frame::{FrameData, Plane, VideoFrame, chroma_size}; + +/// Recycled I420 frames of one size (tightly packed planes). +#[derive(Default)] +pub struct FramePool { + frames: Vec>, + size: (u32, u32), + allocated: u64, +} + +impl FramePool { + pub fn new() -> Self { + Self::default() + } + + /// A `width` x `height` I420 frame nobody else holds, to write into. + /// Its pixels are whatever an earlier user left; clone the `Arc` to + /// 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.frames.clear(); + self.size = (width, height); + } + 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.len() - 1 + } + }; + &mut self.frames[index] + } + + /// Frames allocated since the pool was created. + pub fn allocated(&self) -> u64 { + self.allocated + } + + /// Frames in the pool (free or in use). + pub fn len(&self) -> usize { + self.frames.len() + } + + pub fn is_empty(&self) -> bool { + self.frames.is_empty() + } +} + +/// A zeroed I420 frame with tightly packed planes. +fn blank_i420(width: u32, height: u32) -> VideoFrame { + 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), + u: Plane::filled(cw, ch, 0), + v: Plane::filled(cw, ch, 0), + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reuses_released_frames() { + let mut pool = FramePool::new(); + let a = pool.get(64, 48).clone(); + let b = pool.get(64, 48).clone(); + assert!(!Arc::ptr_eq(&a, &b), "a is still in use"); + assert_eq!(pool.len(), 2); + drop(a); + let c = pool.get(64, 48).clone(); + assert_eq!(pool.allocated(), 2, "the released frame came back"); + assert!(Arc::get_mut(pool.get(64, 48)).is_some()); + drop((b, c)); + // A new size starts over. + let d = pool.get(32, 16).clone(); + assert_eq!((d.width, d.height), (32, 16)); + d.validate().unwrap(); + assert_eq!(pool.len(), 1); + } +} diff --git a/crates/voelin-media/src/scale.rs b/crates/voelin-media/src/scale.rs new file mode 100644 index 0000000..155662b --- /dev/null +++ b/crates/voelin-media/src/scale.rs @@ -0,0 +1,588 @@ +//! Scaling I420 frames, and the pyramid of sizes simulcast layers need. +//! +//! [`PlaneScaler`] resizes one plane with a separable filter whose weights +//! are computed once per size pair: area averaging for downscaling (every +//! source pixel counts by how much of it an output pixel covers, so text +//! and fine lines do not alias at any ratio) and bilinear interpolation for +//! upscaling; exactly half the size takes a 2x2 box fast path. Work is split +//! into bands of output rows on a [`Workers`] pool. +//! +//! [`Pyramid`] turns one captured frame into I420 frames of every size the +//! layers ask for: it converts the capture once at full size +//! ([`Converter`]), then derives each smaller size from the nearest larger +//! one, reusing pooled frames, so a steady stream allocates nothing. + +use std::sync::{Arc, Mutex, PoisonError}; + +use crate::convert::Converter; +use crate::frame::{FrameData, FrameRef, PlaneRef, VideoFrame, chroma_size}; +use crate::pool::FramePool; +use crate::workers::{Slots, Workers}; +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; + +/// Filter taps of one output coordinate: source index of the first tap, and +/// where its weights start. +#[derive(Clone, Copy, Debug)] +struct Taps { + start: u32, + len: u32, + weights: u32, +} + +/// The filter along one axis. +#[derive(Clone, Debug, Default)] +struct Axis { + taps: Vec, + weights: Vec, +} + +impl Axis { + /// Weights (summing to [`ONE`]) mapping `src` samples to `dst`. + 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(); + for o in 0..dst { + scratch.clear(); + if ratio >= 1.0 { + // Area: source pixels overlapping [o, o + 1) * ratio. + let (lo, hi) = (o as f64 * ratio, (o as f64 + 1.0) * ratio); + let first = lo.floor() as usize; + let last = (hi.ceil() as usize).min(src); + for i in first..last { + let overlap = hi.min(i as f64 + 1.0) - lo.max(i as f64); + if overlap > 1e-9 { + scratch.push((i, overlap / ratio)); + } + } + } else { + // Bilinear between the two nearest source pixels. + let s = ((o as f64 + 0.5) * ratio - 0.5).clamp(0.0, (src - 1) as f64); + let i = s.floor() as usize; + let f = s - i as f64; + scratch.push((i, 1.0 - f)); + if i + 1 < src && f > 1e-9 { + scratch.push((i + 1, f)); + } + } + axis.push(&scratch); + } + axis + } + + /// Quantize one output's weights so they sum to exactly [`ONE`]. + fn push(&mut self, taps: &[(usize, f64)]) { + let offset = self.weights.len() as u32; + let mut sum = 0; + for &(_, w) in taps { + let q = (w * f64::from(ONE)).round() as u32; + self.weights.push(q); + sum += q; + } + // Rounding error goes to the largest weight. + let slice = &mut self.weights[offset as usize..]; + if let Some(largest) = slice.iter_mut().max_by_key(|w| **w) { + *largest = (*largest + ONE).saturating_sub(sum); + } + self.taps.push(Taps { start: taps[0].0 as u32, len: taps.len() as u32, weights: offset }); + } + + 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]) + } +} + +/// Resizes planes of one source size to one destination size. +pub struct PlaneScaler { + src: (usize, usize), + dst: (usize, usize), + x: Axis, + y: Axis, + /// Exactly half the size: 2x2 box average. + half: bool, + /// One row of vertically filtered samples per task. + scratch: Vec>>, +} + +impl PlaneScaler { + pub fn new(src: (usize, usize), dst: (usize, usize)) -> Self { + let (src, dst) = ((src.0.max(1), src.1.max(1)), (dst.0.max(1), dst.1.max(1))); + let half = src.0 == dst.0 * 2 && src.1 == dst.1 * 2; + let (x, y) = if half { + (Axis::default(), Axis::default()) + } else { + (Axis::new(src.0, dst.0), Axis::new(src.1, dst.1)) + }; + Self { src, dst, x, y, half, scratch: Vec::new() } + } + + pub fn sizes(&self) -> ((usize, usize), (usize, usize)) { + (self.src, self.dst) + } + + /// Scale `src` into `dst` (`dst_stride` bytes per row). + pub fn scale( + &mut self, + workers: &mut Workers, + src: PlaneRef<'_>, + dst: &mut [u8], + dst_stride: usize, + ) -> Result<()> { + let ((sw, sh), (dw, dh)) = (self.src, self.dst); + if src.stride < sw || src.data.len() < src.stride * (sh - 1) + sw { + return Err(Error::InvalidFrame("scaler source plane too small".into())); + } + if dst_stride < dw || dst.len() < dst_stride * (dh - 1) + dw { + return Err(Error::InvalidFrame("scaler destination plane too small".into())); + } + let tasks = workers.tasks(dh); + let band = dh.div_ceil(tasks); + let tasks = dh.div_ceil(band); + if !self.half { + while self.scratch.len() < tasks { + self.scratch.push(Mutex::new(vec![0; sw])); + } + } + let slots = Slots::new(dst.chunks_mut(band * dst_stride).take(tasks).enumerate()); + let this = &*self; + workers.run(slots.len(), &|task| { + let Some((i, out)) = slots.take(task) else { return }; + let rows = i * band..((i + 1) * band).min(dh); + if this.half { + half_rows(src, out, dst_stride, dw, rows); + } else { + let mut tmp = this.scratch[i].lock().unwrap_or_else(PoisonError::into_inner); + this.filter_rows(src, out, dst_stride, rows, &mut tmp); + } + }); + Ok(()) + } + + fn filter_rows( + &self, + src: PlaneRef<'_>, + out: &mut [u8], + stride: usize, + rows: std::ops::Range, + tmp: &mut [u16], + ) { + let (sw, dw) = (self.src.0, self.dst.0); + let first = rows.start; + for oy in rows { + // Vertical pass: tmp = weighted sum of source rows, with + // MID_BITS fractional bits. + let (start, weights) = self.y.get(oy); + const CHUNK: usize = 64; + let mut acc = [0u32; CHUNK]; + let mut x0 = 0; + while x0 < sw { + let n = CHUNK.min(sw - x0); + let acc = &mut acc[..n]; + acc.fill(0); + for (k, &w) in weights.iter().enumerate() { + let row = &src.row(start + k, sw)[x0..x0 + n]; + for (a, &p) in acc.iter_mut().zip(row) { + *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; + } + // Horizontal pass. + let line = &mut out[(oy - first) * stride..][..dw]; + for (ox, px) in line.iter_mut().enumerate() { + let (start, weights) = self.x.get(ox); + let sum: u32 = + weights.iter().zip(&tmp[start..]).map(|(&w, &t)| w * u32::from(t)).sum(); + *px = ((sum + (1 << (13 + MID_BITS))) >> (14 + MID_BITS)).min(255) as u8; + } + } + } +} + +/// 2x2 box average of output rows `rows` (source exactly twice the size). +fn half_rows( + src: PlaneRef<'_>, + out: &mut [u8], + stride: usize, + dw: usize, + rows: std::ops::Range, +) { + let first = rows.start; + for oy in rows { + let a = src.row(oy * 2, dw * 2); + let b = src.row(oy * 2 + 1, dw * 2); + let line = &mut out[(oy - first) * stride..][..dw]; + for ((px, a), b) in line.iter_mut().zip(a.chunks_exact(2)).zip(b.chunks_exact(2)) { + let sum = u16::from(a[0]) + u16::from(a[1]) + u16::from(b[0]) + u16::from(b[1]); + *px = ((sum + 2) >> 2) as u8; + } + } +} + +/// Scalers for the three planes of an I420 frame (U and V share one). +struct I420Scaler { + luma: PlaneScaler, + chroma: PlaneScaler, +} + +impl I420Scaler { + fn new(src: (u32, u32), dst: (u32, u32)) -> Self { + let (sc, dc) = (chroma_size(src.0, src.1), chroma_size(dst.0, dst.1)); + Self { + luma: PlaneScaler::new( + (src.0 as usize, src.1 as usize), + (dst.0 as usize, dst.1 as usize), + ), + chroma: PlaneScaler::new(sc, dc), + } + } + + fn scale( + &mut self, + workers: &mut Workers, + src: &VideoFrame, + dst: &mut VideoFrame, + ) -> Result<()> { + let (FrameData::I420 { y, u, v }, FrameData::I420 { y: dy, u: du, v: dv }) = + (&src.data, &mut dst.data) + else { + return Err(Error::InvalidFrame("scaling needs I420 frames".into())); + }; + self.luma.scale(workers, y.view(), &mut dy.data, dy.stride)?; + self.chroma.scale(workers, u.view(), &mut du.data, du.stride)?; + self.chroma.scale(workers, v.view(), &mut dv.data, dv.stride)?; + dst.timestamp = src.timestamp; + Ok(()) + } +} + +/// Scale an I420 frame into another of a different size (allocates filter +/// tables; for repeated use see [`Pyramid`]). +pub fn scale_i420(workers: &mut Workers, src: &VideoFrame, dst: &mut VideoFrame) -> Result<()> { + src.validate()?; + dst.validate()?; + I420Scaler::new((src.width, src.height), (dst.width, dst.height)).scale(workers, src, dst) +} + +/// One size of the pyramid. +struct Level { + size: (u32, u32), + /// The level this one is scaled from; `None`: from the full-size frame. + source: Option, + scaler: Option, + pool: FramePool, + /// This frame's picture at this size. + current: Option>, + /// Needed for this frame (an output is due, or a needed level is scaled + /// from it). + needed: bool, +} + +/// Turns captured frames into I420 frames of several sizes; see the +/// [module docs](self). +pub struct Pyramid { + converter: Converter, + input: (u32, u32), + full: FramePool, + levels: Vec, + /// For each output: its level. + outputs: Vec, + /// The output sizes the plan was made for. + planned: Vec<(u32, u32)>, +} + +impl Pyramid { + /// `threads` as in [`Workers::new`](crate::workers::Workers::new) (0: + /// one per CPU). + pub fn new(threads: usize) -> Self { + Self { + converter: Converter::new(threads), + input: (0, 0), + full: FramePool::new(), + levels: Vec::new(), + outputs: Vec::new(), + planned: Vec::new(), + } + } + + /// Threads converting and scaling, the caller included. + pub fn threads(&self) -> usize { + self.converter.threads() + } + + /// Plan the levels for these output sizes and this input size. + fn plan(&mut self, input: (u32, u32), sizes: &[(u32, u32)]) { + self.input = input; + self.planned.clear(); + self.planned.extend_from_slice(sizes); + let mut distinct: Vec<(u32, u32)> = sizes.iter().copied().filter(|&s| s != input).collect(); + distinct.sort_unstable_by_key(|&(w, h)| std::cmp::Reverse(u64::from(w) * u64::from(h))); + distinct.dedup(); + self.levels.clear(); + for size in distinct { + // The smallest planned level that covers this size, else the + // full frame. + let source = self + .levels + .iter() + .enumerate() + .filter(|(_, l)| l.size.0 >= size.0 && l.size.1 >= size.1) + .min_by_key(|(_, l)| u64::from(l.size.0) * u64::from(l.size.1)) + .map(|(i, _)| i); + let from = source.map_or(input, |i| self.levels[i].size); + self.levels.push(Level { + size, + source, + scaler: Some(I420Scaler::new(from, size)), + pool: FramePool::new(), + current: None, + needed: false, + }); + } + self.outputs.clear(); + for &size in sizes { + let level = self.levels.iter().position(|l| l.size == size).unwrap_or(usize::MAX); + self.outputs.push(level); + } + } + + /// Produce frames for the outputs of this capture: `sizes[i]` is output + /// `i`'s size, and `out[i]` gets its frame if `due[i]` (else `None`). + /// Outputs of the same size share one frame; the capture is converted + /// once. Allocates only when sizes change or all pooled frames are in + /// use. + pub fn process( + &mut self, + frame: &FrameRef<'_>, + sizes: &[(u32, u32)], + due: &[bool], + out: &mut [Option>], + ) -> Result<()> { + let input = (frame.width, frame.height); + if input != self.input || sizes != self.planned.as_slice() { + self.plan(input, sizes); + } + for level in &mut self.levels { + level.needed = false; + level.current = None; + } + let mut full_needed = false; + for (i, &level) in self.outputs.iter().enumerate() { + if !due.get(i).copied().unwrap_or(false) { + continue; + } + let mut at = level; + if at == usize::MAX { + full_needed = true; + continue; + } + // Mark the chain of sources. + loop { + self.levels[at].needed = true; + match self.levels[at].source { + Some(s) => at = s, + None => { + full_needed = true; + break; + } + } + } + } + let full = if full_needed { + let slot = self.full.get(input.0, input.1); + let target = Arc::get_mut(slot).expect("the pool hands out unshared frames"); + self.converter.to_i420_into(frame, target)?; + Some(slot.clone()) + } else { + None + }; + for i in 0..self.levels.len() { + if !self.levels[i].needed { + continue; + } + let source = match self.levels[i].source { + Some(s) => self.levels[s].current.clone(), + None => full.clone(), + } + .expect("sources come first and are needed"); + let level = &mut self.levels[i]; + let slot = level.pool.get(level.size.0, level.size.1); + let target = Arc::get_mut(slot).expect("the pool hands out unshared frames"); + let scaler = level.scaler.as_mut().expect("planned"); + scaler.scale(self.converter.workers(), &source, target)?; + level.current = Some(slot.clone()); + } + for (i, slot) in out.iter_mut().enumerate() { + *slot = None; + if !due.get(i).copied().unwrap_or(false) { + continue; + } + *slot = match self.outputs.get(i) { + Some(&usize::MAX) => full.clone(), + Some(&level) => self.levels[level].current.clone(), + None => None, + }; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + use crate::convert; + use crate::frame::{PixelsRef, Plane}; + + fn gray(w: usize, h: usize, f: impl Fn(usize, usize) -> u8) -> Plane { + let mut data = vec![0; w * h]; + for y in 0..h { + for x in 0..w { + data[y * w + x] = f(x, y); + } + } + Plane::new(data, w) + } + + fn scale_plane(src: &Plane, sw: usize, sh: usize, dw: usize, dh: usize) -> Vec { + let mut workers = Workers::new("test-scale", 3); + let mut scaler = PlaneScaler::new((sw, sh), (dw, dh)); + let mut out = vec![0; dw * dh]; + scaler.scale(&mut workers, src.view(), &mut out, dw).unwrap(); + out + } + + #[test] + fn flat_stays_flat_at_any_ratio() { + for (sw, sh, dw, dh) in + [(64, 48, 32, 24), (1920, 1080, 1280, 720), (97, 55, 30, 17), (40, 30, 64, 45)] + { + let src = gray(sw, sh, |_, _| 77); + let out = scale_plane(&src, sw, sh, dw, dh); + assert!(out.iter().all(|&p| p == 77), "{sw}x{sh} -> {dw}x{dh}"); + } + } + + #[test] + fn area_average_and_half() { + // Alternating columns 0/200 average to 100 at half and a third of + // the width. + let src = gray(12, 4, |x, _| if x % 2 == 0 { 0 } else { 200 }); + assert!(scale_plane(&src, 12, 4, 6, 2).iter().all(|&p| p == 100)); + let third = scale_plane(&src, 12, 4, 4, 4); + // Each output covers three columns: 0,200,0 or 200,0,200. + assert_eq!(third[..4], [67, 133, 67, 133]); + // A gradient keeps its mean. + let src = gray(300, 10, |x, _| (x * 255 / 299) as u8); + let out = scale_plane(&src, 300, 10, 128, 7); + let mean = |d: &[u8]| d.iter().map(|&p| f64::from(p)).sum::() / d.len() as f64; + assert!((mean(&out) - mean(&src.data)).abs() < 1.0); + assert!(out.windows(2).take(127).all(|w| w[0] <= w[1]), "monotonic"); + } + + fn bgra(w: u32, h: u32, n: u32) -> VideoFrame { + let mut data = vec![0; (w * h * 4) as usize]; + for y in 0..h { + for x in 0..w { + let i = ((y * w + x) * 4) as usize; + let inside = x / 16 % 2 == (y / 16 + n) % 2; + let c = if inside { [30, 90, 240, 255] } else { [200, 200, 200, 255] }; + data[i..i + 4].copy_from_slice(&c); + } + } + VideoFrame::from_bgra(w, h, (w * 4) as usize, data) + .unwrap() + .with_timestamp(Duration::from_millis(u64::from(n))) + } + + #[test] + fn pyramid_outputs_share_and_recycle() { + let mut pyramid = Pyramid::new(3); + let sizes = [(320, 240), (160, 120), (320, 240), (106, 80)]; + let mut out = vec![None; 4]; + let src = bgra(320, 240, 0); + pyramid.process(&src.view(), &sizes, &[true, true, true, true], &mut out).unwrap(); + let frames: Vec> = out.iter().map(|f| f.clone().unwrap()).collect(); + assert!(Arc::ptr_eq(&frames[0], &frames[2]), "same size, same frame"); + for (f, &(w, h)) in frames.iter().zip(&sizes) { + assert_eq!((f.width, f.height), (w, h)); + f.validate().unwrap(); + } + // The full size matches a direct conversion. + let direct = convert::to_i420(&src).unwrap(); + assert_eq!(*frames[0], *direct); + // Scaled levels look like the source scaled directly. + for i in [1, 3] { + let mut expected = VideoFrame::black_i420(sizes[i].0, sizes[i].1); + scale_i420(&mut Workers::new("test", 1), &frames[0], &mut expected).unwrap(); + let psnr = convert::psnr(&frames[i], &expected).unwrap(); + assert!(psnr > 35.0, "level {i}: {psnr:.1} dB"); + } + + // Not due: no frame. Frames still held are not reused. + pyramid + .process(&bgra(320, 240, 1).view(), &sizes, &[false, true, false, false], &mut out) + .unwrap(); + assert!(out[0].is_none() && out[3].is_none()); + assert!(!Arc::ptr_eq(out[1].as_ref().unwrap(), &frames[1])); + assert_eq!(out[1].as_ref().unwrap().timestamp, Duration::from_millis(1)); + drop(frames); + // Steady state: the pools stop growing. + for n in 2..10 { + pyramid.process(&bgra(320, 240, n).view(), &sizes, &[true; 4], &mut out).unwrap(); + } + let allocated = pyramid.full.allocated() + + pyramid.levels.iter().map(|l| l.pool.allocated()).sum::(); + for n in 10..20 { + pyramid.process(&bgra(320, 240, n).view(), &sizes, &[true; 4], &mut out).unwrap(); + } + let after = pyramid.full.allocated() + + pyramid.levels.iter().map(|l| l.pool.allocated()).sum::(); + assert_eq!(allocated, after); + } + + #[test] + fn converter_handles_strides_and_unpadded_last_rows() { + let src = bgra(66, 34, 3); + let FrameData::Bgra(plane) = &src.data else { unreachable!() }; + // Re-pack with a 300-byte stride and no padding after the last row. + let stride = 300; + let mut data = vec![0xee; stride * 33 + 66 * 4]; + for y in 0..34 { + let row = plane.row(y, 66 * 4); + data[y * stride..y * stride + 66 * 4].copy_from_slice(row); + } + let view = FrameRef { + width: 66, + height: 34, + timestamp: src.timestamp, + pixels: PixelsRef::Bgra(PlaneRef::new(&data, stride)), + }; + let mut converter = Converter::new(4); + let mut pool = FramePool::new(); + let target = Arc::get_mut(pool.get(66, 34)).unwrap(); + converter.to_i420_into(&view, target).unwrap(); + assert_eq!(*target, *convert::to_i420(&src).unwrap()); + // Odd height, RGBA. + let odd = VideoFrame::from_rgba(33, 17, 33 * 4, vec![128; 33 * 17 * 4]).unwrap(); + let target = Arc::get_mut(pool.get(33, 17)).unwrap(); + converter.to_i420_into(&odd.view(), target).unwrap(); + assert_eq!(*target, *convert::to_i420(&odd).unwrap()); + // I420 and NV12 sources are copied. + let i420 = convert::to_i420(&src).unwrap().into_owned(); + let target = Arc::get_mut(pool.get(66, 34)).unwrap(); + converter.to_i420_into(&i420.view(), target).unwrap(); + assert_eq!(*target, i420); + assert!(converter.to_i420_into(&odd.view(), target).is_err(), "size mismatch"); + } +} diff --git a/crates/voelin-media/src/workers.rs b/crates/voelin-media/src/workers.rs new file mode 100644 index 0000000..b904187 --- /dev/null +++ b/crates/voelin-media/src/workers.rs @@ -0,0 +1,316 @@ +//! A small fork-join thread pool for per-frame pixel work. +//! +//! [`Workers::run`] splits a job into numbered tasks that the pool's threads +//! and the calling thread claim until none are left, and returns once all of +//! them finished. Unlike `std::thread::scope` it spawns nothing per job, and +//! unlike a general task queue it allocates nothing per job: the job is a +//! borrowed closure, published through a mutex and condition variable +//! (futexes on Linux and Android, SRW locks on Windows). +#![allow(unsafe_code)] + +use std::any::Any; +use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; +use std::thread::JoinHandle; + +/// Most tasks one job is split into (see [`Workers::tasks`]). +pub const MAX_TASKS: usize = 64; + +/// The job of one [`Workers::run`] call. +#[derive(Clone, Copy)] +struct Job { + /// The caller's closure with its lifetime erased; see [`Workers::run`] + /// for why it stays valid while a worker uses it. + f: *const (dyn Fn(usize) + Sync + 'static), + tasks: usize, +} + +// SAFETY: the closure is `Sync`, so calling it from several threads through +// a shared pointer is allowed; the pointer is only dereferenced while the +// `run` call that owns the closure waits (see `Workers::run`). +unsafe impl Send for Job {} + +struct State { + /// Bumped for every job. + generation: u64, + job: Option, + /// Workers that took the current job and have not given it back. + active: usize, + /// Tasks of the current job that are done. + finished: usize, + panic: Option>, + stop: bool, +} + +struct Shared { + state: Mutex, + /// Workers wait here for a job. + wake: Condvar, + /// The caller waits here for the last task. + done: Condvar, + /// The next task to claim. + next: AtomicUsize, +} + +impl Shared { + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +/// Run tasks of `job` until none are left; returns how many this thread +/// ran. +fn claim(shared: &Shared, job: Job, panic: &mut Option>) -> usize { + let mut count = 0; + loop { + let task = shared.next.fetch_add(1, Ordering::Relaxed); + if task >= job.tasks { + return count; + } + // SAFETY: `job.f` points to the closure of the `run` call that + // published `job`; that call does not return before every thread + // that took the job gave it back (`active`), so the closure lives. + let f = unsafe { &*job.f }; + if let Err(e) = catch_unwind(AssertUnwindSafe(|| f(task))) { + panic.get_or_insert(e); + } + count += 1; + } +} + +/// A pool of threads for splitting per-frame work. Stops its threads when +/// dropped. +pub struct Workers { + shared: Arc, + threads: Vec>, +} + +impl Workers { + /// A pool that uses `threads` threads in total, the caller of + /// [`Workers::run`] included (so `threads - 1` are spawned). 0 means one + /// per available CPU. + pub fn new(name: &str, threads: usize) -> Self { + let threads = match threads { + 0 => std::thread::available_parallelism().map_or(1, |n| n.get()), + n => n, + }; + let shared = Arc::new(Shared { + state: Mutex::new(State { + generation: 0, + job: None, + active: 0, + finished: 0, + panic: None, + stop: false, + }), + wake: Condvar::new(), + done: Condvar::new(), + next: AtomicUsize::new(0), + }); + let mut workers = Self { shared, threads: Vec::new() }; + for i in 1..threads { + let shared = workers.shared.clone(); + let spawned = std::thread::Builder::new() + .name(format!("{name}-{i}")) + .spawn(move || worker(&shared)); + match spawned { + Ok(thread) => workers.threads.push(thread), + Err(e) => { + tracing::warn!("cannot start a pixel worker thread: {e}"); + break; + } + } + } + workers + } + + /// Threads that work on a job, the caller included. + pub fn threads(&self) -> usize { + self.threads.len() + 1 + } + + /// A good number of tasks to split a job of `units` independent parts + /// (e.g. pairs of rows) into: a few per thread, so a thread that gets + /// descheduled does not hold everyone up. + pub fn tasks(&self, units: usize) -> usize { + (self.threads() * 3).min(MAX_TASKS).min(units).max(1) + } + + /// Call `f(0)`, ..., `f(tasks - 1)` on the pool's threads and this one, + /// each exactly once, and return when all returned. A panic in `f` is + /// resumed here after the other tasks finished. + pub fn run(&mut self, tasks: usize, f: &(dyn Fn(usize) + Sync)) { + if tasks <= 1 || self.threads.is_empty() { + (0..tasks).for_each(f); + return; + } + // SAFETY: this only erases the lifetime. The pointer is published in + // `State::job` below and removed before this function returns. A + // worker copies it only while holding the lock and counts itself in + // `active` in the same critical section; it gives it back + // (`active -= 1`) after its last use. This function waits until + // `active` is zero, and takes `&mut self`, so no second job can + // overlap. Hence `f` outlives every dereference of the pointer. + let f_static: &'static (dyn Fn(usize) + Sync) = unsafe { std::mem::transmute(f) }; + let job = Job { f: f_static, tasks }; + { + let mut state = self.shared.lock(); + self.shared.next.store(0, Ordering::Relaxed); + state.generation = state.generation.wrapping_add(1); + state.job = Some(job); + state.finished = 0; + } + self.shared.wake.notify_all(); + let mut panic = None; + let count = claim(&self.shared, job, &mut panic); + let mut state = self.shared.lock(); + state.finished += count; + while state.finished < tasks || state.active > 0 { + state = self.shared.done.wait(state).unwrap_or_else(PoisonError::into_inner); + } + state.job = None; + let panic = panic.or_else(|| state.panic.take()); + drop(state); + if let Some(panic) = panic { + resume_unwind(panic); + } + } +} + +fn worker(shared: &Shared) { + let mut seen = 0; + loop { + let job = { + let mut state = shared.lock(); + loop { + if state.stop { + return; + } + if let Some(job) = state.job + && state.generation != seen + { + seen = state.generation; + state.active += 1; + break job; + } + state = shared.wake.wait(state).unwrap_or_else(PoisonError::into_inner); + } + }; + let mut panic = None; + let count = claim(shared, job, &mut panic); + let mut state = shared.lock(); + state.finished += count; + state.active -= 1; + if panic.is_some() && state.panic.is_none() { + state.panic = panic; + } + if state.active == 0 && state.finished >= job.tasks { + shared.done.notify_all(); + } + } +} + +impl Drop for Workers { + fn drop(&mut self) { + self.shared.lock().stop = true; + self.shared.wake.notify_all(); + for thread in self.threads.drain(..) { + let _ = thread.join(); + } + } +} + +/// Hands out the items of a slice to the tasks of a [`Workers::run`] job, +/// each item to exactly one task, without `unsafe` or allocation. +pub struct Slots { + slots: [Mutex>; MAX_TASKS], + len: usize, +} + +impl Slots { + /// Up to [`MAX_TASKS`] items; more panic. + pub fn new(items: impl IntoIterator) -> Self { + let slots = std::array::from_fn(|_| Mutex::new(None)); + let mut len = 0; + for (slot, item) in slots.iter().zip(items) { + *slot.lock().unwrap_or_else(PoisonError::into_inner) = Some(item); + len += 1; + } + Self { slots, len } + } + + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + /// Item `i`, once. + pub fn take(&self, i: usize) -> Option { + self.slots.get(i)?.lock().unwrap_or_else(PoisonError::into_inner).take() + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::AtomicU64; + + use super::*; + + #[test] + fn runs_every_task_once() { + let mut workers = Workers::new("test-workers", 4); + assert_eq!(workers.threads(), 4); + for round in 0..200 { + let tasks = 1 + round % 40; + let hits: Vec = (0..tasks).map(|_| AtomicU64::new(0)).collect(); + workers.run(tasks, &|i| { + hits[i].fetch_add(1, Ordering::Relaxed); + }); + assert!(hits.iter().all(|h| h.load(Ordering::Relaxed) == 1), "round {round}"); + } + } + + #[test] + fn borrows_and_mutates_through_slots() { + let mut workers = Workers::new("test-workers", 3); + let mut data = vec![0u32; 1000]; + let slots = Slots::new(data.chunks_mut(100)); + assert_eq!(slots.len(), 10); + workers.run(slots.len(), &|i| { + for x in slots.take(i).unwrap() { + *x = i as u32 + 1; + } + }); + assert!(data.chunks(100).enumerate().all(|(i, c)| c.iter().all(|&x| x == i as u32 + 1))); + } + + #[test] + fn panics_reach_the_caller_and_the_pool_survives() { + let mut workers = Workers::new("test-workers", 2); + let result = catch_unwind(AssertUnwindSafe(|| { + workers.run(8, &|i| assert_ne!(i, 5, "task five")); + })); + assert!(result.is_err()); + let count = AtomicU64::new(0); + workers.run(8, &|_| { + count.fetch_add(1, Ordering::Relaxed); + }); + assert_eq!(count.load(Ordering::Relaxed), 8); + } + + #[test] + fn single_thread_runs_inline() { + let mut workers = Workers::new("test-workers", 1); + assert_eq!(workers.threads(), 1); + assert_eq!(workers.tasks(100), 3); + let count = AtomicU64::new(0); + workers.run(5, &|_| { + count.fetch_add(1, Ordering::Relaxed); + }); + assert_eq!(count.load(Ordering::Relaxed), 5); + } +} diff --git a/crates/voelin-media/tests/wlroots_capture.rs b/crates/voelin-media/tests/wlroots_capture.rs new file mode 100644 index 0000000..d0edba4 --- /dev/null +++ b/crates/voelin-media/tests/wlroots_capture.rs @@ -0,0 +1,97 @@ +//! wlroots capture against a real compositor: lists outputs, captures the +//! background colour, changes it through sway's IPC and sees the change. +//! +//! Needs a headless sway and its sockets, e.g. +//! +//! ```sh +//! printf 'output HEADLESS-1 resolution 640x480 bg #204080 solid_color\n' > /tmp/sway.conf +//! XDG_RUNTIME_DIR=/tmp/vsw WLR_BACKENDS=headless WLR_LIBINPUT_NO_DEVICES=1 \ +//! WLR_RENDERER=pixman sway -c /tmp/sway.conf & +//! VOELIN_WLROOTS_TEST_DISPLAY=/tmp/vsw/wayland-1 \ +//! VOELIN_WLROOTS_TEST_SWAYSOCK=$(ls /tmp/vsw/sway-ipc.*.sock) \ +//! cargo test -p voelin-media --test wlroots_capture +//! ``` +//! +//! Skipped without `VOELIN_WLROOTS_TEST_DISPLAY`. +#![cfg(all(target_os = "linux", feature = "wlroots"))] + +use std::sync::mpsc; +use std::time::Duration; + +use voelin_media::capture::wlroots::WlrootsCapture; +use voelin_media::capture::{FrameSink, ScreenCapture}; +use voelin_media::{CaptureOptions, FrameRef, PixelsRef, SourceId}; + +/// Sends the centre pixel (RGB) and size of each frame. +struct Probe(mpsc::Sender<([u8; 3], u32, u32)>); + +impl FrameSink for Probe { + fn max_fps(&self) -> u32 { + 30 + } + + fn frame(&mut self, frame: FrameRef<'_>) -> bool { + let (x, y) = (frame.width as usize / 2, frame.height as usize / 2); + let rgb = match frame.pixels { + PixelsRef::Bgra(p) => { + let px = &p.row(y, frame.width as usize * 4)[x * 4..x * 4 + 4]; + [px[2], px[1], px[0]] + } + PixelsRef::Rgba(p) => { + let px = &p.row(y, frame.width as usize * 4)[x * 4..x * 4 + 4]; + [px[0], px[1], px[2]] + } + _ => panic!("unexpected format {:?}", frame.format()), + }; + self.0.send((rgb, frame.width, frame.height)).is_ok() + } +} + +fn sway_background(color: &str) { + let Some(sock) = std::env::var_os("VOELIN_WLROOTS_TEST_SWAYSOCK") else { return }; + let status = std::process::Command::new("swaymsg") + .env("SWAYSOCK", sock) + .args(["output", "*", "bg", color, "solid_color"]) + .status() + .expect("swaymsg"); + assert!(status.success()); +} + +#[tokio::test] +async fn captures_outputs() { + let Some(display) = std::env::var_os("VOELIN_WLROOTS_TEST_DISPLAY") else { + eprintln!("skipped: VOELIN_WLROOTS_TEST_DISPLAY is not set"); + return; + }; + sway_background("#204080"); + let mut capture = WlrootsCapture::with_display(&display); + assert!(capture.is_available()); + let sources = capture.sources().unwrap(); + assert!(!sources.is_empty(), "no outputs"); + eprintln!("outputs: {sources:?}"); + assert_eq!(sources[0].id, SourceId::Monitor(0)); + assert!(capture.start(&SourceId::Monitor(99), &CaptureOptions::default()).await.is_err()); + + let (tx, rx) = mpsc::channel(); + let options = CaptureOptions { cursor: false, ..CaptureOptions::default() }; + capture.start_sink(&SourceId::Monitor(0), &options, Box::new(Probe(tx))).await.unwrap(); + let (rgb, w, h) = rx.recv_timeout(Duration::from_secs(5)).expect("a first frame"); + assert_eq!((w, h), (sources[0].width, sources[0].height)); + assert_eq!(rgb, [0x20, 0x40, 0x80]); + if std::env::var_os("VOELIN_WLROOTS_TEST_SWAYSOCK").is_some() { + // New content: a new frame with the new colour. + sway_background("#c04020"); + let changed = (0..20).any(|_| { + rx.recv_timeout(Duration::from_secs(5)).is_ok_and(|(rgb, ..)| rgb == [0xc0, 0x40, 0x20]) + }); + assert!(changed, "the background change was not captured"); + } + capture.stop(); + + // The queue API copies frames out. + let mut frames = capture.start(&SourceId::Monitor(0), &options).await.unwrap(); + let frame = frames.recv_timeout(Duration::from_secs(5)).expect("a queued frame"); + assert_eq!((frame.width, frame.height), (w, h)); + capture.stop(); + sway_background("#204080"); +} diff --git a/docs/media.md b/docs/media.md index 0142556..683a4a6 100644 --- a/docs/media.md +++ b/docs/media.md @@ -11,15 +11,21 @@ MediaTime::new(frame.pts_90khz, Frequency::NINETY_KHZ), data)`), and received | Item | What it is | |---|---| | `VideoFrame { width, height, timestamp, data: FrameData }` | `FrameData::I420 { y, u, v }`, `Nv12 { y, uv }`, `Bgra(Plane)`, `Rgba(Plane)`; `Plane { data, stride }` | +| `FrameRef { width, height, timestamp, pixels: PixelsRef }` | the same with borrowed planes (`PlaneRef { data: &[u8], stride }`), e.g. a mapped capture buffer; `VideoFrame::view()`, `FrameRef::to_frame()` | | `AudioBuffer { samples, channels, timestamp }` | interleaved `f32`, 48 kHz | | `convert::to_rgba(&frame, out, stride)`, `to_rgba_vec`, `to_i420`, `psnr` | BT.601 limited range (the WebRTC default). `to_rgba` writes straight into a Slint `SharedPixelBuffer` (`make_mut_bytes()`, stride `width * 4`) | | `Codec` | `Vp8`, `Vp9`, `H264`, `Av1`; `FromStr` for SDP/MIME names; `From`/`TryFrom` `str0m::format::Codec` with feature `str0m` | -| `VideoEncoder` | `encode(&frame, force_keyframe) -> Vec`, `set_bitrate(bps)`, `codec()`, `backend()` | +| `VideoEncoder` | `encode(&frame, force_keyframe) -> Vec`; `encode_with(&frame, force_keyframe, &mut |EncodedChunk| ..)` hands out the encoder's own buffer (no copy); `set_bitrate(bps)` (libvpx: in place, no keyframe), `set_fps`, `speed()`, `codec()`, `backend()` | | `EncodedFrame { data, keyframe, pts_90khz }` | one frame for `Peer::write` | | `VideoDecoder` | `decode(&[u8]) -> Option` (timestamp zero; the caller knows the RTP time) | -| `EncoderConfig { fps, bitrate_bps, keyframe_interval, content, threads }` | resolution follows the frames; a size change restarts with a keyframe | +| `EncoderConfig { fps, bitrate_bps, keyframe_interval, content, threads, speed }` | resolution follows the frames; a size change restarts with a keyframe; `threads` is a maximum (0: all CPUs but one), still capped at one per 320x240 pixels; `speed: None` adapts libvpx `cpu-used` to the encode time | | `Codecs` | `new()`, `with_openh264(lib)`, `decoders()` (viewer order), `encoders()` / `encoder_codecs()` (streamer order), `new_decoder(codec)`, `new_encoder(codec, config)`, `pick_encoder(&accepted)` | -| `ScreenCapture` | `sources()`, `start(&SourceId, &CaptureOptions)` (async: the portal asks the user), `stop()` | +| `ScreenCapture` | `sources()`, `start_sink(&SourceId, &CaptureOptions, Box)` (frames borrowed from the capture buffer, on the backend's thread), `start(..)` (copies into a queue), `stop()`; async: the portal asks the user | +| `FrameSink` | `max_fps()` (may change while capturing), `wants(timestamp)` (asked before anything is mapped or copied), `frame(FrameRef) -> bool` | +| `FramePacer` | frame-rate cap by timestamps, evenly spaced | +| `convert::Converter` | `to_i420_into(&FrameRef, &mut VideoFrame)`: any stride, BGRx/BGRA/RGBx/RGBA/I420/NV12, row bands on all cores, no allocation | +| `scale::{PlaneScaler, Pyramid, scale_i420}` | area-average downscaling (bilinear up), 2x2 box fast path; `Pyramid::process(&FrameRef, sizes, due, out)` converts once and derives every size from the nearest larger one | +| `pool::FramePool`, `handoff::Handoff`, `workers::Workers` | recycled `Arc`s; one-slot latest-wins handoff between threads (counts replaced items); fork-join pool without per-job allocation | | `AudioCapture` | `start() -> FrameReceiver`, `stop()` | | `FrameReceiver` | bounded queue that drops the oldest item; `recv().await`, `try_recv()`, `recv_timeout()` | | `capture::default_screen_capture()`, `default_audio_capture()` | the backend for this session | @@ -47,20 +53,58 @@ PipeWire). The desktop app and voelinctl use `media-desktop`, the Android app `media`. Codecs are always chosen through `Codecs`, so each build uses its own. ``` -streamer: ScreenCapture ─ VideoEncoder (codec of our offer) ─┐ - AudioCapture ─ 20 ms stereo Opus (128 kbit/s) ─────┴─ MediaSink: StreamSink / EncodedSource +streamer: capture thread ── FrameSink: pace, convert + scale (Pyramid on all cores) + │ one Handoff per layer (newest frame wins) + ├─ encoder thread, layer 0 ─┐ + ├─ encoder thread, layer 1 ─┤ + └─ ... ├─ MediaSink: StreamSink / EncodedSource + AudioCapture ─ 20 ms stereo Opus (128 kbit/s) ─┘ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder ─ picture callback ─ Latest stream audio ─ session audio thread (mixer, own volume) ─ speakers ``` - `Streamer::start(&codecs, StreamerConfig)` starts capturing right away (the portal asks the user then), so a cancelled dialog never starts a stream; - frames are encoded only after `attach(sink)`, i.e. once the stream is live. - The encoder runs at the setup's bitrate; a viewer's keyframe request (on - the sink) forces a keyframe, and is kept until the encoder produced one. - Audio follows the capture clock across gaps. With the test pattern - (`SourceId::Synthetic`) the audio is a quiet sine tone. The portal's restore - token is available afterwards (`restore_token()`) to store. + frames are converted and encoded only after `attach(sink)`, i.e. once the + stream is live. Audio follows the capture clock across gaps. With the test + pattern (`SourceId::Synthetic`, `synthetic_pattern`) the audio is a quiet + sine tone. The portal's restore token is available afterwards + (`restore_token()`) to store. +- Threads: the capture backend calls the streamer's `FrameSink` on its own + thread with the frame still in its capture buffer. Frames over the + frame-rate cap (`StreamerConfig::fps`, any value >= 1) are skipped before + anything is read. The rest is converted to I420 once, on all cores, and + scaled for every layer that is due (`Pyramid`, recycled frames). Each + layer's newest frame goes through a one-slot handoff to that layer's + encoder thread; a frame the encoder was too busy for is replaced and + counted, never queued, so latency stays one frame. +- Simulcast: `StreamerConfig::layers` (`voelin_stream::LayerSpec`; empty: + one layer 0 at `bitrate_kbps`) are all encoded, each with its own encoder + at `output_size()` of the source, its own frame-rate cap (`max_fps`, + paced by timestamps) and its share of the CPUs. Frames carry `layer` and + `keyframe`. `MediaSink::take_layer_keyframes` is polled by the encoder + threads; exactly the requested layers encode a keyframe, kept due until + one is produced; a still screen sends no frames, so a request is answered + by encoding the last picture again. Each layer follows + `MediaSink::layer_bitrate(id)` when the sink knows it (capped by + `max_bitrate`), else its configured bitrate; libvpx changes it in place + without a keyframe. +- `Streamer::reconfigure(&codecs, StreamerConfigUpdate { fps, bitrate_kbps, + codec, layers })` applies from the next frame without restarting the + capture: encoders are created first (an error changes nothing), layers + keep their encoder when their id stays, new ids get threads, removed ones + stop, a new codec swaps every encoder (first frame a keyframe), and the + frame-rate cap reaches the capture backend (X11 and the test pattern + retime, the portal renegotiates the rate with the compositor). +- `stats()`: `StreamerStats` with capture fps, convert time and threads, + dropped frames, codec, and per layer (`LayerStats`) size, frames, + keyframes, dropped, fps, kbit/s, encode time, target bitrate, threads + and encoder speed. Counters are atomics; rates are computed once a + second, and a one-line summary is logged every 5 s at debug level + (`RUST_LOG=voelin_core::media=debug`). +- `CaptureBackend`: `Auto` (the session default: portal on Wayland, X11, + WGC), `Portal`, `X11`, `Wlroots`; `name()` / `FromStr` use the settings + spellings `auto`, `portal`, `x11`, `wlroots`. - `peer_config(&codecs, config)` makes a viewer accept only what we decode and a streamer offer only the codec it encodes (VP8 unless changed): all viewers get the same frames, and a viewer picks from the offer. @@ -103,14 +147,31 @@ encoders (H.264, VP9, VP8), then Google's software VP8 and H.264. Decoders return the newest finished picture per `decode` call (NV12 or I420). libvpx settings follow libwebrtc's realtime setup: one pass CBR, no lag, -`VPX_DL_REALTIME`, error resilient, `cpu-used` 8 (VP8: fixed speed −8), keyframes -only at start and on request unless `keyframe_interval` is set, screen content -tuning (`VP8E_SET_SCREEN_CONTENT_MODE`, `VP9E_SET_TUNE_CONTENT`, static -threshold), VP9 row-mt, tiles and cyclic-refresh AQ. `set_bitrate` reconfigures -the running encoder (`vpx_codec_enc_config_set`). The C API is wrapped in -`codec/vpx/raw.rs`, one of three modules with `unsafe` code (with the X11 SHM -mapping and the `Send` wrapper in `codec/mediacodec.rs`); existing safe -wrappers either encode only or cannot change the bitrate at runtime. +`VPX_DL_REALTIME`, error resilient, keyframes only at start and on request +unless `keyframe_interval` is set, screen content tuning +(`VP8E_SET_SCREEN_CONTENT_MODE`, `VP9E_SET_TUNE_CONTENT`, static threshold), +VP9 row-mt, tile columns from the thread count and width (tiles are at least +256 pixels wide) and cyclic-refresh AQ, VP8 token partitions from the thread +count. Threads: all CPUs but one (libvpx threads spin-wait on each other and +slow down many times over when every core is taken), or the streamer's share +of them per layer, at most one per 320x240 pixels. `cpu-used` adapts to the +measured encode time against the frame interval (faster at once when one frame overruns the interval or the +mean is above 75 %; slower when the mean stayed below 35 % for 15 frames, +waiting twice as long after each slower step that had to be undone): VP8 +starts at −10 and moves within −10..−6 (on screen content −12 and faster +were no quicker and about 3 dB worse, −5 and slower about ten times slower +for under 1 dB), VP9 starts at 8 within 5..9; `EncoderConfig::speed` fixes +it instead. Frame durations for rate +control follow the timestamps (variable frame rate), at least 3/4 of the +nominal interval. `set_bitrate` reconfigures the running encoder +(`vpx_codec_enc_config_set`). The C API is wrapped in +`codec/vpx/raw.rs`; existing safe wrappers either encode only or cannot +change the bitrate at runtime. The other modules with `unsafe` code, each +with SAFETY comments: the X11 and wlroots shared-memory mappings +(`capture/x11/shm.rs`, `capture/wlroots.rs`), the DMA-BUF mapping and sync +ioctl (`capture/dmabuf.rs`), the lifetime-erased job of the worker pool +(`workers.rs`), the `Arc` raw pointers of the handoff (`handoff.rs`), and +the `Send` wrapper in `codec/mediacodec.rs`. The OpenH264 encoder has no safe runtime bitrate change in the `openh264` crate, so `set_bitrate` recreates it (the next frame is an IDR). It enables @@ -148,7 +209,8 @@ found at ..."). |---|---|---| | any | `SyntheticScreen` | `SineSource` | | Linux X11 (`x11`, default) | `X11Capture`: MIT-SHM 1.2 (memfd passed to the server) or GetImage; RandR 1.5 monitors; windows from `_NET_CLIENT_LIST` (root children without a WM); XFixes cursor blended in | | -| Linux Wayland (`pipewire`, default) | `PortalCapture`: xdg-desktop-portal ScreenCast via `ashpd`, frames from a PipeWire video stream | `PipeWireAudioCapture`: default sink monitor (`stream.capture.sink = true`) | +| Linux Wayland (`pipewire`, default) | `PortalCapture`: xdg-desktop-portal ScreenCast via `ashpd`, frames from a PipeWire video stream (LINEAR DMA-BUF or shared memory) | `PipeWireAudioCapture`: default sink monitor (`stream.capture.sink = true`) | +| Linux wlroots (`wlroots`, default) | `WlrootsCapture`: `ext-image-copy-capture-v1`, else `wlr-screencopy-unstable-v1`, outputs only, shared memory | | | Windows | `WindowsCapture`: Windows Graphics Capture (`windows-capture`), monitors and windows | `WasapiLoopback`: process loopback excluding our own process tree, falling back to plain loopback | | Android | `ExternalScreenCapture` fed by the app (MediaProjection → `ImageReader`, RGBA; see [android.md](android.md)) | `ExternalAudioCapture` fed by the app (`AudioPlaybackCapture`, 48 kHz float) | @@ -169,10 +231,26 @@ Notes: desktop's picker. Choices persist with `PersistMode::ExplicitlyRevoked`: store `PortalCapture::restore_token()` (e.g. in `voelin-store` settings) and pass it to `PortalCapture::with_restore_token` next time. The cursor is embedded when - the portal supports it. Only shared-memory buffers (BGRx/BGRA/RGBx/RGBA) are - negotiated; DMA-BUF import is a TODO. Without a session bus or portal, - `start` returns `Error::CaptureUnavailable`; a cancelled dialog returns - `Error::Cancelled`. + the portal supports it. Buffers: LINEAR DMA-BUFs are offered first (a + mandatory modifier property we fixate; mapped once per buffer, read + between `DMA_BUF_IOCTL_SYNC` start and end), shared memory + (BGRx/BGRA/RGBx/RGBA) second. If reading DMA-BUFs is slower than 6 ns per + pixel over the first 30 frames (uncached VRAM), the stream renegotiates to + shared memory; `VOELIN_PORTAL_DMABUF=0` or `with_dmabuf(false)` skips them. + Tiled modifiers would need a GPU import (a later step). The frame rate + asked of the compositor is the sink's cap, renegotiated when it changes; + compositors send frames only when the screen changes. Without a session + bus or portal, `start` returns `Error::CaptureUnavailable`; a cancelled + dialog returns `Error::Cancelled`. +- wlroots: `WlrootsCapture::new()` (`$WAYLAND_DISPLAY`) or `with_display`; + sources are the outputs (`SourceId::Monitor(i)`). The compositor copies + into shared-memory buffers allocated once per size; frames complete only + when the screen changed (`copy_with_damage` / image-copy sessions). The + cursor is painted by the compositor when asked. No window capture + (`ext-foreign-toplevel-list`) and no DMA-BUF capture yet. +- X11 reads through the shared-memory segment in place (cursor blended into + it); the monitor or window geometry is looked up once a second rather than + per frame. x11rb still allocates a small reply buffer per request. - PipeWire system audio captures everything the default sink plays, including our own playback (TeamSpeak voices): PipeWire has no "all but this process" monitor. Excluding our nodes needs a private null sink with links from every @@ -181,6 +259,61 @@ Notes: `start` returns `Error::CaptureUnavailable`. - Windows process loopback needs Windows 10 2004 or later. +## Performance and benchmarks + +Per frame, in steady state, nothing is allocated between the capture buffer +and the encoder input (verified with `voelinctl stream bench`, which counts +heap allocations with a counting global allocator): the synthetic source +renders into one buffer, conversion and scaling write into recycled frames, +handoffs are atomic pointer swaps, and libvpx output is borrowed. The one +allocation per encoded frame is the `Arc<[u8]>` of `EncodedFrame`, whose size +varies per frame and so cannot be recycled. Backends outside our control add +their own (x11rb reply buffers; the Android provider hands owned frames). + +```sh +# The real pipeline on the test pattern, no server: +voelinctl stream bench --res 1920x1080 --fps 60 --codec vp8 --seconds 10 +voelinctl stream bench --res 2560x1440 --fps 30 \ + --layer scale=1,bitrate=6M --layer scale=0.5,bitrate=1500k,fps=30 \ + --layer size=640x360,bitrate=400k,fps=15 +# Conversion and scaling alone: +cargo bench -p voelin-media --bench convert +``` + +`--pattern desktop` (default) is a code-editor-like picture whose document +scrolls three pixels per frame, about as costly to encode as real screen +content; `--pattern simple` is the flat test pattern. The bench prints +capture fps, convert time and threads, per layer fps, kbit/s, keyframes, +frames dropped by the handoff, encode time, threads and `cpu-used`, CPU use +and allocations per captured and per encoded frame. + +Measured with the old pipeline (single thread, allocating) and the new one, +release builds (fat LTO), VP8, desktop pattern, one layer, 8 s, on a shared +4-core VM, runs interleaved. fps sent / CPU cores / heap allocations per +encoded frame: + +| | quiet (load 1-3): before | after | busy (load 6-12): before | after | +|---|---|---|---|---| +| 720p30 | 29.4 / 0.48 / 7.1 | 30.0 / 0.40 / 1.05 | 7.9 / 1.71 / 10.0 | 6.6 / 1.24 / 1.25 | +| 720p60 | 14.7 / 2.37 / 10.2 | 60.0 / 0.69 / 1.03 | 4.6 / 1.23 / 19.1 | 6.4 / 1.28 / 1.25 | +| 1080p30 | 29.6 / 0.83 / 7.1 | 30.0 / 0.75 / 1.05 | 2.7 / 1.30 / 17.4 | 6.9 / 1.27 / 1.24 | +| 1080p60 | 57.2 / 1.47 / 7.1 | 53.7 / 1.42 / 1.03 | 2.4 / 1.33 / 31.4 | 5.7 / 1.40 / 1.28 | +| 1440p30 | 8.4 / 2.26 / 9.7 | 22.7 / 1.71 / 1.07 | 1.9 / 1.31 / 22.6 | 5.5 / 1.26 / 1.30 | +| 1440p60 | 52.5 / 2.24 / 7.2 | 3.2 / 2.02 / 1.50 * | 1.5 / 1.22 / 36.9 | 3.6 / 1.30 / 1.45 | + +\* libvpx with one thread per core collapsed (290 ms per frame) when the +conversion competed for a core; encoders now use all CPUs but one. The busy +column is with that change; a quiet re-run was not possible. Bytes +allocated per encoded frame fell from 5-450 MB (a full RGBA and I420 copy +per frame, more when frames queue up) to 10-130 KB (the encoded frame). +Conversion and scaling take 0.3 ms (720p) to 3-5 ms (1440p, busy) per frame +on 4 threads. With three layers (1440p30 at 6 Mbit/s, 720p30, 360p15) the +quiet machine kept every layer at its rate with 1.6-1.7 cores. + +Build profiles: the dev profile builds the media hot path (yuv, +voelin-media, str0m, x11rb-protocol, pipewire, wayland-client, ...) with +`opt-level = 3`; release builds use fat LTO with one codegen unit. + ## Build requirements Linux (Debian/Ubuntu packages): `libvpx-dev` (feature `vpx`), @@ -208,6 +341,8 @@ run on Windows yet. | Cisco OpenH264 binary | BSD-2-Clause + Cisco's royalty coverage | downloaded by the user, see above | | `dav1d` crate / libdav1d | MIT / BSD-2-Clause | optional, system library | | `x11rb`, `memmap2`, `rustix` | MIT OR Apache-2.0 (rustix also Apache-2.0 WITH LLVM-exception) | | +| `wayland-client`, `wayland-protocols`, `wayland-protocols-wlr` | MIT | wlroots capture | +| `criterion` | Apache-2.0 OR MIT | benchmarks only (dev-dependency) | | `ashpd`, `pipewire`, `libspa` / libpipewire | MIT | libpipewire is dynamic | | `windows-capture`, `wasapi`, `windows` | MIT (`windows`: MIT OR Apache-2.0) | Windows only | | `bzip2` / `libbz2-rs-sys` | MIT OR Apache-2.0 / bzip2-1.0.6 | unpacks the OpenH264 download; `bzip2-1.0.6` is allowed in `deny.toml` | @@ -223,8 +358,12 @@ run on Windows yet. | H.264 library missing / unknown file | unit + integration tests | tested | | AV1 decoder construction, garbage input | unit test (`--features av1`) | tested; no AV1 stream decoded (no encoder available) | | X11 capture (MIT-SHM and GetImage), sources, window capture → VP8 → decode, cursor | `tests/x11_capture.rs` under Xvfb | tested | +| wlroots capture (wlr-screencopy v3): outputs, pixels, a change arriving as a new frame, queue API | `tests/wlroots_capture.rs` against headless sway 1.9 (`VOELIN_WLROOTS_TEST_DISPLAY`) | tested; the ext-image-copy-capture path is untested (sway 1.9 predates it) | +| Converter (strides, unpadded last row, odd sizes, RGBA/I420/NV12), scaler (flat, area average, half), pyramid (sharing, recycling, steady-state pools) | unit tests | tested | +| Simulcast layers (sizes, fps caps, per-layer keyframes), reconfigure (codec, layers, fps) | `voelin-core` `media::tests::simulcast_layers_and_reconfigure` | tested | +| Portal DMA-BUF negotiation | unit test of the offered formats | compiles and formats parse; no compositor with the portal here | | Portal / PipeWire error paths (no bus, bus without portal, no daemon) | unit tests, manual probe | tested | -| Portal capture, PipeWire video and audio streams | – | compiles only (no portal or PipeWire daemon here) | +| Portal capture (shared memory and DMA-BUF), PipeWire video and audio streams | – | compiles only (no portal or PipeWire daemon here) | | Windows Graphics Capture, WASAPI | – | type-checked for `x86_64-pc-windows-gnu` only | | Hardware encoders | – | stubs | | Test pattern → VP8 → decoder, rectangle position and colour | `voelin-core` `media::tests::local_preview_decodes_the_pattern` | tested | diff --git a/tools/voelinctl/src/alloc.rs b/tools/voelinctl/src/alloc.rs new file mode 100644 index 0000000..0af2263 --- /dev/null +++ b/tools/voelinctl/src/alloc.rs @@ -0,0 +1,51 @@ +//! The process's global allocator: the system allocator, counting +//! allocations (for `voelinctl stream bench`, which reports heap +//! allocations per frame). The count is one relaxed atomic add per +//! allocation. +#![allow(unsafe_code)] + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::sync::atomic::{AtomicU64, Ordering}; + +static ALLOCATIONS: AtomicU64 = AtomicU64::new(0); +static BYTES: AtomicU64 = AtomicU64::new(0); + +/// Allocations (including reallocations) and bytes requested so far. +pub fn counts() -> (u64, u64) { + (ALLOCATIONS.load(Ordering::Relaxed), BYTES.load(Ordering::Relaxed)) +} + +pub struct Counting; + +fn count(size: usize) { + ALLOCATIONS.fetch_add(1, Ordering::Relaxed); + BYTES.fetch_add(size as u64, Ordering::Relaxed); +} + +// SAFETY: every method forwards to `System` with the caller's arguments +// unchanged, so `System`'s guarantees hold; counting touches only atomics +// and never allocates. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + count(layout.size()); + // SAFETY: forwarded unchanged (see above). + unsafe { System.alloc(layout) } + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + count(layout.size()); + // SAFETY: forwarded unchanged. + unsafe { System.alloc_zeroed(layout) } + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + count(new_size); + // 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) } + } +} diff --git a/tools/voelinctl/src/bench.rs b/tools/voelinctl/src/bench.rs new file mode 100644 index 0000000..50227b5 --- /dev/null +++ b/tools/voelinctl/src/bench.rs @@ -0,0 +1,342 @@ +//! `voelinctl stream bench`: the streamer's capture → convert → encode +//! pipeline on the test pattern, without a server. Prints frame rates, bit +//! rates and heap allocations per frame in the steady state. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, bail}; +use clap::{Args, Subcommand}; +use voelin_core::media::voelin_media::capture::SourceId; +use voelin_core::media::voelin_media::capture::synthetic::Pattern; +use voelin_core::media::voelin_media::{Codec, Codecs}; +use voelin_core::media::{MediaSink, Streamer, StreamerConfig}; +use voelin_stream::{EncodedFrame, LayerId, LayerSet, LayerSpec, MediaKind}; + +use crate::alloc; + +#[derive(Args, Debug)] +pub struct StreamToolArgs { + #[command(subcommand)] + command: StreamTool, +} + +#[derive(Subcommand, Debug)] +enum StreamTool { + /// Run the streamer's pipeline (capture → convert/scale → encode) on the + /// test pattern without a server; print per-stage and per-layer numbers + /// and heap allocations per frame. + Bench(BenchArgs), +} + +#[derive(Args, Debug)] +struct BenchArgs { + /// Size of the test pattern. + #[arg(long, default_value = "1920x1080")] + res: String, + /// Frame rate of the capture. + #[arg(long, default_value_t = 30)] + fps: u32, + /// Test pattern: `desktop` (text, a scrolling document; about as costly + /// as real screen content) or `simple` (a flat background). + #[arg(long, default_value = "desktop")] + pattern: String, + /// Video codec: vp8, vp9 or h264 (needs --openh264). + #[arg(long, default_value = "vp8")] + codec: String, + /// A simulcast layer, e.g. `scale=0.5,bitrate=1500k,fps=15` (keys: id, + /// scale, size=WxH, fps, bitrate, max, min, rid; bitrates in bit/s with + /// k/M suffixes); repeatable. Without it: one layer at --bitrate. + #[arg(long = "layer")] + layers: Vec, + /// Bitrate in kbit/s without --layer. + #[arg(long, default_value_t = 4608)] + bitrate: u32, + /// Measured time in seconds (after the warm-up). + #[arg(long, default_value_t = 10)] + seconds: u64, + /// Seconds to run before measuring. + #[arg(long, default_value_t = 2)] + warmup: u64, + /// Cisco's OpenH264 library, for --codec h264. + #[arg(long)] + openh264: Option, +} + +pub fn run(args: StreamToolArgs) -> Result<()> { + match args.command { + StreamTool::Bench(args) => bench(args), + } +} + +/// Frames and bytes the sink got for one layer. +#[derive(Default)] +struct LayerCount { + frames: AtomicU64, + keyframes: AtomicU64, + bytes: AtomicU64, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct LayerSnapshot { + frames: u64, + keyframes: u64, + bytes: u64, +} + +/// Counts what the streamer sends; asks for one keyframe per layer at the +/// start, like a new viewer. +struct BenchSink { + layers: Vec<(LayerId, LayerCount)>, + keyframe: AtomicBool, +} + +impl BenchSink { + fn snapshot(&self) -> Vec<(LayerId, LayerSnapshot)> { + self.layers + .iter() + .map(|(id, c)| { + let snapshot = LayerSnapshot { + frames: c.frames.load(Ordering::Relaxed), + keyframes: c.keyframes.load(Ordering::Relaxed), + bytes: c.bytes.load(Ordering::Relaxed), + }; + (*id, snapshot) + }) + .collect() + } +} + +impl MediaSink for BenchSink { + fn send(&self, frame: EncodedFrame) -> bool { + if frame.kind != MediaKind::Video { + return true; + } + if let Some((_, count)) = self.layers.iter().find(|(id, _)| *id == frame.layer) { + count.frames.fetch_add(1, Ordering::Relaxed); + count.keyframes.fetch_add(u64::from(frame.keyframe), Ordering::Relaxed); + count.bytes.fetch_add(frame.data.len() as u64, Ordering::Relaxed); + } + true + } + + fn take_keyframe_request(&self) -> bool { + self.keyframe.swap(false, Ordering::Relaxed) + } + + fn take_layer_keyframes(&self, layers: &mut LayerSet) { + if self.keyframe.swap(false, Ordering::Relaxed) { + for (id, _) in &self.layers { + layers.insert(*id); + } + } + } +} + +/// `x`. +fn parse_size(size: &str) -> Result<(u32, u32)> { + let parsed = size.split_once('x').and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))); + parsed.with_context(|| format!("bad size {size:?}, expected e.g. 1280x720")) +} + +/// Bit/s with an optional `k` / `M` suffix. +fn parse_bitrate(value: &str) -> Result { + let (number, factor) = match value.as_bytes().last() { + Some(b'k' | b'K') => (&value[..value.len() - 1], 1_000.0), + Some(b'm' | b'M') => (&value[..value.len() - 1], 1_000_000.0), + _ => (value, 1.0), + }; + let number: f64 = number.parse().with_context(|| format!("bad bitrate {value:?}"))?; + Ok((number * factor) as u64) +} + +/// `key=value,...` (see `--layer`). +fn parse_layer(spec: &str, index: usize) -> Result { + let mut layer = LayerSpec::single(1_000_000); + layer.id = index as LayerId; + for part in spec.split(',').filter(|p| !p.is_empty()) { + let (key, value) = part.split_once('=').with_context(|| format!("{part:?}: no `=`"))?; + match key { + "id" => layer.id = value.parse().context("layer id")?, + "scale" => layer.scale = value.parse().context("layer scale")?, + "size" => layer.size = Some(parse_size(value)?), + "fps" => layer.max_fps = Some(value.parse().context("layer fps")?), + "bitrate" => layer.bitrate = parse_bitrate(value)?, + "max" => layer.max_bitrate = Some(parse_bitrate(value)?), + "min" => layer.min_bitrate = parse_bitrate(value)?, + "rid" => layer.rid = Some(value.to_owned()), + _ => bail!("unknown layer key {key:?} in {spec:?}"), + } + } + Ok(layer) +} + +/// CPU time of this process (user + system), Linux only. +fn cpu_time() -> Option { + let stat = std::fs::read_to_string("/proc/self/stat").ok()?; + // Fields after the command name, which is in parentheses. + let rest = stat.rsplit_once(')')?.1; + let fields: Vec<&str> = rest.split_whitespace().collect(); + // utime and stime are fields 14 and 15 (1-based), in clock ticks of + // 1/100 s on Linux. + let ticks: u64 = fields.get(11)?.parse::().ok()? + fields.get(12)?.parse::().ok()?; + Some(Duration::from_millis(ticks * 10)) +} + +struct Sample { + at: Instant, + allocations: u64, + bytes: u64, + cpu: Option, + layers: Vec<(LayerId, LayerSnapshot)>, + sent: u64, + captured: u64, + /// Frames the handoffs to the encoders dropped, per layer. + dropped: Vec<(LayerId, u64)>, +} + +fn sample(sink: &BenchSink, streamer: &Streamer) -> Sample { + // Stats first: reading them allocates, which must not count. + let stats = streamer.stats(); + let (allocations, bytes) = alloc::counts(); + Sample { + at: Instant::now(), + allocations, + bytes, + cpu: cpu_time(), + layers: sink.snapshot(), + sent: stats.video_frames, + captured: stats.captured_frames, + dropped: stats.layers.iter().map(|l| (l.id, l.dropped)).collect(), + } +} + +fn bench(args: BenchArgs) -> Result<()> { + let (width, height) = parse_size(&args.res)?; + let pattern = match args.pattern.as_str() { + "desktop" => Pattern::Desktop, + "simple" => Pattern::Simple, + other => bail!("unknown pattern {other:?}: desktop or simple"), + }; + let codec: Codec = args.codec.parse().map_err(|e| anyhow::anyhow!("{e}"))?; + let mut codecs = Codecs::new(); + if let Some(path) = &args.openh264 { + let library = voelin_core::media::voelin_media::codec::h264::OpenH264::load(path) + .context("OpenH264")?; + codecs = codecs.with_openh264(library); + } + let layers = args + .layers + .iter() + .enumerate() + .map(|(i, spec)| parse_layer(spec, i)) + .collect::>>()?; + let ids: Vec = + if layers.is_empty() { vec![0] } else { layers.iter().map(|l| l.id).collect() }; + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (width, height), + synthetic_pattern: pattern, + fps: args.fps, + bitrate_kbps: args.bitrate, + codec, + audio: false, + layers: layers.clone(), + ..StreamerConfig::default() + }; + let runtime = tokio::runtime::Runtime::new()?; + let streamer = runtime.block_on(Streamer::start(&codecs, config)).context("streamer")?; + let sink = Arc::new(BenchSink { + layers: ids.iter().map(|id| (*id, LayerCount::default())).collect(), + keyframe: AtomicBool::new(true), + }); + streamer.attach(sink.clone()); + println!( + "{width}x{height} {} test pattern at {} fps, {codec}, {} layer(s), {} s after {} s warm-up", + args.pattern, + args.fps, + ids.len(), + args.seconds, + args.warmup + ); + std::thread::sleep(Duration::from_secs(args.warmup)); + let start = sample(&sink, &streamer); + std::thread::sleep(Duration::from_secs(args.seconds)); + let end = sample(&sink, &streamer); + let stats = streamer.stats(); + drop(streamer); + + let secs = (end.at - start.at).as_secs_f64(); + let captured = end.captured - start.captured; + let ms = |d: Duration| d.as_secs_f64() * 1000.0; + println!( + "capture: {:.1} fps; convert + scale: {:.2} ms per frame on {} threads", + captured as f64 / secs, + ms(stats.convert_time), + stats.convert_threads, + ); + let mut output_frames = 0; + for ((id, a), (_, b)) in start.layers.iter().zip(&end.layers) { + let frames = b.frames - a.frames; + output_frames += frames; + let spec = layers.iter().find(|l| l.id == *id); + let size = spec.map_or((width, height), |l| l.output_size(width, height)); + let dropped = |s: &Sample| s.dropped.iter().find(|d| d.0 == *id).map_or(0, |d| d.1); + let layer = stats.layers.iter().find(|l| l.id == *id); + println!( + "layer {id}: {}x{} {:.1} fps {:.0} kbit/s {} keyframes {} dropped encode {:.2} ms \ + ({} threads, speed {})", + size.0, + size.1, + frames as f64 / secs, + (b.bytes - a.bytes) as f64 * 8.0 / secs / 1000.0, + b.keyframes - a.keyframes, + dropped(&end) - dropped(&start), + layer.map_or(0.0, |l| ms(l.encode_time)), + layer.map_or(0, |l| l.threads), + layer.and_then(|l| l.speed).map_or("-".into(), |s| s.to_string()), + ); + } + if let Some(e) = &stats.error { + println!("encoder error: {e}"); + } + if let (Some(a), Some(b)) = (start.cpu, end.cpu) { + println!("cpu: {:.2} cores", (b - a).as_secs_f64() / secs); + } + let allocations = end.allocations - start.allocations; + let bytes = end.bytes - start.bytes; + let sent = (end.sent - start.sent).max(1); + println!( + "heap: {allocations} allocations: {:.2} per captured frame, {:.2} per encoded frame \ + ({:.0} bytes per encoded frame)", + allocations as f64 / captured.max(1) as f64, + allocations as f64 / sent as f64, + bytes as f64 / sent as f64, + ); + if output_frames == 0 { + bail!("no frames were encoded"); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layer_specs() { + let layer = parse_layer("scale=0.5,bitrate=1.5M,fps=15,rid=m", 2).unwrap(); + assert_eq!(layer.id, 2); + assert_eq!(layer.scale, 0.5); + assert_eq!(layer.bitrate, 1_500_000); + assert_eq!(layer.max_fps, Some(15)); + assert_eq!(layer.rid.as_deref(), Some("m")); + let layer = parse_layer("id=7,size=640x360,bitrate=500k,max=800k,min=300k", 0).unwrap(); + assert_eq!((layer.id, layer.size), (7, Some((640, 360)))); + assert_eq!((layer.max_bitrate, layer.min_bitrate), (Some(800_000), 300_000)); + assert!(parse_layer("speed=3", 0).is_err()); + assert!(parse_layer("scale", 0).is_err()); + } +} diff --git a/tools/voelinctl/src/main.rs b/tools/voelinctl/src/main.rs index 4f57f69..ec70b44 100644 --- a/tools/voelinctl/src/main.rs +++ b/tools/voelinctl/src/main.rs @@ -1,5 +1,7 @@ //! `voelinctl`: headless TeamSpeak 3/6 client for development and integration tests. +mod alloc; +mod bench; mod gateway; mod identity; mod observe; @@ -18,6 +20,10 @@ use anyhow::Result; use clap::{Args, Parser, Subcommand}; use tracing_subscriber::EnvFilter; +/// Counts heap allocations for `stream bench`. +#[global_allocator] +static ALLOCATOR: alloc::Counting = alloc::Counting; + #[derive(Parser, Debug)] #[command(version, about)] struct Cli { @@ -50,6 +56,8 @@ enum Command { /// TeamSpeak 6: probe how a client that arrives after a stream started /// can learn about it; prints every command both clients exchange. ProbeStream(probe::ProbeStreamArgs), + /// Stream tools that need no server (`bench`). + Stream(bench::StreamToolArgs), } #[derive(Subcommand, Debug)] @@ -213,6 +221,7 @@ fn main() -> Result<()> { Command::Relay(args) => tokio::runtime::Runtime::new()?.block_on(observe::relay(args)), Command::Gateway(args) => tokio::runtime::Runtime::new()?.block_on(gateway::run(args)), Command::ProbeStream(args) => tokio::runtime::Runtime::new()?.block_on(probe::run(args)), + Command::Stream(args) => bench::run(args), } }