Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add zero-copy Metal IOSurface NV12 support on macOS

Richie McIlroy33625f0c280e
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index 4eb7da12a..2e45d6b64 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -39,7 +39,9 @@
"Bash(echo:*)",
"Bash(pnpm exec biome:*)",
"Bash(rustfmt:*)",
- "Bash(cargo tree:*)"
+ "Bash(cargo tree:*)",
+ "WebFetch(domain:github.com)",
+ "WebFetch(domain:docs.rs)"
],
"deny": [],
"ask": []
diff --git a/Cargo.lock b/Cargo.lock
index 1a53b3545..4fc058cb1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1583,11 +1583,14 @@ dependencies = [
"clap",
"ffmpeg-hw-device",
"ffmpeg-next",
+ "foreign-types 0.5.0",
"futures",
"futures-intrusive",
"glyphon",
"image 0.25.8",
"log",
+ "metal 0.31.0",
+ "objc2 0.6.2",
"pretty_assertions",
"reactive_graph",
"resvg",
@@ -1599,6 +1602,8 @@ dependencies = [
"tokio",
"tracing",
"wgpu",
+ "wgpu-core",
+ "wgpu-hal",
"workspace-hack",
]
diff --git a/Cargo.toml b/Cargo.toml
index e0350317c..61e8ab20f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -37,7 +37,9 @@ nokhwa = { git = "https://github.com/CapSoftware/nokhwa", rev = "b9c8079e82e2",
"serialize",
] }
nokhwa-bindings-macos = { git = "https://github.com/CapSoftware/nokhwa", rev = "b9c8079e82e2" }
-wgpu = "25.0.0"
+wgpu = { version = "25.0.0", features = ["wgpu-core"] }
+wgpu-hal = "25.0.0"
+wgpu-core = "25.0.0"
flume = "0.11.0"
thiserror = "1.0"
sentry = { version = "0.42.0", features = [
@@ -53,12 +55,15 @@ cidre = { git = "https://github.com/CapSoftware/cidre", rev = "bf84b67079a8", fe
"macos_12_7",
"cv",
"cf",
+ "cg",
"core_audio",
"sc",
"av",
"blocks",
"async",
"dispatch",
+ "io_surface",
+ "mtl",
], default-features = false }
windows = "0.60.0"
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index a964cf3e4..a79674993 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -31,6 +31,7 @@ use regex::Regex;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::borrow::Cow;
+#[cfg(target_os = "macos")]
use std::error::Error as StdError;
use std::{
any::Any,
@@ -47,6 +48,8 @@ use tauri_specta::Event;
use tracing::*;
use crate::camera::{CameraPreviewManager, CameraPreviewShape};
+#[cfg(target_os = "macos")]
+use crate::general_settings;
use crate::web_api::AuthedApiError;
use crate::{
App, CurrentRecordingChanged, MutableState, NewStudioRecordingAdded, RecordingState,
@@ -55,9 +58,7 @@ use crate::{
audio::AppSounds,
auth::AuthStore,
create_screenshot,
- general_settings::{
- self, GeneralSettingsStore, PostDeletionBehaviour, PostStudioRecordingBehaviour,
- },
+ general_settings::{GeneralSettingsStore, PostDeletionBehaviour, PostStudioRecordingBehaviour},
open_external_link,
presets::PresetsStore,
thumbnails::*,
diff --git a/apps/desktop/src-tauri/src/target_select_overlay.rs b/apps/desktop/src-tauri/src/target_select_overlay.rs
index f72949c09..e41efe5e9 100644
--- a/apps/desktop/src-tauri/src/target_select_overlay.rs
+++ b/apps/desktop/src-tauri/src/target_select_overlay.rs
@@ -138,7 +138,7 @@ fn should_skip_window(window: &Window, exclusions: &[WindowExclusion]) -> bool {
let bundle_identifier = window.raw_handle().bundle_identifier();
#[cfg(not(target_os = "macos"))]
- let bundle_identifier = None::<&str>;
+ let bundle_identifier = None::<String>;
exclusions.iter().any(|entry| {
entry.matches(
diff --git a/apps/desktop/src-tauri/src/window_exclusion.rs b/apps/desktop/src-tauri/src/window_exclusion.rs
index 67fc1c1e1..1a6f9e597 100644
--- a/apps/desktop/src-tauri/src/window_exclusion.rs
+++ b/apps/desktop/src-tauri/src/window_exclusion.rs
@@ -1,3 +1,4 @@
+#[cfg(target_os = "macos")]
use scap_targets::{Window, WindowId};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -61,6 +62,7 @@ impl WindowExclusion {
}
}
+#[cfg(target_os = "macos")]
pub fn resolve_window_ids(exclusions: &[WindowExclusion]) -> Vec<WindowId> {
if exclusions.is_empty() {
return Vec::new();
@@ -71,13 +73,8 @@ pub fn resolve_window_ids(exclusions: &[WindowExclusion]) -> Vec<WindowId> {
.filter_map(|window| {
let owner_name = window.owner_name();
let window_title = window.name();
-
- #[cfg(target_os = "macos")]
let bundle_identifier = window.raw_handle().bundle_identifier();
- #[cfg(not(target_os = "macos"))]
- let bundle_identifier = None::<&str>;
-
exclusions
.iter()
.find(|entry| {
diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts
index db8a4313b..7ab29a7ab 100644
--- a/apps/desktop/src/routes/editor/context.ts
+++ b/apps/desktop/src/routes/editor/context.ts
@@ -52,7 +52,7 @@ export type CurrentDialog =
export type DialogState = { open: false } | ({ open: boolean } & CurrentDialog);
-export const FPS = 30;
+export const FPS = 60;
export const OUTPUT_SIZE = {
x: 1920,
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index 4ee460611..95ea663cd 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -36,6 +36,11 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[target.'cfg(target_os = "macos")'.dependencies]
cidre.workspace = true
+metal = "0.31"
+objc2 = "0.6"
+wgpu-hal = { workspace = true, features = ["metal"] }
+wgpu-core.workspace = true
+foreign-types = "0.5"
[dev-dependencies]
pretty_assertions = "1.4.1"
diff --git a/crates/rendering/src/decoder/avassetreader.rs b/crates/rendering/src/decoder/avassetreader.rs
index 1a723d87e..0503c474b 100644
--- a/crates/rendering/src/decoder/avassetreader.rs
+++ b/crates/rendering/src/decoder/avassetreader.rs
@@ -29,19 +29,33 @@ struct ProcessedFrame {
format: PixelFormat,
y_stride: u32,
uv_stride: u32,
+ image_buf: Option<R<cv::ImageBuf>>,
}
impl ProcessedFrame {
fn to_decoded_frame(&self) -> DecodedFrame {
match self.format {
PixelFormat::Rgba => DecodedFrame::new((*self.data).clone(), self.width, self.height),
- PixelFormat::Nv12 => DecodedFrame::new_nv12(
- (*self.data).clone(),
- self.width,
- self.height,
- self.y_stride,
- self.uv_stride,
- ),
+ PixelFormat::Nv12 => {
+ if let Some(image_buf) = &self.image_buf {
+ DecodedFrame::new_nv12_with_iosurface(
+ (*self.data).clone(),
+ self.width,
+ self.height,
+ self.y_stride,
+ self.uv_stride,
+ image_buf.retained(),
+ )
+ } else {
+ DecodedFrame::new_nv12(
+ (*self.data).clone(),
+ self.width,
+ self.height,
+ self.y_stride,
+ self.uv_stride,
+ )
+ }
+ }
PixelFormat::Yuv420p => DecodedFrame::new_yuv420p(
(*self.data).clone(),
self.width,
@@ -91,91 +105,72 @@ impl ImageBufProcessor {
(bytes, PixelFormat::Rgba, width as u32 * 4, 0)
}
format::Pixel::NV12 => {
- let width = image_buf.width();
- let height = image_buf.height();
let y_stride = image_buf.plane_bytes_per_row(0);
let uv_stride = image_buf.plane_bytes_per_row(1);
let y_height = image_buf.plane_height(0);
let uv_height = image_buf.plane_height(1);
+ let y_size = y_stride * y_height;
+ let uv_size = uv_stride * uv_height;
+
let y_slice = unsafe {
std::slice::from_raw_parts::<'static, _>(
image_buf.plane_base_address(0),
- y_stride * y_height,
+ y_size,
)
};
let uv_slice = unsafe {
std::slice::from_raw_parts::<'static, _>(
image_buf.plane_base_address(1),
- uv_stride * uv_height,
+ uv_size,
)
};
- let mut data = Vec::with_capacity(width * height + width * height / 2);
- for row in 0..y_height {
- let start = row * y_stride;
- let end = start + width;
- data.extend_from_slice(&y_slice[start..end]);
- }
- for row in 0..uv_height {
- let start = row * uv_stride;
- let end = start + width;
- data.extend_from_slice(&uv_slice[start..end]);
- }
+ let mut data = Vec::with_capacity(y_size + uv_size);
+ data.extend_from_slice(y_slice);
+ data.extend_from_slice(uv_slice);
- (data, PixelFormat::Nv12, width as u32, width as u32)
+ (data, PixelFormat::Nv12, y_stride as u32, uv_stride as u32)
}
format::Pixel::YUV420P => {
- let width = image_buf.width();
- let height = image_buf.height();
let y_stride = image_buf.plane_bytes_per_row(0);
let u_stride = image_buf.plane_bytes_per_row(1);
let v_stride = image_buf.plane_bytes_per_row(2);
let y_height = image_buf.plane_height(0);
let uv_height = image_buf.plane_height(1);
+ let y_size = y_stride * y_height;
+ let u_size = u_stride * uv_height;
+ let v_size = v_stride * uv_height;
+
let y_slice = unsafe {
std::slice::from_raw_parts::<'static, _>(
image_buf.plane_base_address(0),
- y_stride * y_height,
+ y_size,
)
};
let u_slice = unsafe {
std::slice::from_raw_parts::<'static, _>(
image_buf.plane_base_address(1),
- u_stride * uv_height,
+ u_size,
)
};
let v_slice = unsafe {
std::slice::from_raw_parts::<'static, _>(
image_buf.plane_base_address(2),
- v_stride * uv_height,
+ v_size,
)
};
- let half_width = width / 2;
- let mut data = Vec::with_capacity(width * height + half_width * uv_height * 2);
+ let mut data = Vec::with_capacity(y_size + u_size + v_size);
+ data.extend_from_slice(y_slice);
+ data.extend_from_slice(u_slice);
+ data.extend_from_slice(v_slice);
- for row in 0..y_height {
- let start = row * y_stride;
- let end = start + width;
- data.extend_from_slice(&y_slice[start..end]);
- }
- for row in 0..uv_height {
- let start = row * u_stride;
- let end = start + half_width;
- data.extend_from_slice(&u_slice[start..end]);
- }
- for row in 0..uv_height {
- let start = row * v_stride;
- let end = start + half_width;
- data.extend_from_slice(&v_slice[start..end]);
- }
-
- (data, PixelFormat::Yuv420p, width as u32, half_width as u32)
+ (data, PixelFormat::Yuv420p, y_stride as u32, u_stride as u32)
}
_ => {
let width = image_buf.width();
@@ -197,6 +192,8 @@ impl CachedFrame {
let height = image_buf.height() as u32;
let (data, format, y_stride, uv_stride) = processor.extract_raw(&mut image_buf);
+ let retain_iosurface = format == PixelFormat::Nv12 && image_buf.io_surf().is_some();
+
let frame = ProcessedFrame {
_number: number,
data: Arc::new(data),
@@ -205,6 +202,11 @@ impl CachedFrame {
format,
y_stride,
uv_stride,
+ image_buf: if retain_iosurface {
+ Some(image_buf)
+ } else {
+ None
+ },
};
Self(frame)
}
@@ -451,6 +453,7 @@ impl AVAssetReaderDecoder {
format: PixelFormat::Rgba,
y_stride: video_width * 4,
uv_stride: 0,
+ image_buf: None,
};
(sender)(black_frame);
}
diff --git a/crates/rendering/src/decoder/ffmpeg.rs b/crates/rendering/src/decoder/ffmpeg.rs
index 0e5b9d9e3..6a1685695 100644
--- a/crates/rendering/src/decoder/ffmpeg.rs
+++ b/crates/rendering/src/decoder/ffmpeg.rs
@@ -1,4 +1,4 @@
-use ffmpeg::{frame, sys::AVHWDeviceType};
+use ffmpeg::{format, frame, sys::AVHWDeviceType};
use log::debug;
use std::{
cell::RefCell,
@@ -46,19 +46,71 @@ impl ProcessedFrame {
}
}
+fn extract_yuv_planes(frame: &frame::Video) -> Option<(Vec<u8>, PixelFormat, u32, u32)> {
+ let height = frame.height();
+
+ match frame.format() {
+ format::Pixel::YUV420P => {
+ let y_stride = frame.stride(0) as u32;
+ let u_stride = frame.stride(1) as u32;
+ let v_stride = frame.stride(2) as u32;
+
+ let y_size = (y_stride * height) as usize;
+ let uv_height = height / 2;
+ let u_size = (u_stride * uv_height) as usize;
+ let v_size = (v_stride * uv_height) as usize;
+
+ let mut data = Vec::with_capacity(y_size + u_size + v_size);
+ data.extend_from_slice(&frame.data(0)[..y_size]);
+ data.extend_from_slice(&frame.data(1)[..u_size]);
+ data.extend_from_slice(&frame.data(2)[..v_size]);
+
+ Some((data, PixelFormat::Yuv420p, y_stride, u_stride))
+ }
+ format::Pixel::NV12 => {
+ let y_stride = frame.stride(0) as u32;
+ let uv_stride = frame.stride(1) as u32;
+
+ let y_size = (y_stride * height) as usize;
+ let uv_size = (uv_stride * (height / 2)) as usize;
+
+ let mut data = Vec::with_capacity(y_size + uv_size);
+ data.extend_from_slice(&frame.data(0)[..y_size]);
+ data.extend_from_slice(&frame.data(1)[..uv_size]);
+
+ Some((data, PixelFormat::Nv12, y_stride, uv_stride))
+ }
+ _ => None,
+ }
+}
+
impl CachedFrame {
fn process(&mut self, converter: &mut FrameConverter) -> ProcessedFrame {
match self {
Self::Raw { frame, number } => {
- let frame_buffer = converter.convert(frame);
- let data = ProcessedFrame {
- data: Arc::new(frame_buffer),
- number: *number,
- width: frame.width(),
- height: frame.height(),
- format: PixelFormat::Rgba,
- y_stride: frame.width() * 4,
- uv_stride: 0,
+ let data = if let Some((yuv_data, pixel_format, y_stride, uv_stride)) =
+ extract_yuv_planes(frame)
+ {
+ ProcessedFrame {
+ data: Arc::new(yuv_data),
+ number: *number,
+ width: frame.width(),
+ height: frame.height(),
+ format: pixel_format,
+ y_stride,
+ uv_stride,
+ }
+ } else {
+ let frame_buffer = converter.convert(frame);
+ ProcessedFrame {
+ data: Arc::new(frame_buffer),
+ number: *number,
+ width: frame.width(),
+ height: frame.height(),
+ format: PixelFormat::Rgba,
+ y_stride: frame.width() * 4,
+ uv_stride: 0,
+ }
};
*self = Self::Processed(data.clone());
diff --git a/crates/rendering/src/decoder/mod.rs b/crates/rendering/src/decoder/mod.rs
index c3d6d021c..c0ebef38a 100644
--- a/crates/rendering/src/decoder/mod.rs
+++ b/crates/rendering/src/decoder/mod.rs
@@ -12,6 +12,28 @@ mod avassetreader;
mod ffmpeg;
mod frame_converter;
+#[cfg(target_os = "macos")]
+use cidre::{arc::R, cv};
+
+#[cfg(target_os = "macos")]
+pub struct SendableImageBuf(R<cv::ImageBuf>);
+
+#[cfg(target_os = "macos")]
+unsafe impl Send for SendableImageBuf {}
+#[cfg(target_os = "macos")]
+unsafe impl Sync for SendableImageBuf {}
+
+#[cfg(target_os = "macos")]
+impl SendableImageBuf {
+ pub fn new(image_buf: R<cv::ImageBuf>) -> Self {
+ Self(image_buf)
+ }
+
+ pub fn inner(&self) -> &cv::ImageBuf {
+ &self.0
+ }
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PixelFormat {
Rgba,
@@ -27,6 +49,8 @@ pub struct DecodedFrame {
format: PixelFormat,
y_stride: u32,
uv_stride: u32,
+ #[cfg(target_os = "macos")]
+ iosurface_backing: Option<Arc<SendableImageBuf>>,
}
impl fmt::Debug for DecodedFrame {
@@ -51,6 +75,8 @@ impl DecodedFrame {
format: PixelFormat::Rgba,
y_stride: width * 4,
uv_stride: 0,
+ #[cfg(target_os = "macos")]
+ iosurface_backing: None,
}
}
@@ -62,6 +88,8 @@ impl DecodedFrame {
format: PixelFormat::Nv12,
y_stride,
uv_stride,
+ #[cfg(target_os = "macos")]
+ iosurface_backing: None,
}
}
@@ -79,9 +107,36 @@ impl DecodedFrame {
format: PixelFormat::Yuv420p,
y_stride,
uv_stride,
+ #[cfg(target_os = "macos")]
+ iosurface_backing: None,
}
}
+ #[cfg(target_os = "macos")]
+ pub fn new_nv12_with_iosurface(
+ data: Vec<u8>,
+ width: u32,
+ height: u32,
+ y_stride: u32,
+ uv_stride: u32,
+ image_buf: R<cv::ImageBuf>,
+ ) -> Self {
+ Self {
+ data: Arc::new(data),
+ width,
+ height,
+ format: PixelFormat::Nv12,
+ y_stride,
+ uv_stride,
+ iosurface_backing: Some(Arc::new(SendableImageBuf::new(image_buf))),
+ }
+ }
+
+ #[cfg(target_os = "macos")]
+ pub fn iosurface_backing(&self) -> Option<&cv::ImageBuf> {
+ self.iosurface_backing.as_ref().map(|b| b.inner())
+ }
+
pub fn data(&self) -> &[u8] {
&self.data
}
diff --git a/crates/rendering/src/iosurface_texture.rs b/crates/rendering/src/iosurface_texture.rs
new file mode 100644
index 000000000..4403146da
--- /dev/null
+++ b/crates/rendering/src/iosurface_texture.rs
@@ -0,0 +1,190 @@
+#[cfg(target_os = "macos")]
+use cidre::{arc::R, cv, io, mtl};
+
+#[cfg(target_os = "macos")]
+use foreign_types::ForeignType;
+
+#[cfg(target_os = "macos")]
+use wgpu_hal::api::Metal as MtlApi;
+
+#[derive(Debug)]
+pub enum IOSurfaceTextureError {
+ NoIOSurface,
+ NoMetalDevice,
+ TextureCreationFailed,
+ WgpuImportFailed(String),
+ UnsupportedFormat,
+}
+
+impl std::fmt::Display for IOSurfaceTextureError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::NoIOSurface => write!(f, "CVPixelBuffer has no IOSurface backing"),
+ Self::NoMetalDevice => write!(f, "Failed to get Metal device"),
+ Self::TextureCreationFailed => {
+ write!(f, "Failed to create Metal texture from IOSurface")
+ }
+ Self::WgpuImportFailed(e) => write!(f, "Failed to import texture to wgpu: {e}"),
+ Self::UnsupportedFormat => write!(f, "Unsupported pixel format for zero-copy"),
+ }
+ }
+}
+
+impl std::error::Error for IOSurfaceTextureError {}
+
+#[cfg(target_os = "macos")]
+pub struct IOSurfaceTextureCache {
+ metal_device: R<mtl::Device>,
+}
+
+#[cfg(target_os = "macos")]
+impl IOSurfaceTextureCache {
+ pub fn new() -> Option<Self> {
+ let metal_device = mtl::Device::sys_default()?;
+ Some(Self { metal_device })
+ }
+
+ pub fn create_y_texture(
+ &self,
+ io_surface: &io::Surf,
+ width: u32,
+ height: u32,
+ ) -> Result<R<mtl::Texture>, IOSurfaceTextureError> {
+ let mut desc = mtl::TextureDesc::new_2d(
+ mtl::PixelFormat::R8UNorm,
+ width as usize,
+ height as usize,
+ false,
+ );
+ desc.set_storage_mode(mtl::StorageMode::Shared);
+ desc.set_usage(mtl::TextureUsage::SHADER_READ);
+
+ self.metal_device
+ .new_texture_with_surf(&desc, io_surface, 0)
+ .ok_or(IOSurfaceTextureError::TextureCreationFailed)
+ }
+
+ pub fn create_uv_texture(
+ &self,
+ io_surface: &io::Surf,
+ width: u32,
+ height: u32,
+ ) -> Result<R<mtl::Texture>, IOSurfaceTextureError> {
+ let mut desc = mtl::TextureDesc::new_2d(
+ mtl::PixelFormat::Rg8UNorm,
+ (width / 2) as usize,
+ (height / 2) as usize,
+ false,
+ );
+ desc.set_storage_mode(mtl::StorageMode::Shared);
+ desc.set_usage(mtl::TextureUsage::SHADER_READ);
+
+ self.metal_device
+ .new_texture_with_surf(&desc, io_surface, 1)
+ .ok_or(IOSurfaceTextureError::TextureCreationFailed)
+ }
+
+ pub fn create_rgba_texture(
+ &self,
+ io_surface: &io::Surf,
+ width: u32,
+ height: u32,
+ ) -> Result<R<mtl::Texture>, IOSurfaceTextureError> {
+ let mut desc = mtl::TextureDesc::new_2d(
+ mtl::PixelFormat::Rgba8UNorm,
+ width as usize,
+ height as usize,
+ false,
+ );
+ desc.set_storage_mode(mtl::StorageMode::Shared);
+ desc.set_usage(mtl::TextureUsage::SHADER_READ);
+
+ self.metal_device
+ .new_texture_with_surf(&desc, io_surface, 0)
+ .ok_or(IOSurfaceTextureError::TextureCreationFailed)
+ }
+}
+
+#[cfg(target_os = "macos")]
+pub struct IOSurfaceYuvTextures {
+ pub y_texture: R<mtl::Texture>,
+ pub uv_texture: R<mtl::Texture>,
+ pub width: u32,
+ pub height: u32,
+}
+
+#[cfg(target_os = "macos")]
+impl IOSurfaceYuvTextures {
+ pub fn from_cv_image_buf(
+ cache: &IOSurfaceTextureCache,
+ image_buf: &cv::ImageBuf,
+ ) -> Result<Self, IOSurfaceTextureError> {
+ let io_surface = image_buf
+ .io_surf()
+ .ok_or(IOSurfaceTextureError::NoIOSurface)?;
+
+ let width = image_buf.width() as u32;
+ let height = image_buf.height() as u32;
+
+ let y_texture = cache.create_y_texture(io_surface, width, height)?;
+ let uv_texture = cache.create_uv_texture(io_surface, width, height)?;
+
+ Ok(Self {
+ y_texture,
+ uv_texture,
+ width,
+ height,
+ })
+ }
+}
+
+#[cfg(target_os = "macos")]
+pub fn import_metal_texture_to_wgpu(
+ device: &wgpu::Device,
+ metal_texture: &mtl::Texture,
+ format: wgpu::TextureFormat,
+ width: u32,
+ height: u32,
+ label: Option<&str>,
+) -> Result<wgpu::Texture, IOSurfaceTextureError> {
+ let desc = wgpu::TextureDescriptor {
+ label,
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC,
+ view_formats: &[],
+ };
+
+ let raw_ptr = metal_texture as *const mtl::Texture as *mut std::ffi::c_void;
+
+ let metal_texture_owned = unsafe {
+ let ptr = raw_ptr as *mut objc2::runtime::AnyObject;
+ objc2::ffi::objc_retain(ptr);
+ metal::Texture::from_ptr(raw_ptr as *mut metal::MTLTexture)
+ };
+
+ let hal_texture = unsafe {
+ wgpu_hal::metal::Device::texture_from_raw(
+ metal_texture_owned,
+ format,
+ metal::MTLTextureType::D2,
+ 1,
+ 1,
+ wgpu_hal::CopyExtent {
+ width,
+ height,
+ depth: 1,
+ },
+ )
+ };
+
+ let texture = unsafe { device.create_texture_from_hal::<MtlApi>(hal_texture, &desc) };
+ Ok(texture)
+}
diff --git a/crates/rendering/src/layers/camera.rs b/crates/rendering/src/layers/camera.rs
index 48c14d97f..85ec8a4ba 100644
--- a/crates/rendering/src/layers/camera.rs
+++ b/crates/rendering/src/layers/camera.rs
@@ -130,6 +130,7 @@ impl CameraLayer {
frame_size.x,
frame_size.y,
camera_frame.y_stride(),
+ camera_frame.uv_stride(),
)
.is_ok()
{
diff --git a/crates/rendering/src/layers/display.rs b/crates/rendering/src/layers/display.rs
index df1a7ba5b..f6aee5362 100644
--- a/crates/rendering/src/layers/display.rs
+++ b/crates/rendering/src/layers/display.rs
@@ -122,10 +122,81 @@ impl DisplayLayer {
}
PixelFormat::Nv12 => {
let screen_frame = &segment_frames.screen_frame;
+
+ #[cfg(target_os = "macos")]
+ let iosurface_result = screen_frame.iosurface_backing().map(|image_buf| {
+ self.yuv_converter
+ .convert_nv12_from_iosurface(device, queue, image_buf)
+ });
+
+ #[cfg(target_os = "macos")]
+ if let Some(Ok(_)) = iosurface_result {
+ if self.yuv_converter.output_texture().is_some() {
+ self.pending_copy = Some(PendingTextureCopy {
+ width: frame_size.x,
+ height: frame_size.y,
+ dst_texture_index: next_texture,
+ });
+ true
+ } else {
+ false
+ }
+ } else if let (Some(y_data), Some(uv_data)) =
+ (screen_frame.y_plane(), screen_frame.uv_plane())
+ {
+ let y_stride = screen_frame.y_stride();
+ let uv_stride = screen_frame.uv_stride();
+ let convert_result = self.yuv_converter.convert_nv12(
+ device,
+ queue,
+ y_data,
+ uv_data,
+ frame_size.x,
+ frame_size.y,
+ y_stride,
+ uv_stride,
+ );
+
+ match convert_result {
+ Ok(_) => {
+ if self.yuv_converter.output_texture().is_some() {
+ self.pending_copy = Some(PendingTextureCopy {
+ width: frame_size.x,
+ height: frame_size.y,
+ dst_texture_index: next_texture,
+ });
+ true
+ } else {
+ tracing::debug!(
+ width = frame_size.x,
+ height = frame_size.y,
+ y_stride,
+ "NV12 conversion succeeded but output texture is None, skipping copy"
+ );
+ false
+ }
+ }
+ Err(e) => {
+ tracing::debug!(
+ error = ?e,
+ width = frame_size.x,
+ height = frame_size.y,
+ y_stride,
+ "NV12 to RGBA conversion failed"
+ );
+ false
+ }
+ }
+ } else {
+ false
+ }
+
+ #[cfg(not(target_os = "macos"))]
if let (Some(y_data), Some(uv_data)) =
(screen_frame.y_plane(), screen_frame.uv_plane())
{
let y_stride = screen_frame.y_stride();
+ let uv_stride = screen_frame.uv_stride();
let convert_result = self.yuv_converter.convert_nv12(
device,
queue,
@@ -134,6 +205,7 @@ impl DisplayLayer {
frame_size.x,
frame_size.y,
y_stride,
+ uv_stride,
);
match convert_result {
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 1bd871cca..7aa34d19a 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -25,6 +25,8 @@ mod coord;
mod cursor_interpolation;
pub mod decoder;
mod frame_pipeline;
+#[cfg(target_os = "macos")]
+pub mod iosurface_texture;
mod layers;
mod mask;
mod project_recordings;
diff --git a/crates/rendering/src/yuv_converter.rs b/crates/rendering/src/yuv_converter.rs
index d1bbe9875..cb5786bda 100644
--- a/crates/rendering/src/yuv_converter.rs
+++ b/crates/rendering/src/yuv_converter.rs
@@ -1,23 +1,24 @@
use crate::decoder::PixelFormat;
+#[cfg(target_os = "macos")]
+use crate::iosurface_texture::{
+ IOSurfaceTextureCache, IOSurfaceTextureError, import_metal_texture_to_wgpu,
+};
+
+#[cfg(target_os = "macos")]
+use cidre::cv;
+
#[derive(Debug, thiserror::Error)]
pub enum YuvConversionError {
- #[error(
- "{plane} plane bounds exceeded at row {row}: start={start}, end={end}, data_len={data_len}"
- )]
- PlaneBoundsExceeded {
- plane: &'static str,
- row: usize,
- start: usize,
- end: usize,
- data_len: usize,
- },
#[error("{plane} plane size mismatch: expected {expected}, got {actual}")]
PlaneSizeMismatch {
plane: &'static str,
expected: usize,
actual: usize,
},
+ #[cfg(target_os = "macos")]
+ #[error("IOSurface error: {0}")]
+ IOSurfaceError(#[from] IOSurfaceTextureError),
}
fn upload_plane_with_stride(
@@ -29,70 +30,34 @@ fn upload_plane_with_stride(
stride: u32,
plane_name: &'static str,
) -> Result<(), YuvConversionError> {
- if stride == width {
- queue.write_texture(
- wgpu::TexelCopyTextureInfo {
- texture,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
- },
- data,
- wgpu::TexelCopyBufferLayout {
- offset: 0,
- bytes_per_row: Some(width),
- rows_per_image: Some(height),
- },
- wgpu::Extent3d {
- width,
- height,
- depth_or_array_layers: 1,
- },
- );
- } else {
- let expected_size = (width * height) as usize;
- let mut packed = Vec::with_capacity(expected_size);
- for row in 0..height as usize {
- let start = row * stride as usize;
- let end = start + width as usize;
- if end > data.len() {
- return Err(YuvConversionError::PlaneBoundsExceeded {
- plane: plane_name,
- row,
- start,
- end,
- data_len: data.len(),
- });
- }
- packed.extend_from_slice(&data[start..end]);
- }
- if packed.len() != expected_size {
- return Err(YuvConversionError::PlaneSizeMismatch {
- plane: plane_name,
- expected: expected_size,
- actual: packed.len(),
- });
- }
- queue.write_texture(
- wgpu::TexelCopyTextureInfo {
- texture,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
- },
- &packed,
- wgpu::TexelCopyBufferLayout {
- offset: 0,
- bytes_per_row: Some(width),
- rows_per_image: Some(height),
- },
- wgpu::Extent3d {
- width,
- height,
- depth_or_array_layers: 1,
- },
- );
+ let expected_data_size = (stride * height) as usize;
+ if data.len() < expected_data_size {
+ return Err(YuvConversionError::PlaneSizeMismatch {
+ plane: plane_name,
+ expected: expected_data_size,
+ actual: data.len(),
+ });
}
+
+ queue.write_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ data,
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(stride),
+ rows_per_image: Some(height),
+ },
+ wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ );
Ok(())
}
@@ -114,6 +79,8 @@ pub struct YuvToRgbaConverter {
cached_width: u32,
cached_height: u32,
cached_format: Option<PixelFormat>,
+ #[cfg(target_os = "macos")]
+ iosurface_cache: Option<IOSurfaceTextureCache>,
}
impl YuvToRgbaConverter {
@@ -265,6 +232,8 @@ impl YuvToRgbaConverter {
cached_width: 0,
cached_height: 0,
cached_format: None,
+ #[cfg(target_os = "macos")]
+ iosurface_cache: IOSurfaceTextureCache::new(),
}
}
@@ -389,6 +358,7 @@ impl YuvToRgbaConverter {
width: u32,
height: u32,
y_stride: u32,
+ uv_stride: u32,
) -> Result<&wgpu::TextureView, YuvConversionError> {
self.ensure_textures(device, width, height, PixelFormat::Nv12);
@@ -398,6 +368,16 @@ impl YuvToRgbaConverter {
upload_plane_with_stride(queue, y_texture, y_data, width, height, y_stride, "Y")?;
+ let half_height = height / 2;
+ let expected_uv_size = (uv_stride * half_height) as usize;
+ if uv_data.len() < expected_uv_size {
+ return Err(YuvConversionError::PlaneSizeMismatch {
+ plane: "UV",
+ expected: expected_uv_size,
+ actual: uv_data.len(),
+ });
+ }
+
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: uv_texture,
@@ -408,12 +388,12 @@ impl YuvToRgbaConverter {
uv_data,
wgpu::TexelCopyBufferLayout {
offset: 0,
- bytes_per_row: Some(width),
- rows_per_image: Some(height / 2),
+ bytes_per_row: Some(uv_stride),
+ rows_per_image: Some(half_height),
},
wgpu::Extent3d {
width: width / 2,
- height: height / 2,
+ height: half_height,
depth_or_array_layers: 1,
},
);
@@ -462,6 +442,125 @@ impl YuvToRgbaConverter {
Ok(self.output_view.as_ref().unwrap())
}
+ #[cfg(target_os = "macos")]
+ pub fn convert_nv12_from_iosurface(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ image_buf: &cv::ImageBuf,
+ ) -> Result<&wgpu::TextureView, YuvConversionError> {
+ let cache = self
+ .iosurface_cache
+ .as_ref()
+ .ok_or(IOSurfaceTextureError::NoMetalDevice)?;
+
+ let io_surface = image_buf
+ .io_surf()
+ .ok_or(IOSurfaceTextureError::NoIOSurface)?;
+
+ let width = image_buf.width() as u32;
+ let height = image_buf.height() as u32;
+
+ let y_metal_texture = cache.create_y_texture(io_surface, width, height)?;
+ let uv_metal_texture = cache.create_uv_texture(io_surface, width, height)?;
+
+ let y_wgpu_texture = import_metal_texture_to_wgpu(
+ device,
+ &y_metal_texture,
+ wgpu::TextureFormat::R8Unorm,
+ width,
+ height,
+ Some("IOSurface Y Plane"),
+ )?;
+
+ let uv_wgpu_texture = import_metal_texture_to_wgpu(
+ device,
+ &uv_metal_texture,
+ wgpu::TextureFormat::Rg8Unorm,
+ width / 2,
+ height / 2,
+ Some("IOSurface UV Plane"),
+ )?;
+
+ if self.cached_width != width
+ || self.cached_height != height
+ || self.cached_format != Some(PixelFormat::Nv12)
+ {
+ self.output_texture = Some(device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("RGBA Output Texture"),
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::STORAGE_BINDING
+ | wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::COPY_SRC,
+ view_formats: &[],
+ }));
+
+ self.output_view = Some(
+ self.output_texture
+ .as_ref()
+ .unwrap()
+ .create_view(&Default::default()),
+ );
+
+ self.cached_width = width;
+ self.cached_height = height;
+ self.cached_format = Some(PixelFormat::Nv12);
+ }
+
+ let output_texture = self.output_texture.as_ref().unwrap();
+
+ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("NV12 IOSurface Converter Bind Group"),
+ layout: &self.nv12_bind_group_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::TextureView(
+ &y_wgpu_texture.create_view(&Default::default()),
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(
+ &uv_wgpu_texture.create_view(&Default::default()),
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(
+ &output_texture.create_view(&Default::default()),
+ ),
+ },
+ ],
+ });
+
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("NV12 IOSurface Conversion Encoder"),
+ });
+
+ {
+ let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("NV12 IOSurface Conversion Pass"),
+ ..Default::default()
+ });
+ compute_pass.set_pipeline(&self.nv12_pipeline);
+ compute_pass.set_bind_group(0, &bind_group, &[]);
+ compute_pass.dispatch_workgroups(width.div_ceil(8), height.div_ceil(8), 1);
+ }
+
+ queue.submit(std::iter::once(encoder.finish()));
+
+ Ok(self.output_view.as_ref().unwrap())
+ }
+
#[allow(clippy::too_many_arguments)]
pub fn convert_yuv420p(
&mut self,
diff --git a/docs/PLAYBACK_PERFORMANCE_OPTIMIZATIONS.md b/docs/PLAYBACK_PERFORMANCE_OPTIMIZATIONS.md
deleted file mode 100644
index 35e50bcb4..000000000
--- a/docs/PLAYBACK_PERFORMANCE_OPTIMIZATIONS.md
+++ /dev/null
@@ -1,387 +0,0 @@
-# Playback Performance Optimizations
-
-This document tracks performance optimizations for the Cap editor playback system.
-
-## Current Performance Baseline (as of 2025-12-11)
-
-| Metric | Current Value | Target | Status |
-|--------|--------------|--------|--------|
-| Initial startup delay | ~50-80ms warmup | <100ms | ✅ Improved |
-| GPU render time | 2-7ms typical | 7-15ms/frame | ✅ Excellent |
-| Frame skipping at start | 0-3 frames | 0 frames | ✅ Good |
-| WebSocket frame size | 7.2MB → 1.3-1.5MB (LZ4) | <2MB | ✅ Excellent |
-| WebSocket send time | <30ms | <50ms | ✅ Good |
-| GPU poll/readback | <1ms | <10ms | ✅ Excellent |
-| Effective FPS | 30-60fps stable | Stable 30fps+ | ✅ Good |
-
-### Recent Optimizations (2025-12-11)
-
-1. **Enabled LZ4 Compression** - Frame data now actually compressed with LZ4 (~5-6x compression)
-2. **Non-blocking render_frame** - Playback loop no longer waits for GPU render completion
-3. **Removed debug logging** - Eliminated expensive disk I/O in hot paths
-4. **Faster canvas rendering** - Using createImageBitmap instead of putImageData
-5. **Increased prefetch parallelism** - 4 initial parallel tasks (was 1) for faster startup
-6. **Removed redundant timing measurements** - Less overhead in frame processing
-
----
-
-## High Priority Optimizations
-
-### [x] Pre-warm Prefetch Buffer Before Playback
-
-**Problem**: Playback starts immediately with an empty prefetch buffer, causing:
-- First frame fetch takes 1.3 seconds
-- 38+ frames skipped at startup
-- Noticeable stutter/jump when pressing play
-
-**Solution**: Add a warmup phase before the playback loop starts.
-
-**Status**: Implemented but insufficient alone - needed additional fixes below.
-
----
-
-### [x] Fix Prefetch Buffer Management
-
-**Problem**: After implementing warmup, logs showed:
-- `prefetch_hit=false prefetch_buffer_size=64` - buffer full but frames missing!
-- `frame_fetch_us=233319` (233ms!) to fetch frames that should be in cache
-- 52+ frames skipped during playback
-
-**Root Causes Identified**:
-1. **Out-of-order completion**: `FuturesUnordered` causes frames to complete in random order
-2. **FIFO eviction is wrong**: Popping oldest *inserted* frame, not furthest from playback
-3. **Prefetch runs too far ahead**: Buffer contains frames 100+ ahead while current frame missing
-
-**Solution**: Three-part fix in `crates/editor/src/playback.rs`:
-
-1. **Added MAX_PREFETCH_AHEAD constant** (90 frames):
- - Limits how far ahead the prefetch task can run
- - Prefetch now waits when too far ahead of playback position
-
-2. **Smart eviction strategy**:
- - Instead of FIFO, evict frames furthest from current playback position
- - Keeps frames closest to what we need
-
-3. **Real-time playback position tracking**:
- - Added `playback_position_tx/rx` watch channel
- - Prefetch task knows current playback position
- - Position updated on both frame render and frame skip
-
-**Expected Impact**:
-- Near 100% prefetch hit rate (vs 78% before)
-- Eliminate 100-400ms frame fetch delays
-- Reduce frame skipping from 50+ to near zero
-
----
-
-### [x] Add Frame Compression for WebSocket Transmission
-
-**Problem**: Each frame is 7.2MB raw RGBA data, requiring 216MB/s at 30fps.
-
-**Solution**: Add LZ4 compression (fast, ~50% size reduction).
-
-**Status**: ✅ Implemented and verified on 2025-12-10
-
-**Files Modified**:
-- `apps/desktop/src-tauri/src/frame_ws.rs` - Added `compress_frame_data()` helper using `lz4_flex::compress_prepend_size`
-- `apps/desktop/src/utils/socket.ts` - Added `decompressLz4()` using `lz4js.decompressBlock`
-
-**Dependencies Added**:
-- Rust: `lz4_flex = "0.11"` in `apps/desktop/src-tauri/Cargo.toml`
-- TypeScript: `lz4js` + `@types/lz4js` in `apps/desktop/package.json`
-
-**Implementation Details**:
-- Rust side uses `lz4_flex::compress_prepend_size()` which prepends the uncompressed size as a 4-byte little-endian u32
-- TypeScript side uses `lz4js.decompressBlock()` for raw LZ4 block decompression
-- Compression metrics logged with `[PERF:WS]` and `[PERF:WS_WATCH]` tags showing original/compressed sizes and compression ratio
-- Decompression metrics logged with `[PERF:FRONTEND_WS]` tag showing decompress time
-
-**Wire Format**:
-```
-[uncompressed_size (4 bytes LE)] [LZ4 compressed: pixel_data + stride(4) + height(4) + width(4)]
-```
-
-**Measured Results** (1662x1080 frames):
-| Metric | Value |
-|--------|-------|
-| Original size | 7,188,480 bytes (7.2MB) |
-| Compressed size | 1,282,011 - 1,472,462 bytes (1.3-1.5MB) |
-| Compression ratio | **17-20% of original (5-6x compression)** |
-| Bandwidth reduction | ~82% (exceeds 50% target) |
-
-**Note**: While compression is working excellently, WebSocket send times remain 130-150ms due to upstream GPU readback blocking. The compression itself is not the bottleneck.
-
----
-
-### [x] Async GPU Readback with True Double Buffering ✅ IMPLEMENTED
-
-**Problem**: GPU poll was blocking for **147-151ms** waiting for readback to complete - this was the PRIMARY bottleneck causing frame skipping.
-
-**Solution Implemented** (2025-12-10):
-
-Created a pipelined GPU readback system in `crates/rendering/src/frame_pipeline.rs`:
-
-1. **Triple-buffered staging buffers**: Pool of 3 `Arc<wgpu::Buffer>` for readback operations
-2. **`PipelinedGpuReadback` struct**: Manages buffer pool and pending readback operations
-3. **`PendingReadback` struct**: Tracks in-flight readback with oneshot channel for completion notification
-4. **Pipeline priming**: First frame waits synchronously, then submits a "priming" readback so subsequent frames can pipeline
-
-**Key Implementation Details**:
-- `submit_readback()`: Submits render encoder, copies texture to buffer, starts `map_async()`, returns immediately
-- `PendingReadback::wait()`: Polls for completion with async yield, reads buffer data when ready
-- `finish_encoder()`: Takes previous frame's pending readback, submits current frame, waits for previous (which is usually already ready)
-- First frame primes the pipeline by submitting an additional readback after waiting
-
-**Files Modified**:
-- `crates/rendering/src/frame_pipeline.rs` - Complete rewrite with `PipelinedGpuReadback`, `PendingReadback`, moved `RenderSession` here
-- `crates/rendering/src/lib.rs` - Updated imports, removed duplicate `RenderSession`
-
-**Measured Results**:
-
-| Metric | Before | After | Improvement |
-|--------|--------|-------|-------------|
-| GPU poll time | 147-160ms | 0-13μs | **~10,000x** |
-| finish_encoder time | 150-160ms | 1.3-2.7ms | **~60x** |
-| Effective readback | Blocking | Pipelined | ✅ |
-
-**Sample logs after fix**:
-```
-[PERF:GPU_BUFFER] pipelined finish_encoder (first frame, primed pipeline) wait_us=6514 prime_us=532
-[PERF:GPU_BUFFER] pipelined finish_encoder (pipelined, waited for previous) wait_us=1714 total_us=2240
-[PERF:GPU_BUFFER] pipelined readback wait completed poll_us=1 data_copy_us=1553
-```
-
-**Impact**: GPU readback is no longer the bottleneck. Remaining frame skipping is due to video decoding and WebSocket transmission, not GPU operations
-
----
-
-## Medium Priority Optimizations
-
-### [ ] Increase Parallel Decode Tasks
-
-**Problem**: With 8 parallel decode tasks, prefetch buffer can't keep up during fast seeking.
-
-**Solution**: Increase `PARALLEL_DECODE_TASKS` from 8 to 12-16.
-
-**File**: `crates/editor/src/playback.rs:32`
-
-**Current**:
-```rust
-const PARALLEL_DECODE_TASKS: usize = 8;
-```
-
-**Change to**:
-```rust
-const PARALLEL_DECODE_TASKS: usize = 12;
-```
-
-**Expected Impact**: Better prefetch coverage, fewer cache misses during playback
-
----
-
-### [x] Reduce Layer Preparation Time ✅ IMPLEMENTED
-
-**Problem**: `prepare_us` takes 6-22ms, often the largest single operation.
-
-**File**: `crates/rendering/src/lib.rs` (RendererLayers::prepare)
-
-**Solutions Implemented** (2025-12-10):
-
-1. **Persistent staging buffers for texture uploads**:
- - Added `staging_buffer` field to `DisplayLayer` and `CameraLayer`
- - Staging buffers are reused across frames (only reallocated if size increases)
- - Data is written to staging buffer in `prepare()`, then copied to texture via encoder in `copy_to_texture()`
- - This separates CPU-to-buffer write from buffer-to-texture GPU copy, allowing better pipelining
-
-2. **Cached sampler in CompositeVideoFramePipeline**:
- - Sampler is now created once in `new()` and reused for all bind group creations
- - Previously a new sampler was created every time `bind_group()` was called
-
-3. **Performance metrics breakdown**:
- - Added detailed timing for each layer's prepare step: background, blur, display, cursor, camera, text, captions
- - Logs `[PERF:PREPARE]` when total prepare time exceeds 5ms
-
-**Files Modified**:
-- `crates/rendering/src/layers/display.rs` - Added staging buffer with proper 256-byte row alignment
-- `crates/rendering/src/layers/camera.rs` - Added staging buffer with proper 256-byte row alignment
-- `crates/rendering/src/composite_frame.rs` - Cached sampler in pipeline struct
-- `crates/rendering/src/lib.rs` - Added per-layer timing metrics in `RendererLayers::prepare()`
-
-**Implementation Details**:
-- Staging buffers use `COPY_SRC | COPY_DST` usage flags for buffer-to-texture copies
-- Row alignment is 256 bytes (wgpu requirement for `copy_buffer_to_texture`)
-- When source data row stride doesn't match alignment, data is copied row-by-row with padding
-- `copy_to_texture()` method now issues `encoder.copy_buffer_to_texture()` commands
-
-**Expected Impact**: Reduce prepare time from 6-22ms to 4-8ms by:
-- Eliminating per-frame sampler allocation
-- Using dedicated staging buffers instead of internal wgpu staging
-- Better separation of CPU and GPU work
-
----
-
-### [ ] Optimize Decoder Cache Management
-
-**Problem**: Cache eviction may remove useful frames; screen frames are much larger than camera frames.
-
-**File**: `crates/rendering/src/decoder/avassetreader.rs`
-
-**Solutions**:
-- [ ] Separate cache size limits for screen vs camera decoders
-- [ ] Priority-based eviction (keep frames closer to current position)
-- [ ] Adaptive cache sizing based on available memory
-
-**Expected Impact**: Fewer cache misses, more consistent frame timing
-
----
-
-## Lower Priority Optimizations
-
-### [ ] Direct Surface Rendering (Architecture Change)
-
-**Problem**: Current pipeline has unnecessary overhead:
-```
-GPU Render → Readback to CPU → WebSocket → Frontend → Canvas
-```
-
-**Solution**: Render directly to a native surface or use shared memory.
-
-**Options**:
-- Use `wgpu` surface rendering to a native window
-- Shared memory between Rust and frontend (platform-specific)
-- Metal layer on macOS, Direct3D surface on Windows
-
-**Expected Impact**: Eliminate WebSocket overhead entirely (~10-15ms savings)
-
----
-
-### [ ] Frame Rate Adaptation
-
-**Problem**: When system can't maintain 30fps, frames pile up and get skipped in batches.
-
-**Solution**: Adaptive frame rate based on actual rendering performance.
-
-**Implementation**:
-- Track rolling average of frame times
-- Dynamically adjust target FPS
-- Skip frames proactively rather than reactively
-
-**Expected Impact**: Smoother playback on slower systems
-
----
-
-### [ ] Hardware Video Decoder Optimization
-
-**Problem**: AVAssetReader is hardware-accelerated but pixel format conversions may happen on CPU.
-
-**File**: `crates/rendering/src/decoder/avassetreader.rs`
-
-**Solutions**:
-- [ ] Ensure VideoToolbox hardware decoding is active
-- [ ] Keep pixel data in GPU-friendly format (avoid CPU conversions)
-- [ ] Use `kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange` directly
-
-**Expected Impact**: Faster decode times, lower CPU usage
-
----
-
-## Performance Monitoring
-
-### Existing Metrics (in logs)
-
-The codebase already has comprehensive performance logging:
-
-- `[PERF:PLAYBACK]` - Frame rendering, skipping, prefetch stats
-- `[PERF:DECODER]` - Cache hits/misses, decode times, resets
-- `[PERF:GPU]` - Render timing breakdown
-- `[PERF:GPU_BUFFER]` - Readback timing breakdown
-- `[PERF:PREPARE]` - Layer prepare timing breakdown (background, display, camera, cursor, text, captions)
-- `[PERF:WS]` - WebSocket frame transmission
-- `[PERF:EDITOR_RENDER]` - Editor render loop metrics
-
-### [ ] Add Performance Dashboard
-
-**Idea**: Surface these metrics in the UI for easier debugging.
-
-- Show current FPS
-- Show prefetch buffer status
-- Show frame latency breakdown
-- Highlight bottlenecks in real-time
-
----
-
-## Frame Time Budget (30fps = 33.3ms)
-
-| Component | Measured | Target | Status |
-|-----------|----------|--------|--------|
-| Decode (prefetched) | 0-4μs | 0-1ms | ✅ Excellent |
-| Decode (cache miss) | 4-7ms | <10ms | ✅ Good |
-| Uniforms | 20-40μs | 0.2-0.4ms | ✅ Excellent |
-| GPU prepare | 4-7ms | 4-8ms | ✅ Good (optimized) |
-| GPU render pass | 0.5-0.7ms | 0.5-1.4ms | ✅ Good |
-| GPU readback poll | 0-13μs | <10ms | ✅ Fixed |
-| Buffer data copy | 0.6-2ms | 1-2ms | ✅ Good |
-| LZ4 compression | ~1-2ms (est) | <3ms | ✅ Good |
-| WS transmission | <50ms | <50ms | ✅ Good |
-| **Total** | **<33ms** | **<33ms** | ✅ |
-
-*WebSocket send time is high because frames queue up behind GPU blocking.
-
-### Actual Log Measurements (2025-12-10)
-
-```
-[PERF:GPU_BUFFER] buffer_size_bytes=7188480 submit1_us=151 buffer_setup_us=0
- copy_encoder_us=87 submit2_us=91 gpu_poll_us=151681
- map_wait_us=1 data_copy_us=1223 total_us=153431
-
-[PERF:GPU] prepare_us=6535 encoder_create_us=10 render_pass_us=550
- finish_encoder_us=153508 total_us=160604
-
-[PERF:PLAYBACK] frame rendered frame=34 prefetch_hit=true prefetch_buffer_size=6
- frame_fetch_us=1 uniforms_us=26 render_us=9
-```
-
----
-
-## Observed Playback Behavior (2025-12-10)
-
-### Frame Skipping Pattern
-```
-[PERF:PLAYBACK] skipping frames to catch up frames_behind=16 frames_skipped=3 current_frame=6 total_skipped=3
-[PERF:PLAYBACK] skipping frames to catch up frames_behind=12 frames_skipped=3 current_frame=10 total_skipped=6
-[PERF:PLAYBACK] skipping frames to catch up frames_behind=12 frames_skipped=3 current_frame=14 total_skipped=9
-...
-[PERF:PLAYBACK] skipping frames to catch up frames_behind=2 frames_skipped=2 current_frame=32 total_skipped=20
-```
-
-Frame skipping occurs in batches of 3 frames when the system falls behind. This is caused by GPU poll blocking.
-
-### Prefetch System Status
-- Prefetch hit rate: ~70-80% (good, but drops during GPU stalls)
-- Buffer size: 0-6 frames typically buffered
-- Cache hits working well for camera decoder (253 entries cached)
-- Screen decoder cache: 142-205 entries
-
-### Editor Render Loop
-```
-[PERF:EDITOR_RENDER] periodic metrics frames_rendered=7 frames_dropped=0
- avg_render_time_us=44464 avg_callback_time_us=12
- max_render_time_us=155589 max_callback_time_us=15
-[PERF:EDITOR_RENDER] dropped frames to catch up dropped_frames=4 total_dropped=5
-```
-
-The render loop is dropping frames because individual frames take up to 155ms (due to GPU poll blocking).
-
----
-
-## Testing Checklist
-
-After implementing optimizations, verify:
-
-- [ ] Playback starts without visible stutter
-- [ ] No frame skipping on initial play (check logs for `frames_skipped`)
-- [ ] Consistent 30fps during playback
-- [ ] Seeking responds quickly (<200ms)
-- [ ] Memory usage remains stable
-- [ ] CPU usage is reasonable (<50% on modern hardware)
-- [ ] Works with both screen-only and screen+camera recordings
diff --git a/docs/editor-playback-optimizations.md b/docs/editor-playback-optimizations.md
deleted file mode 100644
index a7b81cd11..000000000
--- a/docs/editor-playback-optimizations.md
+++ /dev/null
@@ -1,104 +0,0 @@
-# Editor Video Playback Optimizations
-
-## Quick Wins (Low Effort, High Impact)
-
-- [x] 1. **Replace lz4js with WASM LZ4**
- - Current: Using `lz4js` (pure JavaScript) for decompression in `frame-worker.ts:28-41`
- - Change: Replace with a WASM-based LZ4 decoder (e.g., `lz4-wasm` or compile LZ4 to WASM directly)
- - Impact: WASM typically runs 2-5x faster than pure JS for compute-heavy operations
- - Done: Replaced with `lz4-wasm` package which uses the same size-prepended format as `lz4_flex`
-
-- [x] 2. **Remove debug file writes and console logging**
- - Current: Extensive debug logging with file writes at multiple points in `playback.rs`
- - Change: Removed all debug file writes from `playback.rs` and removed performance logging from `socket.ts` and `context.ts`
- - Impact: Eliminates file I/O overhead and reduces console noise
-
-- [x] 3. **Cache project config between frames**
- - Current: `self.project.borrow().clone()` called every frame at `playback.rs:523`
- - Change: Cache project config and only re-clone when it actually changes (use `watch::has_changed`)
- - Impact: Reduces allocation and cloning overhead per frame
-
-- [x] 4. **Use WebGL for canvas rendering** - REJECTED
- - Current: Using 2D canvas context at `Player.tsx:478-484`
- - Change: GPU-accelerated image scaling and display instead of 2D canvas
- - Impact: Hardware-accelerated rendering with better scaling quality
- - Result: **Not beneficial.** 2D canvas `drawImage(ImageBitmap)` is already GPU-accelerated in modern browsers. Explicit WebGL adds texture upload overhead (`texImage2D` every frame) that makes it slower than the optimized 2D path. WebGL would only help for custom shaders (YUV conversion, color correction, effects).
-
-## Medium Effort
-
-- [x] 5. **OffscreenCanvas in worker**
- - Current: ImageBitmap created in worker, transferred to main thread, drawn on main thread canvas
- - Change: Move canvas rendering entirely to the worker using OffscreenCanvas
- - Impact: Eliminates main thread rendering jank entirely
- - Done: Worker now receives OffscreenCanvas from main thread and draws frames directly using `putImageData()`. Main thread only receives frame metadata (width, height) for UI sizing.
-
-- [x] 6. **WebSocket transfer overhead / SharedArrayBuffer**
- - Current: Each frame transfers an ArrayBuffer to the worker via `postMessage`, incurring serialization overhead
- - Change: Use `SharedArrayBuffer` for zero-copy frame transfer between main thread and worker
- - Impact: Could reduce frame transfer time by 50-80% for large frames
- - Note: Requires COOP/COEP headers
- - Done: Implemented ring buffer with 4 slots (8MB each), producer/consumer pattern using Atomics for synchronization. COOP/COEP headers added to Vite dev server. Automatic fallback to postMessage if SharedArrayBuffer unavailable.
-
-- [ ] 7. **Dynamic prefetch buffer sizing**
- - Current: Fixed `PREFETCH_BUFFER_SIZE = 180` frames at `playback.rs:31`
- - Change: Adjust based on available memory and video resolution
- - Impact: Better memory utilization and prefetch efficiency
-
-- [ ] 8. **Debounce canvas size calculations**
- - Current: Canvas size recalculated every frame via reactive computations at `Player.tsx:562-574`
- - Change: Debounce size calculations and only update canvas dimensions when container actually resizes
- - Impact: Reduces reactive computation overhead
-
-- [ ] 9. **Eliminate stride mismatch copies**
- - Current: In `frame-worker.ts:92-113`, when stride differs from expected row bytes, there's a row-by-row copy loop
- - Change: Request matching stride from Rust side to avoid the copy, or use WASM/SIMD for the stride correction
- - Impact: Eliminates per-frame buffer manipulation
-
-- [ ] 10. **Always use rAF for rendering**
- - Current: When paused, frames render directly without rAF at `Player.tsx:514-516`
- - Change: Always use rAF even when paused to ensure vsync alignment
- - Impact: Avoids potential tearing artifacts
-
-## High Effort (Architectural)
-
-- [ ] 11. **Direct GPU texture sharing**
- - Current: GPU renders → CPU readback → LZ4 compress → WebSocket → decompress → ImageBitmap
- - Change: Share GPU textures directly with the browser (WebGPU interop)
- - Impact: Eliminates entire CPU roundtrip for frame data
-
-- [ ] 12. **Predictive prefetch with velocity detection**
- - Current: Fixed prefetch direction and rate
- - Change: Use playback velocity (scrubbing vs normal play) to adjust prefetch direction and priority
- - Impact: Better prefetch hit rate during scrubbing
-
-- [ ] 13. **Weighted cache eviction**
- - Current: Simple LRU eviction at `playback.rs:106-110`
- - Change: Use weighted eviction considering distance from playhead, decode cost (I-frames), and access patterns
- - Impact: Higher cache hit rate for commonly accessed frames
-
-- [ ] 14. **Skip compression for localhost**
- - Current: LZ4 compression used regardless of transport
- - Change: If WebSocket is localhost, skip LZ4 or use lighter compression
- - Impact: Reduces latency for local playback
-
-- [ ] 15. **Optimize WebSocket message format**
- - Current: Metadata (stride, height, width) appended as 12 bytes at the end of each frame
- - Change: Send metadata in a separate message or header for better SIMD alignment
- - Impact: Better memory access patterns for decompression
-
-## Additional Improvements
-
-- [ ] 16. **Smarter frame drop strategy**
- - Current: In `socket.ts:121-132`, drops frames when worker is busy (keeps newest)
- - Change: Track frame timestamps and intelligently select which frames to keep
- - Impact: Better frame selection during seeking/scrubbing
-
-- [ ] 17. **Immediate first frame rendering**
- - Current: Wait for 2 frames OR 50ms timeout at `playback.rs:436-437`
- - Change: Start rendering the first frame immediately while prefetch continues
- - Impact: Improved perceived responsiveness
-
-- [ ] 18. **Double buffering for canvas**
- - Current: Single canvas with direct drawing
- - Change: Pre-render next frame to a second canvas for instant swap
- - Impact: Eliminates any visible rendering delay