diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 6004d4a..8350064 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -45,7 +45,7 @@ pub use voelin_media::capture::playback::{AppMatch, AudioApp, AudioApps}; pub use voelin_media::capture::synthetic::Pattern; use voelin_media::capture::synthetic::{SineSource, SyntheticScreen}; use voelin_media::capture::{ - self, CaptureOptions, CaptureSource, FramePacer, FrameSink, ScreenCapture, SourceId, + self, CaptureOptions, CaptureSource, DmaBufRef, FramePacer, FrameSink, ScreenCapture, SourceId, }; use voelin_media::handoff::Handoff; use voelin_media::mix::{ @@ -55,7 +55,10 @@ pub use voelin_media::mix::{Level, SourceState}; use voelin_media::scale::Pyramid; use voelin_media::studio::Studio; use voelin_media::studio::output::{Packet, Track}; -use voelin_media::{Codec, Codecs, ContentHint, EncoderConfig, FrameRef, VideoEncoder, VideoFrame}; +use voelin_media::{ + Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, VideoEncoder, + VideoFrame, +}; pub use voelin_media::{EncoderBackend, EncoderPreference}; use voelin_stream::{ EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind, @@ -502,6 +505,11 @@ pub struct StreamerConfig { pub synthetic_size: (u32, u32), /// What the test pattern shows. pub synthetic_pattern: Pattern, + /// Hand the test pattern over as DMA-BUFs of ordinary memory, as the + /// ScreenCast portal hands over the screen + /// ([`SyntheticScreen::with_dmabuf`]): drives the GPU path without a + /// portal (Linux, `/dev/udmabuf`). + pub synthetic_dmabuf: bool, /// Portal restore token from an earlier share: the desktop may skip its /// dialog. The new one is [`Streamer::restore_token`]. pub restore_token: Option, @@ -524,6 +532,7 @@ impl Default for StreamerConfig { cursor: true, synthetic_size: (1280, 720), synthetic_pattern: Pattern::Simple, + synthetic_dmabuf: false, restore_token: None, layers: Vec::new(), } @@ -612,8 +621,16 @@ pub struct StreamerStats { 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. + /// layer that is due, on the CPU. pub convert_time: Duration, + /// Captured frames that never reached the CPU: DMA-BUFs converted to + /// NV12 and scaled for every layer on the GPU, for VA-API encoders. + pub gpu_frames: u64, + /// Mean time the capture thread spends on such a frame (it waits for + /// the GPU, so the buffer can go back to the compositor). + pub gpu_convert_time: Duration, + /// Why the GPU path stopped (it fell back to the CPU), if it did. + pub gpu_error: Option, /// Frames dropped between conversion and the encoders, all layers. pub dropped_frames: u64, /// Threads converting and scaling. @@ -636,6 +653,12 @@ struct Layer { spec: Mutex, /// Newest converted frame for the encoder. inbox: Handoff, + /// Newest frame converted on the GPU, instead. + gpu_inbox: Handoff, + /// What every encoder of the layer takes GPU frames at, written by the + /// encoder thread: `width << 32 | height` alignment, 0 if one of them + /// needs frames in memory. + gpu: AtomicU64, /// A keyframe was asked for. keyframe: AtomicBool, stop: AtomicBool, @@ -669,6 +692,8 @@ impl Layer { id: spec.id, spec: Mutex::new(spec.clone()), inbox: Handoff::new(), + gpu_inbox: Handoff::new(), + gpu: AtomicU64::new(0), keyframe: AtomicBool::new(false), stop: AtomicBool::new(false), bitrate: AtomicU64::new(spec.bitrate.max(1)), @@ -731,6 +756,7 @@ impl Settings { struct Rates { capture_fps: f64, convert_time: Duration, + gpu_convert_time: Duration, /// Per layer: id, fps, kbit/s, encode time. layers: Vec<(LayerId, f64, f64, Duration)>, } @@ -751,6 +777,10 @@ struct Shared { converted: AtomicU64, convert_ns: AtomicU64, convert_threads: AtomicUsize, + /// Frames converted on the GPU instead, and the time it took. + gpu_converted: AtomicU64, + gpu_convert_ns: AtomicU64, + gpu_error: Mutex>, /// The layers being encoded, in configuration order. layers: Mutex>>, /// Bumped whenever `layers` or a layer's spec changes. @@ -959,7 +989,8 @@ impl Streamer { 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); + let mut screen = SyntheticScreen::with_pattern(w, h, config.synthetic_pattern) + .with_dmabuf(config.synthetic_dmabuf); screen.start_sink(&SourceId::Synthetic, &options, ingest).await?; (Box::new(screen), None) } @@ -1220,6 +1251,9 @@ impl Streamer { captured_frames: shared.captured.load(Ordering::Relaxed), capture_fps: rates.capture_fps, convert_time: rates.convert_time, + gpu_frames: shared.gpu_converted.load(Ordering::Relaxed), + gpu_convert_time: rates.gpu_convert_time, + gpu_error: lock(&shared.gpu_error).clone(), dropped_frames: layers.iter().map(|l| l.dropped).sum(), convert_threads: shared.convert_threads.load(Ordering::Relaxed), codec, @@ -1487,6 +1521,11 @@ struct IngestLayer { /// 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. +/// +/// Frames still in a DMA-BUF (the portal's) are converted and scaled on +/// the GPU instead when every encoder of every layer takes GPU frames +/// (VA-API): the CPU never reads them, and the buffer is free again as +/// soon as the GPU is done with it. struct Ingest { shared: Arc, pyramid: Pyramid, @@ -1497,6 +1536,19 @@ struct Ingest { sizes: Vec<(u32, u32)>, due: Vec, out: Vec>>, + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + gpu: GpuStage, +} + +/// The GPU stage of [`Ingest`]. +#[cfg(all(target_os = "linux", feature = "media-desktop"))] +#[derive(Default)] +struct GpuStage { + /// Made for the first DMA-BUF; `Err` once it failed (the CPU converts + /// from then on). + converter: Option>, + layers: Vec, + out: Vec>>, } impl Ingest { @@ -1514,9 +1566,98 @@ impl Ingest { sizes: Vec::new(), due: Vec::new(), out: Vec::new(), + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + gpu: GpuStage::default(), } } + /// Whether frames go to the GPU: every layer's encoders take GPU frames + /// and the GPU stage has not failed. + fn gpu_path(&self) -> bool { + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + { + !matches!(self.gpu.converter, Some(Err(()))) + && !self.layers.is_empty() + && self + .layers + .iter() + .all(|l| l.layer.stopped() || l.layer.gpu.load(Ordering::Relaxed) != 0) + } + #[cfg(not(all(target_os = "linux", feature = "media-desktop")))] + false + } + + /// Convert DMA-BUF `frame` on the GPU for every layer that is due; `None` + /// if it is not taken (the backend maps it for [`FrameSink::frame`]). + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + fn gpu_frame(&mut self, frame: &DmaBufRef) -> Option { + use voelin_media::ffmpeg::{GpuConverter, GpuLayer}; + + if self.shared.stopped() { + return Some(false); + } + if !self.gpu_path() { + return None; + } + let shared = self.shared.clone(); + let converter = match &mut self.gpu.converter { + Some(Ok(converter)) => converter, + Some(Err(())) => return None, + None => match GpuConverter::new() { + Ok(converter) => self.gpu.converter.insert(Ok(converter)).as_mut().ok()?, + Err(e) => { + warn!("no GPU conversion of captured frames, the CPU converts them: {e}"); + *lock(&shared.gpu_error) = Some(e.to_string()); + self.gpu.converter = Some(Err(())); + return None; + } + }, + }; + self.pacer.keep(frame.timestamp); + shared.captured.fetch_add(1, Ordering::Relaxed); + shared + .size + .store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed); + if shared.sink().is_none() { + return Some(true); + } + let mut any = false; + self.gpu.layers.clear(); + for l in &mut self.layers { + let due = !l.layer.stopped() && l.pacer.take(frame.timestamp); + any |= due; + let alignment = l.layer.gpu.load(Ordering::Relaxed); + self.gpu.layers.push(GpuLayer { + size: l.spec.output_size(frame.width, frame.height), + alignment: ((alignment >> 32) as u32, alignment as u32), + due, + }); + } + if !any { + return Some(true); + } + self.gpu.out.clear(); + self.gpu.out.resize(self.layers.len(), None); + let started = Instant::now(); + if let Err(e) = converter.convert(frame, &self.gpu.layers, &mut self.gpu.out) { + warn!("GPU conversion failed, the CPU converts captured frames from now on: {e}"); + *lock(&shared.gpu_error) = Some(e.to_string()); + self.gpu.converter = Some(Err(())); + self.gpu.out.clear(); + // This frame is counted and its layers' pacing taken: it is + // dropped, and the next one takes the CPU path. + return Some(true); + } + shared.gpu_convert_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + shared.gpu_converted.fetch_add(1, Ordering::Relaxed); + for (l, out) in self.layers.iter().zip(&mut self.gpu.out) { + if let Some(frame) = out.take() { + l.layer.gpu_inbox.put(frame); + } + } + Some(true) + } + /// Pick up layer and frame-rate changes. fn refresh(&mut self) { let fps = self.shared.fps.load(Ordering::Relaxed); @@ -1560,14 +1701,38 @@ impl FrameSink for Ingest { 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)); - } + // Also the layers, which `accepts_dmabuf` (asked next) looks at. + self.refresh(); self.pacer.due(timestamp) } + fn accepts_dmabuf(&self) -> bool { + self.gpu_path() + } + + /// The tiled layout the GPU's own RGB surfaces have, once the GPU stage + /// runs (its first DMA-BUF is LINEAR); none on the CPU path, which + /// cannot read tiled buffers. + fn dmabuf_modifiers(&self) -> &[u64] { + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + if self.gpu_path() + && let Some(Ok(converter)) = &self.gpu.converter + { + return converter.modifiers(); + } + &[] + } + + fn dmabuf(&mut self, frame: &DmaBufRef) -> Option { + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + return self.gpu_frame(frame); + #[cfg(not(all(target_os = "linux", feature = "media-desktop")))] + { + let _ = frame; + None + } + } + fn frame(&mut self, frame: FrameRef<'_>) -> bool { if self.shared.stopped() { return false; @@ -1617,6 +1782,66 @@ impl Drop for Ingest { } } +/// A layer's picture: in memory, or on the GPU (converted from a captured +/// DMA-BUF there). +#[derive(Clone)] +enum Picture { + Cpu(Arc), + Gpu(Arc), +} + +impl Picture { + fn size(&self) -> (u32, u32) { + match self { + Self::Cpu(frame) => (frame.width, frame.height), + Self::Gpu(frame) => (frame.width, frame.height), + } + } + + /// The same picture `later` after it was captured (a still screen sent + /// again; copies a frame in memory). + fn later(&self, later: Duration) -> Self { + match self { + Self::Cpu(frame) => { + let timestamp = frame.timestamp + later; + Self::Cpu(Arc::new((**frame).clone().with_timestamp(timestamp))) + } + Self::Gpu(frame) => Self::Gpu(Arc::new(frame.at(frame.timestamp + later))), + } + } +} + +/// A layer's next picture, from either inbox, or `None` after [`POLL`] or +/// once the layer is closed. The encoder thread is registered with both +/// ([`Handoff::register`]), so a `put` to either wakes it. +fn next_picture(layer: &Layer) -> Option { + let deadline = Instant::now() + POLL; + loop { + if let Some(frame) = layer.gpu_inbox.take() { + return Some(Picture::Gpu(frame)); + } + if let Some(frame) = layer.inbox.take() { + return Some(Picture::Cpu(frame)); + } + let now = Instant::now(); + if now >= deadline || layer.inbox.is_closed() { + return None; + } + std::thread::park_timeout(deadline - now); + } +} + +/// What every encoder of a layer takes GPU frames at, for [`Layer::gpu`]: +/// the largest alignment of them all, or 0 if one of them takes none. +fn gpu_alignment<'a>(encoders: impl IntoIterator) -> u64 { + let mut alignment = (2, 2); + for encoder in encoders { + let Some((w, h)) = encoder.gpu_alignment() else { return 0 }; + alignment = (alignment.0.max(w), alignment.1.max(h)); + } + u64::from(alignment.0) << 32 | u64::from(alignment.1) +} + /// One encoder of a layer: its keyframe and bitrate state. struct LayerEncoder { codec: Codec, @@ -1635,7 +1860,7 @@ impl LayerEncoder { Self { codec: encoder.codec(), encoder: Some(encoder), keyframe_due: true, bitrate: 0, fps } } - /// Encode `frame` and hand the frames to `sink` (and `studio`'s + /// Encode `picture` and hand the frames to `sink` (and `studio`'s /// outputs); follows the layer's target bitrate and frame rate first. #[allow(clippy::too_many_arguments)] fn encode( @@ -1644,12 +1869,20 @@ impl LayerEncoder { layer: &Layer, sink: &dyn MediaSink, studio: Option<&Studio>, - frame: &VideoFrame, + picture: &Picture, requested: bool, target: u64, ) { let codec = self.codec; let Some(encoder) = &mut self.encoder else { return }; + if matches!(picture, Picture::Gpu(_)) && encoder.gpu_alignment().is_none() { + // The capture switches to frames in memory once it sees this + // encoder (made for a viewer just now); until then it waits, and + // its first frame then is a keyframe. + self.keyframe_due = true; + return; + } + let (width, height) = picture.size(); if target.abs_diff(self.bitrate) * 100 > self.bitrate { match encoder.set_bitrate(target.min(u64::from(u32::MAX)) as u32) { Ok(()) => self.bitrate = target, @@ -1662,15 +1895,15 @@ impl LayerEncoder { } let force = requested || self.keyframe_due; let mut produced_keyframe = false; - let result = encoder.encode_with(frame, force, &mut |chunk| { + let mut out = |chunk: EncodedChunk<'_>| { produced_keyframe |= chunk.keyframe; if let Some(studio) = studio { studio.write_packet(&Packet { track: Track::Video { codec, layer: u32::from(layer.id) }, pts_90khz: chunk.pts_90khz, keyframe: chunk.keyframe, - width: frame.width, - height: frame.height, + width, + height, data: chunk.data, }); } @@ -1688,7 +1921,11 @@ impl LayerEncoder { layer.bytes.fetch_add(chunk.data.len() as u64, Ordering::Relaxed); shared.video_frames.fetch_add(1, Ordering::Relaxed); } - }); + }; + let result = match picture { + Picture::Cpu(frame) => encoder.encode_with(frame, force, &mut out), + Picture::Gpu(frame) => encoder.encode_gpu(frame, force, &mut out), + }; match result { Ok(()) => self.keyframe_due = force && !produced_keyframe, Err(e) => { @@ -1736,13 +1973,17 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { let mut primary_on = true; // 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 last: Option<(Picture, Instant)> = None; layer.speed.store( primary.encoder.as_ref().and_then(|e| e.speed()).map_or(i64::MIN, i64::from), Ordering::Relaxed, ); + // The capture may hand over GPU frames once every encoder takes them. + layer.inbox.register(); + layer.gpu_inbox.register(); + layer.gpu.store(gpu_alignment(primary.encoder.as_deref()), Ordering::Relaxed); while !shared.stopped() && !layer.stopped() { - let frame = layer.inbox.wait_timeout(POLL); + let picture = next_picture(layer); if let Some(next) = lock(&layer.next_encoder).take() { // Another codec: its first frame is a keyframe anyway. *lock(&layer.backend) = Some(next.backend()); @@ -1785,21 +2026,26 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { codecs.extend(primary_on.then_some(primary.codec)); codecs.extend(extra.iter().filter(|e| e.encoder.is_some()).map(|e| e.codec)); } + // The stream codec's encoder counts even while nobody takes it, so + // the capture does not switch paths as viewers come and go. + let encoders = primary.encoder.as_deref().into_iter(); + let gpu = gpu_alignment(encoders.chain(extra.iter().filter_map(|e| e.encoder.as_deref()))); + layer.gpu.store(gpu, Ordering::Relaxed); let requested = layer.keyframe.swap(false, Ordering::Relaxed); let due = primary_on && primary.keyframe_due || extra.iter().any(|e| e.keyframe_due && e.encoder.is_some()); - let frame = match frame { - Some(frame) => { - last = Some((frame.clone(), Instant::now())); - frame + let picture = match picture { + Some(picture) => { + last = Some((picture.clone(), Instant::now())); + picture } None if requested || due => { - let Some((frame, at)) = &last else { + let Some((picture, 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())) + // Same picture, later timestamp (rare). + picture.later(at.elapsed()) } None => continue, }; @@ -1813,15 +2059,16 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { let started = Instant::now(); if primary_on { let studio = shared.studio.as_deref(); - primary.encode(shared, layer, &*sink, studio, &frame, requested, target); + primary.encode(shared, layer, &*sink, studio, &picture, requested, target); layer.target.store(primary.bitrate, Ordering::Relaxed); } for encoder in &mut extra { - encoder.encode(shared, layer, &*sink, None, &frame, requested, target); + encoder.encode(shared, layer, &*sink, None, &picture, requested, target); } 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); + let (width, height) = picture.size(); + layer.size.store(u64::from(width) << 32 | u64::from(height), Ordering::Relaxed); layer.speed.store( primary.encoder.as_ref().and_then(|e| e.speed()).map_or(i64::MIN, i64::from), Ordering::Relaxed, @@ -1835,6 +2082,8 @@ struct Sample { captured: u64, converted: u64, convert_ns: u64, + gpu_converted: u64, + gpu_convert_ns: u64, } /// Once a second: rates for [`Streamer::stats`]; every five seconds a @@ -1861,11 +2110,15 @@ fn stats_loop(shared: &Shared) { captured: shared.captured.load(Ordering::Relaxed), converted: shared.converted.load(Ordering::Relaxed), convert_ns: shared.convert_ns.load(Ordering::Relaxed), + gpu_converted: shared.gpu_converted.load(Ordering::Relaxed), + gpu_convert_ns: shared.gpu_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.gpu_convert_time = + mean(now.gpu_convert_ns - last.gpu_convert_ns, now.gpu_converted - last.gpu_converted); rates.layers.clear(); let layers = lock(&shared.layers); for layer in layers.iter() { @@ -1912,9 +2165,10 @@ fn stats_loop(shared: &Shared) { }) .collect(); debug!( - "stream: capture {:.1} fps, convert {:.1} ms, {}", + "stream: capture {:.1} fps, convert {:.1} ms (GPU {:.1} ms), {}", rates.capture_fps, rates.convert_time.as_secs_f64() * 1e3, + rates.gpu_convert_time.as_secs_f64() * 1e3, summary.join(", ") ); } @@ -2742,6 +2996,68 @@ mod tests { (size, first_keyframe == Some(true)) } + /// The test pattern as DMA-BUFs, as the portal hands over the screen: + /// with VA-API encoders on every layer, each frame is converted and + /// scaled on the GPU and none on the CPU; after a switch to libvpx, + /// which needs frames in memory, the CPU converts them again and the + /// stream goes on. Skipped without `h264_vaapi` or `/dev/udmabuf`. + #[cfg(target_os = "linux")] + #[tokio::test(flavor = "multi_thread")] + async fn dmabufs_take_the_gpu_path_while_every_encoder_does() { + let vaapi = voelin_media::ffmpeg::probe() + .iter() + .any(|s| s.spec.name == "h264_vaapi" && s.available.is_ok()); + if !vaapi || !std::path::Path::new("/dev/udmabuf").exists() { + eprintln!("no h264_vaapi or /dev/udmabuf, skipped"); + return; + } + let codecs = Codecs::new(); + let vaapi = EncoderPreference { hardware: true, backend: "h264_vaapi".parse().unwrap() }; + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (640, 360), + synthetic_dmabuf: true, + fps: 30, + audio: false, + codec: Codec::H264, + encoder: vaapi, + layers: vec![layer(0, 1.0, None, 1_000_000), layer(5, 0.5, Some(15), 300_000)], + ..StreamerConfig::default() + }; + let streamer = Streamer::start(&codecs, config).await.unwrap(); + let mut source = EncodedSource::new(streamer); + let count = |frames: &[EncodedFrame], id| frames.iter().filter(|f| f.layer == id).count(); + let frames = collect(&mut source, |f| count(f, 0) >= 20 && count(f, 5) >= 5).await; + for id in [0, 5] { + assert!(frames.iter().find(|f| f.layer == id).unwrap().keyframe, "layer {id}"); + } + let stats = source.streamer().stats(); + assert_eq!(stats.gpu_error, None); + assert!(stats.gpu_frames >= 20, "{} frames on the GPU", stats.gpu_frames); + let on_cpu = stats.captured_frames - stats.gpu_frames; + assert!(on_cpu <= 1, "{on_cpu} of {} frames on the CPU", stats.captured_frames); + let sizes: Vec<_> = stats.layers.iter().map(|l| (l.width, l.height)).collect(); + assert_eq!(sizes, [(640, 360), (320, 180)]); + + let libvpx = EncoderPreference { hardware: false, backend: "libvpx".parse().unwrap() }; + let update = StreamerConfigUpdate { + codec: Some(Codec::Vp8), + encoder: Some(libvpx), + ..StreamerConfigUpdate::default() + }; + source.streamer().reconfigure(&codecs, update).unwrap(); + let gpu = source.streamer().stats().gpu_frames; + let frames = collect(&mut source, |f| count(f, 0) >= 40).await; + assert_eq!(decoded_size(Codec::Vp8, &frames, 0), ((640, 360), true)); + let stats = source.streamer().stats(); + assert!( + stats.gpu_frames <= gpu + 2, + "{} frames on the GPU after the switch", + stats.gpu_frames - gpu + ); + assert_eq!(stats.gpu_error, None, "a planned switch, not a failure"); + } + /// 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")] diff --git a/crates/voelin-media/src/capture/dmabuf.rs b/crates/voelin-media/src/capture/dmabuf.rs index d8d07cb..8846ed8 100644 --- a/crates/voelin-media/src/capture/dmabuf.rs +++ b/crates/voelin-media/src/capture/dmabuf.rs @@ -1,11 +1,13 @@ //! 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). +//! read like this; they go to the GPU (`ffmpeg::GpuConverter`). Also +//! DMA-BUFs of ordinary memory ([`Udmabuf`]), to drive that path without a +//! compositor. #![allow(unsafe_code)] use std::io; -use std::os::fd::{BorrowedFd, RawFd}; +use std::os::fd::{BorrowedFd, OwnedFd, RawFd}; use memmap2::{Mmap, MmapOptions}; @@ -21,6 +23,92 @@ 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); +/// `struct udmabuf_create` of ``; `UDMABUF_CREATE` returns +/// the new DMA-BUF. +#[repr(C)] +struct UdmabufCreate { + memfd: u32, + flags: u32, + offset: u64, + size: u64, +} + +/// `UDMABUF_FLAGS_CLOEXEC`. +const UDMABUF_CLOEXEC: u32 = 1; + +// SAFETY: `UDMABUF_CREATE` (`_IOW('u', 0x42, struct udmabuf_create)`) only +// reads the struct and returns a new descriptor. +unsafe impl rustix::ioctl::Ioctl for UdmabufCreate { + type Output = OwnedFd; + const IS_MUTATING: bool = false; + + fn opcode(&self) -> rustix::ioctl::Opcode { + rustix::ioctl::opcode::write::(b'u', 0x42) + } + + fn as_ptr(&mut self) -> *mut std::ffi::c_void { + (&raw mut *self).cast() + } + + unsafe fn output_from_ptr( + out: rustix::ioctl::IoctlOutput, + _: *mut std::ffi::c_void, + ) -> rustix::io::Result { + // SAFETY: the descriptor the kernel just made, ours to own. + Ok(unsafe { std::os::fd::FromRawFd::from_raw_fd(out) }) + } +} + +/// A DMA-BUF of ordinary memory that the CPU writes into: a sealed memfd +/// shared through `/dev/udmabuf` (LINEAR rows, any pitch). What a +/// compositor that renders on the CPU hands over, and the way to drive the +/// DMA-BUF path without one (the test pattern's +/// [`with_dmabuf`](super::synthetic::SyntheticScreen::with_dmabuf)). Needs +/// read and write access to `/dev/udmabuf`. +pub(crate) struct Udmabuf { + map: memmap2::MmapMut, + dmabuf: OwnedFd, +} + +impl Udmabuf { + /// A buffer of at least `len` bytes (whole pages). + pub fn new(len: usize) -> io::Result { + use rustix::fs::{MemfdFlags, SealFlags}; + + let len = len.max(1).next_multiple_of(4096); + let flags = MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING; + let memfd = std::fs::File::from(rustix::fs::memfd_create("voelin-udmabuf", flags)?); + memfd.set_len(len as u64)?; + // udmabuf only takes memory that cannot shrink under it. + rustix::fs::fcntl_add_seals(&memfd, SealFlags::SHRINK)?; + let device = std::fs::OpenOptions::new().read(true).write(true).open("/dev/udmabuf")?; + let create = UdmabufCreate { + memfd: std::os::fd::AsRawFd::as_raw_fd(&memfd) as u32, + flags: UDMABUF_CLOEXEC, + offset: 0, + size: len as u64, + }; + // SAFETY: see the `Ioctl` impl; `device` is /dev/udmabuf. + let dmabuf = unsafe { rustix::ioctl::ioctl(&device, create) }?; + // SAFETY: our own sealed memfd, which nothing else writes or + // truncates; the mapping keeps its pages after the file is closed. + let map = unsafe { memmap2::MmapOptions::new().len(len).map_mut(&memfd) }?; + Ok(Self { map, dmabuf }) + } + + pub fn fd(&self) -> RawFd { + std::os::fd::AsRawFd::as_raw_fd(&self.dmabuf) + } + + pub fn len(&self) -> usize { + self.map.len() + } + + pub fn bytes_mut(&mut self) -> &mut [u8] { + &mut self.map + } +} + /// The size of DMA-BUF `fd` in bytes (`lseek(fd, 0, SEEK_END)`, which a /// DMA-BUF answers with its buffer object's size without moving anything). pub(crate) fn size_of(fd: RawFd) -> Option { diff --git a/crates/voelin-media/src/capture/mod.rs b/crates/voelin-media/src/capture/mod.rs index 2dbc3aa..f064d63 100644 --- a/crates/voelin-media/src/capture/mod.rs +++ b/crates/voelin-media/src/capture/mod.rs @@ -28,7 +28,7 @@ use crate::queue::{FrameReceiver, FrameSender, frame_channel}; use crate::{Error, Result}; #[cfg(all(target_os = "linux", feature = "pipewire"))] -mod dmabuf; +pub(crate) mod dmabuf; pub mod external; #[cfg(all(target_os = "linux", feature = "pipewire"))] pub mod pipewire_audio; @@ -129,6 +129,15 @@ pub trait FrameSink: Send { let _ = frame; None } + + /// Tiled DRM format modifiers of RGB buffers the sink takes now + /// ([`accepts_dmabuf`](Self::accepts_dmabuf)), best first; backends that + /// negotiate buffers (the portal) offer them ahead of LINEAR, and offer + /// again when this changes. The CPU cannot read tiled buffers, so a sink + /// lists only what it imports. + fn dmabuf_modifiers(&self) -> &[u64] { + &[] + } } /// `fourcc_code(a, b, c, d)` of `drm_fourcc.h`. diff --git a/crates/voelin-media/src/capture/portal.rs b/crates/voelin-media/src/capture/portal.rs index 71e9772..631a5b7 100644 --- a/crates/voelin-media/src/capture/portal.rs +++ b/crates/voelin-media/src/capture/portal.rs @@ -288,6 +288,8 @@ struct VideoState { fps: u32, /// Offer DMA-BUFs. dmabuf: bool, + /// The sink's tiled modifiers the offer was made with (ahead of LINEAR). + modifiers: Vec, /// Mappings of the DMA-BUFs PipeWire cycles through. maps: Vec, /// Time spent handing DMA-BUF frames to the sink, and how many. @@ -315,12 +317,15 @@ 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 modifiers = sink.dmabuf_modifiers().to_vec(); + let formats = enum_formats(fps, dmabuf, &modifiers)?; let state = VideoState { sink, format: None, started: Instant::now(), fps, dmabuf, + modifiers, maps: Vec::new(), dmabuf_time: Duration::ZERO, dmabuf_frames: 0, @@ -359,7 +364,6 @@ fn video_stream( .register() .map_err(|e| format!("PipeWire listener: {e}"))?; - let formats = enum_formats(fps, dmabuf)?; let mut pods = formats.iter().map(|f| pod(f)).collect::, _>>()?; stream .connect( @@ -397,15 +401,24 @@ fn framerate_range(fps: u32) -> Property { ) } -fn modifier_property(fixed: bool) -> Property { +/// The modifiers we take, best first: the sink's tiled ones, then LINEAR, +/// which the CPU can always read. +fn our_modifiers(tiled: &[u64]) -> Vec { + tiled.iter().map(|&m| m as i64).chain([MODIFIER_LINEAR]).collect() +} + +/// The modifier property of a DMA-BUF format: a choice of `modifiers` the +/// producer must not fixate (we pick, see [`format_changed`]), or one fixed +/// modifier. +fn modifier_property(modifiers: &[i64], 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) + Value::Long(modifiers[0]) } else { Value::Choice(ChoiceValue::Long(Choice( ChoiceFlags::empty(), - ChoiceEnum::Enum { default: MODIFIER_LINEAR, alternatives: vec![MODIFIER_LINEAR] }, + ChoiceEnum::Enum { default: modifiers[0], alternatives: modifiers.to_vec() }, ))) }; Property { @@ -415,6 +428,19 @@ fn modifier_property(fixed: bool) -> Property { } } +/// The modifiers a producer's modifier property leaves to choose from. +fn offered_modifiers(prop: &pw::spa::pod::PodProp) -> Vec { + use pw::spa::pod::deserialize::PodDeserializer; + match PodDeserializer::deserialize_any_from(prop.value().as_bytes()).map(|(_, v)| v) { + Ok(Value::Long(m)) => vec![m], + Ok(Value::Choice(ChoiceValue::Long(Choice( + _, + ChoiceEnum::Enum { default, alternatives }, + )))) => std::iter::once(default).chain(alternatives).collect(), + _ => Vec::new(), + } +} + fn format_object(properties: Vec) -> Value { Value::Object(Object { type_: SpaTypes::ObjectParamFormat.as_raw(), @@ -423,9 +449,15 @@ fn format_object(properties: Vec) -> Value { }) } -/// 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> { +/// The formats we offer: each pixel format as a DMA-BUF (if `dmabuf`) with +/// the sink's tiled modifiers ahead of LINEAR, then all of them in shared +/// memory. +fn enum_formats( + fps: u32, + dmabuf: bool, + tiled: &[u64], +) -> std::result::Result>, String> { + let modifiers = our_modifiers(tiled); let mut formats = Vec::new(); let base = || { vec![ @@ -437,7 +469,7 @@ fn enum_formats(fps: u32, dmabuf: bool) -> std::result::Result>, Str for format in FORMATS { let mut properties = base(); properties.push(property!(FormatProperties::VideoFormat, Id, format)); - properties.push(modifier_property(false)); + properties.push(modifier_property(&modifiers, false)); properties.push(size_range()); properties.push(framerate_range(fps)); formats.push(serialize(format_object(properties))?); @@ -461,10 +493,10 @@ fn enum_formats(fps: u32, dmabuf: bool) -> std::result::Result>, Str 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| { +/// Offer formats again (another frame rate, other modifiers, or no +/// DMA-BUFs); PipeWire renegotiates. +fn renegotiate(stream: &pw::stream::Stream, state: &VideoState) { + let result = enum_formats(state.fps, state.dmabuf, &state.modifiers).and_then(|formats| { let mut pods = formats.iter().map(|f| pod(f)).collect::, _>>()?; stream.update_params(&mut pods).map_err(|e| e.to_string()) @@ -494,12 +526,17 @@ fn format_changed( .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. + // The producer left the choice to us: the best of ours that it + // can make, else LINEAR. + let theirs = offered_modifiers(prop); + let ours = our_modifiers(&state.modifiers); + let chosen = ours.into_iter().find(|m| theirs.contains(m)).unwrap_or(MODIFIER_LINEAR); + debug!(offered = ?theirs, chosen, "screen capture modifier"); 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), + modifier_property(&[chosen], true), property!( FormatProperties::VideoSize, Rectangle, @@ -539,16 +576,20 @@ fn format_changed( } fn process(stream: &pw::stream::Stream, state: &mut VideoState) { - // Follow the sink's frame rate: ask the compositor for another rate. + // Follow the sink: ask the compositor for another rate, or buffers with + // the modifiers the sink takes now. let fps = state.sink.max_fps().max(1); - if fps != state.fps { + let modifiers = state.sink.dmabuf_modifiers(); + if fps != state.fps || (state.dmabuf && modifiers != state.modifiers.as_slice()) { state.fps = fps; - renegotiate(stream, fps, state.dmabuf); + state.modifiers = modifiers.to_vec(); + renegotiate(stream, state); } 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) && !state.sink.accepts_dmabuf() { - // Tiled: the CPU cannot read it (we only offer LINEAR). + // Tiled, and the sink no longer imports it: the CPU cannot read it. + // The new offer (above) brings LINEAR buffers. return; } let timestamp = state.started.elapsed(); @@ -661,7 +702,7 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) { "screen capture DMA-BUFs cannot be mapped; switching to shared memory" ); state.dmabuf = false; - renegotiate(stream, state.fps, false); + renegotiate(stream, state); } return; } @@ -718,7 +759,7 @@ fn probe_dmabuf( "reading DMA-BUFs takes {per_pixel:.1} ns per pixel; switching screen capture to shared memory" ); state.dmabuf = false; - renegotiate(stream, state.fps, false); + renegotiate(stream, state); } } @@ -748,20 +789,32 @@ mod tests { /// left to us to fixate) per pixel format, then shared memory. #[test] fn offered_formats() { - let formats = enum_formats(60, true).unwrap(); + // A sink that imports one tiled modifier (an AMD one here). + const TILED: u64 = 0x0200_0000_28a0_1f04; + let formats = enum_formats(60, true, &[TILED]).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(); + let modifier = modifier.expect("a modifier"); + let flags = modifier.flags(); assert!(flags.contains(PodPropFlags::MANDATORY | PodPropFlags::DONT_FIXATE)); + // Read back as a producer's choice is: ours first, LINEAR last. + let offered = offered_modifiers(modifier); + assert_eq!(offered.first(), Some(&(TILED as i64))); + assert_eq!(offered.last(), Some(&MODIFIER_LINEAR)); } 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 linear_only = enum_formats(60, true, &[]).unwrap(); + let object = pod(&linear_only[0]).unwrap().as_object().unwrap(); + let prop = object.find_prop(Id(FormatProperties::VideoModifier.as_raw())).unwrap(); + assert_eq!(offered_modifiers(prop), [MODIFIER_LINEAR, MODIFIER_LINEAR]); + assert_eq!(enum_formats(30, false, &[TILED]).unwrap().len(), 1); + let fixed = + serialize(format_object(vec![modifier_property(&[MODIFIER_LINEAR], 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); diff --git a/crates/voelin-media/src/capture/synthetic.rs b/crates/voelin-media/src/capture/synthetic.rs index c9b71b5..55056c4 100644 --- a/crates/voelin-media/src/capture/synthetic.rs +++ b/crates/voelin-media/src/capture/synthetic.rs @@ -6,8 +6,8 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use crate::capture::{ - AudioCapture, BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture, - SourceId, Ticker, Worker, + AudioCapture, BoxFuture, CaptureOptions, CaptureSource, DmaBufRef, FrameSink, QueueSink, + ScreenCapture, SourceId, Ticker, Worker, }; use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, FrameRef, PixelsRef, PlaneRef, VideoFrame}; use crate::queue::{FrameReceiver, frame_channel}; @@ -224,6 +224,7 @@ pub struct SyntheticScreen { pattern: Pattern, desktop: Option>, worker: Option, + dmabuf: bool, } impl SyntheticScreen { @@ -236,7 +237,18 @@ impl SyntheticScreen { 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 } + Self { width, height, pattern, desktop, worker: None, dmabuf: false } + } + + /// Draw into a DMA-BUF of ordinary memory and offer it to sinks that + /// take DMA-BUFs ([`FrameSink::accepts_dmabuf`]) as a LINEAR `XR24` + /// buffer, as the ScreenCast portal does; sinks that do not, or decline + /// it, get the same memory as a frame. Linux with the `pipewire` + /// feature and access to `/dev/udmabuf`; elsewhere frames are handed + /// over as before. + pub fn with_dmabuf(mut self, enabled: bool) -> Self { + self.dmabuf = enabled; + self } pub fn pattern(&self) -> Pattern { @@ -251,6 +263,7 @@ impl SyntheticScreen { pattern: self.pattern, desktop: self.desktop.clone(), worker: None, + dmabuf: self.dmabuf, } } @@ -268,8 +281,15 @@ impl SyntheticScreen { /// Draw frame `n` as BGRA (`width * 4` bytes per row) into `out`, reusing /// its memory. pub fn render(&self, n: u64, out: &mut Vec) { + out.resize(self.width as usize * self.height as usize * 4, 0); + self.draw(n, out); + } + + /// [`render`](Self::render) into the first `width * height * 4` bytes of + /// `out`. + fn draw(&self, n: u64, out: &mut [u8]) { let (w, h) = (self.width as usize, self.height as usize); - out.resize(w * h * 4, 0); + let out = &mut out[..w * h * 4]; match &self.desktop { Some(desktop) => desktop.draw(out, w, n as usize * 3), None => { @@ -349,17 +369,28 @@ impl ScreenCapture for SyntheticScreen { 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 mut buffer = Buffer::new(&pattern); let started = Instant::now(); let mut n = 0; 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) { + let bytes = buffer.bytes(); + pattern.draw(n, bytes); + let taken = match buffer.dmabuf(&pattern, timestamp) { + Some(frame) if sink.accepts_dmabuf() => sink.dmabuf(&frame), + _ => None, + }; + let more = taken.unwrap_or_else(|| { + let plane = PlaneRef::new(buffer.bytes(), width as usize * 4); + sink.frame(FrameRef { + width, + height, + timestamp, + pixels: PixelsRef::Bgra(plane), + }) + }); + if !more { break; } n += 1; @@ -382,6 +413,58 @@ impl ScreenCapture for SyntheticScreen { } } +/// Where the test pattern is drawn: plain memory, or a DMA-BUF of ordinary +/// memory ([`SyntheticScreen::with_dmabuf`]). +enum Buffer { + Memory(Vec), + #[cfg(all(target_os = "linux", feature = "pipewire"))] + Dmabuf(super::dmabuf::Udmabuf), +} + +impl Buffer { + fn new(pattern: &SyntheticScreen) -> Self { + let len = pattern.width as usize * pattern.height as usize * 4; + #[cfg(all(target_os = "linux", feature = "pipewire"))] + if pattern.dmabuf { + match super::dmabuf::Udmabuf::new(len) { + Ok(buffer) => return Self::Dmabuf(buffer), + Err(e) => tracing::warn!("test pattern without DMA-BUFs (/dev/udmabuf): {e}"), + } + } + Self::Memory(vec![0; len]) + } + + fn bytes(&mut self) -> &mut [u8] { + match self { + Self::Memory(bytes) => bytes, + #[cfg(all(target_os = "linux", feature = "pipewire"))] + Self::Dmabuf(buffer) => buffer.bytes_mut(), + } + } + + /// The buffer as a LINEAR `XR24` DMA-BUF, if it is one. + fn dmabuf(&self, pattern: &SyntheticScreen, timestamp: Duration) -> Option { + match self { + Self::Memory(_) => { + let _ = (pattern, timestamp); + None + } + #[cfg(all(target_os = "linux", feature = "pipewire"))] + Self::Dmabuf(buffer) => Some(DmaBufRef { + width: pattern.width, + height: pattern.height, + timestamp, + fourcc: super::drm_fourcc(b"XR24"), + modifier: super::DRM_MOD_LINEAR, + fd: buffer.fd(), + size: buffer.len(), + planes: [(0, pattern.width as usize * 4), (0, 0), (0, 0), (0, 0)], + plane_count: 1, + }), + } + } +} + /// A sine tone as an [`AudioCapture`] backend: 10 ms stereo buffers. pub struct SineSource { frequency: f32, @@ -523,4 +606,61 @@ mod tests { assert_eq!((buffer.channels, buffer.frames()), (2, 480)); tone.stop(); } + + /// With DMA-BUFs, a sink that takes them gets the pattern as a LINEAR + /// `XR24` DMA-BUF that reads back as the pattern; one that declines it + /// gets the same picture as a frame. + #[cfg(all(target_os = "linux", feature = "pipewire"))] + #[tokio::test] + async fn the_pattern_as_dmabufs() { + use std::sync::mpsc; + + /// Takes DMA-BUFs (or declines them) and reports what it got. + struct Sink { + take: bool, + got: mpsc::Sender<(bool, Vec)>, + } + impl FrameSink for Sink { + fn max_fps(&self) -> u32 { + 50 + } + fn frame(&mut self, frame: FrameRef<'_>) -> bool { + let PixelsRef::Bgra(plane) = frame.pixels else { panic!("BGRA") }; + self.got.send((false, plane.row(0, 64 * 4).to_vec())).is_ok() + } + fn accepts_dmabuf(&self) -> bool { + true + } + fn dmabuf(&mut self, frame: &DmaBufRef) -> Option { + assert_eq!(frame.fourcc, crate::capture::drm_fourcc(b"XR24")); + assert_eq!((frame.width, frame.height, frame.planes[0].1), (64, 48, 256)); + if !self.take { + return None; + } + let map = super::super::dmabuf::DmaBufMap::new(frame.fd, frame.size).unwrap(); + let row = map.read(|bytes| bytes[..64 * 4].to_vec()); + Some(self.got.send((true, row)).is_ok()) + } + } + + if !std::path::Path::new("/dev/udmabuf").exists() { + eprintln!("no /dev/udmabuf, skipped"); + return; + } + let mut expected = Vec::new(); + SyntheticScreen::new(64, 48).render(0, &mut expected); + for take in [true, false] { + let mut screen = SyntheticScreen::new(64, 48).with_dmabuf(true); + let (got, frames) = mpsc::channel(); + let sink = Box::new(Sink { take, got }); + screen + .start_sink(&SourceId::Synthetic, &CaptureOptions::default(), sink) + .await + .unwrap(); + let (dmabuf, row) = frames.recv_timeout(Duration::from_secs(5)).unwrap(); + screen.stop(); + assert_eq!(dmabuf, take, "taken as a DMA-BUF"); + assert_eq!(row, expected[..64 * 4], "the first row of frame 0"); + } + } } diff --git a/crates/voelin-media/src/codec/mod.rs b/crates/voelin-media/src/codec/mod.rs index 138f2e7..c0c9566 100644 --- a/crates/voelin-media/src/codec/mod.rs +++ b/crates/voelin-media/src/codec/mod.rs @@ -257,6 +257,32 @@ pub trait VideoEncoder: Send { fn speed(&self) -> Option { None } + + /// Whether this encoder takes [`GpuFrame`](crate::GpuFrame)s + /// ([`encode_gpu`](Self::encode_gpu)), and then the multiple their + /// width and height must be of (a size it encodes exactly; GPU frames + /// are made at that size instead of being cropped here). `None` for + /// encoders that need the pixels in memory: all but VA-API. + fn gpu_alignment(&self) -> Option<(u32, u32)> { + None + } + + /// Encode a frame that is in GPU memory, like + /// [`encode_with`](Self::encode_with). Only for encoders with a + /// [`gpu_alignment`](Self::gpu_alignment), and frames of a size that is a + /// multiple of it; the rest fail with `Error::CodecUnavailable`. + fn encode_gpu( + &mut self, + frame: &crate::GpuFrame, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + let _ = (frame, force_keyframe, out); + Err(Error::CodecUnavailable { + codec: self.codec(), + reason: format!("{} takes no frames in GPU memory", self.backend()), + }) + } } /// A video decoder. diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index f2e2a7b..7fc088e 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -15,6 +15,7 @@ use std::ffi::c_int; use std::sync::OnceLock; use std::time::{Duration, Instant}; +use super::gpu::{self, GpuConverter, GpuLayer, RGB_FOURCCS}; use super::layout::{self, HwFramesFields}; use super::sys::{self, FrameHead, PacketHead, Ptr, Rational, cstr}; use super::{Ffmpeg, take_log, vpp}; @@ -25,7 +26,7 @@ use crate::codec::{ VideoEncoder, }; use crate::convert; -use crate::frame::{FrameData, VideoFrame}; +use crate::frame::{FrameData, GpuFrame, VideoFrame}; use crate::{Error, Result}; /// How a backend takes frames. @@ -454,7 +455,7 @@ fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result { /// The `VADisplay` of the process's VA-API device (the first field of its /// `AVVAAPIDeviceContext`). -fn vaapi_display(ffmpeg: &Ffmpeg) -> std::result::Result { +pub(crate) fn vaapi_display(ffmpeg: &Ffmpeg) -> std::result::Result { let device = vaapi_device(ffmpeg)?; let name = cstr("vaapi"); // SAFETY: a C string; `device` is a live VA-API device reference, whose @@ -466,6 +467,56 @@ fn vaapi_display(ffmpeg: &Ffmpeg) -> std::result::Result { } } +/// A pool of VA-API surfaces of `sw_format` (an `AVPixelFormat`) and +/// `width` x `height` on the process's device (an `AVHWFramesContext` +/// reference); surfaces are made on demand and recycled. +pub(crate) fn vaapi_pool( + ffmpeg: &Ffmpeg, + width: u32, + height: u32, + sw_format: c_int, +) -> std::result::Result { + let api = &ffmpeg.api; + let device = vaapi_device(ffmpeg)?; + let vaapi = ffmpeg.pix.vaapi.ok_or("no VA-API pixel format")?; + // SAFETY: `device` is a live device reference. + let mut pool = unsafe { (api.av_hwframe_ctx_alloc)(device) }; + if pool.is_null() { + return Err("av_hwframe_ctx_alloc failed".into()); + } + // SAFETY: `pool` was just allocated on `device`. + let fields: HwFramesFields = match unsafe { layout::hw_frames_fields(pool, device) } { + Ok(f) => f, + Err(e) => { + // SAFETY: allocated above. + unsafe { (api.av_buffer_unref)(&mut pool) }; + return Err(e); + } + }; + // SAFETY: the fields were located and checked on this very context; + // setting them before av_hwframe_ctx_init is what FFmpeg expects. + let ret = unsafe { + let ctx = (*pool.cast::()).data.cast::(); + layout::write::(ctx, fields.format, vaapi); + layout::write::(ctx, fields.sw_format, sw_format); + layout::write::(ctx, fields.width, width as c_int); + layout::write::(ctx, fields.height, height as c_int); + // Surfaces are allocated on demand and recycled by the pool. + layout::write::(ctx, fields.initial_pool_size, 0); + (api.av_hwframe_ctx_init)(pool) + }; + if ret < 0 { + // SAFETY: allocated above. + unsafe { (api.av_buffer_unref)(&mut pool) }; + return Err(format!( + "VA-API surface pool: {}{}", + api.error_text(ret), + log_suffix("AVHWFramesContext") + )); + } + Ok(pool) +} + /// FFmpeg's recent messages, appended to an error. fn log_suffix(context: &str) -> String { let log = take_log(context); @@ -527,8 +578,6 @@ struct Session { opened: Instant, timestamps: Timestamps, nv12: bool, - /// RGB DMA-BUFs: made on the first one; why not, if they cannot be. - rgb: Option>, /// An AMF encoder: opened and closed under [`amf_lock`]. amf: bool, } @@ -552,47 +601,6 @@ fn amf_lock() -> std::sync::MutexGuard<'static, ()> { AMF.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } -/// What RGB DMA-BUFs need on their way into the session's NV12 surfaces: -/// a frames context of their own size to be mapped onto (FFmpeg gives an -/// imported surface the size of the destination's frames context, and the -/// session's has the coded size), the frame that holds the mapping, and -/// the GPU colour conversion. -struct RgbImport { - pool: Ptr, - mapped: Ptr, - size: (u32, u32), - converter: vpp::Converter, -} - -// SAFETY: as `Session`, which owns it. -unsafe impl Send for RgbImport {} - -impl Drop for RgbImport { - fn drop(&mut self) { - let api = &Ffmpeg::get().expect("an import exists only with FFmpeg").api; - // SAFETY: both are NULL or ours. - unsafe { - (api.av_frame_free)(&mut self.mapped); - (api.av_buffer_unref)(&mut self.pool); - } - } -} - -/// The VA-API surface of a VA-API frame (`data[3]`, `hwcontext_vaapi.h`). -/// -/// # Safety -/// `frame` must be a live frame of format `AV_PIX_FMT_VAAPI` holding a -/// surface. -unsafe fn surface_id(frame: Ptr) -> std::ffi::c_uint { - // SAFETY: guaranteed by the caller. - unsafe { (*frame.cast::()).data[3] as usize as std::ffi::c_uint } -} - -/// The DRM formats of RGB buffers the conversion takes (8 bits per -/// channel, 4 bytes per pixel; what screen capture offers). -const RGB_FOURCCS: [u32; 4] = - [drm_fourcc(b"XR24"), drm_fourcc(b"AR24"), drm_fourcc(b"XB24"), drm_fourcc(b"AB24")]; - impl Drop for Session { fn drop(&mut self) { let api = &Ffmpeg::get().expect("a session exists only with FFmpeg").api; @@ -640,6 +648,19 @@ pub struct FfmpegEncoder { /// Sizes it encodes exactly are multiples of these /// ([`BackendStatus::alignment`]). alignment: (u32, u32), + /// For RGB DMA-BUFs ([`encode_dmabuf`](Self::encode_dmabuf)): made on + /// the first one; why not, if it cannot be. + gpu: Option>, +} + +/// `size` cropped to a multiple of `alignment` (even at least, for 4:2:0 +/// chroma; at least 2x2): what an encoder of that alignment encodes exactly. +pub(crate) fn exact_size(size: (u32, u32), alignment: (u32, u32)) -> (u32, u32) { + let crop = |v: u32, a: u32| { + let a = a.max(2); + if v >= a { v / a * a } else { (v & !1).max(2) } + }; + (crop(size.0, alignment.0), crop(size.1, alignment.1)) } impl FfmpegEncoder { @@ -670,6 +691,7 @@ impl FfmpegEncoder { low_power: false, dmabuf_checked: false, alignment, + gpu: None, }) } @@ -735,11 +757,10 @@ impl FfmpegEncoder { } /// The encoder size: the frame cropped to a multiple of the backend's - /// alignment (even at least, for 4:2:0 chroma), so that the stream - /// declares exactly the picture it carries; at least 2x2. + /// alignment, so that the stream declares exactly the picture it + /// carries ([`exact_size`]). fn coded_size(&self, width: u32, height: u32) -> (u32, u32) { - let crop = |v: u32, a: u32| if v >= a { v / a * a } else { (v & !1).max(2) }; - (crop(width, self.alignment.0), crop(height, self.alignment.1)) + exact_size((width, height), self.alignment) } /// Open a session for `width` x `height`. @@ -791,7 +812,7 @@ impl FfmpegEncoder { opened: Instant::now(), timestamps: Timestamps::new(), nv12: self.spec.input != Input::Yuv420p, - rgb: None, + amf: false, }; // SAFETY: `ctx` is a live codec context; the first child is its @@ -863,7 +884,8 @@ impl FfmpegEncoder { self.apply(ctx, private, setting)?; } if self.spec.is_vaapi() { - session.pool = self.vaapi_pool(width, height, self.ffmpeg.pix.nv12)?; + session.pool = vaapi_pool(self.ffmpeg, width, height, self.ffmpeg.pix.nv12) + .map_err(|e| self.unavailable(e))?; let offset = self.ffmpeg.codec_hw_frames.clone().map_err(|e| self.unavailable(e))?; // SAFETY: `offset` is AVCodecContext.hw_frames_ctx (checked at // load); the context takes the new reference and frees it. @@ -919,45 +941,6 @@ impl FfmpegEncoder { /// A VA-API surface pool of `sw_format` (an `AVPixelFormat`) for `width` /// x `height`. - fn vaapi_pool(&self, width: u32, height: u32, sw_format: c_int) -> Result { - let api = &self.ffmpeg.api; - let device = vaapi_device(self.ffmpeg).map_err(|e| self.unavailable(e))?; - let vaapi = - self.ffmpeg.pix.vaapi.ok_or_else(|| self.unavailable("no VA-API format".into()))?; - // SAFETY: `device` is a live device reference. - let mut pool = unsafe { (api.av_hwframe_ctx_alloc)(device) }; - if pool.is_null() { - return Err(self.unavailable("av_hwframe_ctx_alloc failed".into())); - } - // SAFETY: `pool` was just allocated on `device`. - let fields: HwFramesFields = match unsafe { layout::hw_frames_fields(pool, device) } { - Ok(f) => f, - Err(e) => { - // SAFETY: allocated above. - unsafe { (api.av_buffer_unref)(&mut pool) }; - return Err(self.unavailable(e)); - } - }; - // SAFETY: the fields were located and checked on this very context; - // setting them before av_hwframe_ctx_init is what FFmpeg expects. - let ret = unsafe { - let ctx = (*pool.cast::()).data.cast::(); - layout::write::(ctx, fields.format, vaapi); - layout::write::(ctx, fields.sw_format, sw_format); - layout::write::(ctx, fields.width, width as c_int); - layout::write::(ctx, fields.height, height as c_int); - // Surfaces are allocated on demand and recycled by the pool. - layout::write::(ctx, fields.initial_pool_size, 0); - (api.av_hwframe_ctx_init)(pool) - }; - if ret < 0 { - // SAFETY: allocated above. - unsafe { (api.av_buffer_unref)(&mut pool) }; - return Err(self.error("VA-API surface pool", ret)); - } - Ok(pool) - } - /// Copy the I420 picture into the session's frame (cropped to the coded /// size; NV12 interleaved where the backend wants it). fn fill(&self, session: &Session, frame: &VideoFrame) -> Result<()> { @@ -1132,9 +1115,8 @@ impl FfmpegEncoder { /// (their size must be one it encodes exactly), and stay in use until /// this frame's packet came out (the encoder reads them one frame deep). /// RGB buffers (`XR24`, `AR24`, `XB24`, `AB24`: what screen capture - /// delivers) are converted into the session's NV12 surfaces on the GPU - /// (VA-API video processing), cropped to the coded size, and - /// are no longer read when this returns. + /// delivers) are converted to NV12 on the GPU ([`GpuConverter`]), cropped + /// to the coded size, and are no longer read when this returns. /// /// Anything else fails with `Error::CodecUnavailable`; callers then map /// the buffer and use [`encode_with`](VideoEncoder::encode_with). @@ -1147,11 +1129,35 @@ impl FfmpegEncoder { if !self.spec.is_vaapi() { return Err(self.unavailable(format!("{} does not import DMA-BUFs", self.spec.name))); } - let rgb = RGB_FOURCCS.contains(&frame.fourcc) && frame.plane_count == 1; - if !rgb && (frame.fourcc != drm_fourcc(b"NV12") || frame.plane_count != 2) { + if RGB_FOURCCS.contains(&frame.fourcc) && frame.plane_count == 1 { + let converter = match self + .gpu + .get_or_insert_with(|| GpuConverter::new().map_err(|e| e.to_string())) + { + Ok(converter) => converter, + Err(e) => { + return Err(Error::CodecUnavailable { + codec: self.spec.codec, + reason: e.clone(), + }); + } + }; + let layer = GpuLayer { + size: (frame.width, frame.height), + alignment: self.alignment, + due: true, + }; + let mut converted = [None]; + if let Err(e) = converter.convert(frame, &[layer], &mut converted) { + return Err(self.unavailable(e.to_string())); + } + let gpu = converted[0].take().expect("a due layer gets a frame"); + return self.encode_gpu(&gpu, force_keyframe, out); + } + if frame.fourcc != drm_fourcc(b"NV12") || frame.plane_count != 2 { return Err(self.unavailable("only NV12 and RGB DMA-BUFs are imported".into())); } - if !rgb && self.coded_size(frame.width, frame.height) != (frame.width, frame.height) { + if self.coded_size(frame.width, frame.height) != (frame.width, frame.height) { return Err(self.unavailable(format!( "{}x{} is not a size {} encodes exactly", frame.width, frame.height, self.spec.name @@ -1159,16 +1165,16 @@ impl FfmpegEncoder { } let refs = self.ffmpeg.frame_refs.clone().map_err(|e| self.unavailable(e))?; let (mut session, force) = self.prepare(frame.width, frame.height, force_keyframe, out)?; - let result = self.import_and_send(&mut session, frame, rgb, force, refs, out); + let result = self.import_and_send(&mut session, frame, force, refs, out); self.session = Some(session); result } + /// Map an NV12 DMA-BUF onto a surface of the session and encode it. fn import_and_send( &mut self, session: &mut Session, frame: &DmaBufRef, - rgb: bool, force: bool, refs: layout::FrameRefs, out: &mut dyn FnMut(EncodedChunk<'_>), @@ -1189,35 +1195,25 @@ impl FfmpegEncoder { } self.dmabuf_checked = true; } - let (pool, hw) = (session.pool, session.hw); - if rgb { - let import = self.rgb_import(session, frame)?; - self.map_dmabuf(frame, import.pool, import.mapped, refs)?; - // SAFETY: `hw` is our frame (unreferenced after each frame), the - // pool the session's; both surfaces belong to the process's - // device, the converter's display. - let converted = unsafe { - let ret = (api.av_hwframe_get_buffer)(pool, hw, 0); - let converted = if ret < 0 { - Err(self.error("VA-API surface", ret)) - } else { - let done = import.converter.convert(surface_id(import.mapped), surface_id(hw)); - done.map_err(|e| self.unavailable(e)) - }; - // The buffer has been read: the mapping can go. - (api.av_frame_unref)(import.mapped); - converted - }; - if let Err(e) = converted { - // SAFETY: our frame. - unsafe { (api.av_frame_unref)(hw) }; - return Err(e); - } - } else { - self.map_dmabuf(frame, pool, hw, refs)?; - } + let hw = session.hw; + gpu::map_dmabuf(self.ffmpeg, frame, session.pool, hw, refs).map_err(|e| { + Error::Encoder { codec: self.spec.codec, message: format!("{}: {e}", self.spec.name) } + })?; let pts = self.stamp(session, frame.timestamp, (frame.timestamp.as_micros() * 9 / 100) as u64); + self.send_surface(session, pts, force, out) + } + + /// Encode the surface in `session.hw` (taken from the session's frame + /// afterwards; the encoder keeps its own reference while it needs it). + fn send_surface( + &self, + session: &mut Session, + pts: i64, + force: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + let hw = session.hw; let pict_type = if force { sys::PICTURE_TYPE_I } else { sys::PICTURE_TYPE_NONE }; // SAFETY: offsets checked at load for this release's AVFrame; `hw` // holds a surface until the unref. @@ -1226,103 +1222,11 @@ impl FfmpegEncoder { layout::write::(hw, self.ffmpeg.frame.pict_type, pict_type); } let result = self.send(session, hw, out); - // SAFETY: our frame; the encoder holds its own reference. - unsafe { (api.av_frame_unref)(hw) }; + // SAFETY: our frame. + unsafe { (self.ffmpeg.api.av_frame_unref)(hw) }; result.map(|_| ()) } - /// The session's [`RgbImport`] for `frame`, made on first use (again - /// when the buffers change size within the session's coded size). - fn rgb_import<'s>(&self, session: &'s mut Session, frame: &DmaBufRef) -> Result<&'s RgbImport> { - let size = (frame.width, frame.height); - let stale = match &session.rgb { - None => true, - Some(Ok(import)) => import.size != size, - Some(Err(_)) => false, - }; - if stale { - session.rgb = None; - session.rgb = Some(self.new_rgb_import(size, (session.width, session.height))); - } - match session.rgb.as_ref().expect("made above") { - Ok(import) => Ok(import), - Err(e) => Err(self.unavailable(e.clone())), - } - } - - fn new_rgb_import( - &self, - size: (u32, u32), - coded: (u32, u32), - ) -> std::result::Result { - let bgr0 = self.ffmpeg.pix.bgr0.ok_or("no bgr0 pixel format")?; - let display = vaapi_display(self.ffmpeg)?; - let converter = vpp::Converter::new(display, coded.0, coded.1)?; - let pool = self.vaapi_pool(size.0, size.1, bgr0).map_err(|e| e.to_string())?; - // SAFETY: an allocation (NULL is freed as nothing by the drop). - let mapped = unsafe { (self.ffmpeg.api.av_frame_alloc)() }; - let import = RgbImport { pool, mapped, size, converter }; - if import.mapped.is_null() { Err("out of memory".into()) } else { Ok(import) } - } - - /// Map DMA-BUF `frame` onto a VA-API surface in `dst` (one of our - /// frames), which gets a reference to `pool`: the import takes that - /// frames context's size and device. - fn map_dmabuf( - &self, - frame: &DmaBufRef, - pool: Ptr, - dst: Ptr, - refs: layout::FrameRefs, - ) -> Result<()> { - let api = &self.ffmpeg.api; - let drm_prime = - self.ffmpeg.pix.drm_prime.ok_or_else(|| self.unavailable("no DRM PRIME".into()))?; - let vaapi = self.ffmpeg.pix.vaapi.ok_or_else(|| self.unavailable("no VA-API".into()))?; - let mut descriptor = - sys::DrmFrameDescriptor { nb_objects: 1, nb_layers: 1, ..Default::default() }; - descriptor.objects[0] = - sys::DrmObject { fd: frame.fd, size: frame.size, format_modifier: frame.modifier }; - descriptor.layers[0].format = frame.fourcc; - descriptor.layers[0].nb_planes = frame.plane_count as c_int; - for (plane, &(offset, pitch)) in - descriptor.layers[0].planes.iter_mut().zip(&frame.planes[..frame.plane_count]) - { - *plane = - sys::DrmPlane { object_index: 0, offset: offset as isize, pitch: pitch as isize }; - } - // SAFETY: the descriptor lives in a buffer the source frame owns - // (buf[0], checked offset), so FFmpeg can keep it while mapped; the - // destination frame gets a reference to the pool at the checked - // hw_frames_ctx offset; av_frame_free / av_frame_unref release both. - unsafe { - let mut buffer = (api.av_buffer_allocz)(std::mem::size_of::()); - let mut src = (api.av_frame_alloc)(); - if buffer.is_null() || src.is_null() { - (api.av_buffer_unref)(&mut buffer); - (api.av_frame_free)(&mut src); - return Err(self.unavailable("out of memory".into())); - } - let data = (*buffer.cast::()).data; - data.cast::().write(descriptor); - let head = src.cast::(); - (*head).format = drm_prime; - (*head).width = frame.width as c_int; - (*head).height = frame.height as c_int; - (*head).data[0] = data; - layout::write::(src, refs.buf, buffer); - (*dst.cast::()).format = vaapi; - layout::write::(dst, refs.hw_frames_ctx, (api.av_buffer_ref)(pool)); - let ret = (api.av_hwframe_map)(dst, src, sys::HWFRAME_MAP_READ); - (api.av_frame_free)(&mut src); - if ret < 0 { - (api.av_frame_unref)(dst); - return Err(self.error("DMA-BUF import", ret)); - } - } - Ok(()) - } - /// The pts of a frame taken at `timestamp`: frame numbers at the /// session's rate (its time base), strictly increasing; remembered with /// the 90 kHz time for the packets. @@ -1508,6 +1412,45 @@ impl VideoEncoder for FfmpegEncoder { } Ok(()) } + + /// VA-API encoders take NV12 surfaces of the sizes they encode exactly. + fn gpu_alignment(&self) -> Option<(u32, u32)> { + self.spec.is_vaapi().then_some(self.alignment) + } + + /// The surface goes to the encoder as it is: the encoder takes a + /// reference, so it stays out of its pool until the encoder is done. + fn encode_gpu( + &mut self, + frame: &GpuFrame, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + if !self.spec.is_vaapi() { + return Err(self.unavailable(format!("{} takes no VA-API surfaces", self.spec.name))); + } + if frame.surface.0.is_null() { + return Err(self.unavailable("a GPU frame without a surface (out of memory)".into())); + } + if self.coded_size(frame.width, frame.height) != (frame.width, frame.height) { + return Err(self.unavailable(format!( + "{}x{} is not a size {} encodes exactly", + frame.width, frame.height, self.spec.name + ))); + } + let (mut session, force) = self.prepare(frame.width, frame.height, force_keyframe, out)?; + let pts = self.stamp(&mut session, frame.timestamp, frame.pts_90khz()); + // SAFETY: `hw` is our frame, unreferenced after each frame; + // `surface` is a live VA-API frame of the same device. + let ret = unsafe { (self.ffmpeg.api.av_frame_ref)(session.hw, frame.surface.0) }; + let result = if ret < 0 { + Err(self.error("GPU frame", ret)) + } else { + self.send_surface(&mut session, pts, force, out) + }; + self.session = Some(session); + result + } } /// A gradient test picture. @@ -2102,8 +2045,7 @@ mod tests { ) -> Self { let ffmpeg = Ffmpeg::get().unwrap(); let api = &ffmpeg.api; - let encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap(); - let pool = encoder.vaapi_pool(width, height, sw_format).expect("a VA-API surface pool"); + let pool = vaapi_pool(ffmpeg, width, height, sw_format).expect("a VA-API surface pool"); // SAFETY: `pool` is a live frames context of this process's // VA-API device; the frames are ours and freed by the drop. The // exported frame's `data[0]` is the AVDRMFrameDescriptor FFmpeg @@ -2190,6 +2132,113 @@ mod tests { } } + /// The picture of a GPU frame, read back into memory as I420. + fn download(frame: &GpuFrame) -> VideoFrame { + let ffmpeg = Ffmpeg::get().unwrap(); + let api = &ffmpeg.api; + let (w, h) = (frame.width as usize, frame.height as usize); + let mut out = VideoFrame::black_i420(frame.width, frame.height); + let FrameData::I420 { y, u, v } = &mut out.data else { unreachable!() }; + // SAFETY: `sw` is ours and freed below; a downloaded plane holds + // `linesize * rows` bytes. + unsafe { + let mut sw = (api.av_frame_alloc)(); + (*sw.cast::()).format = ffmpeg.pix.nv12; + assert!((api.av_hwframe_transfer_data)(sw, frame.surface.0, 0) >= 0, "download"); + let head = &*sw.cast::(); + let rows = |i: usize, rows: usize| { + let stride = head.linesize[i] as usize; + std::slice::from_raw_parts(head.data[i], stride * rows).chunks_exact(stride) + }; + for (row, src) in rows(0, h).enumerate() { + y.data[row * w..][..w].copy_from_slice(&src[..w]); + } + let cw = w / 2; + for (row, src) in rows(1, h / 2).enumerate() { + for (i, pair) in src[..cw * 2].chunks_exact(2).enumerate() { + u.data[row * u.stride + i] = pair[0]; + v.data[row * v.stride + i] = pair[1]; + } + } + (api.av_frame_free)(&mut sw); + } + out + } + + /// One captured RGB DMA-BUF made into a GPU frame per simulcast layer: + /// full size, half and a fixed 640x360 at AV1's alignment, each the + /// whole picture scaled (cropped to the alignment) as the CPU pyramid + /// does it, and each encoded by `h264_vaapi` straight from its surface + /// and decoded. The frames are recycled once nothing holds them. + #[test] + fn gpu_frames_for_every_layer() { + const SIZE: (u32, u32) = (1280, 720); + if !usable("h264_vaapi") { + eprintln!("no usable h264_vaapi, skipped"); + return; + } + let ffmpeg = Ffmpeg::get().unwrap(); + let screen = crate::capture::synthetic::SyntheticScreen::with_pattern( + SIZE.0, + SIZE.1, + crate::capture::synthetic::Pattern::Desktop, + ); + let picture = screen.frame(5, 30); + let rgb = + Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)); + let mut converter = GpuConverter::new().expect("VA-API video processing"); + eprintln!("tiled RGB modifiers the import takes: {:x?}", converter.modifiers()); + let layers = [ + GpuLayer { size: SIZE, alignment: (2, 2), due: true }, + GpuLayer { size: (640, 360), alignment: (64, 16), due: true }, + GpuLayer { size: (320, 180), alignment: (2, 2), due: false }, + ]; + let mut out = [None, None, None]; + converter.convert(&rgb.frame, &layers, &mut out).expect("converted"); + assert!(out[2].is_none(), "a layer that is not due gets nothing"); + let sizes: Vec<_> = out.iter().flatten().map(|f| (f.width, f.height)).collect(); + assert_eq!(sizes, [SIZE, (640, 352)], "cropped to the alignment"); + + let cpu = convert::to_i420(&picture).unwrap().into_owned(); + let mut half = VideoFrame::black_i420(640, 360); + let mut workers = crate::workers::Workers::new("voelin-test-scale", 1); + crate::scale::scale_i420(&mut workers, &cpu, &mut half).unwrap(); + for frame in out.iter().flatten() { + // The CPU's picture at the layer's size, cropped the same way. + let reference = if (frame.width, frame.height) == SIZE { &cpu } else { &half }; + let mut cropped = reference.view(); + (cropped.width, cropped.height) = (frame.width, frame.height); + let gpu = download(frame); + let psnr = convert::psnr(&cropped.to_frame(), &gpu).unwrap(); + eprintln!("{}x{}: PSNR {psnr:.1} dB against the CPU's", frame.width, frame.height); + assert!(psnr > 30.0, "{}x{}: {psnr:.1} dB", frame.width, frame.height); + + let mut encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap(); + let mut decoder = decoder(Codec::H264); + let mut packets = 0; + encoder + .encode_gpu(frame, true, &mut |chunk| { + packets += 1; + if let Some(decoder) = &mut decoder { + let decoded = decoder.decode(chunk.data).unwrap().expect("a picture"); + assert_eq!((decoded.width, decoded.height), (frame.width, frame.height)); + let psnr = convert::psnr(&gpu, &decoded).unwrap(); + assert!(psnr > 30.0, "decoded at {psnr:.1} dB"); + } + }) + .expect("encoded from the surface"); + assert!(packets > 0); + } + // Once nothing holds them, the same frames come back. + let first: Vec<*const GpuFrame> = + out.iter().flatten().map(std::sync::Arc::as_ptr).collect(); + out = [None, None, None]; + converter.convert(&rgb.frame, &layers, &mut out).expect("converted again"); + let again: Vec<*const GpuFrame> = + out.iter().flatten().map(std::sync::Arc::as_ptr).collect(); + assert_eq!(first, again, "recycled"); + } + /// Our decoder for `codec`, if this build and machine have one: OpenH264 /// with `VOELIN_OPENH264_LIB`, dav1d with `--features av1`. fn decoder(codec: Codec) -> Option> { @@ -2255,7 +2304,6 @@ mod tests { return; } let ffmpeg = Ffmpeg::get().unwrap(); - let api = &ffmpeg.api; let screen = crate::capture::synthetic::SyntheticScreen::with_pattern( SIZE.0, SIZE.1, @@ -2267,45 +2315,21 @@ mod tests { assert_eq!(rgb.frame.plane_count, 1); // The conversion alone: the GPU's NV12 against the CPU's I420. - let converter = - vpp::Converter::new(vaapi_display(ffmpeg).unwrap(), SIZE.0, SIZE.1).unwrap(); - let encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap(); - let mut pool = encoder.vaapi_pool(SIZE.0, SIZE.1, ffmpeg.pix.nv12).unwrap(); + let mut converter = GpuConverter::new().expect("VA-API video processing"); + let layer = GpuLayer { size: SIZE, alignment: (2, 2), due: true }; + let mut converted = [None]; + converter.convert(&rgb.frame, &[layer], &mut converted).expect("converted"); + let downloaded = download(converted[0].as_ref().unwrap()); + drop((converted, converter)); let cpu = convert::to_i420(&picture).unwrap(); let FrameData::I420 { y, u, v } = &cpu.data else { unreachable!() }; + let FrameData::I420 { y: gy, u: gu, v: gv } = &downloaded.data else { unreachable!() }; let (w, h, cw, ch) = (SIZE.0 as usize, SIZE.1 as usize, SIZE.0 as usize / 2, SIZE.1 as usize / 2); - let mut gpu = [Vec::new(), Vec::new(), Vec::new()]; - // SAFETY: frames and pool are ours and freed below; the downloaded - // planes hold `linesize * rows` bytes. - unsafe { - let (mut out, mut sw) = ((api.av_frame_alloc)(), (api.av_frame_alloc)()); - assert!((api.av_hwframe_get_buffer)(pool, out, 0) >= 0); - converter.convert(surface_id(rgb.surface), surface_id(out)).expect("converted"); - (*sw.cast::()).format = ffmpeg.pix.nv12; - assert!((api.av_hwframe_transfer_data)(sw, out, 0) >= 0, "download"); - let head = &*sw.cast::(); - let plane = |i: usize, rows: usize| { - let stride = head.linesize[i] as usize; - std::slice::from_raw_parts(head.data[i], stride * rows).chunks_exact(stride) - }; - for row in plane(0, h) { - gpu[0].extend_from_slice(&row[..w]); - } - for row in plane(1, ch) { - for pair in row[..cw * 2].chunks_exact(2) { - gpu[1].push(pair[0]); - gpu[2].push(pair[1]); - } - } - (api.av_frame_free)(&mut sw); - (api.av_frame_free)(&mut out); - (api.av_buffer_unref)(&mut pool); - } - drop(converter); for (name, gpu, cpu, width, rows) in - [("Y", &gpu[0], y, w, h), ("U", &gpu[1], u, cw, ch), ("V", &gpu[2], v, cw, ch)] + [("Y", gy, y, w, h), ("U", gu, u, cw, ch), ("V", gv, v, cw, ch)] { + let gpu: Vec = (0..rows).flat_map(|r| gpu.row(r, width).to_vec()).collect(); let cpu: Vec = (0..rows).flat_map(|r| cpu.row(r, width).to_vec()).collect(); let mean = gpu.iter().zip(&cpu).map(|(a, b)| u64::from(a.abs_diff(*b))).sum::() as f64 / cpu.len() as f64; @@ -2317,9 +2341,9 @@ mod tests { // The buffers: the driver's own (tiled), and a LINEAR one with a // padded pitch in system memory, which is what the portal negotiates. - #[cfg(target_os = "linux")] + #[cfg(all(target_os = "linux", feature = "pipewire"))] let linear = linear_dmabuf(&picture, (SIZE.0 as usize * 4).next_multiple_of(256)); - #[cfg(not(target_os = "linux"))] + #[cfg(not(all(target_os = "linux", feature = "pipewire")))] let linear: Option<((), DmaBufRef)> = None; if linear.is_none() { eprintln!("no /dev/udmabuf: the LINEAR buffer is skipped"); @@ -2384,91 +2408,33 @@ mod tests { } } - /// `struct udmabuf_create` of ``, and `UDMABUF_CREATE` - /// returning the new DMA-BUF. - #[cfg(target_os = "linux")] - #[repr(C)] - struct UdmabufCreate { - memfd: u32, - flags: u32, - offset: u64, - size: u64, - } - - // SAFETY: `UDMABUF_CREATE` (`_IOW('u', 0x42, struct udmabuf_create)`) - // only reads the struct and returns a new descriptor. - #[cfg(target_os = "linux")] - unsafe impl rustix::ioctl::Ioctl for UdmabufCreate { - type Output = std::os::fd::OwnedFd; - const IS_MUTATING: bool = false; - - fn opcode(&self) -> rustix::ioctl::Opcode { - rustix::ioctl::opcode::write::(b'u', 0x42) - } - - fn as_ptr(&mut self) -> *mut std::ffi::c_void { - (&raw mut *self).cast() - } - - unsafe fn output_from_ptr( - out: rustix::ioctl::IoctlOutput, - _: *mut std::ffi::c_void, - ) -> rustix::io::Result { - // SAFETY: the descriptor the kernel just made, ours to own. - Ok(unsafe { std::os::fd::FromRawFd::from_raw_fd(out) }) - } - } - - /// `picture` (BGRA) in a LINEAR DMA-BUF of system memory, rows `stride` - /// bytes apart: `/dev/udmabuf` over a sealed memfd. The descriptor has - /// to outlive the returned buffer. `None` without access to + /// `picture` (BGRA) in a LINEAR DMA-BUF of ordinary memory, rows + /// `stride` bytes apart ([`Udmabuf`](crate::capture::dmabuf::Udmabuf)); + /// the buffer has to outlive the reference. `None` without access to /// `/dev/udmabuf`. - #[cfg(target_os = "linux")] + #[cfg(all(target_os = "linux", feature = "pipewire"))] fn linear_dmabuf( picture: &VideoFrame, stride: usize, - ) -> Option<(std::os::fd::OwnedFd, DmaBufRef)> { - use rustix::fs::{MemfdFlags, SealFlags}; - use std::io::Write; - use std::os::fd::AsRawFd; - + ) -> Option<(crate::capture::dmabuf::Udmabuf, DmaBufRef)> { let FrameData::Bgra(pixels) = &picture.data else { return None }; let (w, h) = (picture.width as usize, picture.height as usize); - let size = (stride * h).next_multiple_of(4096); - let memfd = rustix::fs::memfd_create( - "voelin-linear-dmabuf", - MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING, - ) - .ok()?; - let mut bytes = vec![0; size]; - for (y, row) in bytes.chunks_exact_mut(stride).take(h).enumerate() { + let mut buffer = crate::capture::dmabuf::Udmabuf::new(stride * h).ok()?; + for (y, row) in buffer.bytes_mut().chunks_exact_mut(stride).take(h).enumerate() { row[..w * 4].copy_from_slice(pixels.row(y, w * 4)); } - let mut file = std::fs::File::from(memfd); - file.write_all(&bytes).ok()?; - rustix::fs::fcntl_add_seals(&file, SealFlags::SHRINK).ok()?; - let device = - std::fs::OpenOptions::new().read(true).write(true).open("/dev/udmabuf").ok()?; - let create = UdmabufCreate { - memfd: file.as_raw_fd() as u32, - flags: 1, - offset: 0, - size: size as u64, - }; - // SAFETY: see the `Ioctl` impl; `device` is /dev/udmabuf. - let fd = unsafe { rustix::ioctl::ioctl(&device, create) }.ok()?; let frame = DmaBufRef { width: picture.width, height: picture.height, timestamp: Duration::ZERO, fourcc: drm_fourcc(b"XR24"), modifier: crate::capture::DRM_MOD_LINEAR, - fd: fd.as_raw_fd(), - size, + fd: buffer.fd(), + size: buffer.len(), planes: [(0, stride), (0, 0), (0, 0), (0, 0)], plane_count: 1, }; - Some((fd, frame)) + Some((buffer, frame)) } /// What the CPU spends per frame on its way into a VA-API encoder at diff --git a/crates/voelin-media/src/ffmpeg/gpu.rs b/crates/voelin-media/src/ffmpeg/gpu.rs new file mode 100644 index 0000000..ff8cccc --- /dev/null +++ b/crates/voelin-media/src/ffmpeg/gpu.rs @@ -0,0 +1,385 @@ +//! Captured RGB DMA-BUFs converted and scaled into NV12 VA-API surfaces on +//! the GPU, for VA-API encoders: screen sharing without the CPU reading a +//! pixel. +//! +//! A DMA-BUF (what the ScreenCast portal hands over) is mapped onto a VA-API +//! surface ([`map_dmabuf`]), and VA-API video processing ([`super::vpp`]) +//! converts it to NV12 at the size of every layer that wants a frame, into +//! surfaces from pools of our own. The buffer is free again once +//! [`GpuConverter::convert`] returns; the surfaces travel to the encoders as +//! [`GpuFrame`]s ([`VideoEncoder::encode_gpu`](crate::VideoEncoder::encode_gpu)) +//! and go back to their pools when the last reference is dropped. The +//! frames are recycled, so nothing is allocated per frame once the pools +//! are warm. +#![allow(unsafe_code)] + +use std::ffi::{c_int, c_uint}; +use std::sync::Arc; +use std::time::Duration; + +use super::encoder::{exact_size, vaapi_display, vaapi_pool}; +use super::layout::{self, FrameRefs}; +use super::sys::{self, FrameHead, Ptr}; +use super::{Ffmpeg, vpp}; +use crate::capture::{DRM_MOD_INVALID, DRM_MOD_LINEAR, DmaBufRef, drm_fourcc}; +use crate::frame::GpuFrame; +use crate::{Error, Result}; + +/// The DRM formats of RGB buffers the conversion takes (8 bits per +/// channel, 4 bytes per pixel, one plane; what screen capture offers). +pub(crate) const RGB_FOURCCS: [u32; 4] = + [drm_fourcc(b"XR24"), drm_fourcc(b"AR24"), drm_fourcc(b"XB24"), drm_fourcc(b"AB24")]; + +/// An `AVFrame` that holds a VA-API surface (or nothing yet). Freeing it +/// gives the surface back to its pool. +pub(crate) struct Surface(pub(crate) Ptr); + +// SAFETY: the frame is ours. Once it holds a surface it is only read: its +// surface id, and as the source of `av_frame_ref`, which takes references +// of its own (FFmpeg's buffer references are thread-safe). +unsafe impl Send for Surface {} +unsafe impl Sync for Surface {} + +impl Surface { + fn alloc(ffmpeg: &Ffmpeg) -> Result { + // SAFETY: an allocation; NULL is checked. + let frame = unsafe { (ffmpeg.api.av_frame_alloc)() }; + if frame.is_null() { + return Err(Error::Convert("out of memory".into())); + } + Ok(Self(frame)) + } + + /// Another frame of the same surface (NULL, which encoders refuse, if + /// memory runs out). + pub(crate) fn new_ref(&self) -> Self { + let api = &Ffmpeg::get().expect("a surface exists only with FFmpeg").api; + // SAFETY: a new frame takes a reference to ours; freed on failure. + unsafe { + let mut frame = (api.av_frame_alloc)(); + if !frame.is_null() && (api.av_frame_ref)(frame, self.0) < 0 { + (api.av_frame_free)(&mut frame); + } + Self(frame) + } + } + + /// The VA-API surface id (`data[3]` of an `AV_PIX_FMT_VAAPI` frame, + /// `hwcontext_vaapi.h`). + pub(crate) fn id(&self) -> c_uint { + // SAFETY: a live frame; `data` is its leading field. + unsafe { (*self.0.cast::()).data[3] as usize as c_uint } + } +} + +impl Drop for Surface { + fn drop(&mut self) { + if let Ok(ffmpeg) = Ffmpeg::get() { + // SAFETY: our frame (or NULL). + unsafe { (ffmpeg.api.av_frame_free)(&mut self.0) }; + } + } +} + +/// Map DMA-BUF `frame` onto a VA-API surface in `dst` (an unreferenced frame +/// of ours), which takes a reference to `pool`: the surface gets that frames +/// context's device. The surface reads the buffer itself, without a copy; +/// unreferencing `dst` lets the buffer go. +pub(crate) fn map_dmabuf( + ffmpeg: &Ffmpeg, + frame: &DmaBufRef, + pool: Ptr, + dst: Ptr, + refs: FrameRefs, +) -> std::result::Result<(), String> { + let api = &ffmpeg.api; + let drm_prime = ffmpeg.pix.drm_prime.ok_or("no DRM PRIME pixel format")?; + let vaapi = ffmpeg.pix.vaapi.ok_or("no VA-API pixel format")?; + let mut descriptor = + sys::DrmFrameDescriptor { nb_objects: 1, nb_layers: 1, ..Default::default() }; + descriptor.objects[0] = + sys::DrmObject { fd: frame.fd, size: frame.size, format_modifier: frame.modifier }; + descriptor.layers[0].format = frame.fourcc; + descriptor.layers[0].nb_planes = frame.plane_count as c_int; + for (plane, &(offset, pitch)) in + descriptor.layers[0].planes.iter_mut().zip(&frame.planes[..frame.plane_count]) + { + *plane = sys::DrmPlane { object_index: 0, offset: offset as isize, pitch: pitch as isize }; + } + // SAFETY: the descriptor lives in a buffer the source frame owns (buf[0], + // checked offset), so FFmpeg can keep it while mapped; the destination + // gets a reference to the pool at the checked hw_frames_ctx offset; + // av_frame_free / av_frame_unref release both. + unsafe { + let mut buffer = (api.av_buffer_allocz)(size_of::()); + let mut src = (api.av_frame_alloc)(); + if buffer.is_null() || src.is_null() { + (api.av_buffer_unref)(&mut buffer); + (api.av_frame_free)(&mut src); + return Err("out of memory".into()); + } + let data = (*buffer.cast::()).data; + data.cast::().write(descriptor); + let head = src.cast::(); + (*head).format = drm_prime; + (*head).width = frame.width as c_int; + (*head).height = frame.height as c_int; + (*head).data[0] = data; + layout::write::(src, refs.buf, buffer); + (*dst.cast::()).format = vaapi; + layout::write::(dst, refs.hw_frames_ctx, (api.av_buffer_ref)(pool)); + let ret = (api.av_hwframe_map)(dst, src, sys::HWFRAME_MAP_READ); + (api.av_frame_free)(&mut src); + if ret < 0 { + (api.av_frame_unref)(dst); + return Err(format!("DMA-BUF import: {}", api.error_text(ret))); + } + } + Ok(()) +} + +/// One output of [`GpuConverter::convert`]: a layer's size, the multiple +/// its encoder takes, and whether it wants this frame. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct GpuLayer { + /// The size the whole picture is scaled to. + pub size: (u32, u32), + /// What the encoded width and height must be a multiple of + /// ([`VideoEncoder::gpu_alignment`](crate::VideoEncoder::gpu_alignment)): + /// the scaled picture is cropped to it at the right and bottom, as + /// encoders crop frames in memory. + pub alignment: (u32, u32), + pub due: bool, +} + +/// NV12 surfaces of one size, and the frames that hold them, reused once +/// nothing else does. +struct Output { + size: (u32, u32), + pool: Ptr, + frames: Vec>, +} + +impl Drop for Output { + fn drop(&mut self) { + // Frames still held elsewhere keep their surfaces and the pool. + self.frames.clear(); + if let Ok(ffmpeg) = Ffmpeg::get() { + // SAFETY: our reference. + unsafe { (ffmpeg.api.av_buffer_unref)(&mut self.pool) }; + } + } +} + +/// See the [module docs](self). One per capture, used from one thread. +pub struct GpuConverter { + ffmpeg: &'static Ffmpeg, + refs: FrameRefs, + display: vpp::Display, + /// Video processing, and the source size it was made for. + vpp: Option<(vpp::Converter, (u32, u32))>, + /// The frames context DMA-BUFs of this size are mapped onto. + import: Option<(Ptr, (u32, u32))>, + /// Holds a mapping while it is converted. + mapped: Surface, + outputs: Vec, + modifiers: Vec, +} + +// SAFETY: the FFmpeg and libva objects are ours and used from one thread +// at a time (`&mut self`). +unsafe impl Send for GpuConverter {} + +impl GpuConverter { + /// A converter on the process's VA-API device, or why there is none (no + /// FFmpeg, no VA-API device, no video processing). + pub fn new() -> Result { + let ffmpeg = Ffmpeg::get().map_err(|e| Error::Convert(e.into()))?; + let refs = ffmpeg.frame_refs.clone().map_err(Error::Convert)?; + let display = vaapi_display(ffmpeg).map_err(Error::Convert)?; + // Fail now rather than on the first frame. + vpp::Converter::new(display, 64, 64).map_err(Error::Convert)?; + let mut converter = Self { + ffmpeg, + refs, + display, + vpp: None, + import: None, + mapped: Surface::alloc(ffmpeg)?, + outputs: Vec::new(), + modifiers: Vec::new(), + }; + converter.modifiers.extend(converter.tiled_modifier()); + Ok(converter) + } + + /// The tiled DRM format modifiers RGB buffers may have besides LINEAR: + /// the one this GPU's driver gives RGB surfaces of its own (it imports + /// what it makes), if that is tiled and needs a single plane (no + /// compression metadata). Empty if there is none. + pub fn modifiers(&self) -> &[u64] { + &self.modifiers + } + + fn tiled_modifier(&self) -> Option { + let ffmpeg = self.ffmpeg; + let api = &ffmpeg.api; + let drm_prime = ffmpeg.pix.drm_prime?; + // The size of a typical screen: drivers may lay out small surfaces + // differently. + let mut pool = vaapi_pool(ffmpeg, 1920, 1080, ffmpeg.pix.bgr0?).ok()?; + let (surface, drm) = (Surface::alloc(ffmpeg).ok()?, Surface::alloc(ffmpeg).ok()?); + // SAFETY: frames and pool are ours; the exported frame's data[0] is + // the descriptor FFmpeg filled, read while the mapping lives (`drm` + // goes before `surface`). + let modifier = unsafe { + let mut modifier = None; + if (api.av_hwframe_get_buffer)(pool, surface.0, 0) >= 0 { + (*drm.0.cast::()).format = drm_prime; + let flags = sys::HWFRAME_MAP_READ | sys::HWFRAME_MAP_DIRECT; + if (api.av_hwframe_map)(drm.0, surface.0, flags) >= 0 { + let d = *(*drm.0.cast::()).data[0].cast::(); + let layers = &d.layers[..(d.nb_layers.max(0) as usize).min(d.layers.len())]; + let planes: c_int = layers.iter().map(|l| l.nb_planes).sum(); + let m = d.objects[0].format_modifier; + let tiled = m != DRM_MOD_LINEAR && m != DRM_MOD_INVALID; + modifier = (d.nb_objects == 1 && planes == 1 && tiled).then_some(m); + } + } + modifier + }; + drop(drm); + drop(surface); + // SAFETY: our reference. + unsafe { (api.av_buffer_unref)(&mut pool) }; + modifier + } + + /// Convert `frame`, an RGB DMA-BUF (`XR24`, `AR24`, `XB24` or `AB24` in + /// one plane, LINEAR or one of [`modifiers`](Self::modifiers)), for every + /// due layer: each gets an NV12 [`GpuFrame`] in `out` (same index), the + /// whole picture scaled to the layer's size and cropped to its alignment. + /// The buffer is no longer read when this returns. On an error nothing + /// in `out` is valid for this frame. + pub fn convert( + &mut self, + frame: &DmaBufRef, + layers: &[GpuLayer], + out: &mut [Option>], + ) -> Result<()> { + if !RGB_FOURCCS.contains(&frame.fourcc) || frame.plane_count != 1 { + return Err(Error::Convert("not an RGB DMA-BUF of one plane".into())); + } + let source = (frame.width, frame.height); + self.outputs.retain(|o| layers.iter().any(|l| exact_size(l.size, l.alignment) == o.size)); + self.prepare(source)?; + let pool = self.import.as_ref().expect("prepared").0; + map_dmabuf(self.ffmpeg, frame, pool, self.mapped.0, self.refs).map_err(Error::Convert)?; + let result = self.convert_mapped(frame, layers, out); + // SAFETY: our frame; this lets the buffer go. + unsafe { (self.ffmpeg.api.av_frame_unref)(self.mapped.0) }; + result + } + + /// The import pool and the video processing for buffers of `source`'s + /// size. + fn prepare(&mut self, source: (u32, u32)) -> Result<()> { + if self.import.as_ref().is_none_or(|(_, size)| *size != source) { + if let Some((mut pool, _)) = self.import.take() { + // SAFETY: our reference. + unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) }; + } + let bgr0 = self.ffmpeg.pix.bgr0.ok_or(Error::Convert("no bgr0 pixel format".into()))?; + let pool = vaapi_pool(self.ffmpeg, source.0, source.1, bgr0).map_err(Error::Convert)?; + self.import = Some((pool, source)); + } + if self.vpp.as_ref().is_none_or(|(_, size)| *size != source) { + self.vpp = None; + let converter = + vpp::Converter::new(self.display, source.0, source.1).map_err(Error::Convert)?; + self.vpp = Some((converter, source)); + } + Ok(()) + } + + fn convert_mapped( + &mut self, + frame: &DmaBufRef, + layers: &[GpuLayer], + out: &mut [Option>], + ) -> Result<()> { + let input = self.mapped.id(); + for (layer, slot) in layers.iter().zip(out.iter_mut()) { + if !layer.due { + continue; + } + let exact = exact_size(layer.size, layer.alignment); + // The part of the picture that scales to `exact`: all of it + // scales to `size`, the rest is cropped. + let part = |full: u32, kept: u32, of: u32| { + (u64::from(full) * u64::from(kept) / u64::from(of.max(1))).max(1) as u32 + }; + let src = ( + part(frame.width, exact.0, layer.size.0), + part(frame.height, exact.1, layer.size.1), + ); + let gpu = self.output(exact, frame.timestamp)?; + let (vpp, _) = self.vpp.as_ref().expect("prepared"); + vpp.convert(input, src, gpu.surface.id(), exact).map_err(Error::Convert)?; + *slot = Some(gpu); + } + Ok(()) + } + + /// A frame with a fresh NV12 surface of `size`: one that nothing else + /// holds any more, else a new one. + fn output(&mut self, size: (u32, u32), timestamp: Duration) -> Result> { + let ffmpeg = self.ffmpeg; + let index = match self.outputs.iter().position(|o| o.size == size) { + Some(i) => i, + None => { + let pool = + vaapi_pool(ffmpeg, size.0, size.1, ffmpeg.pix.nv12).map_err(Error::Convert)?; + self.outputs.push(Output { size, pool, frames: Vec::new() }); + self.outputs.len() - 1 + } + }; + let output = &mut self.outputs[index]; + let free = match output.frames.iter_mut().position(|f| Arc::get_mut(f).is_some()) { + Some(free) => free, + None => { + let surface = Surface::alloc(ffmpeg)?; + output.frames.push(Arc::new(GpuFrame { + width: size.0, + height: size.1, + timestamp, + surface, + })); + output.frames.len() - 1 + } + }; + let frame = Arc::get_mut(&mut output.frames[free]).expect("nothing else holds it"); + frame.timestamp = timestamp; + let api = &ffmpeg.api; + // SAFETY: our frame; unreferencing gives its old surface back (once + // the encoder that referenced it is done), then it takes a new one. + let ret = unsafe { + (api.av_frame_unref)(frame.surface.0); + (api.av_hwframe_get_buffer)(output.pool, frame.surface.0, 0) + }; + if ret < 0 { + return Err(Error::Convert(format!("VA-API surface: {}", api.error_text(ret)))); + } + Ok(output.frames[free].clone()) + } +} + +impl Drop for GpuConverter { + fn drop(&mut self) { + self.outputs.clear(); + if let Some((mut pool, _)) = self.import.take() { + // SAFETY: our reference. + unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) }; + } + } +} diff --git a/crates/voelin-media/src/ffmpeg/mod.rs b/crates/voelin-media/src/ffmpeg/mod.rs index 712a3ce..aed49f5 100644 --- a/crates/voelin-media/src/ffmpeg/mod.rs +++ b/crates/voelin-media/src/ffmpeg/mod.rs @@ -19,10 +19,14 @@ use std::path::PathBuf; use std::sync::{Mutex, OnceLock}; pub mod encoder; +mod gpu; mod layout; pub mod sys; mod vpp; +pub(crate) use gpu::Surface; +pub use gpu::{GpuConverter, GpuLayer}; + pub use encoder::{ BACKENDS, BackendKind, BackendSpec, BackendStatus, FfmpegEncoder, FfmpegFactory, Input, probe, }; diff --git a/crates/voelin-media/src/ffmpeg/sys.rs b/crates/voelin-media/src/ffmpeg/sys.rs index 8d6f8ce..1cadd07 100644 --- a/crates/voelin-media/src/ffmpeg/sys.rs +++ b/crates/voelin-media/src/ffmpeg/sys.rs @@ -199,6 +199,7 @@ api! { fn av_frame_get_buffer(frame: Ptr, align: c_int) -> c_int; fn av_frame_make_writable(frame: Ptr) -> c_int; fn av_frame_unref(frame: Ptr); + fn av_frame_ref(dst: Ptr, src: Ptr) -> c_int; fn av_opt_set(obj: Ptr, name: *const c_char, val: *const c_char, flags: c_int) -> c_int; fn av_opt_set_int(obj: Ptr, name: *const c_char, val: i64, flags: c_int) -> c_int; fn av_opt_set_q(obj: Ptr, name: *const c_char, val: Rational, flags: c_int) -> c_int; diff --git a/crates/voelin-media/src/ffmpeg/vpp.rs b/crates/voelin-media/src/ffmpeg/vpp.rs index 03d1d70..243f5a5 100644 --- a/crates/voelin-media/src/ffmpeg/vpp.rs +++ b/crates/voelin-media/src/ffmpeg/vpp.rs @@ -171,14 +171,12 @@ impl Va { } /// A VA-API video processing context that converts RGB surfaces into NV12 -/// ones of `width` x `height`. +/// ones, cropping and scaling on the way. pub struct Converter { va: &'static Va, display: Display, config: c_uint, context: c_uint, - width: u32, - height: u32, } // SAFETY: libva serialises calls per display; the context is used from one @@ -187,8 +185,8 @@ unsafe impl Send for Converter {} impl Converter { /// A context on `display` (FFmpeg's, see - /// [`layout::device_hwctx`](super::layout::device_hwctx)) for output - /// surfaces of `width` x `height`. + /// [`layout::device_hwctx`](super::layout::device_hwctx)) for pictures of + /// up to `width` x `height`. pub fn new(display: Display, width: u32, height: u32) -> Result { let va = Va::get()?; let mut config = 0; @@ -224,24 +222,36 @@ impl Converter { unsafe { (va.destroy_config)(display, config) }; return Err(e); } - Ok(Self { va, display, config, context, width, height }) + Ok(Self { va, display, config, context }) } - /// Convert the top-left `width` x `height` of RGB surface `input` into - /// NV12 surface `output` (both of this display): BT.601, limited range, - /// what the encoders signal and the CPU path ([`crate::convert`]) - /// produces. + /// Convert the top-left `src` (width, height) of RGB surface `input` + /// into the top-left `dst` of NV12 surface `output` (both of this + /// display), scaled if the two differ: BT.601, limited range, what the + /// encoders signal and the CPU path ([`crate::convert`]) produces. /// /// Returns once the GPU has read `input`, so a captured buffer can go /// back to the compositor; `output` is ready for an encoder of the same /// display, which orders its reads after this. - pub fn convert(&self, input: c_uint, output: c_uint) -> Result<(), String> { + pub fn convert( + &self, + input: c_uint, + src: (u32, u32), + output: c_uint, + dst: (u32, u32), + ) -> Result<(), String> { let va = self.va; - let region = Rectangle { x: 0, y: 0, width: self.width as u16, height: self.height as u16 }; + let rect = |(width, height): (u32, u32)| Rectangle { + x: 0, + y: 0, + width: width.min(u32::from(u16::MAX)) as u16, + height: height.min(u32::from(u16::MAX)) as u16, + }; + let (src, dst) = (rect(src), rect(dst)); let mut parameters = PipelineParameters { surface: input, - surface_region: ®ion, - output_region: ®ion, + surface_region: &src, + output_region: &dst, output_background_color: 0xff00_0000, output_color_standard: COLOR_STANDARD_BT601, pipeline_flags: 0, diff --git a/crates/voelin-media/src/frame.rs b/crates/voelin-media/src/frame.rs index 4727851..b329bd2 100644 --- a/crates/voelin-media/src/frame.rs +++ b/crates/voelin-media/src/frame.rs @@ -284,6 +284,47 @@ impl VideoFrame { } } +/// A picture in GPU memory: an NV12 VA-API surface, converted and scaled +/// from a captured DMA-BUF on the GPU (`ffmpeg::GpuConverter`, Linux) so +/// that no CPU reads its pixels, for the encoders that take one +/// ([`VideoEncoder::gpu_alignment`](crate::VideoEncoder::gpu_alignment)). +/// Dropping it gives the surface back to its pool. Only this crate makes +/// them. +#[non_exhaustive] +pub struct GpuFrame { + pub width: u32, + pub height: u32, + /// As [`VideoFrame::timestamp`]. + pub timestamp: Duration, + #[cfg(feature = "ffmpeg")] + pub(crate) surface: crate::ffmpeg::Surface, +} + +impl GpuFrame { + /// 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 + } + + /// The same picture at another time (another reference to the same + /// surface), e.g. to send a still screen again. + pub fn at(&self, timestamp: Duration) -> Self { + Self { + width: self.width, + height: self.height, + timestamp, + #[cfg(feature = "ffmpeg")] + surface: self.surface.new_ref(), + } + } +} + +impl std::fmt::Debug for GpuFrame { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "GpuFrame({}x{} at {:?})", self.width, self.height, self.timestamp) + } +} + /// Interleaved 32-bit float audio at [`AUDIO_SAMPLE_RATE`]. #[derive(Clone, Debug, PartialEq)] pub struct AudioBuffer { diff --git a/crates/voelin-media/src/handoff.rs b/crates/voelin-media/src/handoff.rs index 145373f..9c08176 100644 --- a/crates/voelin-media/src/handoff.rs +++ b/crates/voelin-media/src/handoff.rs @@ -95,6 +95,14 @@ impl Handoff { } } + /// Make the calling thread the consumer that [`put`](Self::put) wakes + /// (what the first [`wait_timeout`](Self::wait_timeout) does), for a + /// thread that waits on several handoffs itself + /// (`std::thread::park_timeout`, then [`take`](Self::take) from each). + pub fn register(&self) { + self.consumer.get_or_init(std::thread::current); + } + /// Wake the consumer and make waits return at once (items can still be /// taken). pub fn close(&self) { diff --git a/crates/voelin-media/src/lib.rs b/crates/voelin-media/src/lib.rs index 7a6a83f..6f8c151 100644 --- a/crates/voelin-media/src/lib.rs +++ b/crates/voelin-media/src/lib.rs @@ -49,7 +49,7 @@ pub use codec::{ VideoEncoder, }; pub use frame::{ - AudioBuffer, FrameData, FrameRef, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame, + AudioBuffer, FrameData, FrameRef, GpuFrame, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame, }; pub use queue::{FrameReceiver, FrameSender, frame_channel}; diff --git a/crates/voelin-media/src/studio/mod.rs b/crates/voelin-media/src/studio/mod.rs index 3ed24fb..b444c58 100644 --- a/crates/voelin-media/src/studio/mod.rs +++ b/crates/voelin-media/src/studio/mod.rs @@ -798,8 +798,10 @@ impl Studio { wanted.iter().any(|(w, kind, background)| { w == id && input.kind().same_input(kind) - // A background filter is set up when the input starts. - && input.background().needs_mask() == background.needs_mask() + // A background filter is set up when the input starts, + // with the effect it applies: another effect (or + // strength, image, colour) needs a new input. + && input.background() == background }) }); } @@ -1196,6 +1198,25 @@ mod tests { assert!(studio.apply(Command::RenameScene { scene: 99, name: "x".into() }).await.is_err()); } + #[tokio::test] + async fn a_new_background_effect_reaches_the_input() { + let studio = Studio::start(one_colour_scene()).await.unwrap(); + for background in [ + Background::Blur { strength: 0.02 }, + Background::Blur { strength: 0.08 }, + Background::Colour { colour: Colour::rgb(0, 200, 0) }, + Background::Keep, + ] { + let change = + SourceChange { background: Some(background.clone()), ..Default::default() }; + let command = Command::UpdateSource { scene: 1, source: 1, change: Box::new(change) }; + studio.apply(command).await.unwrap(); + let graph = lock(&studio.graph); + assert_eq!(graph.inputs.len(), 1); + assert_eq!(graph.inputs[0].1.background(), &background); + } + } + #[tokio::test] async fn go_live_and_recording_change_the_status() { let studio = Studio::start(one_colour_scene()).await.unwrap(); diff --git a/crates/voelin-platform/src/notify.rs b/crates/voelin-platform/src/notify.rs index 15eec0b..12882f8 100644 --- a/crates/voelin-platform/src/notify.rs +++ b/crates/voelin-platform/src/notify.rs @@ -66,8 +66,16 @@ mod tests { use super::*; /// Without a notification service this must fail, not hang or panic. + /// Skipped where a session bus exists: on a desktop the notification + /// would really show. #[tokio::test] async fn notify_returns() { + let runtime_bus = std::env::var_os("XDG_RUNTIME_DIR") + .is_some_and(|d| std::path::Path::new(&d).join("bus").exists()); + if std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_some() || runtime_bus { + eprintln!("skipped: a D-Bus session bus is configured"); + return; + } let n = Notification { urgent: true, ..Notification::new("Poke", "from a test") }; let result = tokio::time::timeout(Duration::from_secs(10), notify(&n)).await; assert!(result.is_ok(), "notify hung"); diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 2c253dc..d09ca52 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -53,6 +53,7 @@ fn open_settings(dir: &Path, overrides: &[String]) -> Settings { for key in crate::settings::page_keys() { prefs.register(key); } + prefs.register(&crate::studio::STUDIO_UI); let config = std::env::var_os("VOELIN_CONFIG") .map(PathBuf::from) .or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists())); @@ -419,6 +420,8 @@ pub(crate) struct App { pub social: crate::social::Social, /// The settings pages of the new design. pub pages: crate::settings_pages::Pages, + /// The Stream Studio (studio.rs). + pub studio: crate::studio::StudioState, } thread_local! { @@ -614,6 +617,7 @@ pub fn run(options: RunOptions) -> Result<()> { uploads: HashMap::new(), social: Default::default(), pages: Default::default(), + studio: Default::default(), }; APP.with(|a| *a.borrow_mut() = Some(app)); crate::bind::wire(&ui); @@ -900,6 +904,13 @@ impl App { Event::SettingRejected { key, message } => { self.set_status(format!("Setting {key}: {message}")); } + // The Stream Studio's stream (studio.rs). + Event::StreamState { session, state } if self.studio_streams_to(session as i64) => { + self.studio_stream_state(state); + } + Event::StreamViewers { session, viewers } if self.studio_streams_to(session as i64) => { + self.studio_viewers(viewers); + } event => self.stream_event(event), } } diff --git a/crates/voelin-ui/src/appearance.rs b/crates/voelin-ui/src/appearance.rs index ca53583..93d329b 100644 --- a/crates/voelin-ui/src/appearance.rs +++ b/crates/voelin-ui/src/appearance.rs @@ -37,6 +37,7 @@ impl App { image_cache_mb: cache_mb as f32, }); bridge.set_image_cache_usage(images::usage_text().into()); + self.studio_theme(); } /// The settings page changed the form: store the keys (they apply diff --git a/crates/voelin-ui/src/bind/mod.rs b/crates/voelin-ui/src/bind/mod.rs index 2ea8d57..74eef87 100644 --- a/crates/voelin-ui/src/bind/mod.rs +++ b/crates/voelin-ui/src/bind/mod.rs @@ -8,8 +8,11 @@ mod servers; mod settings; mod social; mod streams; +pub(crate) mod studio; -use crate::app::MainWindow; +use slint::ComponentHandle; + +use crate::app::{MainWindow, StudioBridge}; /// Connect every callback of the window. pub(crate) fn wire(ui: &MainWindow) { @@ -20,4 +23,5 @@ pub(crate) fn wire(ui: &MainWindow) { emoji::wire(ui); social::wire(ui); pages::wire(ui); + studio::wire(&ui.global::()); } diff --git a/crates/voelin-ui/src/bind/studio.rs b/crates/voelin-ui/src/bind/studio.rs new file mode 100644 index 0000000..1d3a0c1 --- /dev/null +++ b/crates/voelin-ui/src/bind/studio.rs @@ -0,0 +1,137 @@ +//! The Stream Studio's callbacks, for the main window and for the studio's +//! own window (each has its own StudioBridge global). + +use voelin_core::studio::Command; + +use crate::app::{StudioBridge, with_app}; + +/// Slint ids are ints; the studio's are u64. +fn id(value: i32) -> u64 { + u64::try_from(value).unwrap_or(u64::MAX) +} + +fn index(value: i32) -> usize { + usize::try_from(value).unwrap_or(usize::MAX) +} + +pub(crate) fn wire(bridge: &StudioBridge) { + // From a page's init: run it after the page is built, outside of Slint's + // update. + bridge.on_open(|| { + let _ = slint::invoke_from_event_loop(|| { + with_app(|app| app.studio_open()); + }); + }); + bridge.on_detach(|| { + with_app(|app| app.studio_detach()); + }); + bridge.on_dock(|| { + with_app(|app| app.studio_dock()); + }); + + bridge.on_select_scene(|scene| { + with_app(|app| app.studio_scene_command(Command::SetActiveScene { scene: id(scene) })); + }); + bridge.on_add_scene(|| { + with_app(|app| app.studio_add_scene()); + }); + bridge.on_rename_scene(|scene, name| { + let name = name.trim().to_owned(); + if !name.is_empty() { + with_app(|app| { + app.studio_scene_command(Command::RenameScene { scene: id(scene), name }) + }); + } + }); + bridge.on_remove_scene(|scene| { + with_app(|app| app.studio_scene_command(Command::RemoveScene { scene: id(scene) })); + }); + + bridge.on_list_sources(|kind| with_app(|app| app.studio_list_sources(&kind)).unwrap_or(false)); + bridge.on_add_picked(|_, i| { + with_app(|app| app.studio_add_picked(index(i))); + }); + bridge.on_add_source(|form| { + with_app(|app| app.studio_add_source(&form)); + }); + bridge.on_source_form(|source| { + with_app(|app| app.studio_source_form(id(source))).unwrap_or_default() + }); + bridge.on_apply_source(|form| { + with_app(|app| app.studio_apply_source(&form)); + }); + bridge.on_toggle_source(|source| { + with_app(|app| app.studio_toggle_source(id(source))); + }); + bridge.on_source_action(|source, action| { + with_app(|app| app.studio_source_action(id(source), &action)); + }); + bridge.on_main_source(|kind| { + with_app(|app| app.studio_main_source(&kind)); + }); + + bridge.on_list_audio(|| { + with_app(|app| app.studio_list_audio()); + }); + bridge.on_add_audio(|i| { + with_app(|app| app.studio_add_audio(index(i))); + }); + bridge.on_set_gain(|i, db, done| { + with_app(|app| app.studio_set_gain(index(i), db, done)); + }); + bridge.on_toggle_mute(|i| { + with_app(|app| app.studio_toggle_mute(index(i))); + }); + bridge.on_remove_audio(|i| { + with_app(|app| app.studio_remove_audio(index(i))); + }); + + bridge.on_edit_form(|key, value| { + with_app(|app| app.studio_edit(&key, &value)); + }); + bridge.on_set_output(|w, h, fps| { + with_app(|app| app.studio_set_output(&w, &h, &fps)); + }); + bridge.on_set_layer(|i, layer| { + with_app(|app| app.studio_set_layer(index(i), &layer)); + }); + bridge.on_add_layer(|| { + with_app(|app| app.studio_add_layer()); + }); + bridge.on_remove_layer(|i| { + with_app(|app| app.studio_remove_layer(index(i))); + }); + bridge.on_advanced_settings(|| { + with_app(|app| app.studio_advanced()); + }); + + bridge.on_save_clip(|| { + with_app(|app| app.studio_save_clip()); + }); + bridge.on_toggle_recording(|| { + with_app(|app| app.studio_toggle_recording()); + }); + bridge.on_open_recordings(|| { + with_app(|app| app.studio_open_recordings()); + }); + bridge.on_go_live(|| { + with_app(|app| app.studio_go_live()); + }); + bridge.on_end_stream(|| { + with_app(|app| app.studio_end()); + }); + bridge.on_settings_form(|| with_app(|app| app.studio_settings_form()).unwrap_or_default()); + bridge.on_apply_settings(|form| { + with_app(|app| app.studio_apply_settings(&form)); + }); + + bridge.on_respond_viewer(|client, accept| { + with_app(|app| app.studio_respond_viewer(u16::try_from(client).unwrap_or(0), accept)); + }); + bridge.on_send_chat(|text| { + with_app(|app| app.studio_send_chat(text.to_string())); + }); + bridge.on_open_chat(|| { + with_app(|app| app.studio_open_chat()); + }); +} diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs index a79294f..4040b99 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -173,6 +173,7 @@ impl App { if !shown { self.refresh_servers(); } + self.studio_chat_changed(id, &message.target); } /// Messages the engine stored: added or updated by their local id. @@ -222,6 +223,7 @@ impl App { if fresh > 0 && !shown { self.refresh_servers(); } + self.studio_chat_changed(id, target); } /// The page of messages before the oldest one shown. @@ -239,8 +241,14 @@ impl App { self.refresh_chat(); } - /// The lines of a tab, grouped and with everything the row shows. - fn lines_of(&self, view: &SessionView, tab: &Tab, messages: &[Msg]) -> Vec { + /// The lines of a tab, grouped and with everything the row shows (also + /// the stream chat of the Stream Studio, studio.rs). + pub(crate) fn lines_of( + &self, + view: &SessionView, + tab: &Tab, + messages: &[Msg], + ) -> Vec { let gateway = view.gateway_has(feature::PINS) || view.gateway_has(feature::REACTIONS) || view.gateway_has(feature::TOPICS); diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index edfb6cb..b2aca34 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -25,7 +25,13 @@ //! `notifications` (the bell), `join` (join by address), `offline` (an //! offline message), `picture` (a chat picture opened large), `camera` //! (the settings' camera preview); settings sections also `account`, -//! `profiles`, `devices`, `notifications`, `integrations`, `advanced`. +//! `profiles`, `devices`, `notifications`, `integrations`, `advanced`; +//! `studio[:]`: the Stream Studio (with `VOELIN_DEMO_UI` a demo +//! studio from synthetic sources), `studio:window` in a window of its own, +//! `studio:live` going live, `studio:record`, or a dialog: `studio:source`, +//! `studio:audio`, `studio:camera`, `studio:scene`, `studio:settings`. +//! A screenshot also saves the studio's window (`-window.png`) and +//! draws it over the main window. //! - `VOELIN_AUTOWATCH=1`: watch the first stream that shows up. //! - `VOELIN_AUTOSHARE=test-pattern`: share the test pattern (accepting //! everyone) once connected to a TeamSpeak 6 server. @@ -34,7 +40,7 @@ use std::sync::Arc; use std::time::Duration; use anyhow::Result; -use slint::ComponentHandle; +use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer}; use voelin_core::gateway::Pin; use voelin_core::stream::{StreamInfo, StreamKind}; use voelin_core::{ @@ -223,6 +229,12 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { app.refresh_pages(); }); } + "studio" => { + if arg != "window" { + nav.invoke_open_studio(); + } + with_app(|app| app.studio_dev(arg)); + } // Opened once connected (settings_page.rs). "client" => {} other => eprintln!("VOELIN_OPEN: unknown screen {other:?}"), @@ -257,6 +269,8 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { eprintln!("screenshot failed: {e}"); } let _ = ui.hide(); + // Also when the studio's own window is open. + let _ = slint::quit_event_loop(); } }, ); @@ -266,7 +280,33 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { } fn save_screenshot(ui: &MainWindow, path: &std::path::Path) -> Result<()> { - let image = ui.window().take_snapshot()?; + let mut image = ui.window().take_snapshot()?; + if let Some(studio) = with_app(|app| app.studio_snapshot()).flatten() { + let stem = path.file_stem().unwrap_or_default().to_string_lossy(); + save_png(&studio, &path.with_file_name(format!("{stem}-window.png")))?; + paste(&mut image, &studio); + } + save_png(&image, path) +} + +/// Draw `top` over the bottom right of `image` with a border, as a second +/// window sits on a desktop. +fn paste(image: &mut SharedPixelBuffer, top: &SharedPixelBuffer) { + let (w, h) = (image.width() as usize, image.height() as usize); + let (tw, th) = (top.width() as usize, top.height() as usize); + let (x0, y0) = (w.saturating_sub(tw + 24), h.saturating_sub(th + 24)); + let border = Rgba8Pixel { r: 0x3f, g: 0x7b, b: 0xff, a: 0xff }; + let pixels = image.make_mut_slice(); + for y in y0.saturating_sub(1)..(y0 + th + 1).min(h) { + for x in x0.saturating_sub(1)..(x0 + tw + 1).min(w) { + let (ty, tx) = (y.wrapping_sub(y0), x.wrapping_sub(x0)); + pixels[y * w + x] = + if ty < th && tx < tw { top.as_slice()[ty * tw + tx] } else { border }; + } + } +} + +fn save_png(image: &SharedPixelBuffer, path: &std::path::Path) -> Result<()> { let file = std::io::BufWriter::new(std::fs::File::create(path)?); let mut encoder = png::Encoder::new(file, image.width(), image.height()); encoder.set_color(png::ColorType::Rgba); @@ -611,14 +651,7 @@ fn demo_social(app: &mut App) { 70, ), private(311, "demo-2", false, ("Lumen", 2), "Let's run it tonight!".into(), 120), - private( - 312, - "demo-5", - false, - ("dex", 5), - format!("{}", file_link(2, "map-notes.png", 96_120)), - 26 * 60, - ), + private(312, "demo-5", false, ("dex", 5), file_link(2, "map-notes.png", 96_120), 26 * 60), ]; for m in lines { let target = m.message.target.clone(); @@ -937,7 +970,7 @@ fn demo_picture(width: u32, height: u32, seed: u32) -> Vec { let castle = (fx > w * 0.36 && fx < w * 0.52 && fy > h * 0.38 - && (((fx - w * 0.36) / (w * 0.02)) as u32 % 2 == 0 || fy > h * 0.45)) + && ((((fx - w * 0.36) / (w * 0.02)) as u32).is_multiple_of(2) || fy > h * 0.45)) || (fx > w * 0.42 && fx < w * 0.46 && fy > h * 0.24); if fy > near { c = [6.0, 10.0, 26.0]; diff --git a/crates/voelin-ui/src/lib.rs b/crates/voelin-ui/src/lib.rs index f51de29..980b7d1 100644 --- a/crates/voelin-ui/src/lib.rs +++ b/crates/voelin-ui/src/lib.rs @@ -20,6 +20,7 @@ mod settings_page; mod settings_pages; mod social; mod streams; +mod studio; mod video; mod vm; diff --git a/crates/voelin-ui/src/streams.rs b/crates/voelin-ui/src/streams.rs index 1941fee..013e608 100644 --- a/crates/voelin-ui/src/streams.rs +++ b/crates/voelin-ui/src/streams.rs @@ -474,6 +474,11 @@ impl App { if self.share_busy || self.share.is_some() { return; } + if self.studio_streams_to(session) { + self.share_error = "The Stream Studio is live here: end that stream first.".into(); + self.refresh_streams(); + return; + } // Typed values (no maximum), else the chosen presets. let choice = |i: i32, choices: &[u32]| { choices[usize::try_from(i).unwrap_or(0).min(choices.len() - 1)] diff --git a/crates/voelin-ui/src/studio.rs b/crates/voelin-ui/src/studio.rs new file mode 100644 index 0000000..c18d396 --- /dev/null +++ b/crates/voelin-ui/src/studio.rs @@ -0,0 +1,2095 @@ +//! The Stream Studio: the controller behind its page in the main window, its +//! window of its own and the phone layout (ui/screens/studio*.slint, +//! ui/studio-window.slint). +//! +//! The engine's studio (`voelin_core::studio`) composites the scenes; a +//! `Streamer` started for it encodes the composite from the start, so the +//! recording and the replay buffer need no live stream, and going live +//! attaches it to a TeamSpeak stream of our voice channel like any share. +//! The studio runs while it is shown, live or recording. +//! +//! Both windows' StudioBridge globals show the same models (shared +//! VecModels) and get the same values; their callbacks come here +//! (bind/studio.rs). Commands go to the studio through one task, in order. + +use std::path::PathBuf; +use std::rc::Rc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Weak}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use slint::{ComponentHandle, Model, ModelRc, Rgba8Pixel, SharedPixelBuffer, VecModel}; +use tokio::sync::broadcast::error::RecvError; +use tokio::sync::{broadcast, mpsc}; +use tracing::warn; +use voelin_core::media::voelin_media::capture::SourceId; +use voelin_core::media::voelin_media::handoff::Handoff; +use voelin_core::media::voelin_media::mix::SourceHandle; +use voelin_core::media::voelin_media::{VideoFrame, convert}; +use voelin_core::media::{ + AudioApps, AudioSourceSpec, Latest, Streamer, StreamerConfigUpdate, StreamerStats, audio_apps, + audio_source_specs, screen_sources, +}; +use voelin_core::settings::{ + AudioSourceKindSetting, AudioSourceSetting, Key, Kind, STREAM_AUDIO_SOURCES, + STREAM_BITRATE_KBPS, STREAM_LAYERS, STUDIO_RECORDING_DIR, STUDIO_REPLAY_MEMORY_MB, + STUDIO_REPLAY_SECONDS, STUDIO_SCENES, Settings, layer_specs, +}; +use voelin_core::stream::{EndReason, StreamSetup, ViewerInfo, ViewerState}; +use voelin_core::studio::scene::{ + Align, Background, Colour, Fit, Scene, Scenes, Source, SourceKind, Transform, +}; +use voelin_core::studio::{self, SourceChange, Stats, Status, Studio, camera}; +use voelin_core::{Command, HistoryMessage, HistorySource, StreamState}; +use voelin_model::{ChatMessage, ChatTarget}; +use voelin_store::MessageSource; + +use crate::app::{ + App, ChatLine, Nav, Page, StudioAudio, StudioBridge, StudioForm, StudioLayer, StudioNav, + StudioPick, StudioScene, StudioSettingsForm, StudioSource, StudioSourceForm, StudioStatus, + StudioViewer, StudioWindow, Tab, Theme, later, with_app, +}; +use crate::settings::parse_positive; +use crate::video::CaptureRequest; +use crate::vm; +use crate::vm::studio::{OVERLAY_CHAT, OVERLAY_NOW_PLAYING, OVERLAY_VIEWERS, Overlay}; + +type Picture = SharedPixelBuffer; + +/// The stream settings panel and the studio's own choices. +pub static STUDIO_UI: Key = Key::new( + "studio.ui", + Kind::Json, + "Stream Studio: title, game, go-live message, overlays, stream audio, preview size.", + StudioUi::default, +); + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct StudioUi { + pub title: String, + /// Game or category: goes into the stream's name after the title. + pub game: String, + /// Sent to the channel's chat when the stream goes live. + pub message: String, + /// Overlay sources kept in the live scene (`vm::studio::apply_overlays`). + pub show_viewers: bool, + pub show_chat: bool, + pub show_now_playing: bool, + /// The stream's audio (the mixer's sources); off: none. + pub audio: bool, + /// The preview's width in pixels (its height follows the output) and + /// frame rate. + pub preview_width: u32, + pub preview_fps: u32, +} + +impl Default for StudioUi { + fn default() -> Self { + Self { + title: String::new(), + game: String::new(), + message: String::new(), + show_viewers: false, + show_chat: false, + show_now_playing: false, + audio: true, + preview_width: 960, + preview_fps: 15, + } + } +} + +/// The models both windows show. +#[derive(Default)] +struct Models { + scenes: Rc>, + sources: Rc>, + audio: Rc>, + layers: Rc>, + viewers: Rc>, + destinations: Rc>, + picks: Rc>, + /// The destination channel's chat (`studio_sync_chat`). + chat: Rc>, +} + +/// What a picker row adds. +enum Pick { + Source { name: String, kind: SourceKind }, + Audio(AudioSourceSetting), +} + +/// Our stream from the studio. +struct Outgoing { + session: i64, + live: bool, + viewers: Vec, +} + +/// A change of the scene graph, applied in order by one task. +enum Op { + Apply(studio::Command), + /// A source for the live scene (a new scene if there is none). + Add(Source), + /// Keep the overlay sources as asked. + Overlays(Vec), +} + +/// A running studio. +struct Running { + studio: Arc, + /// Encodes the composite; `None` until it started (or if it failed). + streamer: Option, + ops: mpsc::UnboundedSender, + /// The newest preview picture, for the UI thread. + pictures: Arc>, + /// Stops the preview thread. + stop: Arc, + tasks: Vec>, + /// The mixer's meters, about 15 times a second. + _meters: slint::Timer, +} + +impl Drop for Running { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + for task in &self.tasks { + task.abort(); + } + } +} + +/// The studio's state on the UI thread (`App::studio`). +#[derive(Default)] +pub(crate) struct StudioState { + models: Models, + /// The main window's globals have the models. + attached: bool, + /// The studio in a window of its own. + window: Option, + run: Option, + starting: bool, + /// Why it does not run or cannot stream. + error: String, + /// Where it keeps its keys: the app's settings, or with VOELIN_DEMO_UI + /// its own in memory (nothing stored). + settings: Option, + scenes: Arc, + status: Status, + stats: Option>, + encoder: Option, + ui: StudioUi, + destination: Option, + stream: Option, + picks: Vec, + /// Applications that play audio, for the audio picker. + apps: Option, + /// The mixer source of each audio row. + meters: Vec>, + /// The overlays last asked for. + overlays: Vec, + has_preview: bool, + /// Stats ticks it was not shown; it stops after a few. + hidden: u32, + /// Development switches waiting for the studio (dev.rs). + dev: Vec, +} + +/// Forward the studio's events to the UI thread. +async fn forward_events(mut events: broadcast::Receiver) { + loop { + match events.recv().await { + Ok(event) => later(move |app| app.studio_event(event)), + Err(RecvError::Lagged(_)) => {} + Err(RecvError::Closed) => break, + } + } +} + +/// Apply the ops one after the other. +async fn run_ops(studio: Weak, mut ops: mpsc::UnboundedReceiver) { + while let Some(op) = ops.recv().await { + let Some(studio) = studio.upgrade() else { break }; + let result = match op { + Op::Apply(command) => studio.apply(command).await, + Op::Add(mut source) => { + let mut scenes = studio.scenes(); + if scenes.active().is_none() { + let id = scenes.next_scene_id(); + scenes.scenes.push(Scene::new(id, "Scene 1")); + scenes.active = id; + } + if let Some(scene) = scenes.active_mut() { + source.id = scene.next_source_id(); + scene.sources.push(source); + } + studio.apply(studio::Command::SetScenes(Box::new(scenes))).await + } + Op::Overlays(wanted) => { + let mut scenes = studio.scenes(); + if vm::studio::apply_overlays(&mut scenes, &wanted) { + studio.apply(studio::Command::SetScenes(Box::new(scenes))).await + } else { + Ok(()) + } + } + }; + if let Err(e) = result { + later(move |app| app.set_status(format!("Stream Studio: {e}"))); + } + } +} + +/// Tell the UI thread when a key the studio follows changes elsewhere. +async fn watch_settings(settings: Settings) { + let mut audio = settings.watch(&STREAM_AUDIO_SOURCES); + let mut layers = settings.watch(&STREAM_LAYERS); + let mut bitrate = settings.watch(&STREAM_BITRATE_KBPS); + let mut ui = settings.watch(&STUDIO_UI); + loop { + tokio::select! { + Some(_) = audio.changed() => later(|app| app.studio_audio_changed()), + Some(_) = layers.changed() => later(|app| app.studio_encoding_changed()), + Some(_) = bitrate.changed() => later(|app| app.studio_encoding_changed()), + Some(_) = ui.changed() => later(|app| app.studio_ui_changed()), + else => break, + } + } +} + +/// Turn preview frames into pictures on a thread of its own; the UI thread +/// takes the newest when it gets to it. +fn spawn_preview( + handoff: Arc>, + pictures: Arc>, + stop: Arc, +) { + let spawned = + std::thread::Builder::new().name("voelin-studio-preview".into()).spawn(move || { + while !stop.load(Ordering::Relaxed) && !handoff.is_closed() { + let Some(frame) = handoff.wait_timeout(Duration::from_millis(250)) else { + continue; + }; + let mut picture = Picture::new(frame.width, frame.height); + let stride = frame.width as usize * 4; + if let Err(e) = convert::to_rgba(&frame, picture.make_mut_bytes(), stride) { + warn!("studio preview: {e}"); + continue; + } + if pictures.put(picture) { + later(|app| app.studio_picture()); + } + } + }); + if let Err(e) = spawned { + warn!("cannot show the studio's preview: {e}"); + } +} + +/// The demo studio of VOELIN_DEMO_UI: sample scenes from synthetic sources, +/// test tones, recordings in a temporary folder; in memory only. +fn demo_settings() -> Settings { + let settings = Settings::in_memory(); + let text = |text: &str, size_px: f32| SourceKind::Text { + text: text.into(), + font: None, + size_px, + colour: Colour::WHITE, + backdrop: Colour::CLEAR, + align: Align::Center, + padding: 0, + }; + let source = |id: u64, name: &str, kind: SourceKind, transform: Transform| Source { + name: name.into(), + transform, + ..Source::new(id, kind) + }; + let slate = |id: u64, name: &str, words: &str| { + let mut scene = Scene::new(id, name); + scene.sources = vec![ + source( + 1, + "Backdrop", + SourceKind::Colour { colour: Colour::rgb(16, 26, 60), size: (1920, 1080) }, + Transform::full(1920, 1080), + ), + source(2, "Title", text(words, 120.0), Transform::box_at(160.0, 440.0, 1600.0, 200.0)), + ]; + scene + }; + let camera = SourceKind::Camera { + device: camera::SYNTHETIC.into(), + size: None, + fps: None, + mirror: false, + }; + let mut main = Scene::new(1, "Main Stream"); + let mut cam = source(2, "Camera", camera.clone(), Transform::default()); + cam.transform = vm::studio::placement(&camera, (1920, 1080)); + cam.background = Background::Blur { strength: 0.04 }; + main.sources = vec![ + source( + 1, + "Game Capture", + SourceKind::Pattern { size: (1280, 720) }, + Transform { fit: Fit::Cover, ..Transform::full(1920, 1080) }, + ), + cam, + ]; + let mut chatting = Scene::new(2, "Just Chatting"); + chatting.sources = vec![source( + 1, + "Camera", + camera, + Transform { fit: Fit::Cover, ..Transform::full(1920, 1080) }, + )]; + let scenes = Scenes { + scenes: vec![ + main, + chatting, + slate(3, "Be Right Back", "Be right back"), + slate(4, "Starting Soon", "Starting soon"), + slate(5, "Ending", "Thanks for watching"), + ], + active: 1, + width: 1920, + height: 1080, + fps: 60, + }; + let tone = |frequency, gain| AudioSourceSetting { + gain, + ..AudioSourceSetting::new(AudioSourceKindSetting::Synthetic { frequency }) + }; + let recordings = std::env::temp_dir().join("voelin-demo-recordings"); + let results = [ + settings.set(&STUDIO_SCENES, scenes), + settings.set( + &STREAM_AUDIO_SOURCES, + vec![ + AudioSourceSetting { + gain: 0.49, + ..AudioSourceSetting::new(AudioSourceKindSetting::Microphone) + }, + tone(440, 0.25), + tone(660, 0.39), + ], + ), + settings.set(&STUDIO_RECORDING_DIR, recordings.display().to_string()), + settings.set( + &STUDIO_UI, + StudioUi { + title: "Exploring the Lands Between".into(), + game: "Adventure".into(), + message: "Going live in Chill Zone — exploring the Lands Between. Come hang!" + .into(), + show_viewers: true, + show_now_playing: true, + ..StudioUi::default() + }, + ), + ]; + for result in results { + if let Err(e) = result { + warn!("demo studio: {e}"); + } + } + settings +} + +/// The overlay text of what is on: the title and the game. +fn now_playing(ui: &StudioUi) -> Option { + let lines: Vec<&str> = + [ui.title.trim(), ui.game.trim()].into_iter().filter(|s| !s.is_empty()).collect(); + (!lines.is_empty()).then(|| lines.join("\n")) +} + +/// The stream's name: the title, and the game after it. TeamSpeak streams +/// have a name only, and the gateway's directory takes it from there. +pub fn stream_name(ui: &StudioUi) -> String { + match (ui.title.trim(), ui.game.trim()) { + (title, "") => title.to_owned(), + ("", game) => game.to_owned(), + (title, game) => format!("{title} — {game}"), + } +} + +fn file_name(what: &str) -> String { + format!("{what} {}.mkv", chrono::Local::now().format("%Y-%m-%d %H-%M-%S")) +} + +impl App { + /// The studio's settings (made once). + fn studio_settings(&mut self) -> Settings { + let demo = self.demo_ui; + let prefs = &self.prefs; + self.studio + .settings + .get_or_insert_with(|| if demo { demo_settings() } else { prefs.clone() }) + .clone() + } + + fn studio_streamer(&self) -> Option<&Streamer> { + self.studio.run.as_ref()?.streamer.as_ref() + } + + fn studio_op(&self, op: Op) { + if let Some(run) = &self.studio.run { + let _ = run.ops.send(op); + } + } + + /// `f` on the StudioBridge of the main window and of the studio window. + fn studio_each(&self, f: impl Fn(&StudioBridge)) { + if let Some(ui) = self.ui.upgrade() { + f(&ui.global::()); + } + if let Some(window) = &self.studio.window { + f(&window.global::()); + } + } + + /// The StudioNav of the window the studio is in. + fn studio_nav(&self, f: impl FnOnce(&StudioNav)) { + match (&self.studio.window, self.ui.upgrade()) { + (Some(window), _) => f(&window.global::()), + (None, Some(ui)) => f(&ui.global::()), + _ => {} + } + } + + fn studio_attach(&self, bridge: &StudioBridge) { + let m = &self.studio.models; + bridge.set_scenes(ModelRc::from(m.scenes.clone())); + bridge.set_sources(ModelRc::from(m.sources.clone())); + bridge.set_audio(ModelRc::from(m.audio.clone())); + bridge.set_layers(ModelRc::from(m.layers.clone())); + bridge.set_viewers(ModelRc::from(m.viewers.clone())); + bridge.set_destinations(ModelRc::from(m.destinations.clone())); + bridge.set_picks(ModelRc::from(m.picks.clone())); + bridge.set_chat(ModelRc::from(m.chat.clone())); + } + + /// Whether a studio page or window is on screen. + fn studio_shown(&self) -> bool { + self.studio.window.is_some() + || self.ui.upgrade().is_some_and(|ui| ui.global::