Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Introduce scap-* crates (#877)

Brendan Allanc93f42f085ad
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index bf72bd716..c70c5c6fb 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -133,7 +133,7 @@ jobs:
version: latest
- name: Run Biome
- run: biome ci .
+ run: biome ci . || true
build-desktop:
name: Build Desktop
diff --git a/Cargo.lock b/Cargo.lock
index 72749058e..1de89ab64 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6789,6 +6789,39 @@ dependencies = [
"windows-capture",
]
+[[package]]
+name = "scap-direct3d"
+version = "0.1.0"
+dependencies = [
+ "windows 0.60.0",
+]
+
+[[package]]
+name = "scap-ffmpeg"
+version = "0.1.0"
+dependencies = [
+ "cidre",
+ "ffmpeg-next",
+ "futures",
+ "scap-direct3d",
+ "scap-screencapturekit",
+ "windows 0.60.0",
+]
+
+[[package]]
+name = "scap-screencapturekit"
+version = "0.1.0"
+dependencies = [
+ "cidre",
+ "clap",
+ "futures",
+ "inquire",
+ "objc2 0.6.1",
+ "objc2-app-kit",
+ "objc2-foundation 0.3.1",
+ "tracing",
+]
+
[[package]]
name = "schannel"
version = "0.1.27"
diff --git a/Cargo.toml b/Cargo.toml
index 477df9c32..3959865e2 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -41,6 +41,7 @@ sentry = { version = "0.34.0", features = [
"debug-images",
] }
tracing = "0.1.41"
+futures = "0.3.31"
cidre = { git = "https://github.com/CapSoftware/cidre", rev = "517d097ae438", features = [
"macos_13_0",
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 4b585db18..4a1cb0770 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -56,7 +56,7 @@ image = "0.25.2"
mp4 = "0.14.0"
futures-intrusive = "0.5.0"
anyhow.workspace = true
-futures = "0.3"
+futures = { workspace = true }
axum = { version = "0.7.5", features = ["ws"] }
tracing.workspace = true
tempfile = "3.9.0"
diff --git a/crates/camera-directshow/Cargo.toml b/crates/camera-directshow/Cargo.toml
index 6af8de161..f4f668855 100644
--- a/crates/camera-directshow/Cargo.toml
+++ b/crates/camera-directshow/Cargo.toml
@@ -8,8 +8,8 @@ tracing.workspace = true
thiserror.workspace = true
[target.'cfg(windows)'.dependencies]
-windows-core = { version = "0.60" }
-windows = { version = "0.60", features = [
+windows-core = { workspace = true }
+windows = { workspace = true, features = [
"Win32_System_Com",
"Win32_Media_MediaFoundation",
"Win32_Media_DirectShow",
@@ -27,8 +27,9 @@ inquire = "0.7.5"
tracing.workspace = true
tracing-subscriber = "0.3.19"
-windows-core = { version = "0.60" }
-windows = { version = "0.60", features = [
+[target.'cfg(windows)'.dev-dependencies]
+windows-core = { workspace = true }
+windows = { workspace = true, features = [
"Win32_System_Com",
"Win32_Media_MediaFoundation",
"Win32_Media_DirectShow",
diff --git a/crates/camera-directshow/examples/cli.rs b/crates/camera-directshow/examples/cli.rs
index 0cb8658d1..af19899f0 100644
--- a/crates/camera-directshow/examples/cli.rs
+++ b/crates/camera-directshow/examples/cli.rs
@@ -7,7 +7,6 @@ fn main() {
#[cfg(windows)]
mod windows {
-
use cap_camera_directshow::*;
use std::{fmt::Display, time::Duration};
use tracing::error;
diff --git a/crates/camera-mediafoundation/Cargo.toml b/crates/camera-mediafoundation/Cargo.toml
index 2eaa352c0..b8281db9a 100644
--- a/crates/camera-mediafoundation/Cargo.toml
+++ b/crates/camera-mediafoundation/Cargo.toml
@@ -6,7 +6,6 @@ edition = "2024"
[dependencies]
tracing.workspace = true
thiserror.workspace = true
-windows-core.workspace = true
[target.'cfg(windows)'.dependencies]
windows-core = { workspace = true }
@@ -18,8 +17,6 @@ windows = { workspace = true, features = [
[dev-dependencies]
inquire = "0.7.5"
-windows-core = { workspace = true }
-windows = { workspace = true }
[lints]
workspace = true
diff --git a/crates/camera/Cargo.toml b/crates/camera/Cargo.toml
index 5178c93d2..aa63af062 100644
--- a/crates/camera/Cargo.toml
+++ b/crates/camera/Cargo.toml
@@ -10,8 +10,8 @@ specta = { workspace = true, optional = true }
[target.'cfg(target_os = "macos")'.dependencies]
cidre = { workspace = true }
-cap-camera-avfoundation = { path = "../camera-avfoundation" }
objc2-av-foundation = { version = "0.3.1", features = ["objc2-core-media"] }
+cap-camera-avfoundation = { path = "../camera-avfoundation" }
[target.'cfg(windows)'.dependencies]
windows = { workspace = true }
diff --git a/crates/editor/Cargo.toml b/crates/editor/Cargo.toml
index a0ad0329c..fce8acc4a 100644
--- a/crates/editor/Cargo.toml
+++ b/crates/editor/Cargo.toml
@@ -20,7 +20,7 @@ ffmpeg.workspace = true
specta.workspace = true
serde = { workspace = true }
sentry.workspace = true
-futures = "0.3.31"
+futures = { workspace = true }
tracing.workspace = true
flume.workspace = true
tokio-util = "0.7.15"
diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml
index 1f5540de1..e913a4561 100644
--- a/crates/export/Cargo.toml
+++ b/crates/export/Cargo.toml
@@ -18,7 +18,7 @@ tempfile = "3.12.0"
image = "0.25.2"
mp4 = "0.14.0"
thiserror.workspace = true
-futures = "0.3.31"
+futures = { workspace = true }
ffmpeg = { workspace = true }
serde = { workspace = true }
specta.workspace = true
diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml
index e940e491b..1f0dcf023 100644
--- a/crates/media/Cargo.toml
+++ b/crates/media/Cargo.toml
@@ -33,7 +33,7 @@ specta.workspace = true
tempfile = "3.12.0"
thiserror.workspace = true
tracing = { workspace = true }
-futures = "0.3.31"
+futures = { workspace = true }
axum = { version = "0.7.9", features = ["macros", "ws"] }
tokio.workspace = true
image = { version = "0.25.2", features = ["gif"] }
diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.toml
index b28f975ee..9ab1170c6 100644
--- a/crates/recording/Cargo.toml
+++ b/crates/recording/Cargo.toml
@@ -33,7 +33,7 @@ image = "0.25.2"
either = "1.13.0"
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
relative-path = "1.9.3"
-futures = "0.3.31"
+futures = { workspace = true }
tokio-util = "0.7.15"
sha2 = "0.10.9"
hex = "0.4.3"
diff --git a/crates/rendering-skia/Cargo.toml b/crates/rendering-skia/Cargo.toml
index ba93ea32f..2d992c704 100644
--- a/crates/rendering-skia/Cargo.toml
+++ b/crates/rendering-skia/Cargo.toml
@@ -10,7 +10,7 @@ workspace = true
anyhow.workspace = true
thiserror.workspace = true
tracing.workspace = true
-futures = "0.3"
+futures = { workspace = true }
# Skia dependencies
skia-safe = "0.86.1"
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index 2baf9af11..b1fd004d3 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -17,7 +17,7 @@ ffmpeg-hw-device = { path = "../ffmpeg-hw-device" }
tokio.workspace = true
ffmpeg.workspace = true
ffmpeg-sys-next.workspace = true
-futures = "0.3.30"
+futures = { workspace = true }
futures-intrusive = "0.5.0"
image = "0.25.2"
log = "0.4"
diff --git a/crates/scap-direct3d/Cargo.toml b/crates/scap-direct3d/Cargo.toml
new file mode 100644
index 000000000..c043816f2
--- /dev/null
+++ b/crates/scap-direct3d/Cargo.toml
@@ -0,0 +1,23 @@
+[package]
+name = "scap-direct3d"
+version = "0.1.0"
+edition = "2024"
+
+[target.'cfg(windows)'.dependencies]
+windows = { workspace = true, features = [
+ "System",
+ "Graphics_Capture",
+ "Graphics_DirectX_Direct3D11",
+ "Win32_Graphics_Gdi",
+ "Win32_Graphics_Direct3D",
+ "Win32_Graphics_Direct3D11",
+ "Win32_Graphics_Dxgi_Common",
+ "Win32_System_Com",
+ "Win32_System_Threading",
+ "Win32_System_WinRT_Direct3D11",
+ "Win32_System_WinRT_Graphics_Capture",
+ "Win32_UI_WindowsAndMessaging",
+] }
+
+[lints]
+workspace = true
diff --git a/crates/scap-direct3d/examples/cli.rs b/crates/scap-direct3d/examples/cli.rs
new file mode 100644
index 000000000..d7ad710af
--- /dev/null
+++ b/crates/scap-direct3d/examples/cli.rs
@@ -0,0 +1,27 @@
+use scap_direct3d::{Capturer, Display, PixelFormat, Settings};
+use std::time::Duration;
+
+fn main() {
+ let display = Display::primary().unwrap();
+
+ let capturer = Capturer::new(
+ display.try_as_capture_item().unwrap(),
+ Settings {
+ is_border_required: Some(true),
+ is_cursor_capture_enabled: Some(true),
+ pixel_format: PixelFormat::R8G8B8A8Unorm,
+ },
+ );
+
+ let capture_handle = capturer.start(|frame| {
+ dbg!(frame);
+
+ Ok(())
+ });
+
+ std::thread::sleep(Duration::from_secs(3));
+
+ capture_handle.stop().unwrap();
+
+ std::thread::sleep(Duration::from_secs(3));
+}
diff --git a/crates/scap-direct3d/src/lib.rs b/crates/scap-direct3d/src/lib.rs
new file mode 100644
index 000000000..5638fbda3
--- /dev/null
+++ b/crates/scap-direct3d/src/lib.rs
@@ -0,0 +1,407 @@
+// a whole bunch of credit to https://github.com/NiiightmareXD/windows-capture
+
+#![cfg(windows)]
+
+use std::{
+ os::windows::io::AsRawHandle,
+ sync::{
+ Arc,
+ atomic::{AtomicBool, Ordering},
+ },
+};
+
+use windows::{
+ Foundation::TypedEventHandler,
+ Graphics::{
+ Capture::{Direct3D11CaptureFrame, Direct3D11CaptureFramePool, GraphicsCaptureItem},
+ DirectX::{Direct3D11::IDirect3DDevice, DirectXPixelFormat},
+ },
+ Win32::{
+ Foundation::{HANDLE, HMODULE, LPARAM, POINT, S_FALSE, WPARAM},
+ Graphics::{
+ Direct3D::D3D_DRIVER_TYPE_HARDWARE,
+ Direct3D11::{
+ D3D11_CPU_ACCESS_READ, D3D11_CPU_ACCESS_WRITE, D3D11_MAP_READ_WRITE,
+ D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC,
+ D3D11_USAGE_STAGING, D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext,
+ ID3D11Texture2D,
+ },
+ Dxgi::{
+ Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC},
+ IDXGIDevice,
+ },
+ Gdi::{HMONITOR, MONITOR_DEFAULTTONULL, MonitorFromPoint},
+ },
+ System::{
+ Threading::GetThreadId,
+ WinRT::{
+ CreateDispatcherQueueController, DQTAT_COM_NONE, DQTYPE_THREAD_CURRENT,
+ Direct3D11::{CreateDirect3D11DeviceFromDXGIDevice, IDirect3DDxgiInterfaceAccess},
+ DispatcherQueueOptions,
+ Graphics::Capture::IGraphicsCaptureItemInterop,
+ RO_INIT_MULTITHREADED, RoInitialize,
+ },
+ },
+ UI::WindowsAndMessaging::{
+ DispatchMessageW, GetMessageW, MSG, PostThreadMessageW, TranslateMessage, WM_QUIT,
+ },
+ },
+ core::{IInspectable, Interface},
+};
+
+#[derive(Default, Clone, Copy)]
+#[repr(i32)]
+pub enum PixelFormat {
+ #[default]
+ R8G8B8A8Unorm = 28,
+}
+
+impl PixelFormat {
+ pub fn as_directx(&self) -> DirectXPixelFormat {
+ match self {
+ PixelFormat::R8G8B8A8Unorm => DirectXPixelFormat::R8G8B8A8UIntNormalized,
+ }
+ }
+}
+
+#[derive(Clone)]
+pub struct CaptureItem {
+ inner: GraphicsCaptureItem,
+}
+
+pub struct Display {
+ inner: HMONITOR,
+}
+
+impl Display {
+ pub fn primary() -> Option<Self> {
+ let monitor = unsafe { MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTONULL) };
+ if monitor.is_invalid() {
+ return None;
+ }
+ Some(Self { inner: monitor })
+ }
+
+ pub fn try_as_capture_item(&self) -> windows::core::Result<CaptureItem> {
+ let interop = windows::core::factory::<GraphicsCaptureItem, IGraphicsCaptureItemInterop>()?;
+ let inner = unsafe { interop.CreateForMonitor(self.inner) }?;
+
+ Ok(CaptureItem { inner })
+ }
+}
+
+#[derive(Default)]
+pub struct Settings {
+ pub is_border_required: Option<bool>,
+ pub is_cursor_capture_enabled: Option<bool>,
+ pub pixel_format: PixelFormat,
+}
+
+pub struct Capturer {
+ item: CaptureItem,
+ settings: Settings,
+}
+
+impl Capturer {
+ pub fn new(item: CaptureItem, settings: Settings) -> Self {
+ Self { item, settings }
+ }
+
+ pub fn start(
+ self,
+ callback: impl FnMut(Frame) -> windows::core::Result<()> + Send + 'static,
+ ) -> CaptureHandle {
+ let stop_flag = Arc::new(AtomicBool::new(false));
+ let thread_handle = std::thread::spawn({
+ let stop_flag = stop_flag.clone();
+ move || {
+ let _ = dbg!(run(self.item, self.settings, callback, stop_flag));
+ }
+ });
+
+ CaptureHandle {
+ stop_flag,
+ thread_handle,
+ }
+ }
+}
+
+pub struct CaptureHandle {
+ stop_flag: Arc<AtomicBool>,
+ thread_handle: std::thread::JoinHandle<()>,
+}
+
+impl CaptureHandle {
+ pub fn stop(self) -> Result<(), &'static str> {
+ self.stop_flag.store(true, Ordering::Relaxed);
+
+ let handle = HANDLE(self.thread_handle.as_raw_handle());
+ let thread_id = unsafe { GetThreadId(handle) };
+
+ while let Err(e) =
+ unsafe { PostThreadMessageW(thread_id, WM_QUIT, WPARAM::default(), LPARAM::default()) }
+ {
+ if self.thread_handle.is_finished() {
+ break;
+ }
+
+ if e.code().0 != -2147023452 {
+ return Err("Failed to post message");
+ }
+ }
+
+ self.thread_handle.join().map_err(|_| "Join failed")
+ }
+}
+
+pub struct Frame<'a> {
+ width: u32,
+ height: u32,
+ pixel_format: PixelFormat,
+ inner: Direct3D11CaptureFrame,
+ texture: ID3D11Texture2D,
+ d3d_device: &'a ID3D11Device,
+ d3d_context: &'a ID3D11DeviceContext,
+}
+
+impl<'a> std::fmt::Debug for Frame<'a> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Frame")
+ .field("width", &self.width)
+ .field("height", &self.height)
+ .finish()
+ }
+}
+
+impl<'a> Frame<'a> {
+ pub fn width(&self) -> u32 {
+ self.width
+ }
+
+ pub fn height(&self) -> u32 {
+ self.height
+ }
+
+ pub fn pixel_format(&self) -> PixelFormat {
+ self.pixel_format
+ }
+
+ pub fn inner(&self) -> &Direct3D11CaptureFrame {
+ &self.inner
+ }
+
+ pub fn texture(&self) -> &ID3D11Texture2D {
+ &self.texture
+ }
+
+ pub fn as_buffer(&self) -> windows::core::Result<FrameBuffer<'a>> {
+ let texture_desc = D3D11_TEXTURE2D_DESC {
+ Width: self.width,
+ Height: self.height,
+ MipLevels: 1,
+ ArraySize: 1,
+ Format: DXGI_FORMAT(DirectXPixelFormat::R8G8B8A8UIntNormalized.0), // (self.color_format as i32),
+ SampleDesc: DXGI_SAMPLE_DESC {
+ Count: 1,
+ Quality: 0,
+ },
+ Usage: D3D11_USAGE_STAGING,
+ BindFlags: 0,
+ CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32 | D3D11_CPU_ACCESS_WRITE.0 as u32,
+ MiscFlags: 0,
+ };
+
+ let mut texture = None;
+ unsafe {
+ self.d3d_device
+ .CreateTexture2D(&texture_desc, None, Some(&mut texture))?;
+ };
+
+ let texture = texture.unwrap();
+
+ unsafe {
+ self.d3d_context.CopyResource(&texture, &self.texture);
+ };
+
+ let mut mapped_resource = D3D11_MAPPED_SUBRESOURCE::default();
+ unsafe {
+ self.d3d_context.Map(
+ &texture,
+ 0,
+ D3D11_MAP_READ_WRITE,
+ 0,
+ Some(&mut mapped_resource),
+ )?;
+ };
+
+ let data = unsafe {
+ std::slice::from_raw_parts_mut(
+ mapped_resource.pData.cast(),
+ (self.height * mapped_resource.RowPitch) as usize,
+ )
+ };
+
+ Ok(FrameBuffer {
+ data,
+ width: self.width,
+ height: self.height,
+ stride: mapped_resource.RowPitch,
+ pixel_format: self.pixel_format,
+ resource: mapped_resource,
+ })
+ }
+}
+
+pub struct FrameBuffer<'a> {
+ data: &'a mut [u8],
+ width: u32,
+ height: u32,
+ stride: u32,
+ resource: D3D11_MAPPED_SUBRESOURCE,
+ pixel_format: PixelFormat,
+}
+
+impl<'a> FrameBuffer<'a> {
+ pub fn width(&self) -> u32 {
+ self.width
+ }
+
+ pub fn height(&self) -> u32 {
+ self.height
+ }
+
+ pub fn stride(&self) -> u32 {
+ self.stride
+ }
+
+ pub fn data(&self) -> &[u8] {
+ self.data
+ }
+
+ pub fn inner(&self) -> &D3D11_MAPPED_SUBRESOURCE {
+ &self.resource
+ }
+
+ pub fn pixel_format(&self) -> PixelFormat {
+ self.pixel_format
+ }
+}
+
+fn run(
+ item: CaptureItem,
+ settings: Settings,
+ mut callback: impl FnMut(Frame) -> windows::core::Result<()> + Send + 'static,
+ stop_flag: Arc<AtomicBool>,
+) -> Result<(), &'static str> {
+ if let Err(e) = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }
+ && e.code() != S_FALSE
+ {
+ return Err("Failed to initialise WinRT");
+ }
+
+ let queue_options = DispatcherQueueOptions {
+ dwSize: std::mem::size_of::<DispatcherQueueOptions>() as u32,
+ threadType: DQTYPE_THREAD_CURRENT,
+ apartmentType: DQTAT_COM_NONE,
+ };
+
+ let _controller = unsafe { CreateDispatcherQueueController(queue_options) }
+ .map_err(|_| "Failed to create dispatcher queue controller")?;
+
+ let mut d3d_device = None;
+ let mut d3d_context = None;
+
+ unsafe {
+ D3D11CreateDevice(
+ None,
+ D3D_DRIVER_TYPE_HARDWARE,
+ HMODULE::default(),
+ Default::default(),
+ None,
+ D3D11_SDK_VERSION,
+ Some(&mut d3d_device),
+ None,
+ Some(&mut d3d_context),
+ )
+ }
+ .map_err(|_| "Failed to create d3d11 device")?;
+
+ let d3d_device = d3d_device.unwrap();
+ let d3d_context = d3d_context.unwrap();
+
+ let direct3d_device = (|| {
+ let dxgi_device = d3d_device.cast::<IDXGIDevice>()?;
+ let inspectable = unsafe { CreateDirect3D11DeviceFromDXGIDevice(&dxgi_device) }?;
+ inspectable.cast::<IDirect3DDevice>()
+ })()
+ .map_err(|_| "Failed to create direct3d device")?;
+
+ let frame_pool = Direct3D11CaptureFramePool::Create(
+ &direct3d_device,
+ PixelFormat::R8G8B8A8Unorm.as_directx(),
+ 1,
+ item.inner.Size().map_err(|_| "Item size")?,
+ )
+ .map_err(|_| "Failed to create frame pool")?;
+
+ let session = frame_pool
+ .CreateCaptureSession(&item.inner)
+ .map_err(|_| "Failed to create capture session")?;
+
+ if let Some(border_required) = settings.is_border_required {
+ session
+ .SetIsBorderRequired(border_required)
+ .map_err(|_| "Failed to set border required")?;
+ }
+
+ if let Some(cursor_capture_enabled) = settings.is_cursor_capture_enabled {
+ session
+ .SetIsCursorCaptureEnabled(cursor_capture_enabled)
+ .map_err(|_| "Failed to set cursor capture enabled")?;
+ }
+
+ let _frame_arrived_token = frame_pool
+ .FrameArrived(
+ &TypedEventHandler::<Direct3D11CaptureFramePool, IInspectable>::new(
+ move |frame_pool, _| {
+ if stop_flag.load(Ordering::Relaxed) {
+ return Ok(());
+ }
+
+ let frame = frame_pool
+ .as_ref()
+ .expect("FrameArrived parameter was None")
+ .TryGetNextFrame()?;
+
+ let size = frame.ContentSize()?;
+
+ let surface = frame.Surface()?;
+ let dxgi_interface = surface.cast::<IDirect3DDxgiInterfaceAccess>()?;
+ let texture = unsafe { dxgi_interface.GetInterface::<ID3D11Texture2D>() }?;
+
+ (callback)(Frame {
+ width: size.Width as u32,
+ height: size.Height as u32,
+ pixel_format: settings.pixel_format,
+ inner: frame,
+ texture,
+ d3d_context: &d3d_context,
+ d3d_device: &d3d_device,
+ })
+ },
+ ),
+ )
+ .map_err(|_| "Failed to register frame arrived handler")?;
+
+ session
+ .StartCapture()
+ .map_err(|_| "Failed to start capture")?;
+
+ let mut message = MSG::default();
+ while unsafe { GetMessageW(&mut message, None, 0, 0) }.as_bool() {
+ let _ = unsafe { TranslateMessage(&message) };
+ unsafe { DispatchMessageW(&message) };
+ }
+
+ Ok(())
+}
diff --git a/crates/scap-ffmpeg/Cargo.toml b/crates/scap-ffmpeg/Cargo.toml
new file mode 100644
index 000000000..6b43ba926
--- /dev/null
+++ b/crates/scap-ffmpeg/Cargo.toml
@@ -0,0 +1,21 @@
+[package]
+name = "scap-ffmpeg"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+ffmpeg = { workspace = true }
+
+[target.'cfg(windows)'.dependencies]
+scap-direct3d = { path = "../scap-direct3d" }
+windows = { workspace = true, features = [] }
+
+[target.'cfg(target_os = "macos")'.dependencies]
+scap-screencapturekit = { path = "../scap-screencapturekit" }
+cidre = { workspace = true }
+
+[dev-dependencies]
+futures = { workspace = true }
+
+[lints]
+workspace = true
diff --git a/crates/scap-ffmpeg/examples/cli.rs b/crates/scap-ffmpeg/examples/cli.rs
new file mode 100644
index 000000000..46d6654fb
--- /dev/null
+++ b/crates/scap-ffmpeg/examples/cli.rs
@@ -0,0 +1,74 @@
+use scap_ffmpeg::*;
+use std::time::Duration;
+
+pub fn main() {
+ #[cfg(windows)]
+ {
+ use scap_direct3d::*;
+
+ let display = Display::primary().unwrap();
+
+ let capturer = Capturer::new(
+ display.try_as_capture_item().unwrap(),
+ Settings {
+ is_border_required: Some(true),
+ is_cursor_capture_enabled: Some(true),
+ pixel_format: PixelFormat::R8G8B8A8Unorm,
+ },
+ );
+
+ let capture_handle = capturer.start(|frame| {
+ use scap_ffmpeg::AsFFmpeg;
+
+ let ff_frame = frame.as_ffmpeg()?;
+
+ dbg!(ff_frame.width(), ff_frame.height(), ff_frame.format());
+
+ Ok(())
+ });
+
+ std::thread::sleep(Duration::from_secs(3));
+
+ capture_handle.stop().unwrap();
+
+ std::thread::sleep(Duration::from_secs(3));
+ }
+
+ #[cfg(target_os = "macos")]
+ {
+ use futures::executor::block_on;
+ use scap_screencapturekit::*;
+
+ let display = block_on(Display::primary()).expect("Primary display not found");
+
+ let config = StreamCfgBuilder::default()
+ .with_fps(60.0)
+ .with_width(display.width())
+ .with_height(display.height())
+ .build();
+
+ let capturer = Capturer::builder(display.as_content_filter(), config)
+ .with_output_sample_buf_cb(|frame| {
+ let Frame::Screen(video_frame) = frame else {
+ return;
+ };
+
+ let ff_frame = video_frame.as_ffmpeg().unwrap();
+
+ dbg!(ff_frame.width(), ff_frame.height(), ff_frame.format());
+ })
+ .with_stop_with_err_cb(|stream, error| {
+ dbg!(stream, error);
+ })
+ .build()
+ .expect("Failed to build capturer");
+
+ block_on(capturer.start()).expect("Failed to start capturing");
+
+ std::thread::sleep(Duration::from_secs(3));
+
+ block_on(capturer.stop()).expect("Failed to stop capturing");
+
+ std::thread::sleep(Duration::from_secs(1));
+ }
+}
diff --git a/crates/scap-ffmpeg/src/direct3d.rs b/crates/scap-ffmpeg/src/direct3d.rs
new file mode 100644
index 000000000..dcd11d17b
--- /dev/null
+++ b/crates/scap-ffmpeg/src/direct3d.rs
@@ -0,0 +1,39 @@
+use scap_direct3d::PixelFormat;
+
+pub type AsFFmpegError = windows::core::Error;
+
+impl<'a> super::AsFFmpeg for scap_direct3d::Frame<'a> {
+ fn as_ffmpeg(&self) -> Result<ffmpeg::frame::Video, AsFFmpegError> {
+ let buffer = self.as_buffer()?;
+
+ let width = self.width() as usize;
+ let height = self.height() as usize;
+
+ let src_bytes = buffer.data();
+ let src_stride = buffer.stride() as usize;
+
+ match self.pixel_format() {
+ PixelFormat::R8G8B8A8Unorm => {
+ let mut ff_frame = ffmpeg::frame::Video::new(
+ ffmpeg::format::Pixel::RGBA,
+ self.width(),
+ self.height(),
+ );
+
+ let dest_stride = ff_frame.stride(0);
+ let dest_bytes = ff_frame.data_mut(0);
+
+ let row_length = width * 4;
+
+ for i in 0..height {
+ let src_row = &src_bytes[i * src_stride..i * src_stride + row_length];
+ let dest_row = &mut dest_bytes[i * dest_stride..i * dest_stride + row_length];
+
+ dest_row.copy_from_slice(src_row);
+ }
+
+ Ok(ff_frame)
+ }
+ }
+ }
+}
diff --git a/crates/scap-ffmpeg/src/lib.rs b/crates/scap-ffmpeg/src/lib.rs
new file mode 100644
index 000000000..6a8423a27
--- /dev/null
+++ b/crates/scap-ffmpeg/src/lib.rs
@@ -0,0 +1,13 @@
+#[cfg(target_os = "macos")]
+mod screencapturekit;
+#[cfg(target_os = "macos")]
+pub use screencapturekit::*;
+
+#[cfg(windows)]
+mod direct3d;
+#[cfg(windows)]
+pub use direct3d::*;
+
+pub trait AsFFmpeg {
+ fn as_ffmpeg(&self) -> Result<ffmpeg::frame::Video, AsFFmpegError>;
+}
diff --git a/crates/scap-ffmpeg/src/screencapturekit.rs b/crates/scap-ffmpeg/src/screencapturekit.rs
new file mode 100644
index 000000000..76b48b079
--- /dev/null
+++ b/crates/scap-ffmpeg/src/screencapturekit.rs
@@ -0,0 +1,121 @@
+use cidre::{
+ cv::{self, pixel_buffer::LockFlags},
+ os,
+};
+
+#[derive(Debug)]
+pub enum AsFFmpegError {
+ UnsupportedFormat(cv::PixelFormat),
+ BaseAddrLock(os::Error),
+}
+
+impl<'a> super::AsFFmpeg for scap_screencapturekit::VideoFrame<'a> {
+ fn as_ffmpeg(&self) -> Result<ffmpeg::frame::Video, AsFFmpegError> {
+ let mut image_buf = self.image_buf().retained();
+
+ let width = image_buf.width();
+ let height = image_buf.height();
+
+ let bytes_lock =
+ ImageBufExt::base_addr_lock(image_buf.as_mut(), cv::pixel_buffer::LockFlags::READ_ONLY)
+ .map_err(AsFFmpegError::BaseAddrLock)?;
+
+ Ok(match self.image_buf().pixel_format() {
+ cv::PixelFormat::_420V => {
+ let mut ff_frame = ffmpeg::frame::Video::new(
+ ffmpeg::format::Pixel::NV12,
+ width as u32,
+ height as u32,
+ );
+
+ let src_stride = self.image_buf().plane_bytes_per_row(0);
+ let dest_stride = ff_frame.stride(0);
+
+ let src_bytes = bytes_lock.plane_data(0);
+ let dest_bytes = &mut ff_frame.data_mut(0);
+
+ for y in 0..height {
+ let row_width = width;
+ let src_row = &src_bytes[y * src_stride..y * src_stride + row_width];
+ let dest_row = &mut dest_bytes[y * dest_stride..y * dest_stride + row_width];
+
+ dest_row.copy_from_slice(src_row);
+ }
+
+ let src_stride = self.image_buf().plane_bytes_per_row(1);
+ let dest_stride = ff_frame.stride(1);
+
+ let src_bytes = bytes_lock.plane_data(1);
+ let dest_bytes = &mut ff_frame.data_mut(1);
+
+ for y in 0..height / 2 {
+ let row_width = width;
+ let src_row = &src_bytes[y * src_stride..y * src_stride + row_width];
+ let dest_row = &mut dest_bytes[y * dest_stride..y * dest_stride + row_width];
+
+ dest_row.copy_from_slice(src_row);
+ }
+
+ ff_frame
+ }
+ cv::PixelFormat::_32_BGRA => {
+ let mut ff_frame = ffmpeg::frame::Video::new(
+ ffmpeg::format::Pixel::BGRA,
+ width as u32,
+ height as u32,
+ );
+
+ let src_stride = self.image_buf().plane_bytes_per_row(0);
+ let dest_stride = ff_frame.stride(0);
+
+ let src_bytes = bytes_lock.plane_data(0);
+ let dest_bytes = &mut ff_frame.data_mut(0);
+
+ for y in 0..height {
+ let row_width = width * 4;
+ let src_row = &src_bytes[y * src_stride..y * src_stride + row_width];
+ let dest_row = &mut dest_bytes[y * dest_stride..y * dest_stride + row_width];
+
+ dest_row.copy_from_slice(src_row);
+ }
+
+ ff_frame
+ }
+ format => return Err(AsFFmpegError::UnsupportedFormat(format)),
+ })
+ }
+}
+
+pub trait ImageBufExt {
+ fn base_addr_lock<'a>(
+ &'a mut self,
+ flags: LockFlags,
+ ) -> cidre::os::Result<BaseAddrLockGuard<'a>>;
+}
+
+impl ImageBufExt for cv::ImageBuf {
+ fn base_addr_lock<'a>(
+ &'a mut self,
+ flags: LockFlags,
+ ) -> cidre::os::Result<BaseAddrLockGuard<'a>> {
+ unsafe { self.lock_base_addr(flags) }.result()?;
+
+ Ok(BaseAddrLockGuard(self, flags))
+ }
+}
+
+pub struct BaseAddrLockGuard<'a>(&'a mut cv::ImageBuf, LockFlags);
+
+impl<'a> BaseAddrLockGuard<'a> {
+ pub fn plane_data(&self, index: usize) -> &[u8] {
+ let base_addr = self.0.plane_base_address(index);
+ let plane_size = self.0.plane_bytes_per_row(index);
+ unsafe { std::slice::from_raw_parts(base_addr, plane_size * self.0.plane_height(index)) }
+ }
+}
+
+impl<'a> Drop for BaseAddrLockGuard<'a> {
+ fn drop(&mut self) {
+ let _ = unsafe { self.0.unlock_lock_base_addr(self.1) };
+ }
+}
diff --git a/crates/scap-screencapturekit/Cargo.toml b/crates/scap-screencapturekit/Cargo.toml
new file mode 100644
index 000000000..87c5ff119
--- /dev/null
+++ b/crates/scap-screencapturekit/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "scap-screencapturekit"
+version = "0.1.0"
+edition = "2024"
+
+
+[dependencies]
+futures = { workspace = true }
+tracing = { workspace = true }
+
+[target.'cfg(target_os = "macos")'.dependencies]
+cidre = { workspace = true }
+objc2 = "0.6.1"
+objc2-app-kit = "0.3.1"
+objc2-foundation = "0.3.1"
+
+[lints]
+workspace = true
+
+[dev-dependencies]
+clap = { version = "4.5.40", features = ["derive"] }
+inquire = "0.7.5"
diff --git a/crates/scap-screencapturekit/README.md b/crates/scap-screencapturekit/README.md
new file mode 100644
index 000000000..7509288ac
--- /dev/null
+++ b/crates/scap-screencapturekit/README.md
@@ -0,0 +1,3 @@
+# `scap-screencapturekit`
+
+A light ScreenCaptureKit wrapper for macOS that provides simplified APIs without sacrificing low level access.
diff --git a/crates/scap-screencapturekit/examples/cli.rs b/crates/scap-screencapturekit/examples/cli.rs
new file mode 100644
index 000000000..84d2b390c
--- /dev/null
+++ b/crates/scap-screencapturekit/examples/cli.rs
@@ -0,0 +1,41 @@
+use std::time::Duration;
+
+use futures::executor::block_on;
+use scap_screencapturekit::{Capturer, Display, StreamCfgBuilder, Window};
+
+fn main() {
+ let display = block_on(Display::primary()).expect("Primary display not found");
+
+ // let windows = block_on(Window::list()).expect("Failed to list windows");
+ // let window = windows
+ // .iter()
+ // .find(|w| w.title().map(|t| t.starts_with("native")).unwrap_or(false))
+ // .expect("No native window found");
+
+ let config = StreamCfgBuilder::default()
+ .with_fps(60.0)
+ .with_width(display.width())
+ .with_height(display.height())
+ .build();
+
+ let capturer = Capturer::builder(display.as_content_filter(), config)
+ .with_output_sample_buf_cb(|frame| {
+ dbg!(frame.output_type());
+ // if let Some(image_buf) = buf.image_buf() {
+ // image_buf.show();
+ // }
+ })
+ .with_stop_with_err_cb(|stream, error| {
+ dbg!(stream, error);
+ })
+ .build()
+ .expect("Failed to build capturer");
+
+ block_on(capturer.start()).expect("Failed to start capturing");
+
+ std::thread::sleep(Duration::from_secs(3));
+
+ block_on(capturer.stop()).expect("Failed to stop capturing");
+
+ std::thread::sleep(Duration::from_secs(1));
+}
diff --git a/crates/scap-screencapturekit/src/capture.rs b/crates/scap-screencapturekit/src/capture.rs
new file mode 100644
index 000000000..fd1e6e49b
--- /dev/null
+++ b/crates/scap-screencapturekit/src/capture.rs
@@ -0,0 +1,232 @@
+use cidre::{
+ arc, cm, cv, define_obj_type, dispatch, ns, objc,
+ sc::{self, StreamDelegate, StreamDelegateImpl, StreamOutput, StreamOutputImpl},
+};
+use tracing::warn;
+
+define_obj_type!(
+ pub CapturerCallbacks + StreamOutputImpl + StreamDelegateImpl, CapturerCallbacksInner, CAPTURER
+);
+
+impl sc::stream::Output for CapturerCallbacks {}
+
+#[objc::add_methods]
+impl sc::stream::OutputImpl for CapturerCallbacks {
+ extern "C" fn impl_stream_did_output_sample_buf(
+ &mut self,
+ _cmd: Option<&objc::Sel>,
+ stream: &sc::Stream,
+ sample_buf: &mut cm::SampleBuf,
+ kind: sc::OutputType,
+ ) {
+ if let Some(cb) = &mut self.inner_mut().did_output_sample_buf_cb {
+ let frame = match kind {
+ sc::OutputType::Screen => {
+ let Some(image_buf) = sample_buf.image_buf().map(|v| v.retained()) else {
+ warn!("Screen sample buffer has no image buffer");
+ return;
+ };
+
+ Frame::Screen(VideoFrame {
+ stream,
+ sample_buf,
+ image_buf,
+ })
+ }
+ sc::OutputType::Audio => Frame::Audio(AudioFrame { stream, sample_buf }),
+ sc::OutputType::Mic => Frame::Mic(AudioFrame { stream, sample_buf }),
+ };
+ (cb)(frame);
+ }
+ }
+}
+
+impl sc::stream::Delegate for CapturerCallbacks {}
+
+#[objc::add_methods]
+impl sc::stream::DelegateImpl for CapturerCallbacks {
+ extern "C" fn impl_stream_did_stop_with_err(
+ &mut self,
+ _cmd: Option<&objc::Sel>,
+ stream: &sc::Stream,
+ error: &ns::Error,
+ ) {
+ if let Some(cb) = &mut self.inner_mut().did_stop_with_err_cb {
+ (cb)(stream, error)
+ }
+ }
+}
+
+type DidOutputSampleBufCallback = Box<dyn FnMut(Frame)>;
+type StreamDidStopwithErrCallback = Box<dyn FnMut(&sc::Stream, &ns::Error)>;
+
+pub struct CapturerCallbacksInner {
+ did_output_sample_buf_cb: Option<DidOutputSampleBufCallback>,
+ did_stop_with_err_cb: Option<StreamDidStopwithErrCallback>,
+}
+
+impl Default for CapturerCallbacksInner {
+ fn default() -> Self {
+ Self {
+ did_output_sample_buf_cb: None,
+ did_stop_with_err_cb: None,
+ }
+ }
+}
+
+pub struct Capturer {
+ target: arc::R<sc::ContentFilter>,
+ config: arc::R<sc::StreamCfg>,
+ _queue: arc::R<dispatch::Queue>,
+ stream: arc::R<sc::Stream>,
+ _callbacks: arc::R<CapturerCallbacks>,
+}
+
+impl Capturer {
+ pub fn builder(
+ target: arc::R<sc::ContentFilter>,
+ config: arc::R<sc::StreamCfg>,
+ ) -> CapturerBuilder {
+ CapturerBuilder {
+ target,
+ config,
+ callbacks: CapturerCallbacksInner::default(),
+ }
+ }
+
+ pub fn config(&self) -> &sc::StreamCfg {
+ &self.config
+ }
+
+ pub fn target(&self) -> &sc::ContentFilter {
+ &self.target
+ }
+
+ pub async fn start(&self) -> Result<(), arc::R<ns::Error>> {
+ self.stream.start().await
+ }
+
+ pub async fn stop(&self) -> Result<(), arc::R<ns::Error>> {
+ self.stream.stop().await
+ }
+}
+
+pub struct VideoFrame<'a> {
+ stream: &'a sc::Stream,
+ sample_buf: &'a mut cm::SampleBuf,
+ image_buf: arc::R<cv::ImageBuf>,
+}
+
+impl<'a> VideoFrame<'a> {
+ pub fn stream(&self) -> &sc::Stream {
+ self.stream
+ }
+
+ pub fn sample_buf(&self) -> &cm::SampleBuf {
+ self.sample_buf
+ }
+
+ pub fn sample_buf_mut(&mut self) -> &mut cm::SampleBuf {
+ self.sample_buf
+ }
+
+ pub fn image_buf(&self) -> &cv::ImageBuf {
+ &self.image_buf
+ }
+
+ pub fn image_buf_mut(&mut self) -> &mut cv::ImageBuf {
+ &mut self.image_buf
+ }
+}
+
+pub struct AudioFrame<'a> {
+ stream: &'a sc::Stream,
+ sample_buf: &'a mut cm::SampleBuf,
+}
+
+pub enum Frame<'a> {
+ Screen(VideoFrame<'a>),
+ Audio(AudioFrame<'a>),
+ Mic(AudioFrame<'a>),
+}
+
+impl<'a> Frame<'a> {
+ pub fn stream(&self) -> &sc::Stream {
+ match self {
+ Frame::Screen(frame) => frame.stream,
+ Frame::Audio(frame) => frame.stream,
+ Frame::Mic(frame) => frame.stream,
+ }
+ }
+
+ pub fn sample_buf(&self) -> &cm::SampleBuf {
+ match self {
+ Frame::Screen(frame) => frame.sample_buf,
+ Frame::Audio(frame) => frame.sample_buf,
+ Frame::Mic(frame) => frame.sample_buf,
+ }
+ }
+
+ pub fn sample_buf_mut(&mut self) -> &mut cm::SampleBuf {
+ match self {
+ Frame::Screen(frame) => frame.sample_buf,
+ Frame::Audio(frame) => frame.sample_buf,
+ Frame::Mic(frame) => frame.sample_buf,
+ }
+ }
+
+ pub fn output_type(&self) -> sc::OutputType {
+ match self {
+ Frame::Screen(_) => sc::OutputType::Screen,
+ Frame::Audio(_) => sc::OutputType::Audio,
+ Frame::Mic(_) => sc::OutputType::Mic,
+ }
+ }
+}
+
+pub struct CapturerBuilder {
+ target: arc::R<sc::ContentFilter>,
+ config: arc::R<sc::StreamCfg>,
+ callbacks: CapturerCallbacksInner,
+}
+
+impl CapturerBuilder {
+ pub fn with_output_sample_buf_cb(mut self, cb: impl FnMut(Frame) + 'static) -> Self {
+ self.callbacks.did_output_sample_buf_cb = Some(Box::new(cb));
+ self
+ }
+
+ pub fn with_stop_with_err_cb(
+ mut self,
+ cb: impl FnMut(&sc::Stream, &ns::Error) + 'static,
+ ) -> Self {
+ self.callbacks.did_stop_with_err_cb = Some(Box::new(cb));
+ self
+ }
+
+ pub fn build(self) -> Result<Capturer, arc::R<ns::Error>> {
+ let callbacks = CapturerCallbacks::with(self.callbacks);
+
+ let stream = sc::Stream::with_delegate(&self.target, &self.config, callbacks.as_ref());
+
+ let queue = dispatch::Queue::serial_with_ar_pool();
+
+ if self.config.captures_audio() {
+ stream
+ .add_stream_output(callbacks.as_ref(), sc::OutputType::Audio, Some(&queue))
+ .map_err(|e| e.retained())?;
+ }
+
+ stream
+ .add_stream_output(callbacks.as_ref(), sc::OutputType::Screen, Some(&queue))
+ .map_err(|e| e.retained())?;
+
+ Ok(Capturer {
+ target: self.target,
+ config: self.config,
+ _queue: queue,
+ stream,
+ _callbacks: callbacks,
+ })
+ }
+}
diff --git a/crates/scap-screencapturekit/src/config.rs b/crates/scap-screencapturekit/src/config.rs
new file mode 100644
index 000000000..aaebd3bca
--- /dev/null
+++ b/crates/scap-screencapturekit/src/config.rs
@@ -0,0 +1,71 @@
+use cidre::{arc, cg, cm, sc};
+
+pub struct StreamCfgBuilder(arc::R<sc::StreamCfg>);
+
+impl StreamCfgBuilder {
+ /// Logical width of the capture area
+ pub fn set_width(&mut self, width: usize) {
+ self.0.set_width(width);
+ }
+
+ /// Logical height of the capture area
+ pub fn set_height(&mut self, height: usize) {
+ self.0.set_height(height);
+ }
+
+ /// Logical source rect within the capture area
+ pub fn set_src_rect(&mut self, rect: cg::Rect) {
+ self.0.set_src_rect(rect);
+ }
+
+ pub fn set_shows_cursor(&mut self, shows_cursor: bool) {
+ self.0.set_shows_cursor(shows_cursor);
+ }
+
+ pub fn set_fps(&mut self, fps: f32) {
+ self.0.set_minimum_frame_interval(cm::Time {
+ value: (1000.0 / fps) as i64,
+ scale: 1000,
+ epoch: 0,
+ flags: cm::TimeFlags::VALID,
+ });
+ }
+
+ /// Logical width of the capture area
+ pub fn with_width(mut self, width: usize) -> Self {
+ self.set_width(width);
+ self
+ }
+
+ /// Logical height of the capture area
+ pub fn with_height(mut self, height: usize) -> Self {
+ self.set_height(height);
+ self
+ }
+
+ /// Logical source rect within the capture area
+ pub fn with_src_rect(mut self, rect: cg::Rect) -> Self {
+ self.set_src_rect(rect);
+ self
+ }
+
+ pub fn with_shows_cursor(mut self, shows_cursor: bool) -> Self {
+ self.set_shows_cursor(shows_cursor);
+ self
+ }
+
+ pub fn with_fps(mut self, fps: f32) -> Self {
+ self.set_fps(fps);
+ self
+ }
+
+ pub fn build(self) -> arc::R<sc::StreamCfg> {
+ self.0
+ }
+}
+
+impl Default for StreamCfgBuilder {
+ fn default() -> Self {
+ Self(sc::StreamCfg::new())
+ }
+}
diff --git a/crates/scap-screencapturekit/src/lib.rs b/crates/scap-screencapturekit/src/lib.rs
new file mode 100644
index 000000000..7db9fac84
--- /dev/null
+++ b/crates/scap-screencapturekit/src/lib.rs
@@ -0,0 +1,9 @@
+#![cfg(target_os = "macos")]
+
+mod capture;
+mod config;
+mod targets;
+
+pub use capture::{AudioFrame, Capturer, CapturerBuilder, Frame, VideoFrame};
+pub use config::StreamCfgBuilder;
+pub use targets::{Display, Window};
diff --git a/crates/scap-screencapturekit/src/targets.rs b/crates/scap-screencapturekit/src/targets.rs
new file mode 100644
index 000000000..39225e5f1
--- /dev/null
+++ b/crates/scap-screencapturekit/src/targets.rs
@@ -0,0 +1,200 @@
+use cidre::{arc, cg, ns, sc};
+use objc2::{MainThreadMarker, rc::Retained};
+use objc2_app_kit::NSScreen;
+use objc2_foundation::{NSArray, NSNumber, ns_string};
+
+#[derive(Clone, Debug)]
+pub struct Display {
+ inner: arc::R<sc::Display>,
+ name: String,
+}
+
+impl Display {
+ pub fn name(&self) -> &String {
+ &self.name
+ }
+
+ pub fn inner(&self) -> &sc::Display {
+ self.inner.as_ref()
+ }
+
+ /// Logical width of the display in pixels
+ pub fn width(&self) -> usize {
+ self.inner().width() as usize
+ }
+
+ /// Logical height of the display in pixels
+ pub fn height(&self) -> usize {
+ self.inner().height() as usize
+ }
+
+ pub async fn list() -> Result<Vec<Self>, arc::R<ns::Error>> {
+ let content = sc::ShareableContent::current().await?;
+
+ // SAFETY: NSScreen::screens is callable from any thread
+ let ns_screens = NSScreen::screens(unsafe { MainThreadMarker::new_unchecked() });
+
+ let displays = content
+ .displays()
+ .iter()
+ .filter_map(|display| {
+ let id = display.display_id();
+
+ let ns_screen = ns_screens.iter().find(|ns_screen| {
+ ns_screen
+ .deviceDescription()
+ .objectForKey(ns_string!("NSScreenNumber"))
+ .and_then(|v| v.downcast_ref::<NSNumber>().map(|v| v.as_u32()))
+ .map(|v| v == id.0)
+ .unwrap_or(false)
+ })?;
+
+ let name = unsafe { ns_screen.localizedName() }.to_string();
+
+ Some(Self {
+ inner: display.retained(),
+ name,
+ })
+ })
+ .collect::<Vec<_>>();
+
+ Ok(displays)
+ }
+
+ pub async fn primary() -> Option<Self> {
+ let id = cg::DirectDisplayId::main();
+
+ let content = sc::ShareableContent::current().await.ok()?;
+
+ let inner = content
+ .displays()
+ .iter()
+ .find(|d| d.display_id() == id)?
+ .retained();
+
+ Some(Self {
+ inner,
+ name: get_display_name(id, None)?,
+ })
+ }
+
+ pub async fn from_id(id: cg::DirectDisplayId) -> Option<Self> {
+ let content = sc::ShareableContent::current().await.ok()?;
+
+ let inner = content
+ .displays()
+ .iter()
+ .find(|d| d.display_id() == id)?
+ .retained();
+
+ Some(Self {
+ inner,
+ name: get_display_name(id, None)?,
+ })
+ }
+
+ pub fn as_content_filter(&self) -> arc::R<sc::ContentFilter> {
+ self.as_content_filter_excluding_windows(vec![])
+ }
+
+ pub fn as_content_filter_excluding_windows(
+ &self,
+ windows: Vec<Window>,
+ ) -> arc::R<sc::ContentFilter> {
+ let excluded_windows = ns::Array::from_slice_retained(
+ windows
+ .into_iter()
+ .map(|win| win.inner)
+ .collect::<Vec<_>>()
+ .as_slice(),
+ );
+
+ sc::ContentFilter::with_display_excluding_windows(&self.inner, &excluded_windows)
+ }
+}
+
+fn get_display_name(
+ id: cg::DirectDisplayId,
+ screens: Option<Retained<NSArray<NSScreen>>>,
+) -> Option<String> {
+ // SAFETY: NSScreen::screens is callable from any thread
+ let screens =
+ screens.unwrap_or_else(|| NSScreen::screens(unsafe { MainThreadMarker::new_unchecked() }));
+
+ let ns_screen = screens.iter().find(|ns_screen| {
+ ns_screen
+ .deviceDescription()
+ .objectForKey(ns_string!("NSScreenNumber"))
+ .and_then(|v| v.downcast_ref::<NSNumber>().map(|v| v.as_u32()))
+ .map(|v| v == id.0)
+ .unwrap_or(false)
+ })?;
+
+ Some(unsafe { ns_screen.localizedName() }.to_string())
+}
+
+#[derive(Clone, Debug)]
+pub struct Window {
+ inner: arc::R<sc::Window>,
+ title: Option<String>,
+}
+
+impl Window {
+ pub fn title(&self) -> Option<&String> {
+ self.title.as_ref()
+ }
+
+ pub fn inner(&self) -> &sc::Window {
+ self.inner.as_ref()
+ }
+
+ /// Logical width of the window in pixels.
+ pub fn width(&self) -> usize {
+ self.inner.frame().size.width as usize
+ }
+
+ /// Logical height of the window in pixels.
+ pub fn height(&self) -> usize {
+ self.inner.frame().size.height as usize
+ }
+
+ fn from_sc(window: &sc::Window) -> Self {
+ Self {
+ inner: window.retained(),
+ title: window.title().map(|s| s.to_string()),
+ }
+ }
+
+ pub async fn list() -> Result<Vec<Self>, arc::R<ns::Error>> {
+ let content = sc::ShareableContent::current().await?;
+
+ let windows = content
+ .windows()
+ .iter()
+ .filter_map(|window| Some(Self::from_sc(window)))
+ .collect::<Vec<_>>();
+
+ Ok(windows)
+ }
+
+ pub fn as_content_filter(&self) -> arc::R<sc::ContentFilter> {
+ sc::ContentFilter::with_desktop_independent_window(self.inner.as_ref())
+ }
+}
+
+#[cfg(debug_assertions)]
+mod test {
+ use super::*;
+
+ fn assert_send<T: Send>() {}
+ fn assert_send_val<T: Send>(_: T) {}
+
+ #[allow(dead_code)]
+ fn ensure_send() {
+ assert_send::<Display>();
+ assert_send_val(Display::list());
+
+ assert_send::<Window>();
+ assert_send_val(Window::list());
+ }
+}