M8 (part 1): tsc-media screen and system-audio capture

- ScreenCapture / AudioCapture traits (async start for the portal),
  SourceId / CaptureSource / CaptureOptions, platform default backends
- Synthetic sources: animated test pattern (moving rectangle + frame
  counter) and a sine tone, for tests and synthetic streams
- X11 (feature x11): x11rb with MIT-SHM over a memfd (GetImage fallback),
  RandR 1.5 monitors, window listing (_NET_CLIENT_LIST or root children),
  XFixes cursor blending
- Wayland (feature pipewire): ScreenCast portal via ashpd with restore
  tokens (PersistMode::ExplicitlyRevoked) and a PipeWire video stream
  (SHM BGRx/RGBx family); clear "unavailable" errors without bus/portal
- PipeWire system audio from the default sink monitor
  (stream.capture.sink), 48 kHz stereo f32
- Windows: Windows Graphics Capture (windows-capture) and WASAPI process
  loopback excluding our own process tree, falling back to plain loopback
  (type-checked for x86_64-pc-windows-gnu, not run)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-26 04:56:02 +00:00
1 parent cc4cb52011
commit 9b21f68cfb
10 files changed
+2073 -1

No files matched your search

+1 -1
View File
@@ -9,7 +9,7 @@ repository.workspace = true
publish.workspace = true
[features]
default = ["vpx", "openh264", "openh264-download"]
default = ["vpx", "openh264", "openh264-download", "x11", "pipewire"]
# VP8 and VP9 through the system libvpx (pkg-config `vpx`).
vpx = ["dep:libvpx-native-sys"]
# H.264 through Cisco's prebuilt OpenH264 library, loaded at runtime. The
+225
View File
@@ -0,0 +1,225 @@
//! Screen and system-audio capture.
//!
//! Backends deliver frames on a [`FrameReceiver`] from their own thread; the
//! queue drops the oldest frame when the consumer falls behind.
//!
//! | Backend | Screen | System audio |
//! |---|---|---|
//! | [`synthetic`] | test pattern | sine tone |
//! | `x11` (Linux, feature `x11`) | MIT-SHM / GetImage, XFixes cursor | |
//! | `portal` / `pipewire_audio` (Linux, feature `pipewire`) | ScreenCast portal + PipeWire | default sink monitor |
//! | `windows` | Windows Graphics Capture | WASAPI process loopback |
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use crate::frame::{AudioBuffer, VideoFrame};
use crate::queue::FrameReceiver;
use crate::{Error, Result};
#[cfg(all(target_os = "linux", feature = "pipewire"))]
pub mod pipewire_audio;
#[cfg(all(target_os = "linux", feature = "pipewire"))]
pub mod portal;
#[cfg(all(target_os = "linux", feature = "pipewire"))]
mod pw;
pub mod synthetic;
#[cfg(windows)]
pub mod windows;
#[cfg(all(target_os = "linux", feature = "x11"))]
pub mod x11;
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
/// What to capture.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum SourceId {
/// A monitor, by the backend's index (see [`ScreenCapture::sources`]).
Monitor(u32),
/// A top-level window by native handle (X11 window id, Windows `HWND`).
Window(u64),
/// Whatever the user picks in the desktop portal's dialog.
Portal,
/// The synthetic test pattern.
Synthetic,
}
/// A source as shown in a picker.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CaptureSource {
pub id: SourceId,
pub name: String,
/// Current size; 0 if unknown (portal).
pub width: u32,
pub height: u32,
/// The primary monitor.
pub primary: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CaptureOptions {
/// Maximum frame rate.
pub fps: u32,
/// Draw the mouse cursor into the frames.
pub cursor: bool,
/// Frames queued before the oldest is dropped.
pub queue: usize,
}
impl Default for CaptureOptions {
fn default() -> Self {
Self { fps: 30, cursor: true, queue: 2 }
}
}
/// A screen / window capture backend.
pub trait ScreenCapture: Send {
/// Short name for logs (`"x11"`, `"portal"`, ...).
fn backend(&self) -> &'static str;
/// Monitors and windows that can be captured. The portal backend
/// returns a single [`SourceId::Portal`] entry: its dialog picks.
fn sources(&mut self) -> Result<Vec<CaptureSource>>;
/// Start capturing (stopping a previous capture). Async because the
/// portal asks the user. Frames stop when [`ScreenCapture::stop`] is
/// called, the backend is dropped, or the receiver is dropped.
fn start(
&mut self,
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>>;
fn stop(&mut self);
}
/// A system-audio capture backend: 48 kHz stereo `f32` buffers.
pub trait AudioCapture: Send {
fn backend(&self) -> &'static str;
fn start(&mut self) -> Result<FrameReceiver<AudioBuffer>>;
fn stop(&mut self);
}
/// The screen capture backend for this session: the ScreenCast portal on
/// Wayland, X11 otherwise on Linux, Windows Graphics Capture on Windows.
pub fn default_screen_capture() -> Result<Box<dyn ScreenCapture>> {
#[cfg(target_os = "linux")]
{
let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|t| t == "wayland");
#[cfg(feature = "pipewire")]
if wayland {
return Ok(Box::new(portal::PortalCapture::new()));
}
#[cfg(feature = "x11")]
if std::env::var_os("DISPLAY").is_some() {
return Ok(Box::new(x11::X11Capture::new()));
}
let _ = wayland;
}
#[cfg(windows)]
return Ok(Box::new(windows::WindowsCapture::new()));
#[allow(unreachable_code)]
Err(Error::CaptureUnavailable {
backend: "screen",
reason: "no screen capture backend for this session in this build".into(),
})
}
/// The system-audio backend: PipeWire on Linux, WASAPI loopback on Windows.
pub fn default_audio_capture() -> Result<Box<dyn AudioCapture>> {
#[cfg(all(target_os = "linux", feature = "pipewire"))]
return Ok(Box::new(pipewire_audio::PipeWireAudioCapture::new()));
#[cfg(windows)]
return Ok(Box::new(windows::WasapiLoopback::new()));
#[allow(unreachable_code)]
Err(Error::CaptureUnavailable {
backend: "audio",
reason: "no system audio capture backend in this build".into(),
})
}
/// A capture thread that is stopped and joined on drop.
pub(crate) struct Worker {
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
}
impl Worker {
/// Run `f` on a named thread; it should return once the flag is set.
pub fn spawn(name: &str, f: impl FnOnce(Arc<AtomicBool>) + Send + 'static) -> Result<Self> {
let stop = Arc::new(AtomicBool::new(false));
let flag = stop.clone();
let thread = std::thread::Builder::new().name(name.to_owned()).spawn(move || f(flag))?;
Ok(Self { stop, thread: Some(thread) })
}
pub fn stop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(thread) = self.thread.take() {
thread.thread().unpark();
let _ = thread.join();
}
}
}
impl Drop for Worker {
fn drop(&mut self) {
self.stop();
}
}
/// Paces a capture loop at a fixed rate.
pub(crate) struct Ticker {
interval: Duration,
next: Instant,
}
impl Ticker {
pub fn new(fps: u32) -> Self {
Self { interval: Duration::from_secs(1) / fps.max(1), next: Instant::now() }
}
/// Sleep until the next tick. Returns `false` if `stop` got set.
pub fn wait(&mut self, stop: &AtomicBool) -> bool {
self.next += self.interval;
let now = Instant::now();
if self.next < now {
// Fell behind: skip ticks instead of bursting.
self.next = now;
}
while !stop.load(Ordering::Relaxed) {
let now = Instant::now();
if now >= self.next {
return true;
}
// Woken early by `Worker::stop`.
std::thread::park_timeout(self.next - now);
}
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn worker_stops_promptly() {
let started = Instant::now();
let mut worker = Worker::spawn("test", |stop| {
let mut ticker = Ticker::new(1);
while ticker.wait(&stop) {}
})
.unwrap();
std::thread::sleep(Duration::from_millis(20));
worker.stop();
assert!(started.elapsed() < Duration::from_millis(900));
}
}
@@ -0,0 +1,178 @@
//! System audio on Linux: a PipeWire capture stream on the monitor of the
//! default sink (`stream.capture.sink = true`), converted by PipeWire to
//! 48 kHz stereo `f32`.
//!
//! The monitor carries everything the sink plays, including this app's own
//! playback (TeamSpeak voices). PipeWire has no "all but this process"
//! monitor; excluding our nodes would need a private null sink with links from
//! every other application's output node (tracked through the registry).
//! TODO; until then, the engine should play voices to a different sink or
//! accept that viewers hear them.
use std::time::Instant;
use pipewire as pw;
use pw::spa::param::audio::{AudioFormat, AudioInfoRaw};
use pw::spa::pod::{Object, Value};
use pw::spa::utils::SpaTypes;
use tracing::warn;
use crate::capture::AudioCapture;
use crate::capture::pw::{PwThread, pod, serialize};
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer};
use crate::queue::{FrameReceiver, FrameSender, frame_channel};
use crate::{Error, Result};
const BACKEND: &str = "pipewire";
/// Name of our capture node in PipeWire.
pub const NODE_NAME: &str = "tsc-system-audio";
/// Captures the default sink's monitor through PipeWire.
#[derive(Default)]
pub struct PipeWireAudioCapture {
thread: Option<PwThread>,
}
impl PipeWireAudioCapture {
pub fn new() -> Self {
Self::default()
}
}
impl AudioCapture for PipeWireAudioCapture {
fn backend(&self) -> &'static str {
BACKEND
}
fn start(&mut self) -> Result<FrameReceiver<AudioBuffer>> {
self.stop();
// Half a second at PipeWire's usual 10-20 ms quantum.
let (tx, rx) = frame_channel(50);
let thread = PwThread::spawn("tsc-pipewire-audio", None, move |core, mainloop| {
audio_stream(core, mainloop, tx)
})
.map_err(|reason| Error::CaptureUnavailable { backend: BACKEND, reason })?;
self.thread = Some(thread);
Ok(rx)
}
fn stop(&mut self) {
self.thread = None;
}
}
struct AudioState {
tx: FrameSender<AudioBuffer>,
channels: u16,
started: Instant,
mainloop: pw::main_loop::MainLoopWeak,
}
fn audio_stream(
core: &pw::core::CoreRc,
mainloop: &pw::main_loop::MainLoopRc,
tx: FrameSender<AudioBuffer>,
) -> std::result::Result<(pw::stream::StreamRc, pw::stream::StreamListener<AudioState>), String> {
let props = pw::properties::properties! {
*pw::keys::MEDIA_TYPE => "Audio",
*pw::keys::MEDIA_CATEGORY => "Capture",
*pw::keys::MEDIA_ROLE => "Music",
*pw::keys::STREAM_CAPTURE_SINK => "true",
*pw::keys::NODE_NAME => NODE_NAME,
*pw::keys::NODE_DESCRIPTION => "TeamSpeak stream system audio",
};
let stream = pw::stream::StreamRc::new(core.clone(), NODE_NAME, props)
.map_err(|e| format!("PipeWire stream: {e}"))?;
let state =
AudioState { tx, channels: 2, started: Instant::now(), mainloop: mainloop.downgrade() };
let listener = stream
.add_local_listener_with_user_data(state)
.state_changed(|_, state, _, new| {
if let pw::stream::StreamState::Error(e) = &new {
warn!("system audio stream failed: {e}");
if let Some(mainloop) = state.mainloop.upgrade() {
mainloop.quit();
}
}
})
.param_changed(|_, state, id, param| {
let Some(param) = param else { return };
if id != pw::spa::param::ParamType::Format.as_raw() {
return;
}
let mut info = AudioInfoRaw::new();
if info.parse(param).is_ok() && info.channels() > 0 {
state.channels = info.channels() as u16;
}
})
.process(|stream, state| {
let Some(mut buffer) = stream.dequeue_buffer() else { return };
let Some(data) = buffer.datas_mut().first_mut() else { return };
let chunk = data.chunk();
let (offset, size) = (chunk.offset() as usize, chunk.size() as usize);
let Some(bytes) = data.data() else { return };
let Some(bytes) = bytes.get(offset..offset + size) else { return };
let samples: Vec<f32> = bytes
.chunks_exact(4)
.map(|b| f32::from_le_bytes(b.try_into().expect("4 bytes")))
.collect();
if samples.is_empty() {
return;
}
let buffer = AudioBuffer {
samples,
channels: state.channels,
timestamp: state.started.elapsed(),
};
if !state.tx.send(buffer)
&& let Some(mainloop) = state.mainloop.upgrade()
{
mainloop.quit();
}
})
.register()
.map_err(|e| format!("PipeWire listener: {e}"))?;
let mut info = AudioInfoRaw::new();
info.set_format(AudioFormat::F32LE);
info.set_rate(AUDIO_SAMPLE_RATE);
info.set_channels(2);
let format = serialize(Value::Object(Object {
type_: SpaTypes::ObjectParamFormat.as_raw(),
id: pw::spa::param::ParamType::EnumFormat.as_raw(),
properties: info.into(),
}))?;
stream
.connect(
pw::spa::utils::Direction::Input,
None,
pw::stream::StreamFlags::AUTOCONNECT
| pw::stream::StreamFlags::MAP_BUFFERS
| pw::stream::StreamFlags::RT_PROCESS,
&mut [pod(&format)?],
)
.map_err(|e| format!("cannot connect the system audio stream: {e}"))?;
Ok((stream, listener))
}
#[cfg(test)]
mod tests {
use super::*;
/// Without a PipeWire daemon, start fails with a clear error instead of
/// hanging. Skipped where a daemon socket exists.
#[test]
fn unavailable_without_daemon() {
let socket = std::env::var_os("XDG_RUNTIME_DIR")
.is_some_and(|d| std::path::Path::new(&d).join("pipewire-0").exists());
if socket || std::env::var_os("PIPEWIRE_REMOTE").is_some() {
eprintln!("skipped: a PipeWire daemon is running");
return;
}
let mut capture = PipeWireAudioCapture::new();
let err = capture.start().err().expect("no daemon");
assert!(matches!(err, Error::CaptureUnavailable { backend: "pipewire", .. }), "{err}");
assert!(err.to_string().contains("PipeWire"), "{err}");
}
}
+380
View File
@@ -0,0 +1,380 @@
//! Wayland screen capture: the xdg-desktop-portal ScreenCast interface
//! (`ashpd`) picks the source and hands over a PipeWire remote; frames come
//! through a PipeWire video stream.
//!
//! The portal can remember the user's choice: pass the token from
//! [`PortalCapture::restore_token`] to [`PortalCapture::with_restore_token`]
//! next time (it persists until the user revokes it). Only shared-memory
//! buffers (`BGRx` / `RGBx` family) are negotiated; DMA-BUF import is a TODO.
use std::time::{Duration, Instant};
use ashpd::desktop::PersistMode;
use ashpd::desktop::screencast::{CursorMode, Screencast, SelectSourcesOptions, SourceType};
use pipewire as pw;
use pw::spa::param::format::{FormatProperties, MediaSubtype, MediaType};
use pw::spa::param::video::{VideoFormat, VideoInfoRaw};
use pw::spa::pod::{Value, object, property};
use pw::spa::utils::{Fraction, Rectangle, SpaTypes};
use tracing::{debug, warn};
use crate::capture::pw::{PwThread, pod, serialize};
use crate::capture::{BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId};
use crate::frame::VideoFrame;
use crate::queue::{FrameReceiver, FrameSender, frame_channel};
use crate::{Error, Result};
const BACKEND: &str = "portal";
fn portal_error(e: ashpd::Error) -> Error {
match e {
ashpd::Error::Response(ashpd::desktop::ResponseError::Cancelled)
| ashpd::Error::Portal(ashpd::PortalError::Cancelled(_)) => Error::Cancelled,
// No bus, no portal service, or no ScreenCast interface.
ashpd::Error::Zbus(_)
| ashpd::Error::Portal(ashpd::PortalError::ZBus(_))
| ashpd::Error::PortalNotFound(_) => Error::CaptureUnavailable {
backend: BACKEND,
reason: format!("the ScreenCast portal is not available: {e}"),
},
other => Error::Capture { backend: BACKEND, message: other.to_string() },
}
}
/// A portal session kept open while capturing.
struct Session {
proxy: Screencast,
session: ashpd::desktop::Session<Screencast>,
}
/// ScreenCast portal + PipeWire backend (Wayland, also works on X11 desktops
/// that run xdg-desktop-portal).
#[derive(Default)]
pub struct PortalCapture {
restore_token: Option<String>,
session: Option<Session>,
thread: Option<PwThread>,
}
impl PortalCapture {
pub fn new() -> Self {
Self::default()
}
/// Reuse an earlier choice without asking (a token from
/// [`PortalCapture::restore_token`]).
pub fn with_restore_token(token: Option<String>) -> Self {
Self { restore_token: token, session: None, thread: None }
}
/// Token to persist after a successful start; `None` before that or if
/// the portal did not grant persistence.
pub fn restore_token(&self) -> Option<&str> {
self.restore_token.as_deref()
}
/// Whether the ScreenCast portal answers on the session bus.
pub async fn is_available() -> bool {
match Screencast::new().await {
// Reading a property needs the service to exist.
Ok(proxy) => proxy.available_source_types().await.is_ok(),
Err(_) => false,
}
}
async fn open(&mut self, options: &CaptureOptions) -> Result<(std::os::fd::OwnedFd, u32)> {
let proxy = Screencast::new().await.map_err(portal_error)?;
let session = proxy.create_session(Default::default()).await.map_err(portal_error)?;
let modes = proxy.available_cursor_modes().await.unwrap_or_default();
let cursor = if !options.cursor {
CursorMode::Hidden
} else if modes.contains(CursorMode::Embedded) {
CursorMode::Embedded
} else {
// Metadata cursors would need drawing; fall back to none.
CursorMode::Hidden
};
let select = SelectSourcesOptions::default()
.set_cursor_mode(cursor)
.set_sources(SourceType::Monitor | SourceType::Window)
.set_multiple(false)
.set_restore_token(self.restore_token.as_deref())
.set_persist_mode(PersistMode::ExplicitlyRevoked);
proxy
.select_sources(&session, select)
.await
.map_err(portal_error)?
.response()
.map_err(portal_error)?;
let streams = proxy
.start(&session, None, Default::default())
.await
.map_err(portal_error)?
.response()
.map_err(portal_error)?;
if let Some(token) = streams.restore_token() {
self.restore_token = Some(token.to_owned());
}
let stream = streams.streams().first().ok_or(Error::Cancelled)?;
let node = stream.pipe_wire_node_id();
debug!(node, size = ?stream.size(), "portal stream started");
let fd = proxy
.open_pipe_wire_remote(&session, Default::default())
.await
.map_err(portal_error)?;
self.session = Some(Session { proxy, session });
Ok((fd, node))
}
}
impl ScreenCapture for PortalCapture {
fn backend(&self) -> &'static str {
BACKEND
}
fn sources(&mut self) -> Result<Vec<CaptureSource>> {
Ok(vec![CaptureSource {
id: SourceId::Portal,
name: "Choose a screen or window".into(),
width: 0,
height: 0,
primary: true,
}])
}
/// Asks the user through the portal dialog (unless a restore token
/// applies). Needs a tokio runtime (the D-Bus connection runs on it).
fn start(
&mut self,
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>> {
let source = source.clone();
let options = options.clone();
Box::pin(async move {
if source != SourceId::Portal {
return Err(Error::SourceNotFound(source));
}
self.stop();
let (fd, node) = self.open(&options).await?;
let (tx, rx) = frame_channel(options.queue);
let fps = options.fps.max(1);
let thread = PwThread::spawn("tsc-portal-capture", Some(fd), move |core, mainloop| {
video_stream(core, mainloop, node, fps, tx)
})
.map_err(|e| Error::Capture { backend: BACKEND, message: e })?;
self.thread = Some(thread);
Ok(rx)
})
}
fn stop(&mut self) {
self.thread = None;
if let Some(s) = self.session.take() {
// Closing needs the async runtime; do it in the background if there
// is one, else the portal closes the session with the connection.
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.spawn(async move {
let _ = s.session.close().await;
drop(s.proxy);
});
}
}
}
}
impl Drop for PortalCapture {
fn drop(&mut self) {
self.stop();
}
}
struct VideoState {
tx: FrameSender<VideoFrame>,
format: Option<(VideoFormat, u32, u32)>,
started: Instant,
interval: Duration,
last: Option<Instant>,
mainloop: pw::main_loop::MainLoopWeak,
}
fn video_stream(
core: &pw::core::CoreRc,
mainloop: &pw::main_loop::MainLoopRc,
node: u32,
fps: u32,
tx: FrameSender<VideoFrame>,
) -> std::result::Result<(pw::stream::StreamRc, pw::stream::StreamListener<VideoState>), String> {
let props = pw::properties::properties! {
*pw::keys::MEDIA_TYPE => "Video",
*pw::keys::MEDIA_CATEGORY => "Capture",
*pw::keys::MEDIA_ROLE => "Screen",
};
let stream = pw::stream::StreamRc::new(core.clone(), "tsc-screen-capture", props)
.map_err(|e| format!("PipeWire stream: {e}"))?;
let state = VideoState {
tx,
format: None,
started: Instant::now(),
// Accept frames slightly early so rounding does not halve the rate.
interval: Duration::from_secs(1) / fps * 9 / 10,
last: None,
mainloop: mainloop.downgrade(),
};
let listener = stream
.add_local_listener_with_user_data(state)
.state_changed(|_, state, _, new| {
if let pw::stream::StreamState::Error(e) = &new {
warn!("screen capture stream failed: {e}");
}
if matches!(
new,
pw::stream::StreamState::Error(_) | pw::stream::StreamState::Unconnected
) && let Some(mainloop) = state.mainloop.upgrade()
{
mainloop.quit();
}
})
.param_changed(|_, state, id, param| {
let Some(param) = param else { return };
if id != pw::spa::param::ParamType::Format.as_raw() {
return;
}
let Ok((MediaType::Video, MediaSubtype::Raw)) =
pw::spa::param::format_utils::parse_format(param)
else {
return;
};
let mut info = VideoInfoRaw::new();
if info.parse(param).is_ok() {
let size = info.size();
debug!(format = ?info.format(), size.width, size.height, "screen capture format");
state.format = Some((info.format(), size.width, size.height));
}
})
.process(|stream, state| {
let Some(mut buffer) = stream.dequeue_buffer() else { return };
let Some((format, width, height)) = state.format else { return };
let now = Instant::now();
if state.last.is_some_and(|last| now - last < state.interval) {
return;
}
let Some(data) = buffer.datas_mut().first_mut() else { return };
let Some(frame) = copy_frame(data, format, width, height) else { return };
state.last = Some(now);
if !state.tx.send(frame.with_timestamp(now - state.started))
&& let Some(mainloop) = state.mainloop.upgrade()
{
// Nobody receives frames anymore.
mainloop.quit();
}
})
.register()
.map_err(|e| format!("PipeWire listener: {e}"))?;
let format = serialize(Value::Object(object!(
SpaTypes::ObjectParamFormat,
pw::spa::param::ParamType::EnumFormat,
property!(FormatProperties::MediaType, Id, MediaType::Video),
property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw),
property!(
FormatProperties::VideoFormat,
Choice,
Enum,
Id,
VideoFormat::BGRx,
VideoFormat::BGRx,
VideoFormat::BGRA,
VideoFormat::RGBx,
VideoFormat::RGBA
),
property!(
FormatProperties::VideoSize,
Choice,
Range,
Rectangle,
Rectangle { width: 1920, height: 1080 },
Rectangle { width: 1, height: 1 },
Rectangle { width: 8192, height: 8192 }
),
property!(
FormatProperties::VideoFramerate,
Choice,
Range,
Fraction,
Fraction { num: fps, denom: 1 },
Fraction { num: 0, denom: 1 },
Fraction { num: fps, denom: 1 }
),
)))?;
stream
.connect(
pw::spa::utils::Direction::Input,
Some(node),
pw::stream::StreamFlags::AUTOCONNECT | pw::stream::StreamFlags::MAP_BUFFERS,
&mut [pod(&format)?],
)
.map_err(|e| format!("cannot connect to the screen cast node {node}: {e}"))?;
Ok((stream, listener))
}
/// Copy one shared-memory buffer into a frame. `None` for buffers without
/// mapped data (DMA-BUF), empty or corrupted chunks, and unknown formats.
fn copy_frame(
data: &mut pw::spa::buffer::Data,
format: VideoFormat,
width: u32,
height: u32,
) -> Option<VideoFrame> {
let bgra = match format {
VideoFormat::BGRx | VideoFormat::BGRA => true,
VideoFormat::RGBx | VideoFormat::RGBA => false,
_ => return None,
};
let chunk = data.chunk();
if chunk.size() == 0 || chunk.flags().contains(pw::spa::buffer::ChunkFlags::CORRUPTED) {
return None;
}
let offset = chunk.offset() as usize;
let row = width as usize * 4;
let stride = usize::try_from(chunk.stride()).ok().filter(|&s| s >= row).unwrap_or(row);
let bytes = data.data()?;
let bytes = bytes.get(offset..)?;
let needed = stride * (height as usize).checked_sub(1)? + row;
if bytes.len() < needed {
return None;
}
let mut pixels = Vec::with_capacity(row * height as usize);
for y in 0..height as usize {
pixels.extend_from_slice(&bytes[y * stride..y * stride + row]);
}
let frame = if bgra {
VideoFrame::from_bgra(width, height, row, pixels)
} else {
VideoFrame::from_rgba(width, height, row, pixels)
};
frame.ok()
}
#[cfg(test)]
mod tests {
use super::*;
/// Without a session bus the portal must fail cleanly, not hang or
/// panic. Skipped where a bus exists (it could open a real dialog).
#[tokio::test]
async fn unavailable_without_session_bus() {
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 mut capture = PortalCapture::new();
assert_eq!(capture.sources().unwrap()[0].id, SourceId::Portal);
let err = capture.start(&SourceId::Portal, &CaptureOptions::default()).await.err().unwrap();
assert!(matches!(err, Error::CaptureUnavailable { backend: "portal", .. }), "{err}");
assert!(!PortalCapture::is_available().await);
assert!(capture.restore_token().is_none());
}
}
+103
View File
@@ -0,0 +1,103 @@
//! Shared PipeWire plumbing: a thread running a main loop.
use std::os::fd::OwnedFd;
use std::thread::JoinHandle;
use pipewire as pw;
use pw::spa::pod::{Pod, Value, serialize::PodSerializer};
/// A thread with a PipeWire main loop; quits and joins on drop.
pub(crate) struct PwThread {
quit: pw::channel::Sender<()>,
thread: Option<JoinHandle<()>>,
}
impl PwThread {
/// Connect to PipeWire on a new thread (through `fd`, e.g. a portal
/// remote, or to the user's daemon), let `setup` create the streams, and
/// run the loop until stopped. Setup errors are returned here.
///
/// `setup` returns what must stay alive while the loop runs (streams,
/// listeners); it can stop the loop itself through the main loop.
pub fn spawn<S, K>(name: &str, fd: Option<OwnedFd>, setup: S) -> Result<Self, String>
where
S: FnOnce(&pw::core::CoreRc, &pw::main_loop::MainLoopRc) -> Result<K, String>
+ Send
+ 'static,
K: 'static,
{
let (quit, quit_rx) = pw::channel::channel::<()>();
let (init_tx, init_rx) = std::sync::mpsc::channel::<Result<(), String>>();
let thread = std::thread::Builder::new()
.name(name.to_owned())
.spawn(move || {
pw::init();
let started = (|| {
let mainloop = pw::main_loop::MainLoopRc::new(None)
.map_err(|e| format!("PipeWire main loop: {e}"))?;
let context = pw::context::ContextRc::new(&mainloop, None)
.map_err(|e| format!("PipeWire context: {e}"))?;
let core = match fd {
Some(fd) => context.connect_fd_rc(fd, None),
None => context.connect_rc(None),
}
.map_err(|e| format!("cannot connect to PipeWire: {e}"))?;
let keep = setup(&core, &mainloop)?;
Ok::<_, String>((mainloop, context, core, keep))
})();
let (mainloop, _context, _core, keep) = match started {
Ok(parts) => parts,
Err(e) => {
let _ = init_tx.send(Err(e));
return;
}
};
let weak = mainloop.downgrade();
let _quit = quit_rx.attach(mainloop.loop_(), move |()| {
if let Some(mainloop) = weak.upgrade() {
mainloop.quit();
}
});
let _ = init_tx.send(Ok(()));
mainloop.run();
drop(keep);
})
.map_err(|e| e.to_string())?;
let mut this = Self { quit, thread: Some(thread) };
match init_rx.recv() {
Ok(Ok(())) => Ok(this),
Ok(Err(e)) => {
this.stop();
Err(e)
}
Err(_) => {
this.stop();
Err("the PipeWire thread ended during setup".into())
}
}
}
pub fn stop(&mut self) {
let _ = self.quit.send(());
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
impl Drop for PwThread {
fn drop(&mut self) {
self.stop();
}
}
/// Serialize a format object for `Stream::connect`.
pub(crate) fn serialize(value: Value) -> Result<Vec<u8>, String> {
PodSerializer::serialize(std::io::Cursor::new(Vec::new()), &value)
.map(|(cursor, _)| cursor.into_inner())
.map_err(|e| format!("cannot build the PipeWire format: {e:?}"))
}
pub(crate) fn pod(bytes: &[u8]) -> Result<&Pod, String> {
Pod::from_bytes(bytes).ok_or_else(|| "invalid PipeWire format pod".to_owned())
}
+261
View File
@@ -0,0 +1,261 @@
//! Synthetic sources for tests and `--synthetic` streaming: an animated test
//! pattern (a rectangle moving over a flat background, plus a frame counter)
//! and a sine tone.
use std::time::Duration;
use crate::capture::{
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, Ticker, Worker,
};
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, VideoFrame};
use crate::queue::{FrameReceiver, frame_channel};
use crate::{Error, Result};
/// Background colour of the pattern (RGB).
pub const BACKGROUND: [u8; 3] = [24, 40, 72];
/// Colour of the moving rectangle (RGB).
pub const RECT_COLOR: [u8; 3] = [240, 90, 30];
/// Colour of the frame counter (RGB).
pub const TEXT_COLOR: [u8; 3] = [255, 255, 255];
/// 3x5 bitmaps of the digits 0-9, one row per 3 bits.
const DIGITS: [[u8; 5]; 10] = [
[7, 5, 5, 5, 7],
[2, 6, 2, 2, 7],
[7, 1, 7, 4, 7],
[7, 1, 7, 1, 7],
[5, 5, 7, 1, 1],
[7, 4, 7, 1, 7],
[7, 4, 7, 5, 7],
[7, 1, 2, 2, 2],
[7, 5, 7, 5, 7],
[7, 5, 7, 1, 7],
];
/// The test pattern as a [`ScreenCapture`] backend.
pub struct SyntheticScreen {
width: u32,
height: u32,
worker: Option<Worker>,
}
impl SyntheticScreen {
pub fn new(width: u32, height: u32) -> Self {
Self { width: width.max(16), height: height.max(16), worker: None }
}
/// The moving rectangle in frame `n`: `(x, y, width, height)`.
pub fn rect(&self, n: u64) -> (u32, u32, u32, u32) {
let (rw, rh) = ((self.width / 5).max(8), (self.height / 5).max(8));
let range = u64::from(self.width - rw);
let step = u64::from((self.width / 60).max(1));
// Back and forth across the frame.
let pos = (n * step) % (2 * range.max(1));
let x = if pos > range { 2 * range - pos } else { pos };
(x as u32, (self.height - rh) / 2, rw, rh)
}
/// Frame `n` as BGRA, stamped `n / fps` seconds.
pub fn frame(&self, n: u64, fps: u32) -> VideoFrame {
let (w, h) = (self.width as usize, self.height as usize);
let mut data = vec![0; w * h * 4];
let bgra = |c: [u8; 3]| [c[2], c[1], c[0], 255];
for px in data.chunks_exact_mut(4) {
px.copy_from_slice(&bgra(BACKGROUND));
}
let mut fill = |x0: usize, y0: usize, rw: usize, rh: usize, c: [u8; 3]| {
for y in y0..(y0 + rh).min(h) {
for x in x0..(x0 + rw).min(w) {
data[(y * w + x) * 4..][..4].copy_from_slice(&bgra(c));
}
}
};
let (rx, ry, rw, rh) = self.rect(n);
fill(rx as usize, ry as usize, rw as usize, rh as usize, RECT_COLOR);
// Frame counter in the top-left corner.
let scale = (h / 48).max(1);
for (i, digit) in n.to_string().bytes().enumerate() {
let bitmap = DIGITS[usize::from(digit - b'0')];
let x0 = scale * 2 + i * 4 * scale;
for (row, bits) in bitmap.iter().enumerate() {
for col in 0..3 {
if bits & (4 >> col) != 0 {
let (x, y) = (x0 + col * scale, scale * 2 + row * scale);
fill(x, y, scale, scale, TEXT_COLOR);
}
}
}
}
let timestamp = Duration::from_secs(n) / fps.max(1);
VideoFrame::from_bgra(self.width, self.height, w * 4, data)
.expect("pattern buffer matches its size")
.with_timestamp(timestamp)
}
}
impl ScreenCapture for SyntheticScreen {
fn backend(&self) -> &'static str {
"synthetic"
}
fn sources(&mut self) -> Result<Vec<CaptureSource>> {
Ok(vec![CaptureSource {
id: SourceId::Synthetic,
name: "Test pattern".into(),
width: self.width,
height: self.height,
primary: true,
}])
}
fn start(
&mut self,
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>> {
let source = source.clone();
let options = options.clone();
Box::pin(async move {
if source != SourceId::Synthetic {
return Err(Error::SourceNotFound(source));
}
self.stop();
let (tx, rx) = frame_channel(options.queue);
let pattern = SyntheticScreen::new(self.width, self.height);
let fps = options.fps;
self.worker = Some(Worker::spawn("tsc-synthetic-video", move |stop| {
let mut ticker = Ticker::new(fps);
let mut n = 0;
while tx.send(pattern.frame(n, fps)) && ticker.wait(&stop) {
n += 1;
}
})?);
Ok(rx)
})
}
fn stop(&mut self) {
self.worker = None;
}
}
/// A sine tone as an [`AudioCapture`] backend: 10 ms stereo buffers.
pub struct SineSource {
frequency: f32,
amplitude: f32,
worker: Option<Worker>,
}
impl SineSource {
/// Samples per channel in one buffer (10 ms).
pub const BUFFER_FRAMES: usize = AUDIO_SAMPLE_RATE as usize / 100;
pub fn new(frequency: f32, amplitude: f32) -> Self {
Self { frequency, amplitude, worker: None }
}
/// Buffer `n` of the tone (continuous across buffers).
pub fn buffer(&self, n: u64) -> AudioBuffer {
let start = n * Self::BUFFER_FRAMES as u64;
let mut samples = Vec::with_capacity(Self::BUFFER_FRAMES * 2);
for i in 0..Self::BUFFER_FRAMES as u64 {
let t = (start + i) as f64 / f64::from(AUDIO_SAMPLE_RATE);
let s = f64::from(self.amplitude)
* (2.0 * std::f64::consts::PI * f64::from(self.frequency) * t).sin();
samples.extend([s as f32; 2]);
}
AudioBuffer { samples, channels: 2, timestamp: Duration::from_millis(n * 10) }
}
}
impl AudioCapture for SineSource {
fn backend(&self) -> &'static str {
"synthetic"
}
fn start(&mut self) -> Result<FrameReceiver<AudioBuffer>> {
self.stop();
// Half a second of audio before the oldest is dropped.
let (tx, rx) = frame_channel(50);
let tone = SineSource::new(self.frequency, self.amplitude);
self.worker = Some(Worker::spawn("tsc-synthetic-audio", move |stop| {
let mut ticker = Ticker::new(100);
let mut n = 0;
while tx.send(tone.buffer(n)) && ticker.wait(&stop) {
n += 1;
}
})?);
Ok(rx)
}
fn stop(&mut self) {
self.worker = None;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::convert;
fn rgb_at(frame: &VideoFrame, x: u32, y: u32) -> [u8; 3] {
let rgba = convert::to_rgba_vec(frame).unwrap();
let i = ((y * frame.width + x) * 4) as usize;
[rgba[i], rgba[i + 1], rgba[i + 2]]
}
#[test]
fn pattern_moves_and_counts() {
let screen = SyntheticScreen::new(320, 240);
let (x0, y0, w, h) = screen.rect(0);
let (x1, ..) = screen.rect(10);
assert_ne!(x0, x1);
let frame = screen.frame(10, 30);
assert_eq!(frame.timestamp, Duration::from_secs(10) / 30);
assert_eq!(rgb_at(&frame, x1 + w / 2, y0 + h / 2), RECT_COLOR);
assert_eq!(rgb_at(&frame, 319, 239), BACKGROUND);
// The "1" of "10" lights its middle column at the top.
let scale = 240 / 48;
assert_eq!(rgb_at(&frame, (scale * 2 + scale) as u32, (scale * 2) as u32), TEXT_COLOR);
// The rectangle bounces within the frame.
for n in 0..500 {
let (x, _, w, _) = screen.rect(n);
assert!(x + w <= 320);
}
}
#[test]
fn sine_is_continuous() {
let tone = SineSource::new(1000.0, 0.5);
let a = tone.buffer(0);
let b = tone.buffer(1);
assert_eq!(a.frames(), 480);
let last = a.samples[a.samples.len() - 2];
let next = b.samples[0];
// Adjacent samples of a 1 kHz tone differ by at most 2*pi*f/rate*amp.
assert!((last - next).abs() < 0.07, "{last} -> {next}");
assert!(a.samples.iter().all(|s| s.abs() <= 0.5));
}
#[tokio::test]
async fn capture_runs_until_stopped() {
let mut screen = SyntheticScreen::new(64, 48);
let options = CaptureOptions { fps: 50, ..CaptureOptions::default() };
assert!(screen.start(&SourceId::Monitor(0), &options).await.is_err());
let mut frames = screen.start(&SourceId::Synthetic, &options).await.unwrap();
let first = frames.recv().await.unwrap();
let second = frames.recv().await.unwrap();
assert_eq!((first.width, first.height), (64, 48));
assert!(second.timestamp > first.timestamp);
screen.stop();
// The worker is gone: the channel closes after the queued frames.
while frames.recv().await.is_some() {}
let mut tone = SineSource::new(440.0, 0.25);
let mut audio = tone.start().unwrap();
let buffer = audio.recv_timeout(Duration::from_secs(2)).unwrap();
assert_eq!((buffer.channels, buffer.frames()), (2, 480));
tone.stop();
}
}
+306
View File
@@ -0,0 +1,306 @@
//! Windows capture: Windows Graphics Capture (`windows-capture`) for monitors
//! and windows, WASAPI loopback (`wasapi`) for system audio.
//!
//! System audio uses process loopback in exclude mode with our own process
//! id, so our own playback (TeamSpeak voices) is not captured (Windows 10
//! 2004 or later). Older systems fall back to plain loopback of the default
//! output device, which includes our playback.
//!
//! Type-checked on Linux (`--target x86_64-pc-windows-gnu`), not run yet.
use std::collections::VecDeque;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use tracing::warn;
use windows_capture::capture::{CaptureControl, Context, GraphicsCaptureApiHandler};
use windows_capture::frame::Frame;
use windows_capture::graphics_capture_api::InternalCaptureControl;
use windows_capture::monitor::Monitor;
use windows_capture::settings::{
ColorFormat, CursorCaptureSettings, DirtyRegionSettings, DrawBorderSettings,
GraphicsCaptureItemType, MinimumUpdateIntervalSettings, SecondaryWindowSettings, Settings,
};
use windows_capture::window::Window;
use crate::capture::{
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, Worker,
};
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, VideoFrame};
use crate::queue::{FrameReceiver, FrameSender, frame_channel};
use crate::{Error, Result};
const BACKEND: &str = "wgc";
fn failed(e: impl std::fmt::Display) -> Error {
Error::Capture { backend: BACKEND, message: e.to_string() }
}
/// Receives frames on the capture thread.
struct Handler {
tx: FrameSender<VideoFrame>,
started: Instant,
scratch: Vec<u8>,
}
impl GraphicsCaptureApiHandler for Handler {
type Flags = (FrameSender<VideoFrame>, Instant);
type Error = String;
fn new(ctx: Context<Self::Flags>) -> std::result::Result<Self, Self::Error> {
let (tx, started) = ctx.flags;
Ok(Self { tx, started, scratch: Vec::new() })
}
fn on_frame_arrived(
&mut self,
frame: &mut Frame,
control: InternalCaptureControl,
) -> std::result::Result<(), Self::Error> {
let buffer = frame.buffer().map_err(|e| e.to_string())?;
let (w, h) = (buffer.width(), buffer.height());
let pixels = buffer.as_nopadding_buffer(&mut self.scratch).to_vec();
let frame =
VideoFrame::from_bgra(w, h, w as usize * 4, pixels).map_err(|e| e.to_string())?;
if !self.tx.send(frame.with_timestamp(self.started.elapsed())) {
control.stop();
}
Ok(())
}
}
/// Windows Graphics Capture backend.
#[derive(Default)]
pub struct WindowsCapture {
control: Option<CaptureControl<Handler, String>>,
}
impl WindowsCapture {
pub fn new() -> Self {
Self::default()
}
}
fn start_item<T>(
item: T,
options: &CaptureOptions,
) -> Result<(CaptureControl<Handler, String>, FrameReceiver<VideoFrame>)>
where
T: TryInto<GraphicsCaptureItemType> + Send + 'static,
{
let (tx, rx) = frame_channel(options.queue);
let cursor = if options.cursor {
CursorCaptureSettings::WithCursor
} else {
CursorCaptureSettings::WithoutCursor
};
let settings = Settings::new(
item,
cursor,
DrawBorderSettings::WithoutBorder,
SecondaryWindowSettings::Default,
MinimumUpdateIntervalSettings::Custom(Duration::from_secs(1) / options.fps.max(1)),
DirtyRegionSettings::Default,
ColorFormat::Bgra8,
(tx, Instant::now()),
);
let control = Handler::start_free_threaded(settings).map_err(failed)?;
Ok((control, rx))
}
impl ScreenCapture for WindowsCapture {
fn backend(&self) -> &'static str {
BACKEND
}
fn sources(&mut self) -> Result<Vec<CaptureSource>> {
let primary = Monitor::primary().ok();
let mut sources = Vec::new();
for monitor in Monitor::enumerate().map_err(failed)? {
let Ok(index) = monitor.index() else { continue };
sources.push(CaptureSource {
id: SourceId::Monitor(index as u32),
name: monitor.name().or_else(|_| monitor.device_name()).unwrap_or_default(),
width: monitor.width().unwrap_or(0),
height: monitor.height().unwrap_or(0),
primary: primary == Some(monitor),
});
}
for window in Window::enumerate().map_err(failed)? {
let Ok(title) = window.title() else { continue };
if title.trim().is_empty() {
continue;
}
sources.push(CaptureSource {
id: SourceId::Window(window.as_raw_hwnd() as usize as u64),
name: title,
width: window.width().unwrap_or(0).max(0) as u32,
height: window.height().unwrap_or(0).max(0) as u32,
primary: false,
});
}
Ok(sources)
}
fn start(
&mut self,
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>> {
let source = source.clone();
let options = options.clone();
Box::pin(async move {
self.stop();
let not_found = || Error::SourceNotFound(source.clone());
let (control, rx) = match source {
SourceId::Monitor(index) => {
let monitor = Monitor::from_index(index as usize).map_err(|_| not_found())?;
start_item(monitor, &options)?
}
SourceId::Window(hwnd) => {
let window = Window::from_raw_hwnd(hwnd as usize as *mut std::ffi::c_void);
if !window.is_valid() {
return Err(not_found());
}
start_item(window, &options)?
}
_ => return Err(not_found()),
};
self.control = Some(control);
Ok(rx)
})
}
fn stop(&mut self) {
if let Some(control) = self.control.take()
&& let Err(e) = control.stop()
{
warn!("stopping Windows Graphics Capture: {e}");
}
}
}
impl Drop for WindowsCapture {
fn drop(&mut self) {
self.stop();
}
}
/// WASAPI loopback of everything except this process (see the module docs).
#[derive(Default)]
pub struct WasapiLoopback {
worker: Option<Worker>,
}
impl WasapiLoopback {
pub fn new() -> Self {
Self::default()
}
}
impl AudioCapture for WasapiLoopback {
fn backend(&self) -> &'static str {
"wasapi"
}
fn start(&mut self) -> Result<FrameReceiver<AudioBuffer>> {
self.stop();
let (tx, rx) = frame_channel(50);
let (init_tx, init_rx) = std::sync::mpsc::channel();
self.worker = Some(Worker::spawn("tsc-wasapi-loopback", move |stop| {
if let Err(e) = loopback(&tx, &stop, &init_tx) {
// After a successful start the receiver just sees the end.
let _ = init_tx.send(Err(e.clone()));
warn!("system audio capture ended: {e}");
}
})?);
match init_rx.recv() {
Ok(Ok(())) => Ok(rx),
Ok(Err(reason)) => {
self.stop();
Err(Error::CaptureUnavailable { backend: "wasapi", reason })
}
Err(_) => {
self.stop();
Err(Error::CaptureUnavailable {
backend: "wasapi",
reason: "capture thread ended".into(),
})
}
}
}
fn stop(&mut self) {
self.worker = None;
}
}
fn open_client() -> std::result::Result<wasapi::AudioClient, String> {
let format = wasapi::WaveFormat::new(
32,
32,
&wasapi::SampleType::Float,
AUDIO_SAMPLE_RATE as usize,
2,
None,
);
let mode = wasapi::StreamMode::EventsShared { autoconvert: true, buffer_duration_hns: 200_000 };
// Everything but our own process tree.
match wasapi::AudioClient::new_application_loopback_client(std::process::id(), false) {
Ok(mut client) => {
match client.initialize_client(&format, &wasapi::Direction::Capture, &mode) {
Ok(()) => return Ok(client),
Err(e) => warn!("process loopback unavailable ({e}), capturing all system audio"),
}
}
Err(e) => warn!("process loopback unavailable ({e}), capturing all system audio"),
}
let enumerator = wasapi::DeviceEnumerator::new().map_err(|e| e.to_string())?;
let device =
enumerator.get_default_device(&wasapi::Direction::Render).map_err(|e| e.to_string())?;
let mut client = device.get_iaudioclient().map_err(|e| e.to_string())?;
// Capture on a render device is loopback.
client
.initialize_client(&format, &wasapi::Direction::Capture, &mode)
.map_err(|e| e.to_string())?;
Ok(client)
}
fn loopback(
tx: &FrameSender<AudioBuffer>,
stop: &std::sync::atomic::AtomicBool,
init: &std::sync::mpsc::Sender<std::result::Result<(), String>>,
) -> std::result::Result<(), String> {
// COM for this thread; "already initialised" is fine.
let _ = wasapi::initialize_mta();
let client = open_client()?;
let event = client.set_get_eventhandle().map_err(|e| e.to_string())?;
let capture = client.get_audiocaptureclient().map_err(|e| e.to_string())?;
client.start_stream().map_err(|e| e.to_string())?;
let _ = init.send(Ok(()));
const FRAME_BYTES: usize = 2 * 4;
let chunk = AUDIO_SAMPLE_RATE as usize / 100 * FRAME_BYTES;
let started = Instant::now();
let mut queue = VecDeque::new();
while !stop.load(Ordering::Relaxed) {
// No events arrive while nothing plays.
if event.wait_for_event(100).is_err() {
continue;
}
capture.read_from_device_to_deque(&mut queue).map_err(|e| e.to_string())?;
while queue.len() >= chunk {
let bytes: Vec<u8> = queue.drain(..chunk).collect();
let samples = bytes
.chunks_exact(4)
.map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
.collect();
let buffer = AudioBuffer { samples, channels: 2, timestamp: started.elapsed() };
if !tx.send(buffer) {
stop.store(true, Ordering::Relaxed);
break;
}
}
}
client.stop_stream().map_err(|e| e.to_string())
}
+593
View File
@@ -0,0 +1,593 @@
//! X11 screen and window capture through x11rb.
//!
//! Pixels come through MIT-SHM (a memfd passed to the server, MIT-SHM 1.2)
//! or, for remote displays and old servers, plain GetImage. XFixes provides
//! the cursor image, which is blended into the frame. Supports 24/32-bit
//! TrueColor visuals (BGRx in memory).
//!
//! Window capture reads the window's own contents, clipped to the screen.
//! Without a compositor, parts covered by other windows may be stale.
mod shm;
use std::fmt::Display;
use std::os::fd::OwnedFd;
use std::time::Instant;
use memmap2::MmapMut;
use tracing::{debug, warn};
use x11rb::connection::Connection;
use x11rb::protocol::randr::ConnectionExt as _;
use x11rb::protocol::shm::ConnectionExt as _;
use x11rb::protocol::xfixes::ConnectionExt as _;
use x11rb::protocol::xproto::{
AtomEnum, ConnectionExt as _, ImageFormat, ImageOrder, MapState, Window, WindowClass,
};
use x11rb::rust_connection::RustConnection;
use crate::capture::{
BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, Ticker, Worker,
};
use crate::frame::VideoFrame;
use crate::queue::{FrameReceiver, frame_channel};
use crate::{Error, Result};
const BACKEND: &str = "x11";
fn unavailable(e: impl Display) -> Error {
Error::CaptureUnavailable { backend: BACKEND, reason: e.to_string() }
}
fn failed(e: impl Display) -> Error {
Error::Capture { backend: BACKEND, message: e.to_string() }
}
/// X11 capture backend.
pub struct X11Capture {
display: Option<String>,
use_shm: bool,
worker: Option<Worker>,
}
impl Default for X11Capture {
fn default() -> Self {
Self::new()
}
}
impl X11Capture {
/// Capture from `$DISPLAY`.
pub fn new() -> Self {
Self { display: None, use_shm: true, worker: None }
}
/// Capture from another display (e.g. `":101"`).
pub fn with_display(display: impl Into<String>) -> Self {
Self { display: Some(display.into()), ..Self::new() }
}
/// Use MIT-SHM when the server supports it (default). Off forces
/// GetImage.
pub fn use_shm(mut self, enabled: bool) -> Self {
self.use_shm = enabled;
self
}
}
impl ScreenCapture for X11Capture {
fn backend(&self) -> &'static str {
BACKEND
}
fn sources(&mut self) -> Result<Vec<CaptureSource>> {
let x = Display11::connect(self.display.as_deref())?;
let mut sources: Vec<CaptureSource> = x
.monitors()?
.into_iter()
.enumerate()
.map(|(i, m)| CaptureSource {
id: SourceId::Monitor(i as u32),
name: m.name,
width: m.rect.width.into(),
height: m.rect.height.into(),
primary: m.primary,
})
.collect();
sources.extend(x.windows()?);
Ok(sources)
}
fn start(
&mut self,
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>> {
let source = source.clone();
let options = options.clone();
Box::pin(async move {
self.stop();
let x = Display11::connect(self.display.as_deref())?;
// Fail here, not in the thread, if the source does not exist.
x.region(&source)?;
let (tx, rx) = frame_channel(options.queue);
let use_shm = self.use_shm;
self.worker = Some(Worker::spawn("tsc-x11-capture", move |stop| {
let mut grabber = Grabber::new(&x, use_shm);
let cursor = options.cursor && x.xfixes;
let started = Instant::now();
let mut ticker = Ticker::new(options.fps);
loop {
match capture(&x, &source, &mut grabber, cursor) {
Ok(frame) => {
if !tx.send(frame.with_timestamp(started.elapsed())) {
break;
}
}
Err(e) => {
// E.g. the window was closed: end the stream.
warn!("X11 capture stopped: {e}");
break;
}
}
if !ticker.wait(&stop) {
break;
}
}
})?);
Ok(rx)
})
}
fn stop(&mut self) {
self.worker = None;
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Rect {
x: i16,
y: i16,
width: u16,
height: u16,
}
struct Monitor {
name: String,
rect: Rect,
primary: bool,
}
/// Part of a drawable to read, and where it is on the root window.
struct Region {
drawable: Window,
rect: Rect,
root_x: i32,
root_y: i32,
}
struct Atoms {
net_client_list: u32,
net_wm_name: u32,
utf8_string: u32,
}
struct Display11 {
conn: RustConnection,
root: Window,
screen: Rect,
shm: bool,
xfixes: bool,
atoms: Atoms,
}
impl Display11 {
fn connect(display: Option<&str>) -> Result<Self> {
let (conn, screen_num) = RustConnection::connect(display).map_err(unavailable)?;
let setup = conn.setup();
if setup.image_byte_order != ImageOrder::LSB_FIRST {
return Err(unavailable("MSB-first X servers are not supported"));
}
let screen = &setup.roots[screen_num];
let (root, root_depth) = (screen.root, screen.root_depth);
let screen_rect =
Rect { x: 0, y: 0, width: screen.width_in_pixels, height: screen.height_in_pixels };
let bpp =
setup.pixmap_formats.iter().find(|f| f.depth == root_depth).map(|f| f.bits_per_pixel);
if bpp != Some(32) {
return Err(unavailable(format!(
"unsupported screen depth {root_depth} ({bpp:?} bits per pixel), need 24/32-bit TrueColor"
)));
}
// MIT-SHM 1.2 is needed to pass a memfd.
let shm = conn
.shm_query_version()
.ok()
.and_then(|c| c.reply().ok())
.is_some_and(|v| (v.major_version, v.minor_version) >= (1, 2));
let xfixes = conn
.xfixes_query_version(4, 0)
.ok()
.and_then(|c| c.reply().ok())
.is_some_and(|v| v.major_version >= 1);
let intern = |name: &[u8]| -> Result<u32> {
Ok(conn.intern_atom(false, name).map_err(failed)?.reply().map_err(failed)?.atom)
};
let atoms = Atoms {
net_client_list: intern(b"_NET_CLIENT_LIST")?,
net_wm_name: intern(b"_NET_WM_NAME")?,
utf8_string: intern(b"UTF8_STRING")?,
};
debug!(shm, xfixes, "connected to X11 display");
Ok(Self { conn, root, screen: screen_rect, shm, xfixes, atoms })
}
/// RandR 1.5 monitors, or the whole screen.
fn monitors(&self) -> Result<Vec<Monitor>> {
let randr = self
.conn
.randr_query_version(1, 5)
.ok()
.and_then(|c| c.reply().ok())
.is_some_and(|v| (v.major_version, v.minor_version) >= (1, 5));
let mut monitors = Vec::new();
if randr
&& let Ok(reply) =
self.conn.randr_get_monitors(self.root, true).map_err(failed)?.reply()
{
for m in reply.monitors {
let name = self
.conn
.get_atom_name(m.name)
.ok()
.and_then(|c| c.reply().ok())
.map(|r| String::from_utf8_lossy(&r.name).into_owned())
.unwrap_or_else(|| "Monitor".into());
let rect = Rect { x: m.x, y: m.y, width: m.width, height: m.height };
if let Some(rect) = clip(rect, self.screen) {
monitors.push(Monitor { name, rect, primary: m.primary });
}
}
}
if monitors.is_empty() {
monitors.push(Monitor { name: "Screen".into(), rect: self.screen, primary: true });
}
Ok(monitors)
}
fn property(&self, window: Window, property: u32, type_: u32) -> Option<Vec<u8>> {
let reply = self
.conn
.get_property(false, window, property, type_, 0, 1 << 16)
.ok()?
.reply()
.ok()?;
(reply.type_ != u32::from(AtomEnum::NONE)).then_some(reply.value)
}
fn window_name(&self, window: Window) -> Option<String> {
let name = self
.property(window, self.atoms.net_wm_name, self.atoms.utf8_string)
.or_else(|| self.property(window, AtomEnum::WM_NAME.into(), AtomEnum::STRING.into()))?;
let name = String::from_utf8_lossy(&name).trim().to_owned();
(!name.is_empty()).then_some(name)
}
/// Named top-level windows: the window manager's client list, or mapped
/// children of the root when there is no window manager.
fn windows(&self) -> Result<Vec<CaptureSource>> {
let clients: Vec<Window> =
match self.property(self.root, self.atoms.net_client_list, AtomEnum::WINDOW.into()) {
Some(v) if !v.is_empty() => {
v.chunks_exact(4).map(|c| u32::from_ne_bytes(c.try_into().unwrap())).collect()
}
_ => {
let tree =
self.conn.query_tree(self.root).map_err(failed)?.reply().map_err(failed)?;
tree.children
.into_iter()
.filter(|&w| {
self.conn
.get_window_attributes(w)
.ok()
.and_then(|c| c.reply().ok())
.is_some_and(|a| {
a.map_state == MapState::VIEWABLE
&& a.class == WindowClass::INPUT_OUTPUT
&& !a.override_redirect
})
})
.collect()
}
};
let mut windows = Vec::new();
for window in clients {
let Some(name) = self.window_name(window) else { continue };
let Ok(geometry) = self.conn.get_geometry(window).map_err(failed)?.reply() else {
continue;
};
windows.push(CaptureSource {
id: SourceId::Window(window.into()),
name,
width: geometry.width.into(),
height: geometry.height.into(),
primary: false,
});
}
Ok(windows)
}
/// What to read for `source` right now.
fn region(&self, source: &SourceId) -> Result<Region> {
match *source {
SourceId::Monitor(i) => {
let monitors = self.monitors()?;
let m = monitors.get(i as usize).ok_or(Error::SourceNotFound(source.clone()))?;
Ok(Region {
drawable: self.root,
rect: m.rect,
root_x: m.rect.x.into(),
root_y: m.rect.y.into(),
})
}
SourceId::Window(id) => {
let window =
Window::try_from(id).map_err(|_| Error::SourceNotFound(source.clone()))?;
let not_found = || Error::SourceNotFound(source.clone());
let geometry = self
.conn
.get_geometry(window)
.map_err(failed)?
.reply()
.map_err(|_| not_found())?;
let bpp = self
.conn
.setup()
.pixmap_formats
.iter()
.find(|f| f.depth == geometry.depth)
.map(|f| f.bits_per_pixel);
if bpp != Some(32) {
return Err(failed(format!(
"window depth {} is not supported",
geometry.depth
)));
}
let origin = self
.conn
.translate_coordinates(window, self.root, 0, 0)
.map_err(failed)?
.reply()
.map_err(|_| not_found())?;
let on_root = Rect {
x: origin.dst_x,
y: origin.dst_y,
width: geometry.width,
height: geometry.height,
};
// GetImage fails for parts of a window outside the screen.
let visible =
clip(on_root, self.screen).ok_or_else(|| failed("the window is off screen"))?;
Ok(Region {
drawable: window,
rect: Rect {
x: visible.x - on_root.x,
y: visible.y - on_root.y,
width: visible.width,
height: visible.height,
},
root_x: visible.x.into(),
root_y: visible.y.into(),
})
}
_ => Err(Error::SourceNotFound(source.clone())),
}
}
}
/// Intersection of two rectangles.
fn clip(a: Rect, b: Rect) -> Option<Rect> {
let x0 = i32::from(a.x).max(b.x.into());
let y0 = i32::from(a.y).max(b.y.into());
let x1 = (i32::from(a.x) + i32::from(a.width)).min(i32::from(b.x) + i32::from(b.width));
let y1 = (i32::from(a.y) + i32::from(a.height)).min(i32::from(b.y) + i32::from(b.height));
(x1 > x0 && y1 > y0).then(|| Rect {
x: x0 as i16,
y: y0 as i16,
width: (x1 - x0) as u16,
height: (y1 - y0) as u16,
})
}
struct Segment {
id: u32,
map: MmapMut,
}
/// Reads regions through MIT-SHM, falling back to GetImage.
struct Grabber {
shm: bool,
segment: Option<Segment>,
}
impl Grabber {
fn new(x: &Display11, want_shm: bool) -> Self {
Self { shm: want_shm && x.shm, segment: None }
}
/// Tightly packed BGRx pixels of the region.
fn grab(&mut self, x: &Display11, r: &Region) -> Result<Vec<u8>> {
let size = usize::from(r.rect.width) * usize::from(r.rect.height) * 4;
if self.shm {
match self.grab_shm(x, r, size) {
Ok(pixels) => return Ok(pixels),
Err(e) => {
debug!("MIT-SHM capture failed, using GetImage: {e}");
self.shm = false;
self.release(x);
}
}
}
let reply = x
.conn
.get_image(
ImageFormat::Z_PIXMAP,
r.drawable,
r.rect.x,
r.rect.y,
r.rect.width,
r.rect.height,
!0,
)
.map_err(failed)?
.reply()
.map_err(failed)?;
let mut data = reply.data;
if data.len() < size {
return Err(failed(format!("GetImage returned {} bytes, expected {size}", data.len())));
}
data.truncate(size);
Ok(data)
}
fn grab_shm(&mut self, x: &Display11, r: &Region, size: usize) -> Result<Vec<u8>> {
if self.segment.as_ref().is_none_or(|s| s.map.len() < size) {
self.release(x);
self.segment = Some(Self::attach(x, size)?);
}
let segment = self.segment.as_ref().expect("attached above");
x.conn
.shm_get_image(
r.drawable,
r.rect.x,
r.rect.y,
r.rect.width,
r.rect.height,
!0,
ImageFormat::Z_PIXMAP.into(),
segment.id,
0,
)
.map_err(failed)?
.reply()
.map_err(failed)?;
Ok(segment.map[..size].to_vec())
}
fn attach(x: &Display11, size: usize) -> Result<Segment> {
let fd = rustix::fs::memfd_create("tsc-x11-capture", rustix::fs::MemfdFlags::CLOEXEC)
.map_err(|e| failed(format!("memfd_create: {e}")))?;
let file = std::fs::File::from(fd);
file.set_len(size as u64)?;
let map = shm::map(&file)?;
let id = x.conn.generate_id().map_err(failed)?;
x.conn
.shm_attach_fd(id, OwnedFd::from(file), false)
.map_err(failed)?
.check()
.map_err(failed)?;
Ok(Segment { id, map })
}
fn release(&mut self, x: &Display11) {
if let Some(segment) = self.segment.take() {
let _ = x.conn.shm_detach(segment.id);
let _ = x.conn.flush();
}
}
}
/// A cursor image: premultiplied ARGB, top-left corner in frame coordinates.
struct Cursor<'a> {
left: i32,
top: i32,
width: usize,
height: usize,
argb: &'a [u32],
}
/// Blend a premultiplied ARGB cursor onto packed BGRx pixels.
fn blend_cursor(bgrx: &mut [u8], width: usize, height: usize, cursor: &Cursor<'_>) {
for cy in 0..cursor.height {
let py = cursor.top + cy as i32;
if py < 0 || py >= height as i32 {
continue;
}
for cx in 0..cursor.width {
let px = cursor.left + cx as i32;
if px < 0 || px >= width as i32 {
continue;
}
let argb = cursor.argb[cy * cursor.width + cx];
let alpha = argb >> 24;
if alpha == 0 {
continue;
}
let i = (py as usize * width + px as usize) * 4;
for (c, shift) in [(0, 0), (1, 8), (2, 16)] {
let src = (argb >> shift) & 0xff;
let dst = u32::from(bgrx[i + c]);
bgrx[i + c] = (src + dst * (255 - alpha) / 255).min(255) as u8;
}
}
}
}
fn capture(
x: &Display11,
source: &SourceId,
grabber: &mut Grabber,
cursor: bool,
) -> Result<VideoFrame> {
let region = x.region(source)?;
let mut pixels = grabber.grab(x, &region)?;
let (w, h) = (usize::from(region.rect.width), usize::from(region.rect.height));
if cursor && let Ok(image) = x.conn.xfixes_get_cursor_image().map_err(failed)?.reply() {
let cursor = Cursor {
left: i32::from(image.x) - i32::from(image.xhot) - region.root_x,
top: i32::from(image.y) - i32::from(image.yhot) - region.root_y,
width: image.width.into(),
height: image.height.into(),
argb: &image.cursor_image,
};
if cursor.argb.len() >= cursor.width * cursor.height {
blend_cursor(&mut pixels, w, h, &cursor);
}
}
VideoFrame::from_bgra(region.rect.width.into(), region.rect.height.into(), w * 4, pixels)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clipping() {
let screen = Rect { x: 0, y: 0, width: 100, height: 50 };
let inside = Rect { x: 10, y: 10, width: 20, height: 20 };
assert_eq!(clip(inside, screen), Some(inside));
let partly = Rect { x: -5, y: 40, width: 20, height: 20 };
assert_eq!(clip(partly, screen), Some(Rect { x: 0, y: 40, width: 15, height: 10 }));
assert_eq!(clip(Rect { x: 100, y: 0, width: 5, height: 5 }, screen), None);
}
#[test]
fn cursor_blending() {
let (w, h) = (4, 3);
let mut pixels = vec![100; w * h * 4];
// Opaque red, half-transparent white (premultiplied), transparent.
let argb = [0xffff0000, 0x80808080, 0x00000000, 0xff00ff00];
let cursor = Cursor { left: 3, top: 2, width: 2, height: 2, argb: &argb };
blend_cursor(&mut pixels, w, h, &cursor);
// Only the top-left cursor pixel lands inside the frame, at (3, 2).
let at = |x: usize, y: usize| pixels[(y * w + x) * 4..][..3].to_vec();
assert_eq!(at(3, 2), [0, 0, 255]);
assert_eq!(at(2, 2), [100, 100, 100]);
let mut pixels = vec![100; 4];
let cursor = Cursor { left: 0, top: 0, width: 1, height: 1, argb: &argb[1..2] };
blend_cursor(&mut pixels, 1, 1, &cursor);
// 128 + 100 * 127 / 255 = 177
assert_eq!(pixels[..3], [177, 177, 177]);
}
}
+18
View File
@@ -0,0 +1,18 @@
//! Shared memory mapping for MIT-SHM captures (the only `unsafe` in X11
//! capture).
#![allow(unsafe_code)]
use std::fs::File;
use memmap2::MmapMut;
/// Map our memfd read-write.
pub(super) fn map(file: &File) -> std::io::Result<MmapMut> {
// SAFETY: memmap2 needs the file not to be truncated, and not to be
// written by others while Rust reads the mapping. The file is an
// anonymous memfd we created and never resize after mapping; the only
// other party is the X server, which writes into it while it executes a
// ShmGetImage request. The capture loop waits for that request's reply
// before reading, and issues no other request on the segment meanwhile.
unsafe { MmapMut::map_mut(file) }
}
+8
View File
@@ -9,17 +9,23 @@
//! and the backends: libvpx (VP8/VP9, feature `vpx`), Cisco's OpenH264
//! loaded at runtime (H.264, feature `openh264`), dav1d (AV1 decoding,
//! feature `av1`)
//! - [`capture`]: [`ScreenCapture`] and [`AudioCapture`] with a synthetic
//! test source, X11 (feature `x11`), the Wayland ScreenCast portal and
//! PipeWire system audio (feature `pipewire`), and Windows Graphics Capture
//! plus WASAPI loopback on Windows
//! - [`queue`]: the bounded, drop-oldest channel capture backends deliver on
//!
//! Encoded frames go to `tsc_stream::Peer::write` with an RTP time of
//! [`EncodedFrame::pts_90khz`] (90 kHz clock); received `MediaFrame`s go to
//! [`VideoDecoder::decode`].
pub mod capture;
pub mod codec;
pub mod convert;
pub mod frame;
pub mod queue;
pub use capture::{AudioCapture, CaptureOptions, CaptureSource, ScreenCapture, SourceId};
pub use codec::{
Codec, Codecs, ContentHint, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder,
VideoEncoder,
@@ -44,6 +50,8 @@ pub enum Error {
CaptureUnavailable { backend: &'static str, reason: String },
#[error("{backend} capture: {message}")]
Capture { backend: &'static str, message: String },
#[error("capture source not found: {0:?}")]
SourceNotFound(SourceId),
#[error("the user cancelled the capture")]
Cancelled,
#[error("download failed: {0}")]