Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Improve macOS recording startup by sharing ScreenCaptureKit warm-up (#1088)

Richie McIlroy14265aeb9c0d
diff --git a/Cargo.lock b/Cargo.lock
index d8fe74ff7..8892a0170 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1007,6 +1007,7 @@ dependencies = [
"cap-recording",
"cap-rendering",
"cap-utils",
+ "cidre 0.11.0",
"clap",
"ffmpeg-next",
"flume",
@@ -7491,6 +7492,7 @@ dependencies = [
"objc",
"serde",
"specta",
+ "tokio",
"tracing",
"windows 0.60.0",
]
diff --git a/apps/cli/Cargo.toml b/apps/cli/Cargo.toml
index 18d52a263..d7c5bd16e 100644
--- a/apps/cli/Cargo.toml
+++ b/apps/cli/Cargo.toml
@@ -24,5 +24,8 @@ tracing.workspace = true
tracing-subscriber = "0.3.19"
flume.workspace = true
+[target.'cfg(target_os = "macos")'.dependencies]
+cidre = { workspace = true }
+
[lints]
workspace = true
diff --git a/apps/cli/src/record.rs b/apps/cli/src/record.rs
index 73137dcb4..25f03e3e9 100644
--- a/apps/cli/src/record.rs
+++ b/apps/cli/src/record.rs
@@ -61,7 +61,10 @@ impl RecordStart {
let actor = studio_recording::Actor::builder(path, target_info)
.with_system_audio(self.system_audio)
.with_custom_cursor(false)
- .build()
+ .build(
+ #[cfg(target_os = "macos")]
+ cidre::sc::ShareableContent::current().await.unwrap(),
+ )
.await
.map_err(|e| e.to_string())?;
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 1d934bcc5..4e997833c 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -19,6 +19,7 @@ mod presets;
mod recording;
mod recording_settings;
mod target_select_overlay;
+mod thumbnails;
mod tray;
mod upload;
mod web_api;
@@ -79,6 +80,8 @@ use tauri_plugin_notification::{NotificationExt, PermissionState};
use tauri_plugin_opener::OpenerExt;
use tauri_plugin_shell::ShellExt;
use tauri_specta::Event;
+#[cfg(target_os = "macos")]
+use tokio::sync::Mutex;
use tokio::sync::{RwLock, oneshot};
use tracing::{error, trace};
use upload::{S3UploadMeta, create_or_get_video, upload_image, upload_video};
@@ -320,6 +323,12 @@ pub struct RequestOpenSettings {
page: String,
}
+#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
+pub struct RequestScreenCapturePrewarm {
+ #[serde(default)]
+ pub force: bool,
+}
+
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct NewNotification {
title: String,
@@ -1939,6 +1948,7 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
RequestOpenRecordingPicker,
RequestNewScreenshot,
RequestOpenSettings,
+ RequestScreenCapturePrewarm,
NewNotification,
AuthenticationInvalid,
audio_meter::AudioInputLevelChange,
@@ -2077,6 +2087,8 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
fake_window::init(&app);
app.manage(target_select_overlay::WindowFocusManager::default());
app.manage(EditorWindowIds::default());
+ #[cfg(target_os = "macos")]
+ app.manage(crate::platform::ScreenCapturePrewarmer::default());
tokio::spawn({
let camera_feed = camera_feed.clone();
@@ -2206,6 +2218,12 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
.await;
});
+ #[cfg(target_os = "macos")]
+ RequestScreenCapturePrewarm::listen_any_spawn(&app, async |event, app| {
+ let prewarmer = app.state::<crate::platform::ScreenCapturePrewarmer>();
+ prewarmer.request(event.force).await;
+ });
+
let app_handle = app.clone();
app.deep_link().on_open_url(move |event| {
deeplink_actions::handle(&app_handle, event.urls());
diff --git a/apps/desktop/src-tauri/src/platform/macos/mod.rs b/apps/desktop/src-tauri/src/platform/macos/mod.rs
index 540744b2f..f6d5d4701 100644
--- a/apps/desktop/src-tauri/src/platform/macos/mod.rs
+++ b/apps/desktop/src-tauri/src/platform/macos/mod.rs
@@ -11,6 +11,9 @@
// use objc::{class, msg_send, sel, sel_impl};
pub mod delegates;
+mod sc_shareable_content;
+
+pub use sc_shareable_content::*;
pub fn set_window_level(window: tauri::Window, level: objc2_app_kit::NSWindowLevel) {
let c_window = window.clone();
diff --git a/apps/desktop/src-tauri/src/platform/macos/sc_shareable_content.rs b/apps/desktop/src-tauri/src/platform/macos/sc_shareable_content.rs
new file mode 100644
index 000000000..d0996cbd2
--- /dev/null
+++ b/apps/desktop/src-tauri/src/platform/macos/sc_shareable_content.rs
@@ -0,0 +1,238 @@
+use cidre::{arc, ns, sc};
+use core_graphics::{display::CGDirectDisplayID, window::CGWindowID};
+use std::sync::Arc;
+use std::{
+ collections::HashMap,
+ sync::{OnceLock, RwLock},
+ time::Instant,
+};
+use tokio::sync::{Mutex, Notify};
+use tracing::{debug, info, trace};
+
+#[derive(Default)]
+struct CacheState {
+ cache: RwLock<Option<ShareableContentCache>>,
+ warmup: Mutex<Option<WarmupTask>>,
+}
+
+type WarmupResult = Result<(), arc::R<ns::Error>>;
+
+#[derive(Clone)]
+struct WarmupTask {
+ notify: Arc<Notify>,
+ result: Arc<Mutex<Option<WarmupResult>>>,
+}
+
+static STATE: OnceLock<CacheState> = OnceLock::new();
+
+fn state() -> &'static CacheState {
+ STATE.get_or_init(CacheState::default)
+}
+
+pub async fn prewarm_shareable_content() -> Result<(), arc::R<ns::Error>> {
+ if state().cache.read().unwrap().is_some() {
+ trace!("ScreenCaptureKit shareable content already warmed");
+ return Ok(());
+ }
+
+ let warmup = {
+ let mut guard = state().warmup.lock().await;
+ if let Some(task) = guard.clone() {
+ trace!("Awaiting in-flight ScreenCaptureKit warmup");
+ task
+ } else {
+ let task = WarmupTask {
+ notify: Arc::new(Notify::new()),
+ result: Arc::new(Mutex::new(None)),
+ };
+ *guard = Some(task.clone());
+ tokio::spawn(run_warmup(task.clone()));
+ task
+ }
+ };
+
+ warmup.notify.notified().await;
+ warmup
+ .result
+ .lock()
+ .await
+ .clone()
+ .expect("ScreenCaptureKit warmup task missing result")
+}
+
+pub async fn get_shareable_content()
+-> Result<Option<arc::R<sc::ShareableContent>>, arc::R<ns::Error>> {
+ let lookup_start = Instant::now();
+
+ if let Some(content) = state()
+ .cache
+ .read()
+ .unwrap()
+ .as_ref()
+ .map(|v| v.content.retained())
+ {
+ trace!(
+ elapsed_ms = lookup_start.elapsed().as_micros() as f64 / 1000.0,
+ "Resolved ScreenCaptureKit from warmed cache"
+ );
+ return Ok(Some(content));
+ }
+
+ prewarm_shareable_content().await?;
+
+ let content = state().cache.read().unwrap();
+ trace!(
+ elapsed_ms = lookup_start.elapsed().as_micros() as f64 / 1000.0,
+ cache_hit = content.is_some(),
+ "Resolved ScreenCaptureKit after cache populate"
+ );
+ Ok(content.as_ref().map(|v| v.content.retained()))
+}
+
+async fn run_warmup(task: WarmupTask) {
+ let result = async {
+ let warm_start = Instant::now();
+ debug!("Populating ScreenCaptureKit shareable content cache");
+
+ let content = sc::ShareableContent::current().await?;
+ let cache = ShareableContentCache::new(content);
+ let elapsed_ms = warm_start.elapsed().as_micros() as f64 / 1000.0;
+
+ let mut guard = state().cache.write().unwrap();
+ let replaced = guard.is_some();
+ *guard = Some(cache);
+
+ info!(
+ elapsed_ms,
+ replaced, "ScreenCaptureKit shareable content cache populated"
+ );
+ Ok::<(), arc::R<ns::Error>>(())
+ }
+ .await;
+
+ {
+ let mut res_guard = task.result.lock().await;
+ *res_guard = Some(result);
+ }
+
+ task.notify.notify_waiters();
+
+ let mut guard = state().warmup.lock().await;
+ if let Some(current) = guard.as_ref()
+ && Arc::ptr_eq(&current.notify, &task.notify)
+ {
+ *guard = None;
+ }
+}
+
+#[derive(Debug)]
+struct ShareableContentCache {
+ #[allow(dead_code)]
+ content: arc::R<sc::ShareableContent>,
+ displays: HashMap<CGDirectDisplayID, arc::R<sc::Display>>,
+ windows: HashMap<CGWindowID, arc::R<sc::Window>>,
+}
+
+unsafe impl Send for ShareableContentCache {}
+unsafe impl Sync for ShareableContentCache {}
+
+impl ShareableContentCache {
+ fn new(content: arc::R<sc::ShareableContent>) -> Self {
+ let displays = content
+ .displays()
+ .iter()
+ .map(|display| (display.display_id().0, display.retained()))
+ .collect();
+
+ let windows = content
+ .windows()
+ .iter()
+ .map(|window| (window.id(), window.retained()))
+ .collect();
+
+ Self {
+ content,
+ displays,
+ windows,
+ }
+ }
+
+ fn display(&self, id: CGDirectDisplayID) -> Option<arc::R<sc::Display>> {
+ self.displays.get(&id).cloned()
+ }
+
+ fn window(&self, id: CGWindowID) -> Option<arc::R<sc::Window>> {
+ self.windows.get(&id).cloned()
+ }
+}
+
+pub(crate) struct ScreenCapturePrewarmer {
+ state: Mutex<PrewarmState>,
+}
+
+impl Default for ScreenCapturePrewarmer {
+ fn default() -> Self {
+ Self {
+ state: Mutex::new(PrewarmState::Idle),
+ }
+ }
+}
+
+impl ScreenCapturePrewarmer {
+ pub async fn request(&self, force: bool) {
+ let should_start = {
+ let mut state = self.state.lock().await;
+
+ if force {
+ *state = PrewarmState::Idle;
+ }
+
+ match *state {
+ PrewarmState::Idle => {
+ *state = PrewarmState::Warming;
+ true
+ }
+ PrewarmState::Warming => {
+ trace!("ScreenCaptureKit prewarm already in progress");
+ false
+ }
+ PrewarmState::Warmed => {
+ if force {
+ *state = PrewarmState::Warming;
+ true
+ } else {
+ trace!("ScreenCaptureKit cache already warmed");
+ false
+ }
+ }
+ }
+ };
+
+ if !should_start {
+ return;
+ }
+
+ let warm_start = std::time::Instant::now();
+ let result = crate::platform::prewarm_shareable_content().await;
+
+ let mut state = self.state.lock().await;
+ match result {
+ Ok(()) => {
+ let elapsed_ms = warm_start.elapsed().as_micros() as f64 / 1000.0;
+ *state = PrewarmState::Warmed;
+ trace!(elapsed_ms, "ScreenCaptureKit cache warmed");
+ }
+ Err(error) => {
+ *state = PrewarmState::Idle;
+ tracing::warn!(error = %error, "ScreenCaptureKit prewarm failed");
+ }
+ }
+ }
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum PrewarmState {
+ Idle,
+ Warming,
+ Warmed,
+}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index ba5209074..f19e8c873 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -14,7 +14,7 @@ use cap_recording::{
};
use cap_rendering::ProjectRecordingsMeta;
use cap_utils::{ensure_dir, spawn_actor};
-use serde::{Deserialize, Serialize};
+use serde::Deserialize;
use specta::Type;
use std::{
collections::{HashMap, VecDeque},
@@ -26,7 +26,7 @@ use std::{
use tauri::{AppHandle, Manager};
use tauri_plugin_dialog::{DialogExt, MessageDialogBuilder};
use tauri_specta::Event;
-use tracing::{debug, error, info, warn};
+use tracing::*;
use crate::{
App, CurrentRecordingChanged, MutableState, NewStudioRecordingAdded, RecordingState,
@@ -37,6 +37,7 @@ use crate::{
general_settings::{GeneralSettingsStore, PostDeletionBehaviour, PostStudioRecordingBehaviour},
open_external_link,
presets::PresetsStore,
+ thumbnails::*,
upload::{
InstantMultipartUpload, build_video_meta, create_or_get_video, prepare_screenshot_upload,
upload_video,
@@ -191,823 +192,24 @@ pub fn list_cameras() -> Vec<cap_camera::CameraInfo> {
cap_camera::list_cameras().collect()
}
-#[derive(Debug, Clone, Serialize, Deserialize, Type)]
-pub struct CaptureDisplayWithThumbnail {
- pub id: scap_targets::DisplayId,
- pub name: String,
- pub refresh_rate: u32,
- pub thumbnail: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, Type)]
-pub struct CaptureWindowWithThumbnail {
- pub id: scap_targets::WindowId,
- pub owner_name: String,
- pub name: String,
- pub bounds: scap_targets::bounds::LogicalBounds,
- pub refresh_rate: u32,
- pub thumbnail: Option<String>,
- pub app_icon: Option<String>,
-}
-
-#[cfg(any(target_os = "macos", windows))]
-const THUMBNAIL_WIDTH: u32 = 320;
-#[cfg(any(target_os = "macos", windows))]
-const THUMBNAIL_HEIGHT: u32 = 180;
-
-#[cfg(any(target_os = "macos", windows))]
-fn normalize_thumbnail_dimensions(image: &image::RgbaImage) -> image::RgbaImage {
- let width = image.width();
- let height = image.height();
-
- if width == THUMBNAIL_WIDTH && height == THUMBNAIL_HEIGHT {
- return image.clone();
- }
-
- if width == 0 || height == 0 {
- return image::RgbaImage::from_pixel(
- THUMBNAIL_WIDTH,
- THUMBNAIL_HEIGHT,
- image::Rgba([0, 0, 0, 0]),
- );
- }
-
- let scale = (THUMBNAIL_WIDTH as f32 / width as f32)
- .min(THUMBNAIL_HEIGHT as f32 / height as f32)
- .max(f32::MIN_POSITIVE);
-
- let scaled_width = (width as f32 * scale)
- .round()
- .clamp(1.0, THUMBNAIL_WIDTH as f32) as u32;
- let scaled_height = (height as f32 * scale)
- .round()
- .clamp(1.0, THUMBNAIL_HEIGHT as f32) as u32;
-
- let resized = image::imageops::resize(
- image,
- scaled_width.max(1),
- scaled_height.max(1),
- image::imageops::FilterType::Lanczos3,
- );
-
- let mut canvas =
- image::RgbaImage::from_pixel(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, image::Rgba([0, 0, 0, 0]));
-
- let offset_x = (THUMBNAIL_WIDTH - scaled_width) / 2;
- let offset_y = (THUMBNAIL_HEIGHT - scaled_height) / 2;
-
- image::imageops::overlay(&mut canvas, &resized, offset_x as i64, offset_y as i64);
-
- canvas
-}
-
-#[cfg(target_os = "macos")]
-async fn capture_thumbnail_from_filter(filter: &cidre::sc::ContentFilter) -> Option<String> {
- use cidre::{cv, sc};
- use image::{ImageEncoder, RgbaImage, codecs::png::PngEncoder};
- use std::{io::Cursor, slice};
-
- let mut config = sc::StreamCfg::new();
- config.set_width(THUMBNAIL_WIDTH as usize);
- config.set_height(THUMBNAIL_HEIGHT as usize);
- config.set_shows_cursor(false);
-
- let sample_buf =
- match unsafe { sc::ScreenshotManager::capture_sample_buf(filter, &config) }.await {
- Ok(buf) => buf,
- Err(err) => {
- warn!(error = ?err, "Failed to capture sample buffer for thumbnail");
- return None;
- }
- };
-
- let Some(image_buf) = sample_buf.image_buf() else {
- warn!("Sample buffer missing image data");
- return None;
- };
- let mut image_buf = image_buf.retained();
-
- let width = image_buf.width();
- let height = image_buf.height();
- if width == 0 || height == 0 {
- warn!(
- width = width,
- height = height,
- "Captured thumbnail had empty dimensions"
- );
- return None;
- }
-
- let pixel_format = image_buf.pixel_format();
-
- let lock =
- match PixelBufferLock::new(image_buf.as_mut(), cv::pixel_buffer::LockFlags::READ_ONLY) {
- Ok(lock) => lock,
- Err(err) => {
- warn!(error = ?err, "Failed to lock pixel buffer for thumbnail");
- return None;
- }
- };
-
- let rgba_data = match pixel_format {
- cv::PixelFormat::_32_BGRA
- | cv::PixelFormat::_32_RGBA
- | cv::PixelFormat::_32_ARGB
- | cv::PixelFormat::_32_ABGR => {
- convert_32bit_pixel_buffer(&lock, width, height, pixel_format)?
- }
- cv::PixelFormat::_420V => {
- convert_nv12_pixel_buffer(&lock, width, height, Nv12Range::Video)?
- }
- other => {
- warn!(?other, "Unsupported pixel format for thumbnail capture");
- return None;
- }
- };
-
- let Some(img) = RgbaImage::from_raw(width as u32, height as u32, rgba_data) else {
- warn!("Failed to construct RGBA image for thumbnail");
- return None;
- };
- let thumbnail = normalize_thumbnail_dimensions(&img);
- let mut png_data = Cursor::new(Vec::new());
- let encoder = PngEncoder::new(&mut png_data);
- if let Err(err) = encoder.write_image(
- thumbnail.as_raw(),
- thumbnail.width(),
- thumbnail.height(),
- image::ColorType::Rgba8.into(),
- ) {
- warn!(error = ?err, "Failed to encode thumbnail as PNG");
- return None;
- }
-
- Some(base64::Engine::encode(
- &base64::engine::general_purpose::STANDARD,
- png_data.into_inner(),
- ))
-}
-
-#[cfg(target_os = "macos")]
-fn convert_32bit_pixel_buffer(
- lock: &PixelBufferLock<'_>,
- width: usize,
- height: usize,
- pixel_format: cidre::cv::PixelFormat,
-) -> Option<Vec<u8>> {
- let base_ptr = lock.base_address();
- if base_ptr.is_null() {
- warn!("Pixel buffer base address was null");
- return None;
- }
-
- let bytes_per_row = lock.bytes_per_row();
- let total_len = bytes_per_row.checked_mul(height)?;
- let raw_data = unsafe { std::slice::from_raw_parts(base_ptr, total_len) };
-
- let mut rgba_data = Vec::with_capacity(width * height * 4);
- for y in 0..height {
- let row_start = y * bytes_per_row;
- let row_end = row_start + width * 4;
- if row_end > raw_data.len() {
- warn!(
- row_start = row_start,
- row_end = row_end,
- raw_len = raw_data.len(),
- "Row bounds exceeded raw data length during thumbnail capture",
- );
- return None;
- }
-
- let row = &raw_data[row_start..row_end];
- for chunk in row.chunks_exact(4) {
- match pixel_format {
- cidre::cv::PixelFormat::_32_BGRA => {
- rgba_data.extend_from_slice(&[chunk[2], chunk[1], chunk[0], chunk[3]])
- }
- cidre::cv::PixelFormat::_32_RGBA => rgba_data.extend_from_slice(chunk),
- cidre::cv::PixelFormat::_32_ARGB => {
- rgba_data.extend_from_slice(&[chunk[1], chunk[2], chunk[3], chunk[0]])
- }
- cidre::cv::PixelFormat::_32_ABGR => {
- rgba_data.extend_from_slice(&[chunk[3], chunk[2], chunk[1], chunk[0]])
- }
- _ => unreachable!(),
- }
- }
- }
-
- Some(rgba_data)
-}
-
-#[cfg(target_os = "macos")]
-#[derive(Copy, Clone)]
-enum Nv12Range {
- Video,
- Full,
-}
-
-#[cfg(target_os = "macos")]
-fn convert_nv12_pixel_buffer(
- lock: &PixelBufferLock<'_>,
- width: usize,
- height: usize,
- range: Nv12Range,
-) -> Option<Vec<u8>> {
- let y_base = lock.base_address_of_plane(0);
- let uv_base = lock.base_address_of_plane(1);
- if y_base.is_null() || uv_base.is_null() {
- warn!("NV12 plane base address was null");
- return None;
- }
-
- let y_stride = lock.bytes_per_row_of_plane(0);
- let uv_stride = lock.bytes_per_row_of_plane(1);
- if y_stride == 0 || uv_stride == 0 {
- warn!(y_stride, uv_stride, "NV12 plane bytes per row was zero");
- return None;
- }
-
- let y_plane_height = lock.height_of_plane(0);
- let uv_plane_height = lock.height_of_plane(1);
- if y_plane_height < height || uv_plane_height < (height + 1) / 2 {
- warn!(
- y_plane_height,
- uv_plane_height,
- expected_y = height,
- expected_uv = (height + 1) / 2,
- "NV12 plane height smaller than expected",
- );
- return None;
- }
-
- let y_plane = unsafe { std::slice::from_raw_parts(y_base, y_stride * y_plane_height) };
- let uv_plane = unsafe { std::slice::from_raw_parts(uv_base, uv_stride * uv_plane_height) };
-
- let mut rgba_data = vec![0u8; width * height * 4];
-
- for y_idx in 0..height {
- let y_row_start = y_idx * y_stride;
- if y_row_start + width > y_plane.len() {
- warn!(
- y_row_start,
- width,
- y_plane_len = y_plane.len(),
- "Y row exceeded plane length during conversion",
- );
- return None;
- }
- let y_row = &y_plane[y_row_start..y_row_start + width];
-
- let uv_row_start = (y_idx / 2) * uv_stride;
- if uv_row_start + width > uv_plane.len() {
- warn!(
- uv_row_start,
- width,
- uv_plane_len = uv_plane.len(),
- "UV row exceeded plane length during conversion",
- );
- return None;
- }
- let uv_row = &uv_plane[uv_row_start..uv_row_start + width];
-
- for x in 0..width {
- let uv_index = (x / 2) * 2;
- if uv_index + 1 >= uv_row.len() {
- warn!(
- uv_index,
- uv_row_len = uv_row.len(),
- "UV index out of bounds during conversion",
- );
- return None;
- }
-
- let y_val = y_row[x];
- let cb = uv_row[uv_index];
- let cr = uv_row[uv_index + 1];
- let (r, g, b) = ycbcr_to_rgb(y_val, cb, cr, range);
- let out = (y_idx * width + x) * 4;
- rgba_data[out] = r;
- rgba_data[out + 1] = g;
- rgba_data[out + 2] = b;
- rgba_data[out + 3] = 255;
- }
- }
-
- Some(rgba_data)
-}
-
-#[cfg(target_os = "macos")]
-fn ycbcr_to_rgb(y: u8, cb: u8, cr: u8, range: Nv12Range) -> (u8, u8, u8) {
- let y = y as f32;
- let cb = cb as f32 - 128.0;
- let cr = cr as f32 - 128.0;
-
- let (y_value, scale) = match range {
- Nv12Range::Video => ((y - 16.0).max(0.0), 1.164383_f32),
- Nv12Range::Full => (y, 1.0_f32),
- };
-
- let r = scale * y_value + 1.596027_f32 * cr;
- let g = scale * y_value - 0.391762_f32 * cb - 0.812968_f32 * cr;
- let b = scale * y_value + 2.017232_f32 * cb;
-
- (clamp_channel(r), clamp_channel(g), clamp_channel(b))
-}
-
-#[cfg(target_os = "macos")]
-fn clamp_channel(value: f32) -> u8 {
- value.max(0.0).min(255.0) as u8
-}
-
-#[cfg(target_os = "macos")]
-struct PixelBufferLock<'a> {
- buffer: &'a mut cidre::cv::PixelBuf,
- flags: cidre::cv::pixel_buffer::LockFlags,
-}
-
-#[cfg(target_os = "macos")]
-impl<'a> PixelBufferLock<'a> {
- fn new(
- buffer: &'a mut cidre::cv::PixelBuf,
- flags: cidre::cv::pixel_buffer::LockFlags,
- ) -> cidre::os::Result<Self> {
- unsafe { buffer.lock_base_addr(flags) }.result()?;
- Ok(Self { buffer, flags })
- }
-
- fn base_address(&self) -> *const u8 {
- unsafe { cv_pixel_buffer_get_base_address(self.buffer) as *const u8 }
- }
-
- fn bytes_per_row(&self) -> usize {
- unsafe { cv_pixel_buffer_get_bytes_per_row(self.buffer) }
- }
-
- fn base_address_of_plane(&self, plane_index: usize) -> *const u8 {
- unsafe { cv_pixel_buffer_get_base_address_of_plane(self.buffer, plane_index) as *const u8 }
- }
-
- fn bytes_per_row_of_plane(&self, plane_index: usize) -> usize {
- unsafe { cv_pixel_buffer_get_bytes_per_row_of_plane(self.buffer, plane_index) }
- }
-
- fn height_of_plane(&self, plane_index: usize) -> usize {
- unsafe { cv_pixel_buffer_get_height_of_plane(self.buffer, plane_index) }
- }
-}
-
-#[cfg(target_os = "macos")]
-impl Drop for PixelBufferLock<'_> {
- fn drop(&mut self) {
- unsafe {
- let _ = self.buffer.unlock_lock_base_addr(self.flags);
- }
- }
-}
-
-#[cfg(target_os = "macos")]
-unsafe fn cv_pixel_buffer_get_base_address(buffer: &cidre::cv::PixelBuf) -> *mut std::ffi::c_void {
- unsafe extern "C" {
- fn CVPixelBufferGetBaseAddress(pixel_buffer: &cidre::cv::PixelBuf)
- -> *mut std::ffi::c_void;
- }
-
- unsafe { CVPixelBufferGetBaseAddress(buffer) }
-}
-
-#[cfg(target_os = "macos")]
-unsafe fn cv_pixel_buffer_get_bytes_per_row(buffer: &cidre::cv::PixelBuf) -> usize {
- unsafe extern "C" {
- fn CVPixelBufferGetBytesPerRow(pixel_buffer: &cidre::cv::PixelBuf) -> usize;
- }
-
- unsafe { CVPixelBufferGetBytesPerRow(buffer) }
-}
-
-#[cfg(target_os = "macos")]
-unsafe fn cv_pixel_buffer_get_base_address_of_plane(
- buffer: &cidre::cv::PixelBuf,
- plane_index: usize,
-) -> *mut std::ffi::c_void {
- unsafe extern "C" {
- fn CVPixelBufferGetBaseAddressOfPlane(
- pixel_buffer: &cidre::cv::PixelBuf,
- plane_index: usize,
- ) -> *mut std::ffi::c_void;
- }
-
- unsafe { CVPixelBufferGetBaseAddressOfPlane(buffer, plane_index) }
-}
-
-#[cfg(target_os = "macos")]
-unsafe fn cv_pixel_buffer_get_bytes_per_row_of_plane(
- buffer: &cidre::cv::PixelBuf,
- plane_index: usize,
-) -> usize {
- unsafe extern "C" {
- fn CVPixelBufferGetBytesPerRowOfPlane(
- pixel_buffer: &cidre::cv::PixelBuf,
- plane_index: usize,
- ) -> usize;
- }
-
- unsafe { CVPixelBufferGetBytesPerRowOfPlane(buffer, plane_index) }
-}
-
-#[cfg(target_os = "macos")]
-unsafe fn cv_pixel_buffer_get_height_of_plane(
- buffer: &cidre::cv::PixelBuf,
- plane_index: usize,
-) -> usize {
- unsafe extern "C" {
- fn CVPixelBufferGetHeightOfPlane(
- pixel_buffer: &cidre::cv::PixelBuf,
- plane_index: usize,
- ) -> usize;
- }
-
- unsafe { CVPixelBufferGetHeightOfPlane(buffer, plane_index) }
-}
-
-#[cfg(target_os = "macos")]
-async fn capture_display_thumbnail(display: &scap_targets::Display) -> Option<String> {
- let filter = display.raw_handle().as_content_filter().await?;
- capture_thumbnail_from_filter(filter.as_ref()).await
-}
-
-#[cfg(windows)]
-async fn capture_display_thumbnail(display: &scap_targets::Display) -> Option<String> {
- use image::{ColorType, ImageEncoder, codecs::png::PngEncoder};
- use scap_direct3d::{Capturer, Settings};
- use std::io::Cursor;
-
- let item = display.raw_handle().try_as_capture_item().ok()?;
-
- let (tx, rx) = std::sync::mpsc::channel();
-
- let settings = Settings {
- is_cursor_capture_enabled: Some(false),
- pixel_format: scap_direct3d::PixelFormat::R8G8B8A8Unorm,
- ..Default::default()
- };
-
- let mut capturer = Capturer::new(
- item,
- settings.clone(),
- move |frame| {
- let _ = tx.send(frame);
- Ok(())
- },
- || Ok(()),
- None,
- )
- .ok()?;
-
- capturer.start().ok()?;
-
- let frame = rx.recv_timeout(std::time::Duration::from_secs(2)).ok()?;
- let _ = capturer.stop();
-
- let width = frame.width();
- let height = frame.height();
-
- if width == 0 || height == 0 {
- return None;
- }
-
- let frame_buffer = frame.as_buffer().ok()?;
- let data = frame_buffer.data();
- let stride = frame_buffer.stride() as usize;
-
- let width_usize = width as usize;
- let height_usize = height as usize;
-
- let Some(row_bytes) = width_usize.checked_mul(4) else {
- warn!(
- frame_width = width,
- "Windows display thumbnail row size overflowed"
- );
- return None;
- };
-
- if stride < row_bytes {
- warn!(
- frame_width = width,
- frame_height = height,
- stride,
- expected_row_bytes = row_bytes,
- "Windows display thumbnail stride smaller than row size"
- );
- return None;
- }
-
- let rows_before_last = height_usize.saturating_sub(1);
- let Some(last_row_start) = rows_before_last.checked_mul(stride) else {
- warn!(
- frame_width = width,
- frame_height = height,
- stride,
- "Windows display thumbnail row offset overflowed"
- );
- return None;
- };
-
- let Some(required_len) = last_row_start.checked_add(row_bytes) else {
- warn!(
- frame_width = width,
- frame_height = height,
- stride,
- required_row_bytes = row_bytes,
- "Windows display thumbnail required length overflowed"
- );
- return None;
- };
-
- if data.len() < required_len {
- warn!(
- frame_width = width,
- frame_height = height,
- stride,
- frame_data_len = data.len(),
- expected_len = required_len,
- "Windows display thumbnail frame buffer missing pixel data"
- );
- return None;
- }
-
- let Some(rgba_capacity) = height_usize.checked_mul(row_bytes) else {
- warn!(
- frame_width = width,
- frame_height = height,
- total_row_bytes = row_bytes,
- "Windows display thumbnail RGBA capacity overflowed"
- );
- return None;
- };
-
- let mut rgba_data = Vec::with_capacity(rgba_capacity);
- for y in 0..height_usize {
- let row_start = y * stride;
- let row_end = row_start + row_bytes;
- rgba_data.extend_from_slice(&data[row_start..row_end]);
- }
-
- let Some(img) = image::RgbaImage::from_raw(width, height, rgba_data) else {
- warn!("Windows display thumbnail failed to construct RGBA image");
- return None;
- };
- let thumbnail = normalize_thumbnail_dimensions(&img);
-
- let mut png_data = Cursor::new(Vec::new());
- let encoder = PngEncoder::new(&mut png_data);
- encoder
- .write_image(
- thumbnail.as_raw(),
- thumbnail.width(),
- thumbnail.height(),
- ColorType::Rgba8.into(),
- )
- .ok()?;
-
- Some(base64::Engine::encode(
- &base64::engine::general_purpose::STANDARD,
- png_data.into_inner(),
- ))
-}
-
-#[cfg(target_os = "macos")]
-async fn capture_window_thumbnail(window: &scap_targets::Window) -> Option<String> {
- let sc_window = window.raw_handle().as_sc().await?;
- let filter = cidre::sc::ContentFilter::with_desktop_independent_window(&sc_window);
- capture_thumbnail_from_filter(filter.as_ref()).await
-}
-
-#[cfg(windows)]
-async fn capture_window_thumbnail(window: &scap_targets::Window) -> Option<String> {
- use image::{ColorType, ImageEncoder, codecs::png::PngEncoder};
- use scap_direct3d::{Capturer, Settings};
- use std::io::Cursor;
-
- let item = window.raw_handle().try_as_capture_item().ok()?;
-
- let (tx, rx) = std::sync::mpsc::channel();
-
- let settings = Settings {
- is_cursor_capture_enabled: Some(false),
- pixel_format: scap_direct3d::PixelFormat::R8G8B8A8Unorm,
- ..Default::default()
- };
-
- let mut capturer = Capturer::new(
- item,
- settings.clone(),
- move |frame| {
- let _ = tx.send(frame);
- Ok(())
- },
- || Ok(()),
- None,
- )
- .ok()?;
-
- capturer.start().ok()?;
-
- let frame = rx.recv_timeout(std::time::Duration::from_secs(2)).ok()?;
- let _ = capturer.stop();
-
- let width = frame.width();
- let height = frame.height();
-
- if width == 0 || height == 0 {
- return None;
- }
-
- let frame_buffer = frame.as_buffer().ok()?;
- let data = frame_buffer.data();
- let stride = frame_buffer.stride() as usize;
-
- let width_usize = width as usize;
- let height_usize = height as usize;
-
- let Some(row_bytes) = width_usize.checked_mul(4) else {
- warn!(
- frame_width = width,
- "Windows window thumbnail row size overflowed"
- );
- return None;
- };
-
- if stride < row_bytes {
- warn!(
- frame_width = width,
- frame_height = height,
- stride,
- expected_row_bytes = row_bytes,
- "Windows window thumbnail stride smaller than row size"
- );
- return None;
- }
-
- let rows_before_last = height_usize.saturating_sub(1);
- let Some(last_row_start) = rows_before_last.checked_mul(stride) else {
- warn!(
- frame_width = width,
- frame_height = height,
- stride,
- "Windows window thumbnail row offset overflowed"
- );
- return None;
- };
-
- let Some(required_len) = last_row_start.checked_add(row_bytes) else {
- warn!(
- frame_width = width,
- frame_height = height,
- stride,
- required_row_bytes = row_bytes,
- "Windows window thumbnail required length overflowed"
- );
- return None;
- };
-
- if data.len() < required_len {
- warn!(
- frame_width = width,
- frame_height = height,
- stride,
- frame_data_len = data.len(),
- expected_len = required_len,
- "Windows window thumbnail frame buffer missing pixel data"
- );
- return None;
- }
-
- let Some(rgba_capacity) = height_usize.checked_mul(row_bytes) else {
- warn!(
- frame_width = width,
- frame_height = height,
- total_row_bytes = row_bytes,
- "Windows window thumbnail RGBA capacity overflowed"
- );
- return None;
- };
-
- let mut rgba_data = Vec::with_capacity(rgba_capacity);
- for y in 0..height_usize {
- let row_start = y * stride;
- let row_end = row_start + row_bytes;
- rgba_data.extend_from_slice(&data[row_start..row_end]);
- }
-
- let Some(img) = image::RgbaImage::from_raw(width, height, rgba_data) else {
- warn!("Windows window thumbnail failed to construct RGBA image");
- return None;
- };
- let thumbnail = normalize_thumbnail_dimensions(&img);
-
- let mut png_data = Cursor::new(Vec::new());
- let encoder = PngEncoder::new(&mut png_data);
- encoder
- .write_image(
- thumbnail.as_raw(),
- thumbnail.width(),
- thumbnail.height(),
- ColorType::Rgba8.into(),
- )
- .ok()?;
-
- Some(base64::Engine::encode(
- &base64::engine::general_purpose::STANDARD,
- png_data.into_inner(),
- ))
-}
-
-#[tauri::command(async)]
+#[tauri::command]
#[specta::specta]
pub async fn list_displays_with_thumbnails() -> Result<Vec<CaptureDisplayWithThumbnail>, String> {
- tokio::task::spawn_blocking(|| collect_displays_with_thumbnails())
- .await
- .map_err(|err| err.to_string())?
+ tokio::task::spawn_blocking(|| {
+ tauri::async_runtime::block_on(collect_displays_with_thumbnails())
+ })
+ .await
+ .map_err(|e| e.to_string())?
}
-#[tauri::command(async)]
+#[tauri::command]
#[specta::specta]
pub async fn list_windows_with_thumbnails() -> Result<Vec<CaptureWindowWithThumbnail>, String> {
- tokio::task::spawn_blocking(|| collect_windows_with_thumbnails())
- .await
- .map_err(|err| err.to_string())?
-}
-
-fn collect_displays_with_thumbnails() -> Result<Vec<CaptureDisplayWithThumbnail>, String> {
- tauri::async_runtime::block_on(async move {
- let displays = screen_capture::list_displays();
-
- let mut results = Vec::new();
- for (capture_display, display) in displays {
- let thumbnail = capture_display_thumbnail(&display).await;
- results.push(CaptureDisplayWithThumbnail {
- id: capture_display.id,
- name: capture_display.name,
- refresh_rate: capture_display.refresh_rate,
- thumbnail,
- });
- }
-
- Ok(results)
- })
-}
-
-fn collect_windows_with_thumbnails() -> Result<Vec<CaptureWindowWithThumbnail>, String> {
- tauri::async_runtime::block_on(async move {
- let windows = screen_capture::list_windows();
-
- debug!(window_count = windows.len(), "Collecting window thumbnails");
- let mut results = Vec::new();
- for (capture_window, window) in windows {
- let thumbnail = capture_window_thumbnail(&window).await;
- let app_icon = window.app_icon().and_then(|bytes| {
- if bytes.is_empty() {
- None
- } else {
- Some(base64::Engine::encode(
- &base64::engine::general_purpose::STANDARD,
- bytes,
- ))
- }
- });
-
- if thumbnail.is_none() {
- warn!(
- window_id = ?capture_window.id,
- window_name = %capture_window.name,
- owner_name = %capture_window.owner_name,
- "Window thumbnail capture returned None",
- );
- } else {
- debug!(
- window_id = ?capture_window.id,
- window_name = %capture_window.name,
- owner_name = %capture_window.owner_name,
- "Captured window thumbnail",
- );
- }
-
- results.push(CaptureWindowWithThumbnail {
- id: capture_window.id,
- name: capture_window.name,
- owner_name: capture_window.owner_name,
- bounds: capture_window.bounds,
- refresh_rate: capture_window.refresh_rate,
- thumbnail,
- app_icon,
- });
- }
-
- info!(windows = results.len(), "Collected window thumbnail data");
-
- Ok(results)
- })
+ tokio::task::spawn_blocking(
+ || tauri::async_runtime::block_on(collect_windows_with_thumbnails()),
+ )
+ .await
+ .map_err(|e| e.to_string())?
}
#[derive(Deserialize, Type, Clone, Debug)]
@@ -1205,6 +407,12 @@ pub async fn start_recording(
Err(e) => return Err(e.to_string()),
};
+ #[cfg(target_os = "macos")]
+ let shareable_content = crate::platform::get_shareable_content()
+ .await
+ .map_err(|e| format!("GetShareableContent: {e}"))?
+ .ok_or_else(|| format!("GetShareableContent/NotAvailable"))?;
+
let (actor, actor_done_rx) = match inputs.mode {
RecordingMode::Studio => {
let mut builder = studio_recording::Actor::builder(
@@ -1226,10 +434,16 @@ pub async fn start_recording(
builder = builder.with_mic_feed(mic_feed);
}
- let (handle, actor_done_rx) = builder.build().await.map_err(|e| {
- error!("Failed to spawn studio recording actor: {e}");
- e.to_string()
- })?;
+ let (handle, actor_done_rx) = builder
+ .build(
+ #[cfg(target_os = "macos")]
+ shareable_content,
+ )
+ .await
+ .map_err(|e| {
+ error!("Failed to spawn studio recording actor: {e}");
+ e.to_string()
+ })?;
(
InProgressRecording::Studio {
@@ -1256,10 +470,16 @@ pub async fn start_recording(
builder = builder.with_mic_feed(mic_feed);
}
- let (handle, actor_done_rx) = builder.build().await.map_err(|e| {
- error!("Failed to spawn studio recording actor: {e}");
- e.to_string()
- })?;
+ let (handle, actor_done_rx) = builder
+ .build(
+ #[cfg(target_os = "macos")]
+ shareable_content,
+ )
+ .await
+ .map_err(|e| {
+ error!("Failed to spawn instant recording actor: {e}");
+ e.to_string()
+ })?;
(
InProgressRecording::Instant {
diff --git a/apps/desktop/src-tauri/src/thumbnails/mac.rs b/apps/desktop/src-tauri/src/thumbnails/mac.rs
new file mode 100644
index 000000000..64918e26a
--- /dev/null
+++ b/apps/desktop/src-tauri/src/thumbnails/mac.rs
@@ -0,0 +1,378 @@
+use cidre::{arc, sc};
+
+use crate::platform::get_shareable_content;
+
+use super::*;
+
+pub async fn capture_display_thumbnail(display: &scap_targets::Display) -> Option<String> {
+ let content = get_shareable_content().await.ok()??;
+
+ let filter = display.raw_handle().as_content_filter(content).await?;
+ capture_thumbnail_from_filter(filter).await
+}
+
+pub async fn capture_window_thumbnail(window: &scap_targets::Window) -> Option<String> {
+ let content = get_shareable_content().await.ok()??;
+
+ let sc_window = window.raw_handle().as_sc(content).await?;
+ let filter = cidre::sc::ContentFilter::with_desktop_independent_window(&sc_window);
+ capture_thumbnail_from_filter(filter).await
+}
+
+async fn capture_thumbnail_from_filter(filter: arc::R<sc::ContentFilter>) -> Option<String> {
+ use cidre::{cv, sc};
+ use image::{ImageEncoder, RgbaImage, codecs::png::PngEncoder};
+ use std::{io::Cursor, slice};
+
+ let mut config = sc::StreamCfg::new();
+ config.set_width(THUMBNAIL_WIDTH as usize);
+ config.set_height(THUMBNAIL_HEIGHT as usize);
+ config.set_shows_cursor(false);
+
+ let sample_buf = match unsafe {
+ sc::ScreenshotManager::capture_sample_buf(filter.as_ref(), &config)
+ }
+ .await
+ {
+ Ok(buf) => buf,
+ Err(err) => {
+ warn!(error = ?err, "Failed to capture sample buffer for thumbnail");
+ return None;
+ }
+ };
+
+ let Some(image_buf) = sample_buf.image_buf() else {
+ warn!("Sample buffer missing image data");
+ return None;
+ };
+ let mut image_buf = image_buf.retained();
+
+ let width = image_buf.width();
+ let height = image_buf.height();
+ if width == 0 || height == 0 {
+ warn!(
+ width = width,
+ height = height,
+ "Captured thumbnail had empty dimensions"
+ );
+ return None;
+ }
+
+ let pixel_format = image_buf.pixel_format();
+
+ let lock =
+ match PixelBufferLock::new(image_buf.as_mut(), cv::pixel_buffer::LockFlags::READ_ONLY) {
+ Ok(lock) => lock,
+ Err(err) => {
+ warn!(error = ?err, "Failed to lock pixel buffer for thumbnail");
+ return None;
+ }
+ };
+
+ let rgba_data = match pixel_format {
+ cv::PixelFormat::_32_BGRA
+ | cv::PixelFormat::_32_RGBA
+ | cv::PixelFormat::_32_ARGB
+ | cv::PixelFormat::_32_ABGR => {
+ convert_32bit_pixel_buffer(&lock, width, height, pixel_format)?
+ }
+ cv::PixelFormat::_420V => {
+ convert_nv12_pixel_buffer(&lock, width, height, Nv12Range::Video)?
+ }
+ other => {
+ warn!(?other, "Unsupported pixel format for thumbnail capture");
+ return None;
+ }
+ };
+
+ let Some(img) = RgbaImage::from_raw(width as u32, height as u32, rgba_data) else {
+ warn!("Failed to construct RGBA image for thumbnail");
+ return None;
+ };
+ let thumbnail = normalize_thumbnail_dimensions(&img);
+ let mut png_data = Cursor::new(Vec::new());
+ let encoder = PngEncoder::new(&mut png_data);
+ if let Err(err) = encoder.write_image(
+ thumbnail.as_raw(),
+ thumbnail.width(),
+ thumbnail.height(),
+ image::ColorType::Rgba8.into(),
+ ) {
+ warn!(error = ?err, "Failed to encode thumbnail as PNG");
+ return None;
+ }
+
+ Some(base64::Engine::encode(
+ &base64::engine::general_purpose::STANDARD,
+ png_data.into_inner(),
+ ))
+}
+
+fn convert_32bit_pixel_buffer(
+ lock: &PixelBufferLock<'_>,
+ width: usize,
+ height: usize,
+ pixel_format: cidre::cv::PixelFormat,
+) -> Option<Vec<u8>> {
+ let base_ptr = lock.base_address();
+ if base_ptr.is_null() {
+ warn!("Pixel buffer base address was null");
+ return None;
+ }
+
+ let bytes_per_row = lock.bytes_per_row();
+ let total_len = bytes_per_row.checked_mul(height)?;
+ let raw_data = unsafe { std::slice::from_raw_parts(base_ptr, total_len) };
+
+ let mut rgba_data = Vec::with_capacity(width * height * 4);
+ for y in 0..height {
+ let row_start = y * bytes_per_row;
+ let row_end = row_start + width * 4;
+ if row_end > raw_data.len() {
+ warn!(
+ row_start = row_start,
+ row_end = row_end,
+ raw_len = raw_data.len(),
+ "Row bounds exceeded raw data length during thumbnail capture",
+ );
+ return None;
+ }
+
+ let row = &raw_data[row_start..row_end];
+ for chunk in row.chunks_exact(4) {
+ match pixel_format {
+ cidre::cv::PixelFormat::_32_BGRA => {
+ rgba_data.extend_from_slice(&[chunk[2], chunk[1], chunk[0], chunk[3]])
+ }
+ cidre::cv::PixelFormat::_32_RGBA => rgba_data.extend_from_slice(chunk),
+ cidre::cv::PixelFormat::_32_ARGB => {
+ rgba_data.extend_from_slice(&[chunk[1], chunk[2], chunk[3], chunk[0]])
+ }
+ cidre::cv::PixelFormat::_32_ABGR => {
+ rgba_data.extend_from_slice(&[chunk[3], chunk[2], chunk[1], chunk[0]])
+ }
+ _ => unreachable!(),
+ }
+ }
+ }
+
+ Some(rgba_data)
+}
+
+#[derive(Copy, Clone)]
+enum Nv12Range {
+ Video,
+ Full,
+}
+
+fn convert_nv12_pixel_buffer(
+ lock: &PixelBufferLock<'_>,
+ width: usize,
+ height: usize,
+ range: Nv12Range,
+) -> Option<Vec<u8>> {
+ let y_base = lock.base_address_of_plane(0);
+ let uv_base = lock.base_address_of_plane(1);
+ if y_base.is_null() || uv_base.is_null() {
+ warn!("NV12 plane base address was null");
+ return None;
+ }
+
+ let y_stride = lock.bytes_per_row_of_plane(0);
+ let uv_stride = lock.bytes_per_row_of_plane(1);
+ if y_stride == 0 || uv_stride == 0 {
+ warn!(y_stride, uv_stride, "NV12 plane bytes per row was zero");
+ return None;
+ }
+
+ let y_plane_height = lock.height_of_plane(0);
+ let uv_plane_height = lock.height_of_plane(1);
+ if y_plane_height < height || uv_plane_height < (height + 1) / 2 {
+ warn!(
+ y_plane_height,
+ uv_plane_height,
+ expected_y = height,
+ expected_uv = (height + 1) / 2,
+ "NV12 plane height smaller than expected",
+ );
+ return None;
+ }
+
+ let y_plane = unsafe { std::slice::from_raw_parts(y_base, y_stride * y_plane_height) };
+ let uv_plane = unsafe { std::slice::from_raw_parts(uv_base, uv_stride * uv_plane_height) };
+
+ let mut rgba_data = vec![0u8; width * height * 4];
+
+ for y_idx in 0..height {
+ let y_row_start = y_idx * y_stride;
+ if y_row_start + width > y_plane.len() {
+ warn!(
+ y_row_start,
+ width,
+ y_plane_len = y_plane.len(),
+ "Y row exceeded plane length during conversion",
+ );
+ return None;
+ }
+ let y_row = &y_plane[y_row_start..y_row_start + width];
+
+ let uv_row_start = (y_idx / 2) * uv_stride;
+ if uv_row_start + width > uv_plane.len() {
+ warn!(
+ uv_row_start,
+ width,
+ uv_plane_len = uv_plane.len(),
+ "UV row exceeded plane length during conversion",
+ );
+ return None;
+ }
+ let uv_row = &uv_plane[uv_row_start..uv_row_start + width];
+
+ for x in 0..width {
+ let uv_index = (x / 2) * 2;
+ if uv_index + 1 >= uv_row.len() {
+ warn!(
+ uv_index,
+ uv_row_len = uv_row.len(),
+ "UV index out of bounds during conversion",
+ );
+ return None;
+ }
+
+ let y_val = y_row[x];
+ let cb = uv_row[uv_index];
+ let cr = uv_row[uv_index + 1];
+ let (r, g, b) = ycbcr_to_rgb(y_val, cb, cr, range);
+ let out = (y_idx * width + x) * 4;
+ rgba_data[out] = r;
+ rgba_data[out + 1] = g;
+ rgba_data[out + 2] = b;
+ rgba_data[out + 3] = 255;
+ }
+ }
+
+ Some(rgba_data)
+}
+
+fn ycbcr_to_rgb(y: u8, cb: u8, cr: u8, range: Nv12Range) -> (u8, u8, u8) {
+ let y = y as f32;
+ let cb = cb as f32 - 128.0;
+ let cr = cr as f32 - 128.0;
+
+ let (y_value, scale) = match range {
+ Nv12Range::Video => ((y - 16.0).max(0.0), 1.164383_f32),
+ Nv12Range::Full => (y, 1.0_f32),
+ };
+
+ let r = scale * y_value + 1.596027_f32 * cr;
+ let g = scale * y_value - 0.391762_f32 * cb - 0.812968_f32 * cr;
+ let b = scale * y_value + 2.017232_f32 * cb;
+
+ (clamp_channel(r), clamp_channel(g), clamp_channel(b))
+}
+
+fn clamp_channel(value: f32) -> u8 {
+ value.max(0.0).min(255.0) as u8
+}
+
+struct PixelBufferLock<'a> {
+ buffer: &'a mut cidre::cv::PixelBuf,
+ flags: cidre::cv::pixel_buffer::LockFlags,
+}
+
+impl<'a> PixelBufferLock<'a> {
+ fn new(
+ buffer: &'a mut cidre::cv::PixelBuf,
+ flags: cidre::cv::pixel_buffer::LockFlags,
+ ) -> cidre::os::Result<Self> {
+ unsafe { buffer.lock_base_addr(flags) }.result()?;
+ Ok(Self { buffer, flags })
+ }
+
+ fn base_address(&self) -> *const u8 {
+ unsafe { cv_pixel_buffer_get_base_address(self.buffer) as *const u8 }
+ }
+
+ fn bytes_per_row(&self) -> usize {
+ unsafe { cv_pixel_buffer_get_bytes_per_row(self.buffer) }
+ }
+
+ fn base_address_of_plane(&self, plane_index: usize) -> *const u8 {
+ unsafe { cv_pixel_buffer_get_base_address_of_plane(self.buffer, plane_index) as *const u8 }
+ }
+
+ fn bytes_per_row_of_plane(&self, plane_index: usize) -> usize {
+ unsafe { cv_pixel_buffer_get_bytes_per_row_of_plane(self.buffer, plane_index) }
+ }
+
+ fn height_of_plane(&self, plane_index: usize) -> usize {
+ unsafe { cv_pixel_buffer_get_height_of_plane(self.buffer, plane_index) }
+ }
+}
+
+impl Drop for PixelBufferLock<'_> {
+ fn drop(&mut self) {
+ unsafe {
+ let _ = self.buffer.unlock_lock_base_addr(self.flags);
+ }
+ }
+}
+
+unsafe fn cv_pixel_buffer_get_base_address(buffer: &cidre::cv::PixelBuf) -> *mut std::ffi::c_void {
+ unsafe extern "C" {
+ fn CVPixelBufferGetBaseAddress(pixel_buffer: &cidre::cv::PixelBuf)
+ -> *mut std::ffi::c_void;
+ }
+
+ unsafe { CVPixelBufferGetBaseAddress(buffer) }
+}
+
+unsafe fn cv_pixel_buffer_get_bytes_per_row(buffer: &cidre::cv::PixelBuf) -> usize {
+ unsafe extern "C" {
+ fn CVPixelBufferGetBytesPerRow(pixel_buffer: &cidre::cv::PixelBuf) -> usize;
+ }
+
+ unsafe { CVPixelBufferGetBytesPerRow(buffer) }
+}
+
+unsafe fn cv_pixel_buffer_get_base_address_of_plane(
+ buffer: &cidre::cv::PixelBuf,
+ plane_index: usize,
+) -> *mut std::ffi::c_void {
+ unsafe extern "C" {
+ fn CVPixelBufferGetBaseAddressOfPlane(
+ pixel_buffer: &cidre::cv::PixelBuf,
+ plane_index: usize,
+ ) -> *mut std::ffi::c_void;
+ }
+
+ unsafe { CVPixelBufferGetBaseAddressOfPlane(buffer, plane_index) }
+}
+
+unsafe fn cv_pixel_buffer_get_bytes_per_row_of_plane(
+ buffer: &cidre::cv::PixelBuf,
+ plane_index: usize,
+) -> usize {
+ unsafe extern "C" {
+ fn CVPixelBufferGetBytesPerRowOfPlane(
+ pixel_buffer: &cidre::cv::PixelBuf,
+ plane_index: usize,
+ ) -> usize;
+ }
+
+ unsafe { CVPixelBufferGetBytesPerRowOfPlane(buffer, plane_index) }
+}
+
+unsafe fn cv_pixel_buffer_get_height_of_plane(
+ buffer: &cidre::cv::PixelBuf,
+ plane_index: usize,
+) -> usize {
+ unsafe extern "C" {
+ fn CVPixelBufferGetHeightOfPlane(
+ pixel_buffer: &cidre::cv::PixelBuf,
+ plane_index: usize,
+ ) -> usize;
+ }
+
+ unsafe { CVPixelBufferGetHeightOfPlane(buffer, plane_index) }
+}
diff --git a/apps/desktop/src-tauri/src/thumbnails/mod.rs b/apps/desktop/src-tauri/src/thumbnails/mod.rs
new file mode 100644
index 000000000..8ae933573
--- /dev/null
+++ b/apps/desktop/src-tauri/src/thumbnails/mod.rs
@@ -0,0 +1,149 @@
+use cap_recording::sources::{list_displays, list_windows};
+use serde::{Deserialize, Serialize};
+use specta::Type;
+use tracing::*;
+
+#[cfg(windows)]
+mod windows;
+#[cfg(windows)]
+pub use windows::*;
+
+#[cfg(target_os = "macos")]
+mod mac;
+#[cfg(target_os = "macos")]
+pub use mac::*;
+
+const THUMBNAIL_WIDTH: u32 = 320;
+const THUMBNAIL_HEIGHT: u32 = 180;
+
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
+pub struct CaptureDisplayWithThumbnail {
+ pub id: scap_targets::DisplayId,
+ pub name: String,
+ pub refresh_rate: u32,
+ pub thumbnail: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
+pub struct CaptureWindowWithThumbnail {
+ pub id: scap_targets::WindowId,
+ pub owner_name: String,
+ pub name: String,
+ pub bounds: scap_targets::bounds::LogicalBounds,
+ pub refresh_rate: u32,
+ pub thumbnail: Option<String>,
+ pub app_icon: Option<String>,
+}
+
+pub fn normalize_thumbnail_dimensions(image: &image::RgbaImage) -> image::RgbaImage {
+ let width = image.width();
+ let height = image.height();
+
+ if width == THUMBNAIL_WIDTH && height == THUMBNAIL_HEIGHT {
+ return image.clone();
+ }
+
+ if width == 0 || height == 0 {
+ return image::RgbaImage::from_pixel(
+ THUMBNAIL_WIDTH,
+ THUMBNAIL_HEIGHT,
+ image::Rgba([0, 0, 0, 0]),
+ );
+ }
+
+ let scale = (THUMBNAIL_WIDTH as f32 / width as f32)
+ .min(THUMBNAIL_HEIGHT as f32 / height as f32)
+ .max(f32::MIN_POSITIVE);
+
+ let scaled_width = (width as f32 * scale)
+ .round()
+ .clamp(1.0, THUMBNAIL_WIDTH as f32) as u32;
+ let scaled_height = (height as f32 * scale)
+ .round()
+ .clamp(1.0, THUMBNAIL_HEIGHT as f32) as u32;
+
+ let resized = image::imageops::resize(
+ image,
+ scaled_width.max(1),
+ scaled_height.max(1),
+ image::imageops::FilterType::Lanczos3,
+ );
+
+ let mut canvas =
+ image::RgbaImage::from_pixel(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, image::Rgba([0, 0, 0, 0]));
+
+ let offset_x = (THUMBNAIL_WIDTH - scaled_width) / 2;
+ let offset_y = (THUMBNAIL_HEIGHT - scaled_height) / 2;
+
+ image::imageops::overlay(&mut canvas, &resized, offset_x as i64, offset_y as i64);
+
+ canvas
+}
+
+pub async fn collect_displays_with_thumbnails() -> Result<Vec<CaptureDisplayWithThumbnail>, String>
+{
+ let displays = list_displays();
+
+ let mut results = Vec::new();
+ for (capture_display, display) in displays {
+ let thumbnail = capture_display_thumbnail(&display).await;
+ results.push(CaptureDisplayWithThumbnail {
+ id: capture_display.id,
+ name: capture_display.name,
+ refresh_rate: capture_display.refresh_rate,
+ thumbnail,
+ });
+ }
+
+ Ok(results)
+}
+
+pub async fn collect_windows_with_thumbnails() -> Result<Vec<CaptureWindowWithThumbnail>, String> {
+ let windows = list_windows();
+
+ debug!(window_count = windows.len(), "Collecting window thumbnails");
+ let mut results = Vec::new();
+ for (capture_window, window) in windows {
+ let thumbnail = capture_window_thumbnail(&window).await;
+ let app_icon = window.app_icon().and_then(|bytes| {
+ if bytes.is_empty() {
+ None
+ } else {
+ Some(base64::Engine::encode(
+ &base64::engine::general_purpose::STANDARD,
+ bytes,
+ ))
+ }
+ });
+
+ if thumbnail.is_none() {
+ warn!(
+ window_id = ?capture_window.id,
+ window_name = %capture_window.name,
+ owner_name = %capture_window.owner_name,
+ "Window thumbnail capture returned None",
+ );
+ } else {
+ debug!(
+ window_id = ?capture_window.id,
+ window_name = %capture_window.name,
+ owner_name = %capture_window.owner_name,
+ "Captured window thumbnail",
+ );
+ }
+
+ results.push(CaptureWindowWithThumbnail {
+ id: capture_window.id,
+ name: capture_window.name,
+ owner_name: capture_window.owner_name,
+ bounds: capture_window.bounds,
+ refresh_rate: capture_window.refresh_rate,
+ thumbnail,
+ app_icon,
+ });
+ }
+
+ info!(windows = results.len(), "Collected window thumbnail data");
+
+ Ok(results)
+}
diff --git a/apps/desktop/src-tauri/src/thumbnails/windows.rs b/apps/desktop/src-tauri/src/thumbnails/windows.rs
new file mode 100644
index 000000000..ec6307b3d
--- /dev/null
+++ b/apps/desktop/src-tauri/src/thumbnails/windows.rs
@@ -0,0 +1,279 @@
+use super::*;
+
+pub async fn capture_display_thumbnail(display: &scap_targets::Display) -> Option<String> {
+ use image::{ColorType, ImageEncoder, codecs::png::PngEncoder};
+ use scap_direct3d::{Capturer, Settings};
+ use std::io::Cursor;
+
+ let item = display.raw_handle().try_as_capture_item().ok()?;
+
+ let (tx, rx) = std::sync::mpsc::channel();
+
+ let settings = Settings {
+ is_cursor_capture_enabled: Some(false),
+ pixel_format: scap_direct3d::PixelFormat::R8G8B8A8Unorm,
+ ..Default::default()
+ };
+
+ let mut capturer = Capturer::new(
+ item,
+ settings.clone(),
+ move |frame| {
+ let _ = tx.send(frame);
+ Ok(())
+ },
+ || Ok(()),
+ None,
+ )
+ .ok()?;
+
+ capturer.start().ok()?;
+
+ let frame = rx.recv_timeout(std::time::Duration::from_secs(2)).ok()?;
+ let _ = capturer.stop();
+
+ let width = frame.width();
+ let height = frame.height();
+
+ if width == 0 || height == 0 {
+ return None;
+ }
+
+ let frame_buffer = frame.as_buffer().ok()?;
+ let data = frame_buffer.data();
+ let stride = frame_buffer.stride() as usize;
+
+ let width_usize = width as usize;
+ let height_usize = height as usize;
+
+ let Some(row_bytes) = width_usize.checked_mul(4) else {
+ warn!(
+ frame_width = width,
+ "Windows display thumbnail row size overflowed"
+ );
+ return None;
+ };
+
+ if stride < row_bytes {
+ warn!(
+ frame_width = width,
+ frame_height = height,
+ stride,
+ expected_row_bytes = row_bytes,
+ "Windows display thumbnail stride smaller than row size"
+ );
+ return None;
+ }
+
+ let rows_before_last = height_usize.saturating_sub(1);
+ let Some(last_row_start) = rows_before_last.checked_mul(stride) else {
+ warn!(
+ frame_width = width,
+ frame_height = height,
+ stride,
+ "Windows display thumbnail row offset overflowed"
+ );
+ return None;
+ };
+
+ let Some(required_len) = last_row_start.checked_add(row_bytes) else {
+ warn!(
+ frame_width = width,
+ frame_height = height,
+ stride,
+ required_row_bytes = row_bytes,
+ "Windows display thumbnail required length overflowed"
+ );
+ return None;
+ };
+
+ if data.len() < required_len {
+ warn!(
+ frame_width = width,
+ frame_height = height,
+ stride,
+ frame_data_len = data.len(),
+ expected_len = required_len,
+ "Windows display thumbnail frame buffer missing pixel data"
+ );
+ return None;
+ }
+
+ let Some(rgba_capacity) = height_usize.checked_mul(row_bytes) else {
+ warn!(
+ frame_width = width,
+ frame_height = height,
+ total_row_bytes = row_bytes,
+ "Windows display thumbnail RGBA capacity overflowed"
+ );
+ return None;
+ };
+
+ let mut rgba_data = Vec::with_capacity(rgba_capacity);
+ for y in 0..height_usize {
+ let row_start = y * stride;
+ let row_end = row_start + row_bytes;
+ rgba_data.extend_from_slice(&data[row_start..row_end]);
+ }
+
+ let Some(img) = image::RgbaImage::from_raw(width, height, rgba_data) else {
+ warn!("Windows display thumbnail failed to construct RGBA image");
+ return None;
+ };
+ let thumbnail = normalize_thumbnail_dimensions(&img);
+
+ let mut png_data = Cursor::new(Vec::new());
+ let encoder = PngEncoder::new(&mut png_data);
+ encoder
+ .write_image(
+ thumbnail.as_raw(),
+ thumbnail.width(),
+ thumbnail.height(),
+ ColorType::Rgba8.into(),
+ )
+ .ok()?;
+
+ Some(base64::Engine::encode(
+ &base64::engine::general_purpose::STANDARD,
+ png_data.into_inner(),
+ ))
+}
+
+pub async fn capture_window_thumbnail(window: &scap_targets::Window) -> Option<String> {
+ use image::{ColorType, ImageEncoder, codecs::png::PngEncoder};
+ use scap_direct3d::{Capturer, Settings};
+ use std::io::Cursor;
+
+ let item = window.raw_handle().try_as_capture_item().ok()?;
+
+ let (tx, rx) = std::sync::mpsc::channel();
+
+ let settings = Settings {
+ is_cursor_capture_enabled: Some(false),
+ pixel_format: scap_direct3d::PixelFormat::R8G8B8A8Unorm,
+ ..Default::default()
+ };
+
+ let mut capturer = Capturer::new(
+ item,
+ settings.clone(),
+ move |frame| {
+ let _ = tx.send(frame);
+ Ok(())
+ },
+ || Ok(()),
+ None,
+ )
+ .ok()?;
+
+ capturer.start().ok()?;
+
+ let frame = rx.recv_timeout(std::time::Duration::from_secs(2)).ok()?;
+ let _ = capturer.stop();
+
+ let width = frame.width();
+ let height = frame.height();
+
+ if width == 0 || height == 0 {
+ return None;
+ }
+
+ let frame_buffer = frame.as_buffer().ok()?;
+ let data = frame_buffer.data();
+ let stride = frame_buffer.stride() as usize;
+
+ let width_usize = width as usize;
+ let height_usize = height as usize;
+
+ let Some(row_bytes) = width_usize.checked_mul(4) else {
+ warn!(
+ frame_width = width,
+ "Windows window thumbnail row size overflowed"
+ );
+ return None;
+ };
+
+ if stride < row_bytes {
+ warn!(
+ frame_width = width,
+ frame_height = height,
+ stride,
+ expected_row_bytes = row_bytes,
+ "Windows window thumbnail stride smaller than row size"
+ );
+ return None;
+ }
+
+ let rows_before_last = height_usize.saturating_sub(1);
+ let Some(last_row_start) = rows_before_last.checked_mul(stride) else {
+ warn!(
+ frame_width = width,
+ frame_height = height,
+ stride,
+ "Windows window thumbnail row offset overflowed"
+ );
+ return None;
+ };
+
+ let Some(required_len) = last_row_start.checked_add(row_bytes) else {
+ warn!(
+ frame_width = width,
+ frame_height = height,
+ stride,
+ required_row_bytes = row_bytes,
+ "Windows window thumbnail required length overflowed"
+ );
+ return None;
+ };
+
+ if data.len() < required_len {
+ warn!(
+ frame_width = width,
+ frame_height = height,
+ stride,
+ frame_data_len = data.len(),
+ expected_len = required_len,
+ "Windows window thumbnail frame buffer missing pixel data"
+ );
+ return None;
+ }
+
+ let Some(rgba_capacity) = height_usize.checked_mul(row_bytes) else {
+ warn!(
+ frame_width = width,
+ frame_height = height,
+ total_row_bytes = row_bytes,
+ "Windows window thumbnail RGBA capacity overflowed"
+ );
+ return None;
+ };
+
+ let mut rgba_data = Vec::with_capacity(rgba_capacity);
+ for y in 0..height_usize {
+ let row_start = y * stride;
+ let row_end = row_start + row_bytes;
+ rgba_data.extend_from_slice(&data[row_start..row_end]);
+ }
+
+ let Some(img) = image::RgbaImage::from_raw(width, height, rgba_data) else {
+ warn!("Windows window thumbnail failed to construct RGBA image");
+ return None;
+ };
+ let thumbnail = normalize_thumbnail_dimensions(&img);
+
+ let mut png_data = Cursor::new(Vec::new());
+ let encoder = PngEncoder::new(&mut png_data);
+ encoder
+ .write_image(
+ thumbnail.as_raw(),
+ thumbnail.width(),
+ thumbnail.height(),
+ ColorType::Rgba8.into(),
+ )
+ .ok()?;
+
+ Some(base64::Engine::encode(
+ &base64::engine::general_purpose::STANDARD,
+ png_data.into_inner(),
+ ))
+}
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index 7393305c2..7079cf7b9 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -16,11 +16,12 @@ use tauri::{
AppHandle, LogicalPosition, Manager, Monitor, PhysicalPosition, PhysicalSize, WebviewUrl,
WebviewWindow, WebviewWindowBuilder, Wry,
};
+use tauri_specta::Event;
use tokio::sync::RwLock;
-use tracing::{debug, error};
+use tracing::{debug, error, warn};
use crate::{
- App, ArcLock, fake_window,
+ App, ArcLock, RequestScreenCapturePrewarm, fake_window,
general_settings::{AppTheme, GeneralSettingsStore},
permissions,
recording_settings::RecordingTargetMode,
@@ -274,6 +275,20 @@ impl ShowCapWindow {
crate::platform::set_window_level(window.as_ref().window(), 50);
}
+ #[cfg(target_os = "macos")]
+ {
+ let app_handle = app.clone();
+ tauri::async_runtime::spawn(async move {
+ let prewarmer =
+ app_handle.state::<crate::platform::ScreenCapturePrewarmer>();
+ prewarmer.request(false).await;
+ });
+
+ if let Err(error) = (RequestScreenCapturePrewarm { force: false }).emit(app) {
+ warn!(%error, "Failed to emit ScreenCaptureKit prewarm event");
+ }
+ }
+
window
}
Self::TargetSelectOverlay { display_id } => {
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 64aa541a2..14ad46d54 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -299,6 +299,7 @@ renderFrameEvent: RenderFrameEvent,
requestNewScreenshot: RequestNewScreenshot,
requestOpenRecordingPicker: RequestOpenRecordingPicker,
requestOpenSettings: RequestOpenSettings,
+requestScreenCapturePrewarm: RequestScreenCapturePrewarm,
requestStartRecording: RequestStartRecording,
targetUnderCursor: TargetUnderCursor
}>({
@@ -320,6 +321,7 @@ renderFrameEvent: "render-frame-event",
requestNewScreenshot: "request-new-screenshot",
requestOpenRecordingPicker: "request-open-recording-picker",
requestOpenSettings: "request-open-settings",
+requestScreenCapturePrewarm: "request-screen-capture-prewarm",
requestStartRecording: "request-start-recording",
targetUnderCursor: "target-under-cursor"
})
@@ -443,6 +445,7 @@ export type RenderFrameEvent = { frame_number: number; fps: number; resolution_b
export type RequestNewScreenshot = null
export type RequestOpenRecordingPicker = { target_mode: RecordingTargetMode | null }
export type RequestOpenSettings = { page: string }
+export type RequestScreenCapturePrewarm = { force?: boolean }
export type RequestStartRecording = { mode: RecordingMode }
export type S3UploadMeta = { id: string }
export type SceneMode = "default" | "cameraOnly" | "hideCamera"
diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rs
index 39a98810a..2bf54f9b7 100644
--- a/crates/recording/src/capture_pipeline.rs
+++ b/crates/recording/src/capture_pipeline.rs
@@ -795,6 +795,7 @@ pub async fn create_screen_capture(
audio_tx: Option<Sender<(ffmpeg::frame::Audio, Timestamp)>>,
start_time: SystemTime,
#[cfg(windows)] d3d_device: ::windows::Win32::Graphics::Direct3D11::ID3D11Device,
+ #[cfg(target_os = "macos")] shareable_content: cidre::arc::R<cidre::sc::ShareableContent>,
) -> Result<ScreenCaptureReturn<ScreenCaptureMethod>, RecordingError> {
let (video_tx, video_rx) = flume::bounded(16);
@@ -808,6 +809,8 @@ pub async fn create_screen_capture(
tokio::runtime::Handle::current(),
#[cfg(windows)]
d3d_device,
+ #[cfg(target_os = "macos")]
+ shareable_content,
)
.await
.map(|v| (v, video_rx))
diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rs
index 187546257..dab814e62 100644
--- a/crates/recording/src/instant_recording.rs
+++ b/crates/recording/src/instant_recording.rs
@@ -185,6 +185,7 @@ impl ActorBuilder {
pub async fn build(
self,
+ #[cfg(target_os = "macos")] shareable_content: cidre::arc::R<cidre::sc::ShareableContent>,
) -> Result<(ActorHandle, oneshot::Receiver<Result<(), String>>), RecordingError> {
spawn_instant_recording_actor(
self.output_path,
@@ -193,6 +194,8 @@ impl ActorBuilder {
capture_system_audio: self.system_audio,
mic_feed: self.mic_feed,
camera_feed: None,
+ #[cfg(target_os = "macos")]
+ shareable_content,
},
)
.await
@@ -238,6 +241,8 @@ pub async fn spawn_instant_recording_actor(
start_time,
#[cfg(windows)]
d3d_device,
+ #[cfg(target_os = "macos")]
+ inputs.shareable_content.retained(),
)
.await?;
diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rs
index 9d48389de..671ac21ac 100644
--- a/crates/recording/src/lib.rs
+++ b/crates/recording/src/lib.rs
@@ -45,6 +45,8 @@ pub struct RecordingBaseInputs {
pub capture_system_audio: bool,
pub mic_feed: Option<Arc<MicrophoneFeedLock>>,
pub camera_feed: Option<Arc<CameraFeedLock>>,
+ #[cfg(target_os = "macos")]
+ pub shareable_content: cidre::arc::R<cidre::sc::ShareableContent>,
}
#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
diff --git a/crates/recording/src/pipeline/builder.rs b/crates/recording/src/pipeline/builder.rs
index cb3972b1b..01fee9b08 100644
--- a/crates/recording/src/pipeline/builder.rs
+++ b/crates/recording/src/pipeline/builder.rs
@@ -122,10 +122,14 @@ impl PipelineBuilder {
// TODO: Shut down tasks if launch failed.
for (name, task) in tasks.into_iter() {
// TODO: Wait for these in parallel?
- tokio::time::timeout(Duration::from_secs(5), task.ready_signal.recv_async())
- .await
- .map_err(|_| MediaError::TaskLaunch(format!("task timed out: '{name}'")))?
- .map_err(|e| MediaError::TaskLaunch(format!("'{name}' build / {e}")))??;
+ let launch_timeout = if cfg!(target_os = "macos") { 15 } else { 5 };
+ tokio::time::timeout(
+ Duration::from_secs(launch_timeout),
+ task.ready_signal.recv_async(),
+ )
+ .await
+ .map_err(|_| MediaError::TaskLaunch(format!("task timed out: '{name}'")))?
+ .map_err(|e| MediaError::TaskLaunch(format!("'{name}' build / {e}")))??;
task_handles.insert(name.clone(), task.join_handle);
stop_rx.push(task.done_rx);
diff --git a/crates/recording/src/sources/screen_capture/macos.rs b/crates/recording/src/sources/screen_capture/macos.rs
index 0f21084d7..53f976d80 100644
--- a/crates/recording/src/sources/screen_capture/macos.rs
+++ b/crates/recording/src/sources/screen_capture/macos.rs
@@ -128,6 +128,7 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
let video_tx = self.video_tx.clone();
let audio_tx = self.audio_tx.clone();
let config = self.config.clone();
+ let shareable_content = self.shareable_content.clone();
self.tokio_handle
.block_on(async move {
@@ -139,7 +140,7 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
let content_filter = display
.raw_handle()
- .as_content_filter()
+ .as_content_filter(shareable_content)
.await
.ok_or_else(|| SourceError::AsContentFilter)?;
diff --git a/crates/recording/src/sources/screen_capture/mod.rs b/crates/recording/src/sources/screen_capture/mod.rs
index b0a95525b..7e438ca57 100644
--- a/crates/recording/src/sources/screen_capture/mod.rs
+++ b/crates/recording/src/sources/screen_capture/mod.rs
@@ -199,6 +199,8 @@ pub struct ScreenCaptureSource<TCaptureFormat: ScreenCaptureFormat> {
_phantom: std::marker::PhantomData<TCaptureFormat>,
#[cfg(windows)]
d3d_device: ::windows::Win32::Graphics::Direct3D11::ID3D11Device,
+ #[cfg(target_os = "macos")]
+ shareable_content: cidre::arc::R<cidre::sc::ShareableContent>,
}
impl<T: ScreenCaptureFormat> std::fmt::Debug for ScreenCaptureSource<T> {
@@ -239,6 +241,8 @@ impl<TCaptureFormat: ScreenCaptureFormat> Clone for ScreenCaptureSource<TCapture
_phantom: std::marker::PhantomData,
#[cfg(windows)]
d3d_device: self.d3d_device.clone(),
+ #[cfg(target_os = "macos")]
+ shareable_content: self.shareable_content.clone(),
}
}
}
@@ -281,6 +285,7 @@ impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
start_time: SystemTime,
tokio_handle: tokio::runtime::Handle,
#[cfg(windows)] d3d_device: ::windows::Win32::Graphics::Direct3D11::ID3D11Device,
+ #[cfg(target_os = "macos")] shareable_content: cidre::arc::R<cidre::sc::ShareableContent>,
) -> Result<Self, ScreenCaptureInitError> {
cap_fail::fail!("ScreenCaptureSource::init");
@@ -407,6 +412,8 @@ impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
_phantom: std::marker::PhantomData,
#[cfg(windows)]
d3d_device,
+ #[cfg(target_os = "macos")]
+ shareable_content: shareable_content.retained(),
})
}
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index 3aefa361c..f50bf4bff 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -174,6 +174,7 @@ impl ActorBuilder {
pub async fn build(
self,
+ #[cfg(target_os = "macos")] shareable_content: cidre::arc::R<cidre::sc::ShareableContent>,
) -> Result<(ActorHandle, oneshot::Receiver<Result<(), String>>), SpawnError> {
spawn_studio_recording_actor(
self.output_path,
@@ -182,6 +183,8 @@ impl ActorBuilder {
capture_system_audio: self.system_audio,
mic_feed: self.mic_feed,
camera_feed: self.camera_feed,
+ #[cfg(target_os = "macos")]
+ shareable_content,
},
self.custom_cursor,
)
@@ -657,10 +660,7 @@ impl SegmentPipelineFactory {
&self.segments_dir,
&self.cursors_dir,
self.index,
- self.base_inputs.capture_target.clone(),
- self.base_inputs.mic_feed.clone(),
- self.base_inputs.capture_system_audio,
- self.base_inputs.camera_feed.clone(),
+ self.base_inputs.clone(),
cursors,
next_cursors_id,
self.custom_cursor_capture,
@@ -698,26 +698,25 @@ async fn create_segment_pipeline(
segments_dir: &PathBuf,
cursors_dir: &Path,
index: u32,
- capture_target: ScreenCaptureTarget,
- mic_feed: Option<Arc<MicrophoneFeedLock>>,
- capture_system_audio: bool,
- camera_feed: Option<Arc<CameraFeedLock>>,
+ base_inputs: RecordingBaseInputs,
prev_cursors: Cursors,
next_cursors_id: u32,
custom_cursor_capture: bool,
start_time: Timestamps,
) -> Result<(Pipeline, oneshot::Receiver<Result<(), String>>), CreateSegmentPipelineError> {
- let system_audio = if capture_system_audio {
+ let system_audio = if base_inputs.capture_system_audio {
let (tx, rx) = flume::bounded(64);
(Some(tx), Some(rx))
} else {
(None, None)
};
- let display = capture_target
+ let display = base_inputs
+ .capture_target
.display()
.ok_or(CreateSegmentPipelineError::NoDisplay)?;
- let crop_bounds = capture_target
+ let crop_bounds = base_inputs
+ .capture_target
.cursor_crop()
.ok_or(CreateSegmentPipelineError::NoBounds)?;
@@ -725,13 +724,15 @@ async fn create_segment_pipeline(
let d3d_device = crate::capture_pipeline::create_d3d_device().unwrap();
let (screen_source, screen_rx) = create_screen_capture(
- &capture_target,
+ &base_inputs.capture_target,
!custom_cursor_capture,
120,
system_audio.0,
start_time.system_time(),
#[cfg(windows)]
d3d_device,
+ #[cfg(target_os = "macos")]
+ base_inputs.shareable_content,
)
.await
.unwrap();
@@ -774,7 +775,7 @@ async fn create_segment_pipeline(
}
};
- let microphone = if let Some(mic_feed) = mic_feed {
+ let microphone = if let Some(mic_feed) = base_inputs.mic_feed {
let (tx, channel) = flume::bounded(8);
let mic_source = AudioInputSource::init(mic_feed, tx);
@@ -879,7 +880,7 @@ async fn create_segment_pipeline(
None
};
- let camera = if let Some(camera_feed) = camera_feed {
+ let camera = if let Some(camera_feed) = base_inputs.camera_feed {
let (tx, channel) = flume::bounded(8);
let camera_source = CameraSource::init(camera_feed, tx);
diff --git a/crates/scap-targets/Cargo.toml b/crates/scap-targets/Cargo.toml
index ae15fdd82..2f35517cd 100644
--- a/crates/scap-targets/Cargo.toml
+++ b/crates/scap-targets/Cargo.toml
@@ -18,6 +18,7 @@ core-graphics = "0.24.0"
core-foundation = "0.10.0"
cocoa = "0.26.0"
objc = "0.2.7"
+tokio = { workspace = true, features = ["sync", "rt"] }
[target.'cfg(target_os = "windows")'.dependencies]
windows = { workspace = true, features = [
diff --git a/crates/scap-targets/src/platform/macos.rs b/crates/scap-targets/src/platform/macos.rs
index a04e4c75c..820101415 100644
--- a/crates/scap-targets/src/platform/macos.rs
+++ b/crates/scap-targets/src/platform/macos.rs
@@ -20,6 +20,7 @@ use core_graphics::{
};
use crate::bounds::{LogicalBounds, LogicalPosition, LogicalSize, PhysicalSize};
+use tracing::trace;
#[derive(Clone, Copy)]
pub struct DisplayImpl(CGDisplay);
@@ -178,30 +179,39 @@ impl DisplayImpl {
}
impl DisplayImpl {
- pub async fn as_sc(&self) -> Option<arc::R<sc::Display>> {
- sc::ShareableContent::current()
- .await
- .ok()?
+ pub async fn as_sc(
+ &self,
+ content: arc::R<sc::ShareableContent>,
+ ) -> Option<arc::R<sc::Display>> {
+ content
.displays()
.iter()
- .find(|d| d.display_id().0 == self.0.id)
- .map(|v| v.retained())
+ .find(|display| display.display_id().0 == self.0.id)
+ .map(|display| display.retained())
}
- pub async fn as_content_filter(&self) -> Option<arc::R<sc::ContentFilter>> {
- self.as_content_filter_excluding_windows(vec![]).await
+ pub async fn as_content_filter(
+ &self,
+ content: arc::R<sc::ShareableContent>,
+ ) -> Option<arc::R<sc::ContentFilter>> {
+ self.as_content_filter_excluding_windows(content, vec![])
+ .await
}
pub async fn as_content_filter_excluding_windows(
&self,
+ content: arc::R<sc::ShareableContent>,
windows: Vec<arc::R<sc::Window>>,
) -> Option<arc::R<sc::ContentFilter>> {
- let excluded_windows =
- ns::Array::from_slice_retained(windows.into_iter().collect::<Vec<_>>().as_slice());
+ let display = content
+ .displays()
+ .iter()
+ .find(|display| display.display_id().0 == self.0.id)
+ .map(|display| display.retained())?;
Some(sc::ContentFilter::with_display_excluding_windows(
- self.as_sc().await?.as_ref(),
- &excluded_windows,
+ display.as_ref(),
+ &ns::Array::from_slice_retained(&windows),
))
}
}
@@ -469,14 +479,12 @@ impl WindowImpl {
}
}
- pub async fn as_sc(&self) -> Option<arc::R<sc::Window>> {
- sc::ShareableContent::current()
- .await
- .ok()?
+ pub async fn as_sc(&self, content: arc::R<sc::ShareableContent>) -> Option<arc::R<sc::Window>> {
+ content
.windows()
.iter()
- .find(|w| w.id() == self.0)
- .map(|v| v.retained())
+ .find(|window| window.id() == self.0)
+ .map(|window| window.retained())
}
pub fn display(&self) -> Option<DisplayImpl> {
diff --git a/crates/scap-targets/src/platform/mod.rs b/crates/scap-targets/src/platform/mod.rs
index bfe03249b..07dff2afe 100644
--- a/crates/scap-targets/src/platform/mod.rs
+++ b/crates/scap-targets/src/platform/mod.rs
@@ -1,5 +1,5 @@
#[cfg(target_os = "macos")]
-mod macos;
+pub mod macos;
#[cfg(target_os = "macos")]
pub use macos::*;