Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Cursor implementation + HW accel
Richie McIlroyeb72e7cefe52
diff --git a/.cargo/config.toml b/.cargo/config.tomlindex 7d8c3a505..deba86f3c 100644--- a/.cargo/config.toml+++ b/.cargo/config.toml@@ -1,2 +1,3 @@[env]FFMPEG_DIR = { relative = true, force = true, value = "target/native-deps" }+LIBCLANG_PATH = "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/LLVM/x64/bin/libclang.dll"\ No newline at end of filediff --git a/apps/desktop/src-tauri/tauri.windows.conf.json b/apps/desktop/src-tauri/tauri.windows.conf.jsonindex bfe86ea44..b6f259b06 100644--- a/apps/desktop/src-tauri/tauri.windows.conf.json+++ b/apps/desktop/src-tauri/tauri.windows.conf.json@@ -1,8 +1,9 @@{- "$schema": "https://schema.tauri.app/config/2","bundle": {- "resources": {- "../../../target/ffmpeg/bin/*.dll": "./"+ "windows": {+ "wix": {+ "version": "0.3.26"+ }}}-}+}\ No newline at end of filediff --git a/crates/flags/src/lib.rs b/crates/flags/src/lib.rsindex 32e7eb358..9dfcfa8d7 100644--- a/crates/flags/src/lib.rs+++ b/crates/flags/src/lib.rs@@ -6,6 +6,6 @@ pub struct Flags {}pub const FLAGS: Flags = Flags {- record_mouse_state: false, // cfg!(debug_assertions),+ record_mouse_state: true, // cfg!(debug_assertions),split: false,};diff --git a/crates/media/src/platform/win.rs b/crates/media/src/platform/win.rsindex 5331c95f1..8a4913587 100644--- a/crates/media/src/platform/win.rs+++ b/crates/media/src/platform/win.rs@@ -25,6 +25,8 @@ use windows::Win32::UI::WindowsAndMessaging::{IDC_CROSS, IDC_HAND, IDC_HELP, IDC_IBEAM, IDC_NO, IDC_PERSON, IDC_PIN, IDC_SIZEALL,IDC_SIZENESW, IDC_SIZENS, IDC_SIZENWSE, IDC_SIZEWE, IDC_UPARROW, IDC_WAIT,};+use windows::Win32::UI::WindowsAndMessaging::{DrawIconEx, GetIconInfo, ICONINFO, DI_NORMAL};+use tracing::debug;#[inline]pub fn bring_window_to_focus(window_id: u32) {@@ -268,6 +270,10 @@ pub fn monitor_bounds(id: u32) -> Bounds {if id == *target_id {let rect = minfo.monitorInfo.rcMonitor;+ debug!(+ "Found monitor with ID {}: bounds: left={}, top={}, right={}, bottom={}",+ id, rect.left, rect.top, rect.right, rect.bottom+ );*bounds = Some(Bounds {x: rect.left as f64,y: rect.top as f64,@@ -289,7 +295,18 @@ pub fn monitor_bounds(id: u32) -> Bounds {)};- bounds.unwrap_or_default()+ // If we didn't find the monitor with the given ID, log a warning and return a default bounds+ if lparams.1.is_none() {+ debug!("Could not find monitor with ID: {}", id);+ return Bounds {+ x: 0.0,+ y: 0.0,+ width: 1920.0, // Default to a common resolution+ height: 1080.0,+ };+ }++ lparams.1.unwrap()}pub fn display_names() -> HashMap<u32, String> {diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rsindex b39856fca..91ef645b3 100644--- a/crates/recording/src/cursor.rs+++ b/crates/recording/src/cursor.rs@@ -118,13 +118,82 @@ pub fn spawn_cursor_recorder(};if mouse_state.coords != last_mouse_state.coords {+ // Get the actual mouse coordinates+ let (mouse_x, mouse_y) = mouse_state.coords;++ #[cfg(windows)]+ let (mouse_x, mouse_y) = {+ // On Windows, ensure we're using the correct coordinate system+ // by getting the virtual screen metrics+ use windows::Win32::UI::WindowsAndMessaging::GetSystemMetrics;+ use windows::Win32::UI::WindowsAndMessaging::{+ SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN+ };++ let virtual_screen_x = unsafe { GetSystemMetrics(SM_XVIRTUALSCREEN) };+ let virtual_screen_y = unsafe { GetSystemMetrics(SM_YVIRTUALSCREEN) };+ let virtual_screen_width = unsafe { GetSystemMetrics(SM_CXVIRTUALSCREEN) };+ let virtual_screen_height = unsafe { GetSystemMetrics(SM_CYVIRTUALSCREEN) };++ // If screen_bounds doesn't match the virtual screen, adjust the coordinates+ if (screen_bounds.x as i32 != virtual_screen_x ||+ screen_bounds.y as i32 != virtual_screen_y ||+ screen_bounds.width as i32 != virtual_screen_width ||+ screen_bounds.height as i32 != virtual_screen_height) &&+ screen_bounds.width > 0.0 && screen_bounds.height > 0.0 {++ // Convert to normalized coordinates in the virtual screen space first+ let norm_x = (mouse_x as f64 - virtual_screen_x as f64) / virtual_screen_width as f64;+ let norm_y = (mouse_y as f64 - virtual_screen_y as f64) / virtual_screen_height as f64;++ // Then convert to the target screen coordinates+ let adjusted_x = (norm_x * screen_bounds.width + screen_bounds.x) as i32;+ let adjusted_y = (norm_y * screen_bounds.height + screen_bounds.y) as i32;++ (adjusted_x, adjusted_y)+ } else {+ (mouse_x, mouse_y)+ }+ };++ // Calculate normalized coordinates (0.0 to 1.0) within the screen bounds+ // Check if screen_bounds dimensions are valid to avoid division by zero+ let x = if screen_bounds.width > 0.0 {+ (mouse_x as f64 - screen_bounds.x) / screen_bounds.width+ } else {+ 0.5 // Fallback if width is invalid+ };++ let y = if screen_bounds.height > 0.0 {+ (mouse_y as f64 - screen_bounds.y) / screen_bounds.height+ } else {+ 0.5 // Fallback if height is invalid+ };++ // Clamp values to ensure they're within valid range+ let x = if x.is_nan() || x.is_infinite() {+ debug!("X coordinate is invalid: {}", x);+ 0.5+ } else {+ x.max(0.0).min(1.0)+ };++ let y = if y.is_nan() || y.is_infinite() {+ debug!("Y coordinate is invalid: {}", y);+ 0.5+ } else {+ y.max(0.0).min(1.0)+ };++ debug!("Normalized coords: ({}, {})", x, y);+let mouse_event = CursorMoveEvent {active_modifiers: vec![],cursor_id: cursor_id.clone(),process_time_ms: elapsed,unix_time_ms: unix_time,- x: (mouse_state.coords.0 as f64 - screen_bounds.x) / screen_bounds.width,- y: (mouse_state.coords.1 as f64 - screen_bounds.y) / screen_bounds.height,+ x,+ y,};response.moves.push(mouse_event);}@@ -138,6 +207,62 @@ pub fn spawn_cursor_recorder(continue;}+ // Get the actual mouse coordinates+ let (mouse_x, mouse_y) = mouse_state.coords;++ #[cfg(windows)]+ let (mouse_x, mouse_y) = {+ // On Windows, ensure we're using the correct coordinate system+ // by getting the virtual screen metrics+ use windows::Win32::UI::WindowsAndMessaging::GetSystemMetrics;+ use windows::Win32::UI::WindowsAndMessaging::{+ SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN+ };++ let virtual_screen_x = unsafe { GetSystemMetrics(SM_XVIRTUALSCREEN) };+ let virtual_screen_y = unsafe { GetSystemMetrics(SM_YVIRTUALSCREEN) };+ let virtual_screen_width = unsafe { GetSystemMetrics(SM_CXVIRTUALSCREEN) };+ let virtual_screen_height = unsafe { GetSystemMetrics(SM_CYVIRTUALSCREEN) };++ // If screen_bounds doesn't match the virtual screen, adjust the coordinates+ if (screen_bounds.x as i32 != virtual_screen_x ||+ screen_bounds.y as i32 != virtual_screen_y ||+ screen_bounds.width as i32 != virtual_screen_width ||+ screen_bounds.height as i32 != virtual_screen_height) &&+ screen_bounds.width > 0.0 && screen_bounds.height > 0.0 {++ // Convert to normalized coordinates in the virtual screen space first+ let norm_x = (mouse_x as f64 - virtual_screen_x as f64) / virtual_screen_width as f64;+ let norm_y = (mouse_y as f64 - virtual_screen_y as f64) / virtual_screen_height as f64;++ // Then convert to the target screen coordinates+ let adjusted_x = (norm_x * screen_bounds.width + screen_bounds.x) as i32;+ let adjusted_y = (norm_y * screen_bounds.height + screen_bounds.y) as i32;++ (adjusted_x, adjusted_y)+ } else {+ (mouse_x, mouse_y)+ }+ };++ // Calculate normalized coordinates (0.0 to 1.0) within the screen bounds+ // Check if screen_bounds dimensions are valid to avoid division by zero+ let x = if screen_bounds.width > 0.0 {+ (mouse_x as f64 - screen_bounds.x) / screen_bounds.width+ } else {+ 0.5 // Fallback if width is invalid+ };++ let y = if screen_bounds.height > 0.0 {+ (mouse_y as f64 - screen_bounds.y) / screen_bounds.height+ } else {+ 0.5 // Fallback if height is invalid+ };++ // Clamp values to ensure they're within valid range+ let x = if x.is_nan() || x.is_infinite() { 0.5 } else { x.max(0.0).min(1.0) };+ let y = if y.is_nan() || y.is_infinite() { 0.5 } else { y.max(0.0).min(1.0) };+let mouse_event = CursorClickEvent {down: pressed,active_modifiers: vec![],@@ -145,8 +270,8 @@ pub fn spawn_cursor_recorder(cursor_id: cursor_id.clone(),process_time_ms: elapsed,unix_time_ms: unix_time,- x: (mouse_state.coords.0 as f64 - screen_bounds.x) / screen_bounds.width,- y: (mouse_state.coords.1 as f64 - screen_bounds.y) / screen_bounds.height,+ x,+ y,};response.clicks.push(mouse_event);}@@ -229,11 +354,11 @@ fn get_cursor_image_data() -> Option<CursorData> {fn get_cursor_image_data() -> Option<CursorData> {use windows::Win32::Foundation::{HWND, POINT};use windows::Win32::Graphics::Gdi::{- BitBlt, CreateCompatibleDC, CreateDIBSection, DeleteDC, DeleteObject, GetDC, GetObjectA,- ReleaseDC, SelectObject, BITMAP, BITMAPINFO, BITMAPINFOHEADER, DIB_RGB_COLORS, SRCCOPY,+ CreateCompatibleDC, CreateDIBSection, DeleteDC, DeleteObject, GetDC,+ GetObjectA, ReleaseDC, SelectObject, BITMAP, BITMAPINFO, BITMAPINFOHEADER, DIB_RGB_COLORS,};use windows::Win32::UI::WindowsAndMessaging::{GetCursorInfo, CURSORINFO, CURSORINFO_FLAGS};- use windows::Win32::UI::WindowsAndMessaging::{GetIconInfo, ICONINFO};+ use windows::Win32::UI::WindowsAndMessaging::{DrawIconEx, GetIconInfo, ICONINFO, DI_NORMAL};unsafe {// Get cursor info@@ -244,45 +369,64 @@ fn get_cursor_image_data() -> Option<CursorData> {ptScreenPos: POINT::default(),};- // Handle Result return typeif GetCursorInfo(&mut cursor_info).is_err() {return None;}- // If no cursor, return Noneif cursor_info.hCursor.is_invalid() {return None;}// Get icon infolet mut icon_info = ICONINFO::default();- // Handle Result return typeif GetIconInfo(cursor_info.hCursor, &mut icon_info).is_err() {return None;}- // Get bitmap info+ // Get bitmap info for the cursorlet mut bitmap = BITMAP::default();+ let bitmap_handle = if !icon_info.hbmColor.is_invalid() {+ icon_info.hbmColor+ } else {+ icon_info.hbmMask+ };+if GetObjectA(- icon_info.hbmColor,+ bitmap_handle,std::mem::size_of::<BITMAP>() as i32,Some(&mut bitmap as *mut _ as *mut _),) == 0{+ // Clean up handles+ if !icon_info.hbmColor.is_invalid() {+ DeleteObject(icon_info.hbmColor);+ }+ if !icon_info.hbmMask.is_invalid() {+ DeleteObject(icon_info.hbmMask);+ }return None;}- // Create compatible DC+ // Create DCslet screen_dc = GetDC(HWND::default());let mem_dc = CreateCompatibleDC(screen_dc);++ // Get cursor dimensions+ let width = bitmap.bmWidth;+ let height = if icon_info.hbmColor.is_invalid() && bitmap.bmHeight > 0 {+ // For mask cursors, the height is doubled (AND mask + XOR mask)+ bitmap.bmHeight / 2+ } else {+ bitmap.bmHeight+ };- // Create bitmap info header+ // Create bitmap info header for 32-bit RGBAlet bi = BITMAPINFOHEADER {biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,- biWidth: bitmap.bmWidth,- biHeight: -bitmap.bmHeight, // Negative height for top-down bitmap+ biWidth: width,+ biHeight: -height, // Negative for top-down DIBbiPlanes: 1,- biBitCount: 32,+ biBitCount: 32, // 32-bit RGBAbiCompression: 0,biSizeImage: 0,biXPelsPerMeter: 0,@@ -301,6 +445,15 @@ fn get_cursor_image_data() -> Option<CursorData> {let dib = CreateDIBSection(mem_dc, &bitmap_info, DIB_RGB_COLORS, &mut bits, None, 0);if dib.is_err() {+ // Clean up+ DeleteDC(mem_dc);+ ReleaseDC(HWND::default(), screen_dc);+ if !icon_info.hbmColor.is_invalid() {+ DeleteObject(icon_info.hbmColor);+ }+ if !icon_info.hbmMask.is_invalid() {+ DeleteObject(icon_info.hbmMask);+ }return None;}@@ -309,42 +462,172 @@ fn get_cursor_image_data() -> Option<CursorData> {// Select DIB into DClet old_bitmap = SelectObject(mem_dc, dib);- // Copy cursor image- if BitBlt(+ // Draw the cursor onto our bitmap with transparency+ if DrawIconEx(mem_dc,0,0,- bitmap.bmWidth,- bitmap.bmHeight,- screen_dc,- cursor_info.ptScreenPos.x,- cursor_info.ptScreenPos.y,- SRCCOPY,- )- .is_err()- {+ cursor_info.hCursor,+ 0, // Use actual size+ 0, // Use actual size+ 0,+ None,+ DI_NORMAL,+ ).is_err() {+ // Clean up+ SelectObject(mem_dc, old_bitmap);+ DeleteObject(dib);+ DeleteDC(mem_dc);+ ReleaseDC(HWND::default(), screen_dc);+ if !icon_info.hbmColor.is_invalid() {+ DeleteObject(icon_info.hbmColor);+ }+ if !icon_info.hbmMask.is_invalid() {+ DeleteObject(icon_info.hbmMask);+ }return None;}// Get image data- let size = (bitmap.bmWidth * bitmap.bmHeight * 4) as usize;+ let size = (width * height * 4) as usize;let mut image_data = vec![0u8; size];std::ptr::copy_nonoverlapping(bits, image_data.as_mut_ptr() as *mut _, size);+ // Calculate hotspot+ let mut hotspot_x = if icon_info.fIcon.as_bool() == false {+ icon_info.xHotspot as f64 / width as f64+ } else {+ 0.5+ };++ let mut hotspot_y = if icon_info.fIcon.as_bool() == false {+ icon_info.yHotspot as f64 / height as f64+ } else {+ 0.5+ };+// CleanupSelectObject(mem_dc, old_bitmap);DeleteObject(dib);DeleteDC(mem_dc);ReleaseDC(HWND::default(), screen_dc);- DeleteObject(icon_info.hbmColor);- DeleteObject(icon_info.hbmMask);+ if !icon_info.hbmColor.is_invalid() {+ DeleteObject(icon_info.hbmColor);+ }+ if !icon_info.hbmMask.is_invalid() {+ DeleteObject(icon_info.hbmMask);+ }- // Convert to PNG format- let image =- image::RgbaImage::from_raw(bitmap.bmWidth as u32, bitmap.bmHeight as u32, image_data)?;+ // Process the image data to ensure proper alpha channel+ for i in (0..size).step_by(4) {+ // Windows DIB format is BGRA, we need to:+ // 1. Swap B and R channels+ let b = image_data[i];+ image_data[i] = image_data[i + 2]; // B <- R+ image_data[i + 2] = b; // R <- B++ // 2. Pre-multiply alpha if needed+ // This is already handled by DrawIconEx+ }+ // Convert to RGBA image+ let mut rgba_image = image::RgbaImage::from_raw(width as u32, height as u32, image_data)?;++ // For text cursor (I-beam), enhance visibility by adding a shadow/outline+ // Check if this is likely a text cursor by examining dimensions and pixels+ let is_text_cursor = width <= 20 && height >= 20 && width <= height / 2;++ if is_text_cursor {+ // Add a subtle shadow/outline to make it visible on white backgrounds+ for y in 0..height as u32 {+ for x in 0..width as u32 {+ let pixel = rgba_image.get_pixel(x, y);+ // If this is a solid pixel of the cursor+ if pixel[3] > 200 { // If alpha is high (visible pixel)+ // Add shadow pixels around it+ for dx in [-1, 0, 1].iter() {+ for dy in [-1, 0, 1].iter() {+ let nx = x as i32 + dx;+ let ny = y as i32 + dy;++ // Skip if out of bounds or same pixel+ if nx < 0 || ny < 0 || nx >= width as i32 || ny >= height as i32 || (*dx == 0 && *dy == 0) {+ continue;+ }++ let nx = nx as u32;+ let ny = ny as u32;++ let shadow_pixel = rgba_image.get_pixel(nx, ny);+ // Only add shadow where there isn't already content+ if shadow_pixel[3] < 100 {+ rgba_image.put_pixel(nx, ny, image::Rgba([0, 0, 0, 100]));+ }+ }+ }+ }+ }+ }+ }++ // Find the bounds of non-transparent pixels to trim whitespace+ let mut min_x = width as u32;+ let mut min_y = height as u32;+ let mut max_x = 0u32;+ let mut max_y = 0u32;++ let mut has_content = false;++ for y in 0..height as u32 {+ for x in 0..width as u32 {+ let pixel = rgba_image.get_pixel(x, y);+ if pixel[3] > 0 { // If pixel has any opacity+ has_content = true;+ min_x = min_x.min(x);+ min_y = min_y.min(y);+ max_x = max_x.max(x);+ max_y = max_y.max(y);+ }+ }+ }++ // Only trim if we found content and there's actually whitespace to trim+ let trimmed_image = if has_content && (min_x > 0 || min_y > 0 || max_x < width as u32 - 1 || max_y < height as u32 - 1) {+ // Add a small padding (2 pixels) around the content+ let padding = 2u32;+ let trim_min_x = min_x.saturating_sub(padding);+ let trim_min_y = min_y.saturating_sub(padding);+ let trim_max_x = (max_x + padding).min(width as u32 - 1);+ let trim_max_y = (max_y + padding).min(height as u32 - 1);++ let trim_width = trim_max_x - trim_min_x + 1;+ let trim_height = trim_max_y - trim_min_y + 1;++ // Create a new image with the trimmed dimensions+ let mut trimmed = image::RgbaImage::new(trim_width, trim_height);++ // Copy the content to the new image+ for y in 0..trim_height {+ for x in 0..trim_width {+ let src_x = trim_min_x + x;+ let src_y = trim_min_y + y;+ let pixel = rgba_image.get_pixel(src_x, src_y);+ trimmed.put_pixel(x, y, *pixel);+ }+ }++ // Adjust hotspot coordinates for the trimmed image+ hotspot_x = (hotspot_x * width as f64 - trim_min_x as f64) / trim_width as f64;+ hotspot_y = (hotspot_y * height as f64 - trim_min_y as f64) / trim_height as f64;++ trimmed+ } else {+ rgba_image+ };++ // Convert to PNG formatlet mut png_data = Vec::new();- image+ trimmed_image.write_to(&mut std::io::Cursor::new(&mut png_data),image::ImageFormat::Png,@@ -353,7 +636,7 @@ fn get_cursor_image_data() -> Option<CursorData> {Some(CursorData {image: png_data,- hotspot: XY::new(0.0, 0.0),+ hotspot: XY::new(hotspot_x, hotspot_y),})}}diff --git a/crates/rendering/src/decoder/ffmpeg.rs b/crates/rendering/src/decoder/ffmpeg.rsindex 7ad27aab9..c928d5218 100644--- a/crates/rendering/src/decoder/ffmpeg.rs+++ b/crates/rendering/src/decoder/ffmpeg.rs@@ -122,9 +122,45 @@ impl FfmpegDecoder {.try_use_hw_device(AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX, Pixel::NV12).ok()} else if cfg!(target_os = "windows") {- decoder- .try_use_hw_device(AVHWDeviceType::AV_HWDEVICE_TYPE_DXVA2, Pixel::DXVA2_VLD)- .ok()+ // For now, disable hardware acceleration on Windows as it's causing issues+ // This ensures reliable playback while we debug the hardware acceleration issues+ None++ // Uncomment the below code once hardware acceleration issues are resolved+ /*+ // Try D3D11VA first - most widely supported on modern Windows+ let d3d11va = decoder+ .try_use_hw_device(AVHWDeviceType::AV_HWDEVICE_TYPE_D3D11VA, Pixel::D3D11)+ .ok();++ if d3d11va.is_some() {+ println!("Using D3D11VA hardware acceleration");+ d3d11va+ } else {+ // Try CUDA for NVIDIA GPUs+ let cuda = decoder+ .try_use_hw_device(AVHWDeviceType::AV_HWDEVICE_TYPE_CUDA, Pixel::CUDA)+ .ok();++ if cuda.is_some() {+ println!("Using CUDA hardware acceleration");+ cuda+ } else {+ // Try QSV for Intel GPUs+ let qsv = decoder+ .try_use_hw_device(AVHWDeviceType::AV_HWDEVICE_TYPE_QSV, Pixel::QSV)+ .ok();++ if qsv.is_some() {+ println!("Using QSV hardware acceleration");+ qsv+ } else {+ println!("Falling back to software decoding");+ None+ }+ }+ }+ */} else {None};