Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
start skia rendering (#705)
Brendan Allandcc9e4f9291b
diff --git a/Cargo.lock b/Cargo.lockindex 7c5ec0328..a049a5c6d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -656,6 +656,26 @@ dependencies = ["syn 2.0.90",]+[[package]]+name = "bindgen"+version = "0.71.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3"+dependencies = [+ "bitflags 2.9.0",+ "cexpr 0.6.0",+ "clang-sys",+ "itertools",+ "log",+ "prettyplease",+ "proc-macro2",+ "quote",+ "regex",+ "rustc-hash 2.1.1",+ "shlex 1.3.0",+ "syn 2.0.90",+]+[[package]]name = "bit-set"version = "0.6.0"@@ -1203,6 +1223,21 @@ dependencies = ["wgpu",]+[[package]]+name = "cap-rendering-skia"+version = "0.1.0"+dependencies = [+ "anyhow",+ "cap-project",+ "foreign-types-shared 0.3.1",+ "futures",+ "metal 0.27.0",+ "skia-safe",+ "thiserror 1.0.69",+ "tracing",+ "tracing-subscriber",+]+[[package]]name = "cap-utils"version = "0.1.0"@@ -4454,6 +4489,21 @@ dependencies = ["objc",]+[[package]]+name = "metal"+version = "0.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c43f73953f8cbe511f021b58f18c3ce1c3d1ae13fe953293e13345bf83217f25"+dependencies = [+ "bitflags 2.9.0",+ "block",+ "core-graphics-types 0.1.3",+ "foreign-types 0.5.0",+ "log",+ "objc",+ "paste",+]+[[package]]name = "metal"version = "0.29.0"@@ -7102,6 +7152,34 @@ version = "0.3.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"+[[package]]+name = "skia-bindings"+version = "0.86.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2bf215f640b53293844d441e93448b437ca4937595f60e3317fbb03d7ac6783"+dependencies = [+ "bindgen 0.71.1",+ "cc",+ "flate2",+ "heck 0.5.0",+ "lazy_static",+ "regex",+ "serde_json",+ "tar",+ "toml",+]++[[package]]+name = "skia-safe"+version = "0.86.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e372258f52414e04de007326fa497581617c9fa872a3225dca5e42212723c426"+dependencies = [+ "bitflags 2.9.0",+ "lazy_static",+ "skia-bindings",+]+[[package]]name = "skrifa"version = "0.22.3"diff --git a/crates/rendering-skia/Cargo.toml b/crates/rendering-skia/Cargo.tomlnew file mode 100644index 000000000..69f43ca41--- /dev/null+++ b/crates/rendering-skia/Cargo.toml@@ -0,0 +1,32 @@+[package]+name = "cap-rendering-skia"+version = "0.1.0"+edition = "2021"++[lints]+workspace = true++[dependencies]+anyhow.workspace = true+thiserror.workspace = true+tracing.workspace = true+futures = "0.3"++# Skia dependencies+skia-safe = { version = "0.86.1", features = ["metal"] }+tracing-subscriber = "0.3"++# Project dependencies+cap-project = { path = "../project" }++[target.'cfg(target_os = "macos")'.dependencies]+metal = "0.27"+foreign-types-shared = "0.3"++[[bin]]+name = "test-skia"+path = "src/bin/test_skia.rs"++[[bin]]+name = "test-background"+path = "src/bin/test_background.rs"\ No newline at end of filediff --git a/crates/rendering-skia/README.md b/crates/rendering-skia/README.mdnew file mode 100644index 000000000..c0c7bb942--- /dev/null+++ b/crates/rendering-skia/README.md@@ -0,0 +1,94 @@+# cap-rendering-skia++A new rendering backend for Cap using Skia, designed to replace the current wgpu-based renderer.++## Status++This crate implements the basic infrastructure for Skia-based rendering with GPU acceleration support:++- ✅ Basic Skia context creation+- ✅ GPU acceleration via Metal (macOS)+- ✅ CPU fallback for other platforms+- ✅ Surface creation and management+- ✅ Basic rendering operations+- ✅ Pixel readback for frame export++## Building and Testing++```bash+# Build the crate+cargo build -p cap-rendering-skia++# Run the test binary+cargo run -p cap-rendering-skia --bin test-skia++# Run tests+cargo test -p cap-rendering-skia+```++The test binary will:+- Create a Skia context (GPU-accelerated on macOS via Metal)+- Test surface creation with various sizes+- Render a gradient with a green circle+- Save the output as `test_render.ppm`++## Architecture++### GPU Support++- **macOS**: Uses Metal backend for GPU acceleration+- **Other platforms**: Falls back to CPU raster backend+- **Future**: Can add Vulkan/OpenGL support for Linux/Windows++### Core Components++- `SkiaRenderContext`: Main context managing GPU/CPU backends+- Surface management with automatic format selection+- Simple API for creating and reading from surfaces++## Migration Plan Progress++### Phase 1: Setup and Infrastructure ✅+- [x] Create new crate with Skia dependencies+- [x] Basic GPU context initialization+- [x] Surface creation and management+- [x] Test binary to verify functionality++### Phase 2: Core Components (In Progress)+- [ ] Frame pipeline implementation+- [ ] Canvas-based layer system+- [ ] Uniform/parameter structures++### Phase 3: Layer Migration (Not Started)+- [ ] Background layer (gradients, solid colors, images)+- [ ] Display layer (video frames with effects)+- [ ] Cursor layer+- [ ] Camera layer+- [ ] Blur effects+- [ ] Caption/text rendering++### Phase 4: Integration (Not Started)+- [ ] Update render_video_to_channel+- [ ] Migrate frame decoding+- [ ] Update export pipeline++### Phase 5: Optimization and Cleanup (Not Started)+- [ ] Performance profiling+- [ ] Remove wgpu dependencies+- [ ] Clean up old shader files++## Next Steps++1. Implement the frame pipeline for managing render passes+2. Create the layer system with Canvas-based rendering+3. Start migrating individual rendering layers from wgpu shaders to Skia operations+4. Integrate with the existing video processing pipeline++## Benefits Over wgpu++- Simpler API - no manual shader management+- Built-in effects and filters+- Better cross-platform consistency+- Rich text rendering capabilities+- Extensive image format support+- Battle-tested 2D graphics performance\ No newline at end of filediff --git a/crates/rendering-skia/src/bin/test_background.rs b/crates/rendering-skia/src/bin/test_background.rsnew file mode 100644index 000000000..0df1657a3--- /dev/null+++ b/crates/rendering-skia/src/bin/test_background.rs@@ -0,0 +1,329 @@+use cap_project::BackgroundSource;+use cap_rendering_skia::layers::{FrameData, SkiaProjectUniforms};+use cap_rendering_skia::{BackgroundLayer, LayerStack, SkiaRenderContext};+use skia_safe::EncodedImageFormat;+use std::fs;++fn main() -> Result<(), Box<dyn std::error::Error>> {+ // Initialize tracing+ tracing_subscriber::fmt::init();++ println!("=== Background Layer Test ===");++ // Create rendering context+ let mut context = SkiaRenderContext::new()?;+ println!("✓ Created rendering context");++ // Test dimensions+ let width = 800;+ let height = 600;++ // Create output directory+ let output_dir = "test_output";+ fs::create_dir_all(output_dir)?;+ println!("✓ Created output directory: {}", output_dir);++ // Test 1: Solid Color Background+ println!("\n1. Testing solid color background...");+ test_color_background(&mut context, width, height, output_dir)?;++ // Test 2: Gradient Background+ println!("\n2. Testing gradient background...");+ test_gradient_background(&mut context, width, height, output_dir)?;++ // Test 3: Multiple gradients with different angles+ println!("\n3. Testing gradient angles...");+ test_gradient_angles(&mut context, width, height, output_dir)?;++ // Test 4: Picture caching+ println!("\n4. Testing picture caching...");+ test_caching(&mut context, width, height)?;++ println!("\n=== All tests completed successfully! ===");+ println!("Check the '{}' directory for output images.", output_dir);++ Ok(())+}++fn test_color_background(+ context: &mut SkiaRenderContext,+ width: u32,+ height: u32,+ output_dir: &str,+) -> Result<(), Box<dyn std::error::Error>> {+ let mut surface = context.create_surface(width, height)?;+ let mut layer_stack = LayerStack::new();++ // Add background layer+ let background_layer = Box::new(BackgroundLayer::new());+ layer_stack.add_recorded(background_layer);++ // Test different colors+ let colors = [+ ([65535, 0, 0], "red"),+ ([0, 65535, 0], "green"),+ ([0, 0, 65535], "blue"),+ ([32768, 32768, 32768], "gray"),+ ];++ for (color, name) in colors {+ let uniforms = SkiaProjectUniforms {+ output_size: (width, height),+ background: BackgroundSource::Color { value: color },+ };++ let frame_data = FrameData {+ uniforms: uniforms.clone(),+ video_frame: None,+ camera_frame: None,+ cursor_position: None,+ };++ // Prepare and render+ futures::executor::block_on(layer_stack.prepare(&frame_data))?;++ let canvas = surface.canvas();+ canvas.clear(skia_safe::Color::BLACK);+ layer_stack.render(canvas, &uniforms);++ // Flush to ensure rendering is complete+ context.flush();++ // Save output+ let image = surface.image_snapshot();+ println!(+ " - Image snapshot for {}: {}x{}",+ name,+ image.width(),+ image.height()+ );+ match image.encode(context.direct_context(), EncodedImageFormat::PNG, 100) {+ Some(data) => {+ let path = format!("{}/background_color_{}.png", output_dir, name);+ fs::write(&path, data.as_bytes())?;+ println!(" ✓ Saved {} background to: {}", name, path);+ }+ None => {+ println!(" ✗ Failed to encode {} color image to PNG", name);+ }+ }+ }++ Ok(())+}++fn test_gradient_background(+ context: &mut SkiaRenderContext,+ width: u32,+ height: u32,+ output_dir: &str,+) -> Result<(), Box<dyn std::error::Error>> {+ let mut surface = context.create_surface(width, height)?;+ let mut layer_stack = LayerStack::new();++ // Add background layer+ let background_layer = Box::new(BackgroundLayer::new());+ layer_stack.add_recorded(background_layer);++ // Test gradient+ let uniforms = SkiaProjectUniforms {+ output_size: (width, height),+ background: BackgroundSource::Gradient {+ from: [65535, 0, 0], // Red+ to: [0, 0, 65535], // Blue+ angle: 45,+ },+ };++ let frame_data = FrameData {+ uniforms: uniforms.clone(),+ video_frame: None,+ camera_frame: None,+ cursor_position: None,+ };++ // Prepare and render+ futures::executor::block_on(layer_stack.prepare(&frame_data))?;++ let canvas = surface.canvas();+ canvas.clear(skia_safe::Color::BLACK);+ layer_stack.render(canvas, &uniforms);++ // Flush to ensure rendering is complete+ context.flush();++ // Save output+ let image = surface.image_snapshot();+ println!(+ " - Image snapshot created: {}x{}",+ image.width(),+ image.height()+ );+ match image.encode(context.direct_context(), EncodedImageFormat::PNG, 100) {+ Some(data) => {+ let path = format!("{}/background_gradient.png", output_dir);+ fs::write(&path, data.as_bytes())?;+ println!(" ✓ Saved gradient background to: {}", path);+ }+ None => {+ println!(" ✗ Failed to encode gradient image to PNG");+ }+ }++ Ok(())+}++fn test_gradient_angles(+ context: &mut SkiaRenderContext,+ width: u32,+ height: u32,+ output_dir: &str,+) -> Result<(), Box<dyn std::error::Error>> {+ let mut surface = context.create_surface(width, height)?;+ let mut layer_stack = LayerStack::new();++ // Add background layer+ let background_layer = Box::new(BackgroundLayer::new());+ layer_stack.add_recorded(background_layer);++ // Test different angles+ let angles = [0u16, 45, 90, 135, 180, 225, 270, 315];++ for angle in angles {+ let uniforms = SkiaProjectUniforms {+ output_size: (width, height),+ background: BackgroundSource::Gradient {+ from: [65535, 32768, 0], // Orange+ to: [32768, 0, 65535], // Purple+ angle,+ },+ };++ let frame_data = FrameData {+ uniforms: uniforms.clone(),+ video_frame: None,+ camera_frame: None,+ cursor_position: None,+ };++ // Prepare and render+ futures::executor::block_on(layer_stack.prepare(&frame_data))?;++ let canvas = surface.canvas();+ canvas.clear(skia_safe::Color::BLACK);+ layer_stack.render(canvas, &uniforms);++ // Flush to ensure rendering is complete+ context.flush();++ // Save output+ let image = surface.image_snapshot();+ println!(+ " - Image snapshot for angle {}: {}x{}",+ angle,+ image.width(),+ image.height()+ );+ match image.encode(context.direct_context(), EncodedImageFormat::PNG, 100) {+ Some(data) => {+ let path = format!(+ "{}/background_gradient_angle_{}.png",+ output_dir, angle as i32+ );+ fs::write(&path, data.as_bytes())?;+ println!(" ✓ Saved gradient with angle {} to: {}", angle, path);+ }+ None => {+ println!(+ " ✗ Failed to encode gradient angle {} image to PNG",+ angle+ );+ }+ }+ }++ Ok(())+}++fn test_caching(+ context: &mut SkiaRenderContext,+ width: u32,+ height: u32,+) -> Result<(), Box<dyn std::error::Error>> {+ let mut surface = context.create_surface(width, height)?;+ let mut layer_stack = LayerStack::new();++ // Add background layer+ let background_layer = Box::new(BackgroundLayer::new());+ let _layer_id = layer_stack.add_recorded(background_layer);++ let uniforms = SkiaProjectUniforms {+ output_size: (width, height),+ background: BackgroundSource::Gradient {+ from: [0, 65535, 0],+ to: [0, 0, 65535],+ angle: 90,+ },+ };++ let frame_data = FrameData {+ uniforms: uniforms.clone(),+ video_frame: None,+ camera_frame: None,+ cursor_position: None,+ };++ // First render - should record+ println!(" - First render (recording)...");+ let start = std::time::Instant::now();+ futures::executor::block_on(layer_stack.prepare(&frame_data))?;+ let canvas = surface.canvas();+ layer_stack.render(canvas, &uniforms);+ let first_render_time = start.elapsed();+ println!(" Time: {:?}", first_render_time);++ // Second render with same uniforms - should use cache+ println!(" - Second render (using cache)...");+ let start = std::time::Instant::now();+ let canvas = surface.canvas();+ layer_stack.render(canvas, &uniforms);+ let cached_render_time = start.elapsed();+ println!(" Time: {:?}", cached_render_time);++ // Cache should make it faster+ if cached_render_time < first_render_time {+ println!(+ " ✓ Caching is working! Cached render is {:.2}x faster",+ first_render_time.as_secs_f64() / cached_render_time.as_secs_f64()+ );+ } else {+ println!(" ⚠ Cached render was not faster (may be due to small render time)");+ }++ // Change uniforms - should re-record+ println!(" - Third render (new gradient, re-recording)...");+ let new_uniforms = SkiaProjectUniforms {+ output_size: (width, height),+ background: BackgroundSource::Gradient {+ from: [65535, 0, 0],+ to: [65535, 65535, 0],+ angle: 45,+ },+ };++ let new_frame_data = FrameData {+ uniforms: new_uniforms.clone(),+ video_frame: None,+ camera_frame: None,+ cursor_position: None,+ };++ let start = std::time::Instant::now();+ futures::executor::block_on(layer_stack.prepare(&new_frame_data))?;+ let canvas = surface.canvas();+ layer_stack.render(canvas, &new_uniforms);+ let new_render_time = start.elapsed();+ println!(" Time: {:?}", new_render_time);++ Ok(())+}diff --git a/crates/rendering-skia/src/bin/test_skia.rs b/crates/rendering-skia/src/bin/test_skia.rsnew file mode 100644index 000000000..12f183836--- /dev/null+++ b/crates/rendering-skia/src/bin/test_skia.rs@@ -0,0 +1,128 @@+use cap_rendering_skia::{SkiaRenderContext, SkiaRenderingError};+use std::fs;++fn main() -> Result<(), Box<dyn std::error::Error>> {+ // Initialize tracing for debug output+ tracing_subscriber::fmt::init();++ println!("=== Skia Rendering Test ===");+ println!("Testing Skia context creation and basic rendering...\n");++ // Create Skia context+ println!("1. Creating Skia context...");+ let mut context = match SkiaRenderContext::new() {+ Ok(ctx) => {+ println!(" ✓ Skia context created successfully");+ ctx+ }+ Err(e) => {+ println!(" ✗ Failed to create Skia context: {}", e);+ return Err(e.into());+ }+ };++ // Check if GPU acceleration is enabled+ if context.is_gpu_accelerated() {+ println!(" ✓ GPU acceleration: ENABLED (Metal)");+ } else {+ println!(" ⚠ GPU acceleration: DISABLED (using CPU backend)");+ }++ // Test surface creation+ println!("\n2. Testing surface creation...");+ let test_sizes = [(800, 600), (1920, 1080), (100, 100)];++ for (width, height) in test_sizes {+ match context.create_surface(width, height) {+ Ok(_) => {+ println!(" ✓ Created {}x{} surface", width, height);+ }+ Err(e) => {+ println!(" ✗ Failed to create {}x{} surface: {}", width, height, e);+ }+ }+ }++ // Test invalid surface creation+ println!("\n3. Testing error handling...");+ match context.create_surface(0, 100) {+ Ok(_) => {+ println!(" ✗ Unexpectedly succeeded creating 0x100 surface");+ }+ Err(SkiaRenderingError::InvalidDimensions(_)) => {+ println!(" ✓ Correctly rejected invalid dimensions");+ }+ Err(e) => {+ println!(" ✗ Wrong error type: {}", e);+ }+ }++ // Test rendering+ println!("\n4. Testing rendering...");+ let render_width = 800;+ let render_height = 600;++ match context.test_render(render_width, render_height) {+ Ok(pixels) => {+ println!(" ✓ Rendering completed successfully");+ println!(" - Output size: {} bytes", pixels.len());+ println!(+ " - Expected size: {} bytes",+ render_width * render_height * 4+ );++ // Save as PPM for easy verification+ let output_path = "test_render.ppm";+ save_as_ppm(&pixels, render_width, render_height, output_path)?;+ println!(" ✓ Saved test render to: {}", output_path);++ // Verify some pixels+ println!("\n5. Verifying pixel data...");+ let center_idx =+ (((render_height / 2) * render_width + (render_width / 2)) * 4) as usize;+ let center_pixel = &pixels[center_idx..center_idx + 4];+ println!(" - Center pixel RGBA: {:?}", center_pixel);++ // The center should be greenish (from the circle)+ if center_pixel[1] > center_pixel[0] && center_pixel[1] > center_pixel[2] {+ println!(" ✓ Center pixel is green as expected");+ } else {+ println!(" ! Center pixel color unexpected");+ }+ }+ Err(e) => {+ println!(" ✗ Rendering failed: {}", e);+ return Err(e.into());+ }+ }++ println!("\n=== All tests completed ===");+ println!("Skia integration is working correctly!");++ Ok(())+}++fn save_as_ppm(pixels: &[u8], width: u32, height: u32, path: &str) -> std::io::Result<()> {+ use std::io::Write;++ let mut file = fs::File::create(path)?;++ // PPM header+ writeln!(file, "P3")?;+ writeln!(file, "{} {}", width, height)?;+ writeln!(file, "255")?;++ // Write pixels (PPM is RGB, our data is RGBA)+ for y in 0..height {+ for x in 0..width {+ let idx = ((y * width + x) * 4) as usize;+ let r = pixels[idx];+ let g = pixels[idx + 1];+ let b = pixels[idx + 2];+ write!(file, "{} {} {} ", r, g, b)?;+ }+ writeln!(file)?;+ }++ Ok(())+}diff --git a/crates/rendering-skia/src/context.rs b/crates/rendering-skia/src/context.rsnew file mode 100644index 000000000..fbc45c93c--- /dev/null+++ b/crates/rendering-skia/src/context.rs@@ -0,0 +1,215 @@+use crate::SkiaRenderingError;+use skia_safe::{gpu, surfaces, Color, Surface};++#[cfg(target_os = "macos")]+use skia_safe::gpu::{mtl, DirectContext, SurfaceOrigin};++pub struct SkiaRenderContext {+ #[cfg(target_os = "macos")]+ gpu_context: Option<GpuContext>,+ _phantom: std::marker::PhantomData<()>,+}++#[cfg(target_os = "macos")]+struct GpuContext {+ direct_context: DirectContext,+ _device: metal::Device,+ _command_queue: metal::CommandQueue,+}++impl SkiaRenderContext {+ pub fn new() -> Result<Self, SkiaRenderingError> {+ #[cfg(target_os = "macos")]+ {+ // Try to create GPU context on macOS+ match Self::create_metal_context() {+ Ok(gpu_context) => {+ tracing::info!("Created Metal GPU context");+ Ok(Self {+ gpu_context: Some(gpu_context),+ _phantom: std::marker::PhantomData,+ })+ }+ Err(e) => {+ tracing::warn!("Failed to create Metal context: {}, falling back to CPU", e);+ Ok(Self {+ gpu_context: None,+ _phantom: std::marker::PhantomData,+ })+ }+ }+ }++ #[cfg(not(target_os = "macos"))]+ {+ tracing::info!("Creating Skia context (CPU backend)");+ Ok(Self {+ _phantom: std::marker::PhantomData,+ })+ }+ }++ #[cfg(target_os = "macos")]+ fn create_metal_context() -> Result<GpuContext, SkiaRenderingError> {+ use foreign_types_shared::ForeignType;++ let device =+ metal::Device::system_default().ok_or_else(|| SkiaRenderingError::NoGpuContext)?;++ let command_queue = device.new_command_queue();++ let backend = unsafe {+ mtl::BackendContext::new(+ device.as_ptr() as mtl::Handle,+ command_queue.as_ptr() as mtl::Handle,+ )+ };++ let direct_context = gpu::direct_contexts::make_metal(&backend, None)+ .ok_or_else(|| SkiaRenderingError::NoGpuContext)?;++ Ok(GpuContext {+ direct_context,+ _device: device,+ _command_queue: command_queue,+ })+ }++ pub fn create_surface(+ &mut self,+ width: u32,+ height: u32,+ ) -> Result<Surface, SkiaRenderingError> {+ if width == 0 || height == 0 {+ return Err(SkiaRenderingError::InvalidDimensions(format!(+ "Invalid surface dimensions: {}x{}",+ width, height+ )));+ }++ #[cfg(target_os = "macos")]+ {+ if let Some(ref mut gpu_context) = self.gpu_context {+ tracing::debug!("Creating GPU surface with dimensions {}x{}", width, height);++ let image_info = skia_safe::ImageInfo::new_n32_premul(+ (width as i32, height as i32),+ Some(skia_safe::ColorSpace::new_srgb()),+ );++ return gpu::surfaces::render_target(+ &mut gpu_context.direct_context,+ gpu::Budgeted::Yes,+ &image_info,+ None,+ SurfaceOrigin::TopLeft,+ None,+ false,+ false,+ )+ .ok_or_else(|| {+ SkiaRenderingError::SurfaceCreationFailed(format!(+ "Failed to create {}x{} GPU surface",+ width, height+ ))+ });+ }+ }++ // Fallback to CPU surface+ tracing::debug!("Creating CPU surface with dimensions {}x{}", width, height);+ surfaces::raster_n32_premul((width as i32, height as i32)).ok_or_else(|| {+ SkiaRenderingError::SurfaceCreationFailed(format!(+ "Failed to create {}x{} surface",+ width, height+ ))+ })+ }++ pub fn flush(&mut self) {+ #[cfg(target_os = "macos")]+ {+ if let Some(ref mut gpu_context) = self.gpu_context {+ gpu_context.direct_context.flush_and_submit();+ }+ }+ }++ /// Test rendering - draws a simple gradient+ pub fn test_render(&mut self, width: u32, height: u32) -> Result<Vec<u8>, SkiaRenderingError> {+ let mut surface = self.create_surface(width, height)?;+ let canvas = surface.canvas();++ // Clear to white+ canvas.clear(Color::WHITE);++ // Draw a simple gradient+ use skia_safe::{Paint, Point, Shader, TileMode};++ let mut paint = Paint::default();+ let colors = vec![Color::from_rgb(255, 0, 0), Color::from_rgb(0, 0, 255)];+ let shader = Shader::linear_gradient(+ (+ Point::new(0.0, 0.0),+ Point::new(width as f32, height as f32),+ ),+ colors.as_slice(),+ None,+ TileMode::Clamp,+ None,+ None,+ )+ .unwrap();+ paint.set_shader(shader);++ canvas.draw_rect(+ skia_safe::Rect::from_xywh(0.0, 0.0, width as f32, height as f32),+ &paint,+ );++ // Draw a circle+ let mut circle_paint = Paint::default();+ circle_paint.set_color(Color::from_rgb(0, 255, 0));+ circle_paint.set_anti_alias(true);+ canvas.draw_circle(+ Point::new(width as f32 / 2.0, height as f32 / 2.0),+ width.min(height) as f32 * 0.3,+ &circle_paint,+ );++ // Flush GPU operations if using GPU backend+ self.flush();++ // Read pixels+ let image_info = surface.image_info();+ let mut pixels = vec![0u8; (width * height * 4) as usize];++ if !surface.read_pixels(&image_info, &mut pixels, (width * 4) as usize, (0, 0)) {+ return Err(SkiaRenderingError::ReadPixelsFailed);+ }++ Ok(pixels)+ }++ pub fn is_gpu_accelerated(&self) -> bool {+ #[cfg(target_os = "macos")]+ {+ self.gpu_context.is_some()+ }+ #[cfg(not(target_os = "macos"))]+ {+ false+ }+ }++ /// Get mutable reference to the direct context (if GPU accelerated)+ #[cfg(target_os = "macos")]+ pub fn direct_context(&mut self) -> Option<&mut DirectContext> {+ self.gpu_context.as_mut().map(|ctx| &mut ctx.direct_context)+ }++ #[cfg(not(target_os = "macos"))]+ pub fn direct_context(&mut self) -> Option<&mut DirectContext> {+ None+ }+}diff --git a/crates/rendering-skia/src/layers/background.rs b/crates/rendering-skia/src/layers/background.rsnew file mode 100644index 000000000..0c35d5b91--- /dev/null+++ b/crates/rendering-skia/src/layers/background.rs@@ -0,0 +1,339 @@+use crate::layers::{FrameData, RecordableLayer, SkiaProjectUniforms};+use crate::SkiaRenderingError;+use cap_project::BackgroundSource;+use skia_safe::{+ Canvas, Color, Image, Paint, Picture, PictureRecorder, Point, Rect, Shader, TileMode,+};+use std::path::PathBuf;++/// Background configuration+#[derive(Debug, Clone, PartialEq)]+pub enum Background {+ Color([u16; 3]),+ Gradient {+ from: [u16; 3],+ to: [u16; 3],+ angle: u16,+ },+ Image {+ path: PathBuf,+ },+ Wallpaper {+ path: PathBuf,+ },+}++impl From<BackgroundSource> for Background {+ fn from(source: BackgroundSource) -> Self {+ match source {+ BackgroundSource::Color { value } => Background::Color(value),+ BackgroundSource::Gradient { from, to, angle } => {+ Background::Gradient { from, to, angle }+ }+ BackgroundSource::Image { path } => {+ if let Some(path) = path {+ Background::Image {+ path: PathBuf::from(path),+ }+ } else {+ // Default to black if no path+ Background::Color([0, 0, 0])+ }+ }+ BackgroundSource::Wallpaper { path } => {+ if let Some(path) = path {+ Background::Wallpaper {+ path: PathBuf::from(path),+ }+ } else {+ // Default to black if no path+ Background::Color([0, 0, 0])+ }+ }+ }+ }+}++/// Skia-based background layer with picture caching+pub struct BackgroundLayer {+ // Current background configuration+ current_background: Option<Background>,++ // Track what we rendered last to detect changes+ last_rendered_background: Option<Background>,+ last_rendered_size: (u32, u32),++ // For image backgrounds+ image_path: Option<PathBuf>,+ loaded_image: Option<Image>,+}++impl BackgroundLayer {+ pub fn new() -> Self {+ Self {+ current_background: None,+ last_rendered_background: None,+ last_rendered_size: (0, 0),+ image_path: None,+ loaded_image: None,+ }+ }++ fn render_background(&self, canvas: &Canvas, bounds: Rect) {+ match &self.current_background {+ Some(Background::Color(color)) => {+ self.render_color(canvas, color, bounds);+ }+ Some(Background::Gradient { from, to, angle }) => {+ self.render_gradient(canvas, from, to, *angle, bounds);+ }+ Some(Background::Image { .. }) | Some(Background::Wallpaper { .. }) => {+ if let Some(image) = &self.loaded_image {+ self.render_image(canvas, image, bounds);+ } else {+ // Fallback to black if image not loaded+ canvas.clear(Color::BLACK);+ }+ }+ None => {+ // Clear to black as default+ canvas.clear(Color::BLACK);+ }+ }+ }++ fn render_color(&self, canvas: &Canvas, color: &[u16; 3], _bounds: Rect) {+ // Convert from u16 (0-65535) to u8 (0-255)+ let skia_color = Color::from_argb(+ 255, // Full opacity+ (color[0] >> 8) as u8,+ (color[1] >> 8) as u8,+ (color[2] >> 8) as u8,+ );+ canvas.clear(skia_color);+ }++ fn render_gradient(+ &self,+ canvas: &Canvas,+ from: &[u16; 3],+ to: &[u16; 3],+ angle: u16,+ bounds: Rect,+ ) {+ // Convert colors from u16 (0-65535) to u8 (0-255)+ let start_color = Color::from_argb(+ 255, // Full opacity+ (from[0] >> 8) as u8,+ (from[1] >> 8) as u8,+ (from[2] >> 8) as u8,+ );+ let end_color = Color::from_argb(+ 255, // Full opacity+ (to[0] >> 8) as u8,+ (to[1] >> 8) as u8,+ (to[2] >> 8) as u8,+ );++ // Convert angle to radians and add 270 degrees to match the original shader+ let angle_rad = (angle as f32 + 270.0).to_radians();+ let center = Point::new(bounds.width() / 2.0, bounds.height() / 2.0);++ // Calculate gradient vector based on angle+ // Use diagonal length to ensure gradient covers entire bounds+ let gradient_length = (bounds.width().powi(2) + bounds.height().powi(2)).sqrt();+ let dx = angle_rad.cos() * gradient_length / 2.0;+ let dy = angle_rad.sin() * gradient_length / 2.0;++ let start_point = Point::new(center.x - dx, center.y - dy);+ let end_point = Point::new(center.x + dx, center.y + dy);++ // Create gradient shader+ let colors = vec![start_color, end_color];+ if let Some(shader) = Shader::linear_gradient(+ (start_point, end_point),+ colors.as_slice(),+ None,+ TileMode::Clamp,+ None,+ None,+ ) {+ let mut paint = Paint::default();+ paint.set_shader(shader);+ canvas.draw_rect(bounds, &paint);+ } else {+ // Fallback to start color if gradient creation fails+ canvas.clear(start_color);+ }+ }++ fn render_image(&self, canvas: &Canvas, image: &Image, bounds: Rect) {+ // Calculate scaling to cover the entire background (similar to CSS background-size: cover)+ let image_aspect = image.width() as f32 / image.height() as f32;+ let bounds_aspect = bounds.width() / bounds.height();++ let scale = if image_aspect > bounds_aspect {+ // Image is wider - fit to height+ bounds.height() / image.height() as f32+ } else {+ // Image is taller - fit to width+ bounds.width() / image.width() as f32+ };++ // Center the image+ let scaled_width = image.width() as f32 * scale;+ let scaled_height = image.height() as f32 * scale;+ let x = bounds.left() + (bounds.width() - scaled_width) / 2.0;+ let y = bounds.top() + (bounds.height() - scaled_height) / 2.0;++ canvas.save();+ canvas.translate((x, y));+ canvas.scale((scale, scale));++ let mut paint = Paint::default();+ paint.set_anti_alias(true);++ canvas.draw_image(image, Point::default(), Some(&paint));+ canvas.restore();+ }+}++impl RecordableLayer for BackgroundLayer {+ fn record(+ &mut self,+ recorder: &mut PictureRecorder,+ bounds: Rect,+ uniforms: &SkiaProjectUniforms,+ ) -> Option<Picture> {+ let canvas = recorder.begin_recording(bounds, None);+ self.render_background(canvas, bounds);++ // Update what was last rendered+ self.last_rendered_background = self.current_background.clone();+ self.last_rendered_size = uniforms.output_size;++ recorder.finish_recording_as_picture(None)+ }++ fn needs_update(&self, uniforms: &SkiaProjectUniforms) -> bool {+ let new_background = Background::from(uniforms.background.clone());+ let new_size = uniforms.output_size;++ // Check against what was last rendered, not what's currently prepared+ self.last_rendered_background.as_ref() != Some(&new_background)+ || self.last_rendered_size != new_size+ }++ fn prepare(&mut self, frame_data: &FrameData) -> Result<(), SkiaRenderingError> {+ let new_background = Background::from(frame_data.uniforms.background.clone());++ // Handle image loading if needed+ match &new_background {+ Background::Image { ref path } | Background::Wallpaper { ref path } => {+ if self.image_path.as_ref() != Some(path) || self.loaded_image.is_none() {+ // For now, we'll do synchronous loading. In a real implementation,+ // this should be async or cached at a higher level+ match std::fs::read(path) {+ Ok(image_data) => {+ let data = skia_safe::Data::new_copy(&image_data);+ if let Some(image) = Image::from_encoded(&data) {+ self.loaded_image = Some(image);+ self.image_path = Some(path.clone());+ } else {+ tracing::error!("Failed to decode image: {:?}", path);+ return Err(SkiaRenderingError::Other(anyhow::anyhow!(+ "Failed to decode image"+ )));+ }+ }+ Err(e) => {+ tracing::error!("Failed to load image: {:?}, error: {}", path, e);+ return Err(SkiaRenderingError::Other(anyhow::anyhow!(+ "Failed to load image: {}",+ e+ )));+ }+ }+ }+ }+ _ => {}+ }++ // Update current state (but not last_rendered, that happens in record())+ self.current_background = Some(new_background);++ Ok(())+ }++ fn is_enabled(&self) -> bool {+ self.current_background.is_some()+ }+}++impl Default for BackgroundLayer {+ fn default() -> Self {+ Self::new()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_background_from_source() {+ // Test color conversion+ let color_source = BackgroundSource::Color {+ value: [65535, 32768, 0],+ };+ let color_bg = Background::from(color_source);+ assert!(matches!(color_bg, Background::Color([65535, 32768, 0])));++ // Test gradient conversion+ let gradient_source = BackgroundSource::Gradient {+ from: [65535, 0, 0],+ to: [0, 0, 65535],+ angle: 45,+ };+ let gradient_bg = Background::from(gradient_source);+ assert!(matches!(+ gradient_bg,+ Background::Gradient { angle: 45, .. }+ ));+ }++ #[test]+ fn test_needs_update() {+ let mut layer = BackgroundLayer::new();+ let uniforms = SkiaProjectUniforms {+ output_size: (800, 600),+ background: BackgroundSource::Color {+ value: [65535, 0, 0],+ },+ };++ // Should need update on first check+ assert!(layer.needs_update(&uniforms));++ // Prepare the layer+ let frame_data = FrameData {+ uniforms: uniforms.clone(),+ video_frame: None,+ camera_frame: None,+ cursor_position: None,+ };+ layer.prepare(&frame_data).unwrap();++ // Should not need update with same uniforms+ assert!(!layer.needs_update(&uniforms));++ // Should need update with different color+ let new_uniforms = SkiaProjectUniforms {+ output_size: (800, 600),+ background: BackgroundSource::Color {+ value: [0, 65535, 0],+ },+ };+ assert!(layer.needs_update(&new_uniforms));+ }+}diff --git a/crates/rendering-skia/src/layers/mod.rs b/crates/rendering-skia/src/layers/mod.rsnew file mode 100644index 000000000..724acc191--- /dev/null+++ b/crates/rendering-skia/src/layers/mod.rs@@ -0,0 +1,210 @@+use crate::SkiaRenderingError;+use skia_safe::{Canvas, Picture, PictureRecorder, Rect};+use std::collections::HashMap;++pub mod background;++pub use background::BackgroundLayer;++/// Project uniforms for Skia rendering (placeholder for now)+#[derive(Debug, Clone)]+pub struct SkiaProjectUniforms {+ pub output_size: (u32, u32),+ pub background: cap_project::BackgroundSource,+ // Add more fields as needed+}++/// Frame data passed to layers during preparation+pub struct FrameData {+ pub uniforms: SkiaProjectUniforms,+ pub video_frame: Option<Vec<u8>>,+ pub camera_frame: Option<Vec<u8>>,+ pub cursor_position: Option<(f32, f32)>,+}++/// Unique identifier for layers+pub type LayerId = usize;++/// Records drawing commands for deferred playback+pub trait RecordableLayer: Send {+ /// Record drawing commands without immediate execution+ fn record(+ &mut self,+ recorder: &mut PictureRecorder,+ bounds: Rect,+ uniforms: &SkiaProjectUniforms,+ ) -> Option<Picture>;++ /// Indicates if this layer's content changed and needs re-recording+ fn needs_update(&self, uniforms: &SkiaProjectUniforms) -> bool;++ /// Prepare any resources needed for this frame (e.g., load images)+ fn prepare(&mut self, _frame_data: &FrameData) -> Result<(), SkiaRenderingError> {+ Ok(())+ }++ /// Whether this layer should be rendered at all+ fn is_enabled(&self) -> bool {+ true+ }+}++/// Direct canvas rendering for dynamic content+pub trait ImmediateLayer: Send {+ /// Render directly to the provided canvas+ fn render(&self, canvas: &Canvas, uniforms: &SkiaProjectUniforms);++ /// Prepare any resources needed for this frame+ fn prepare(&mut self, _frame_data: &FrameData) -> Result<(), SkiaRenderingError> {+ Ok(())+ }++ /// Whether this layer should be rendered at all+ fn is_enabled(&self) -> bool {+ true+ }+}++/// Layer that renders to an intermediate surface (for effects like blur)+pub trait SurfaceLayer: Send {+ /// Render to own surface, return picture for compositing+ fn render_to_surface(&mut self, uniforms: &SkiaProjectUniforms) -> Option<Picture>;++ /// Composite this layer's output onto the target canvas+ fn composite(&self, canvas: &Canvas, picture: &Picture, uniforms: &SkiaProjectUniforms);++ /// Prepare any resources needed for this frame+ fn prepare(&mut self, _frame_data: &FrameData) -> Result<(), SkiaRenderingError> {+ Ok(())+ }++ /// Whether this layer should be rendered at all+ fn is_enabled(&self) -> bool {+ true+ }+}++/// Layer entry in the stack+pub enum LayerEntry {+ Immediate(Box<dyn ImmediateLayer>),+ Recorded(Box<dyn RecordableLayer>),+ Surface(Box<dyn SurfaceLayer>),+}++/// Optimized layer stack with caching+pub struct LayerStack {+ layers: Vec<(LayerId, LayerEntry)>,+ picture_cache: HashMap<LayerId, Picture>,+ next_id: LayerId,+}++impl LayerStack {+ pub fn new() -> Self {+ Self {+ layers: Vec::new(),+ picture_cache: HashMap::new(),+ next_id: 0,+ }+ }++ /// Add a recordable layer (for static/semi-static content)+ pub fn add_recorded(&mut self, layer: Box<dyn RecordableLayer>) -> LayerId {+ let id = self.next_id;+ self.next_id += 1;+ self.layers.push((id, LayerEntry::Recorded(layer)));+ id+ }++ /// Add an immediate layer (for dynamic content)+ pub fn add_immediate(&mut self, layer: Box<dyn ImmediateLayer>) -> LayerId {+ let id = self.next_id;+ self.next_id += 1;+ self.layers.push((id, LayerEntry::Immediate(layer)));+ id+ }++ /// Add a surface layer (for effects)+ pub fn add_surface(&mut self, layer: Box<dyn SurfaceLayer>) -> LayerId {+ let id = self.next_id;+ self.next_id += 1;+ self.layers.push((id, LayerEntry::Surface(layer)));+ id+ }++ /// Prepare all layers for the next frame+ pub async fn prepare(&mut self, frame_data: &FrameData) -> Result<(), SkiaRenderingError> {+ for (_, layer) in &mut self.layers {+ match layer {+ LayerEntry::Immediate(layer) => layer.prepare(frame_data)?,+ LayerEntry::Recorded(layer) => layer.prepare(frame_data)?,+ LayerEntry::Surface(layer) => layer.prepare(frame_data)?,+ }+ }+ Ok(())+ }++ /// Render all layers to the canvas+ pub fn render(&mut self, canvas: &Canvas, uniforms: &SkiaProjectUniforms) {+ let bounds = canvas.local_clip_bounds().unwrap_or_else(|| {+ Rect::from_xywh(+ 0.0,+ 0.0,+ uniforms.output_size.0 as f32,+ uniforms.output_size.1 as f32,+ )+ });++ for (id, layer) in &mut self.layers {+ match layer {+ LayerEntry::Immediate(layer) => {+ if layer.is_enabled() {+ canvas.save();+ layer.render(canvas, uniforms);+ canvas.restore();+ }+ }+ LayerEntry::Recorded(layer) => {+ if !layer.is_enabled() {+ continue;+ }++ // Check if we need to re-record+ if layer.needs_update(uniforms) || !self.picture_cache.contains_key(id) {+ let mut recorder = PictureRecorder::new();+ if let Some(picture) = layer.record(&mut recorder, bounds, uniforms) {+ self.picture_cache.insert(*id, picture);+ }+ }++ // Play back the cached picture+ if let Some(picture) = self.picture_cache.get(id) {+ canvas.draw_picture(picture, None, None);+ }+ }+ LayerEntry::Surface(layer) => {+ if layer.is_enabled() {+ if let Some(picture) = layer.render_to_surface(uniforms) {+ layer.composite(canvas, &picture, uniforms);+ }+ }+ }+ }+ }+ }++ /// Clear cached pictures for all layers+ pub fn clear_cache(&mut self) {+ self.picture_cache.clear();+ }++ /// Clear cache for a specific layer+ pub fn invalidate_layer(&mut self, id: LayerId) {+ self.picture_cache.remove(&id);+ }+}++impl Default for LayerStack {+ fn default() -> Self {+ Self::new()+ }+}diff --git a/crates/rendering-skia/src/lib.rs b/crates/rendering-skia/src/lib.rsnew file mode 100644index 000000000..efba1fe56--- /dev/null+++ b/crates/rendering-skia/src/lib.rs@@ -0,0 +1,36 @@+use thiserror::Error;++pub mod context;+pub mod layers;++pub use context::SkiaRenderContext;+pub use layers::{BackgroundLayer, LayerStack};++#[derive(Error, Debug)]+pub enum SkiaRenderingError {+ #[error("Failed to create GPU context")]+ NoGpuContext,++ #[error("Failed to create surface: {0}")]+ SurfaceCreationFailed(String),++ #[error("Failed to read pixels from surface")]+ ReadPixelsFailed,++ #[error("Invalid dimensions: {0}")]+ InvalidDimensions(String),++ #[error(transparent)]+ Other(#[from] anyhow::Error),+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_error_display() {+ let err = SkiaRenderingError::NoGpuContext;+ assert_eq!(err.to_string(), "Failed to create GPU context");+ }+}diff --git a/crates/rendering-skia/test_output/background_color_blue.png b/crates/rendering-skia/test_output/background_color_blue.pngnew file mode 100644index 000000000..aa35a97a5Binary files /dev/null and b/crates/rendering-skia/test_output/background_color_blue.png differdiff --git a/crates/rendering-skia/test_output/background_color_gray.png b/crates/rendering-skia/test_output/background_color_gray.pngnew file mode 100644index 000000000..7542d5156Binary files /dev/null and b/crates/rendering-skia/test_output/background_color_gray.png differdiff --git a/crates/rendering-skia/test_output/background_color_green.png b/crates/rendering-skia/test_output/background_color_green.pngnew file mode 100644index 000000000..6375193abBinary files /dev/null and b/crates/rendering-skia/test_output/background_color_green.png differdiff --git a/crates/rendering-skia/test_output/background_color_red.png b/crates/rendering-skia/test_output/background_color_red.pngnew file mode 100644index 000000000..c6627a8d0Binary files /dev/null and b/crates/rendering-skia/test_output/background_color_red.png differdiff --git a/crates/rendering-skia/test_output/background_gradient.png b/crates/rendering-skia/test_output/background_gradient.pngnew file mode 100644index 000000000..1802f9ad9Binary files /dev/null and b/crates/rendering-skia/test_output/background_gradient.png differdiff --git a/crates/rendering-skia/test_output/background_gradient_angle_0.png b/crates/rendering-skia/test_output/background_gradient_angle_0.pngnew file mode 100644index 000000000..5f8ce6d83Binary files /dev/null and b/crates/rendering-skia/test_output/background_gradient_angle_0.png differdiff --git a/crates/rendering-skia/test_output/background_gradient_angle_135.png b/crates/rendering-skia/test_output/background_gradient_angle_135.pngnew file mode 100644index 000000000..8a1e6414dBinary files /dev/null and b/crates/rendering-skia/test_output/background_gradient_angle_135.png differdiff --git a/crates/rendering-skia/test_output/background_gradient_angle_180.png b/crates/rendering-skia/test_output/background_gradient_angle_180.pngnew file mode 100644index 000000000..c8707f30dBinary files /dev/null and b/crates/rendering-skia/test_output/background_gradient_angle_180.png differdiff --git a/crates/rendering-skia/test_output/background_gradient_angle_225.png b/crates/rendering-skia/test_output/background_gradient_angle_225.pngnew file mode 100644index 000000000..734ece69fBinary files /dev/null and b/crates/rendering-skia/test_output/background_gradient_angle_225.png differdiff --git a/crates/rendering-skia/test_output/background_gradient_angle_270.png b/crates/rendering-skia/test_output/background_gradient_angle_270.pngnew file mode 100644index 000000000..656e8cfc1Binary files /dev/null and b/crates/rendering-skia/test_output/background_gradient_angle_270.png differdiff --git a/crates/rendering-skia/test_output/background_gradient_angle_315.png b/crates/rendering-skia/test_output/background_gradient_angle_315.pngnew file mode 100644index 000000000..5931e8364Binary files /dev/null and b/crates/rendering-skia/test_output/background_gradient_angle_315.png differdiff --git a/crates/rendering-skia/test_output/background_gradient_angle_45.png b/crates/rendering-skia/test_output/background_gradient_angle_45.pngnew file mode 100644index 000000000..2be2efba5Binary files /dev/null and b/crates/rendering-skia/test_output/background_gradient_angle_45.png differdiff --git a/crates/rendering-skia/test_output/background_gradient_angle_90.png b/crates/rendering-skia/test_output/background_gradient_angle_90.pngnew file mode 100644index 000000000..dc8640e29Binary files /dev/null and b/crates/rendering-skia/test_output/background_gradient_angle_90.png differ