Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
hw accel + consistent pix fmt (#155)
Brendan Allan772eb1c971f1
diff --git a/Cargo.lock b/Cargo.lockindex e2a652dff..f025fdecf 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -784,12 +784,20 @@ dependencies = ["specta",]+[[package]]+name = "cap-gpu-converters"+version = "0.1.0"+dependencies = [+ "wgpu",+]+[[package]]name = "cap-media"version = "0.1.0"dependencies = ["anyhow","cap-flags",+ "cap-gpu-converters","cap-project","cocoa 0.26.0","core-foundation 0.10.0",@@ -799,6 +807,7 @@ dependencies = ["ffmpeg-next","ffmpeg-sys-next","flume 0.11.0",+ "futures","indexmap 2.5.0","nokhwa","nokhwa-bindings-macos",@@ -2262,9 +2271,9 @@ dependencies = [[[package]]name = "futures"-version = "0.3.30"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0"+checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876"dependencies = ["futures-channel","futures-core",@@ -2277,9 +2286,9 @@ dependencies = [[[package]]name = "futures-channel"-version = "0.3.30"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78"+checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10"dependencies = ["futures-core","futures-sink",@@ -2287,15 +2296,15 @@ dependencies = [[[package]]name = "futures-core"-version = "0.3.30"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d"+checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"[[package]]name = "futures-executor"-version = "0.3.30"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d"+checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f"dependencies = ["futures-core","futures-task",@@ -2315,9 +2324,9 @@ dependencies = [[[package]]name = "futures-io"-version = "0.3.30"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1"+checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6"[[package]]name = "futures-lite"@@ -2334,9 +2343,9 @@ dependencies = [[[package]]name = "futures-macro"-version = "0.3.30"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac"+checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650"dependencies = ["proc-macro2","quote",@@ -2345,21 +2354,21 @@ dependencies = [[[package]]name = "futures-sink"-version = "0.3.30"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5"+checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7"[[package]]name = "futures-task"-version = "0.3.30"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004"+checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"[[package]]name = "futures-util"-version = "0.3.30"+version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48"+checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"dependencies = ["futures-channel","futures-core",@@ -4028,7 +4037,7 @@ checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"[[package]]name = "nokhwa"version = "0.10.3"-source = "git+https://github.com/capsoftware/nokhwa?rev=6ce1e8270d57#6ce1e8270d57436e6caa6776247dab70aed13b65"+source = "git+https://github.com/CapSoftware/nokhwa?rev=c5c7e2298764#c5c7e2298764ddf122c2ec0206a8aa7ba80257f0"dependencies = ["flume 0.10.14","image 0.24.9",@@ -4044,7 +4053,7 @@ dependencies = [[[package]]name = "nokhwa-bindings-linux"version = "0.1.0"-source = "git+https://github.com/capsoftware/nokhwa?rev=6ce1e8270d57#6ce1e8270d57436e6caa6776247dab70aed13b65"+source = "git+https://github.com/CapSoftware/nokhwa?rev=c5c7e2298764#c5c7e2298764ddf122c2ec0206a8aa7ba80257f0"dependencies = ["nokhwa-core","v4l",@@ -4054,7 +4063,7 @@ dependencies = [[[package]]name = "nokhwa-bindings-macos"version = "0.2.0"-source = "git+https://github.com/capsoftware/nokhwa?rev=6ce1e8270d57#6ce1e8270d57436e6caa6776247dab70aed13b65"+source = "git+https://github.com/CapSoftware/nokhwa?rev=c5c7e2298764#c5c7e2298764ddf122c2ec0206a8aa7ba80257f0"dependencies = ["block","cocoa-foundation 0.1.2",@@ -4069,7 +4078,7 @@ dependencies = [[[package]]name = "nokhwa-bindings-windows"version = "0.4.0"-source = "git+https://github.com/capsoftware/nokhwa?rev=6ce1e8270d57#6ce1e8270d57436e6caa6776247dab70aed13b65"+source = "git+https://github.com/CapSoftware/nokhwa?rev=c5c7e2298764#c5c7e2298764ddf122c2ec0206a8aa7ba80257f0"dependencies = ["nokhwa-core","once_cell",@@ -4079,7 +4088,7 @@ dependencies = [[[package]]name = "nokhwa-core"version = "0.1.0"-source = "git+https://github.com/capsoftware/nokhwa?rev=6ce1e8270d57#6ce1e8270d57436e6caa6776247dab70aed13b65"+source = "git+https://github.com/CapSoftware/nokhwa?rev=c5c7e2298764#c5c7e2298764ddf122c2ec0206a8aa7ba80257f0"dependencies = ["bytes","image 0.24.9",@@ -5638,8 +5647,8 @@ dependencies = [[[package]]name = "scap"-version = "0.0.5"-source = "git+https://github.com/filleduchaos/scap?rev=8eb00ce1b9bcf#8eb00ce1b9bcfa22d38f7c2857539f2c5139dfe3"+version = "0.0.6"+source = "git+https://github.com/CapSoftware/scap?rev=4d6be030ba2b0cea565ccaee28b1999f25b8dd5d#4d6be030ba2b0cea565ccaee28b1999f25b8dd5d"dependencies = ["cocoa 0.25.0","core-graphics-helmer-fork",diff --git a/Cargo.toml b/Cargo.tomlindex 1d53158e6..29b82b2b9 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -17,4 +17,10 @@ tokio = { version = "1.39.3", features = [] }tauri = { version = "2.0.0" }specta = { version = "=2.0.0-rc.20" }-scap = { git = "https://github.com/filleduchaos/scap", rev = "8eb00ce1b9bcf" }+scap = { git = "https://github.com/CapSoftware/scap", rev = "4d6be030ba2b0cea565ccaee28b1999f25b8dd5d" }+nokhwa = { git = "https://github.com/CapSoftware/nokhwa", rev = "c5c7e2298764", features = [+ "input-native",+ "serialize",+] }+nokhwa-bindings-macos = { git = "https://github.com/CapSoftware/nokhwa", rev = "c5c7e2298764" }+wgpu = "22.1.0"diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex 432a48d16..f2f1273dd 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -46,7 +46,7 @@ tokio.workspace = trueuuid = { version = "1.10.0", features = ["v4"] }scap.workspace = trueffmpeg-sidecar = { git = "https://github.com/CapSoftware/ffmpeg-sidecar", branch = "main" }-wgpu = "22.1.0"+wgpu.workspace = truebytemuck = { version = "1.7", features = ["derive"] }image = "0.25.2"tauri-plugin-fs = "2.0.0-rc.0"diff --git a/apps/desktop/src-tauri/src/cursor.rs b/apps/desktop/src-tauri/src/cursor.rsindex 8a1f5e82f..622ae8c96 100644--- a/apps/desktop/src-tauri/src/cursor.rs+++ b/apps/desktop/src-tauri/src/cursor.rs@@ -138,7 +138,7 @@ pub fn spawn_cursor_recorder(#[cfg(target_os = "macos")]fn get_cursor_image_data() -> Option<Vec<u8>> {use cocoa::base::{id, nil};- use cocoa::foundation::{NSData, NSUInteger};+ use cocoa::foundation::NSUInteger;use objc::rc::autoreleasepool;use objc::runtime::Class;use objc::*;diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 588ee17be..7fce99ff9 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -44,7 +44,6 @@ use scap::frame::Frame;use serde::{Deserialize, Serialize};use serde_json::json;use specta::Type;-use std::ffi::{CStr, OsStr};use std::fs::File;use std::io::BufWriter;use std::io::{BufReader, Write};@@ -2337,7 +2336,8 @@ async fn reset_camera_permissions(_app: AppHandle) -> Result<(), ()> {#[cfg(target_os = "macos")]{#[cfg(debug_assertions)]- let bundle_id = "com.apple.Terminal";+ let bundle_id =+ std::env::var("CAP_BUNDLE_ID").unwrap_or_else(|_| "com.apple.Terminal".to_string());#[cfg(not(debug_assertions))]let bundle_id = "so.cap.desktop";diff --git a/apps/desktop/src-tauri/src/platform/macos/delegates.rs b/apps/desktop/src-tauri/src/platform/macos/delegates.rsindex 0a6869700..4f7065f9d 100644--- a/apps/desktop/src-tauri/src/platform/macos/delegates.rs+++ b/apps/desktop/src-tauri/src/platform/macos/delegates.rs@@ -110,7 +110,7 @@ pub fn setup<R: Runtime>(window: Window<R>, controls_inset: LogicalPosition<f64>}extern "C" fn on_window_did_resize<R: Runtime>(this: &Object, _cmd: Sel, notification: id) {unsafe {- with_window_state(&*this, |state: &mut WindowState<R>| {+ with_window_state(this, |state: &mut WindowState<R>| {position_window_controls(UnsafeWindowHandle(state@@ -205,7 +205,7 @@ pub fn setup<R: Runtime>(window: Window<R>, controls_inset: LogicalPosition<f64>notification: id,) {unsafe {- with_window_state(&*this, |state: &mut WindowState<R>| {+ with_window_state(this, |state: &mut WindowState<R>| {state.window.emit("did-enter-fullscreen", ())@@ -222,7 +222,7 @@ pub fn setup<R: Runtime>(window: Window<R>, controls_inset: LogicalPosition<f64>notification: id,) {unsafe {- with_window_state(&*this, |state: &mut WindowState<R>| {+ with_window_state(this, |state: &mut WindowState<R>| {state.window.emit("will-enter-fullscreen", ())@@ -239,7 +239,7 @@ pub fn setup<R: Runtime>(window: Window<R>, controls_inset: LogicalPosition<f64>notification: id,) {unsafe {- with_window_state(&*this, |state: &mut WindowState<R>| {+ with_window_state(this, |state: &mut WindowState<R>| {state.window.emit("did-exit-fullscreen", ())@@ -266,7 +266,7 @@ pub fn setup<R: Runtime>(window: Window<R>, controls_inset: LogicalPosition<f64>notification: id,) {unsafe {- with_window_state(&*this, |state: &mut WindowState<R>| {+ with_window_state(this, |state: &mut WindowState<R>| {state.window.emit("will-exit-fullscreen", ())diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 591cd12c2..8d0021a1b 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -8,9 +8,8 @@ use std::fs::File;use std::sync::atomic::AtomicBool;use std::sync::Arc;use std::time::{SystemTime, UNIX_EPOCH};-use std::{path::PathBuf, time::Duration};-use tokio::sync::{oneshot, Mutex};-use uuid::Uuid;+use std::path::PathBuf;+use tokio::sync::oneshot;use crate::cursor::spawn_cursor_recorder;use crate::RecordingOptions;diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex 45024711d..ef2f9c03a 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -234,9 +234,9 @@ impl CapWindow {.shadow(true).transparent(true);- let window = window_builder.build()?;+- window+ window_builder.build()?}Self::Changelog => {let mut window_builder = self@@ -284,9 +284,9 @@ impl CapWindow {)).transparent(true);- let window = window_builder.build()?;+- window+ window_builder.build()?}Self::WindowCaptureOccluder => {let mut window_builder = self@@ -487,18 +487,15 @@ fn add_traffic_lights(window: &WebviewWindow<Wry>, controls_inset: Option<Logica);let c_win = target_window.clone();- target_window.on_window_event(move |event| match event {- tauri::WindowEvent::ThemeChanged(..) => {- delegates::position_window_controls(- delegates::UnsafeWindowHandle(- c_win- .ns_window()- .expect("Failed to get native window handle"),- ),- &controls_inset.unwrap_or(LogicalPosition::new(14.0, 22.0)),- );- }- _ => (),+ target_window.on_window_event(move |event| if let tauri::WindowEvent::ThemeChanged(..) = event {+ delegates::position_window_controls(+ delegates::UnsafeWindowHandle(+ c_win+ .ns_window()+ .expect("Failed to get native window handle"),+ ),+ &controls_inset.unwrap_or(LogicalPosition::new(14.0, 22.0)),+ );});}).ok();diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 98d803c49..a16f2614f 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -428,7 +428,7 @@ export type ShowCapturesPanel = nullexport type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments?: ZoomSegment[] }export type TimelineSegment = { timescale: number; start: number; end: number }export type UploadResult = { Success: string } | "NotAuthenticated" | "PlanCheckFailed" | "UpgradeRequired"-export type Video = { duration: number; width: number; height: number; fps: number }+export type Video = { duration: number; width: number; height: number }export type VideoType = "screen" | "output"export type XY<T> = { x: T; y: T }export type ZoomSegment = { start: number; end: number; amount: number }diff --git a/crates/editor/src/project_recordings.rs b/crates/editor/src/project_recordings.rsindex e826b9753..d78e9a05c 100644--- a/crates/editor/src/project_recordings.rs+++ b/crates/editor/src/project_recordings.rs@@ -9,7 +9,6 @@ pub struct Video {pub duration: f64,pub width: u32,pub height: u32,- pub fps: f32,}impl Video {@@ -23,13 +22,10 @@ impl Video {.video().unwrap();- let frame_rate = video_decoder.frame_rate().unwrap();-Video {width: video_decoder.width(),height: video_decoder.height(),duration: input.duration() as f64 / 1_000_000.0,- fps: frame_rate.numerator() as f32 / frame_rate.denominator() as f32,}}}diff --git a/crates/ffmpeg-hw-device/src/lib.rs b/crates/ffmpeg-hw-device/src/lib.rsindex 9d47db197..7407085aa 100644--- a/crates/ffmpeg-hw-device/src/lib.rs+++ b/crates/ffmpeg-hw-device/src/lib.rs@@ -77,7 +77,7 @@ pub trait CodecContextExt {) -> Result<HwDevice, &'static str>;}-impl CodecContextExt for codec::context::Context {+impl CodecContextExt for codec::decoder::decoder::Decoder {fn try_use_hw_device(&mut self,device_type: AVHWDeviceType,@@ -123,3 +123,36 @@ impl CodecContextExt for codec::context::Context {}}}++// impl CodecContextExt for codec::encoder::video::Video {+// fn try_use_hw_device(+// &mut self,+// device_type: AVHWDeviceType,+// pix_fmt: Pixel,+// ) -> Result<HwDevice, &'static str> {+// unsafe {+// let mut hw_device_ctx = null_mut();+// if av_hwdevice_ctx_create(&mut hw_device_ctx, device_type, null(), null_mut(), 0) < 0 {+// return Err("failed to create hw device context");+// }++// let hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx);+// let frames_ctx = (*hw_frames_ref).data as *mut AVHWFramesContext;+// (*frames_ctx).format = self.format().into();+// (*frames_ctx).sw_format = AVPixelFormat::AV_PIX_FMT_NV12;+// (*frames_ctx).width = self.width() as i32;+// (*frames_ctx).height = self.height() as i32;+// (*frames_ctx).initial_pool_size = 20;++// av_hwframe_ctx_init(hw_frames_ref);++// (*self.as_mut().as_mut_ptr()).hw_frames_ctx = av_buffer_ref(hw_frames_ref);++// Ok(HwDevice {+// device_type,+// ctx: hw_device_ctx,+// pix_fmt,+// })+// }+// }+// }diff --git a/crates/gpu-converters/Cargo.toml b/crates/gpu-converters/Cargo.tomlnew file mode 100644index 000000000..7496d8455--- /dev/null+++ b/crates/gpu-converters/Cargo.toml@@ -0,0 +1,7 @@+[package]+name = "cap-gpu-converters"+version = "0.1.0"+edition = "2021"++[dependencies]+wgpu.workspace = truediff --git a/crates/gpu-converters/src/lib.rs b/crates/gpu-converters/src/lib.rsnew file mode 100644index 000000000..ba5fd2825--- /dev/null+++ b/crates/gpu-converters/src/lib.rs@@ -0,0 +1,23 @@+mod nv12_rgba;+mod util;+mod uyvy;+mod uyvy_nv12;+mod uyvy_rgba;++pub use nv12_rgba::NV12ToRGBA;+pub use uyvy_nv12::UYVYToNV12;+pub use uyvy_rgba::UYVYToRGBA;++pub struct NV12Input<'a> {+ y_data: &'a [u8],+ uv_data: &'a [u8],+}++impl<'a> NV12Input<'a> {+ pub fn from_buffer(buffer: &'a [u8], width: u32, height: u32) -> Self {+ Self {+ y_data: &buffer[..(width * height) as usize],+ uv_data: &buffer[(width * height) as usize..],+ }+ }+}diff --git a/crates/gpu-converters/src/nv12_rgba/mod.rs b/crates/gpu-converters/src/nv12_rgba/mod.rsnew file mode 100644index 000000000..3bd317792--- /dev/null+++ b/crates/gpu-converters/src/nv12_rgba/mod.rs@@ -0,0 +1,248 @@+use wgpu::{self, util::DeviceExt};++use crate::NV12Input;++pub struct NV12ToRGBA {+ device: wgpu::Device,+ queue: wgpu::Queue,+ pipeline: wgpu::ComputePipeline,+ bind_group_layout: wgpu::BindGroupLayout,+}++impl NV12ToRGBA {+ pub async fn new() -> Self {+ println!("NV12ToRGBA");+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default());++ // Get adapter for GPU+ let adapter = instance+ .request_adapter(&wgpu::RequestAdapterOptions {+ power_preference: wgpu::PowerPreference::HighPerformance,+ force_fallback_adapter: false,+ compatible_surface: None,+ })+ .await+ .unwrap();++ // Create device and queue+ let (device, queue) = adapter+ .request_device(&wgpu::DeviceDescriptor::default(), None)+ .await+ .unwrap();++ // Shader for NV12 to RGBA conversion+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("NV12 to RGBA Converter"),+ source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!(+ "./shader.wgsl"+ ))),+ });++ // Create pipeline and bind group layout+ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("NV12 Converter Bind Group Layout"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: false },+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: false },+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 2,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::StorageTexture {+ access: wgpu::StorageTextureAccess::WriteOnly,+ format: wgpu::TextureFormat::Rgba8Unorm,+ view_dimension: wgpu::TextureViewDimension::D2,+ },+ count: None,+ },+ ],+ });++ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("NV12 Converter Pipeline Layout"),+ bind_group_layouts: &[&bind_group_layout],+ push_constant_ranges: &[],+ });++ let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {+ label: Some("NV12 Converter Pipeline"),+ layout: Some(&pipeline_layout),+ module: &shader,+ entry_point: "main",+ compilation_options: Default::default(),+ cache: None,+ });++ Self {+ device,+ queue,+ pipeline,+ bind_group_layout,+ }+ }++ pub fn convert(&self, input: NV12Input, width: u32, height: u32) -> Vec<u8> {+ // Create textures for Y and UV planes+ let y_texture = self.device.create_texture_with_data(+ &self.queue,+ &wgpu::TextureDescriptor {+ label: Some("Y Plane 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::Rg8Unorm,+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,+ view_formats: &[],+ },+ wgpu::util::TextureDataOrder::MipMajor,+ input.y_data,+ );++ let uv_texture = self.device.create_texture_with_data(+ &self.queue,+ &wgpu::TextureDescriptor {+ label: Some("UV Plane Texture"),+ size: wgpu::Extent3d {+ width: width / 2,+ height: height / 2,+ depth_or_array_layers: 1,+ },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::Rg8Unorm,+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,+ view_formats: &[],+ },+ wgpu::util::TextureDataOrder::MipMajor,+ input.uv_data,+ );++ // Create output texture+ let output_texture = self.device.create_texture(&wgpu::TextureDescriptor {+ label: Some("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::COPY_SRC,+ view_formats: &[],+ });++ // Create bind group+ let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("NV12 Converter Bind Group"),+ layout: &self.bind_group_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: wgpu::BindingResource::TextureView(+ &y_texture.create_view(&Default::default()),+ ),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: wgpu::BindingResource::TextureView(+ &uv_texture.create_view(&Default::default()),+ ),+ },+ wgpu::BindGroupEntry {+ binding: 2,+ resource: wgpu::BindingResource::TextureView(+ &output_texture.create_view(&Default::default()),+ ),+ },+ ],+ });++ // Create command encoder and dispatch compute shader+ let mut encoder = self+ .device+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {+ label: Some("NV12 Conversion Encoder"),+ });++ {+ let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {+ label: Some("NV12 Conversion Pass"),+ ..Default::default()+ });+ compute_pass.set_pipeline(&self.pipeline);+ compute_pass.set_bind_group(0, &bind_group, &[]);+ compute_pass.dispatch_workgroups((width + 7) / 8, (height + 7) / 8, 1);+ }++ // Create buffer for reading back the results+ let output_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("Output Buffer"),+ size: (width * height * 4) as u64,+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,+ mapped_at_creation: false,+ });++ // Copy texture to buffer+ encoder.copy_texture_to_buffer(+ wgpu::ImageCopyTexture {+ texture: &output_texture,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ wgpu::ImageCopyBuffer {+ buffer: &output_buffer,+ layout: wgpu::ImageDataLayout {+ offset: 0,+ bytes_per_row: Some(width * 4),+ rows_per_image: Some(height),+ },+ },+ wgpu::Extent3d {+ width,+ height,+ depth_or_array_layers: 1,+ },+ );++ // Submit commands+ self.queue.submit(std::iter::once(encoder.finish()));++ // Read back the results+ let buffer_slice = output_buffer.slice(..);+ let (tx, rx) = std::sync::mpsc::channel();+ buffer_slice.map_async(wgpu::MapMode::Read, move |result| {+ tx.send(result).unwrap();+ });+ self.device.poll(wgpu::Maintain::Wait);+ rx.recv().unwrap().unwrap();++ let data = buffer_slice.get_mapped_range();+ data.to_vec()+ }+}diff --git a/crates/gpu-converters/src/nv12_rgba/shader.wgsl b/crates/gpu-converters/src/nv12_rgba/shader.wgslnew file mode 100644index 000000000..0a3c3b687--- /dev/null+++ b/crates/gpu-converters/src/nv12_rgba/shader.wgsl@@ -0,0 +1,37 @@+@group(0) @binding(0) var y_plane: texture_2d<u32>;+@group(0) @binding(1) var uv_plane: texture_2d<u32>;+@group(0) @binding(2) var output: texture_storage_2d<rgba8unorm, write>;++@compute @workgroup_size(8, 8)+fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {+ let coords = global_id.xy;+ let dims = textureDimensions(output);++ if (coords.x >= dims.x || coords.y >= dims.y) {+ return;+ }++ // Sample Y plane+ let y = textureLoad(y_plane, coords, 0).r;++ // Sample UV plane (note: UV plane is half the size)+ let uv_coords = coords / 2;+ let uv = textureLoad(uv_plane, uv_coords, 0).rg;++ // YUV to RGB conversion+ let u = uv.r - 0.5;+ let v = uv.g - 0.5;++ let r = y + 1.402 * v;+ let g = y - 0.344 * u - 0.714 * v;+ let b = y + 1.772 * u;++ let color = vec4<f32>(+ clamp(r, 0.0, 1.0),+ clamp(g, 0.0, 1.0),+ clamp(b, 0.0, 1.0),+ 1.0+ );++ textureStore(output, coords, color);+}diff --git a/crates/gpu-converters/src/util.rs b/crates/gpu-converters/src/util.rsnew file mode 100644index 000000000..73a926fd3--- /dev/null+++ b/crates/gpu-converters/src/util.rs@@ -0,0 +1,52 @@+pub fn read_buffer_to_vec(buffer: &wgpu::Buffer, device: &wgpu::Device) -> Vec<u8> {+ let buffer_slice = buffer.slice(..);+ let (tx, rx) = std::sync::mpsc::channel();+ buffer_slice.map_async(wgpu::MapMode::Read, move |result| {+ tx.send(result).unwrap();+ });+ device.poll(wgpu::Maintain::Wait);+ rx.recv().unwrap().unwrap();++ let data = buffer_slice.get_mapped_range();+ data.to_vec()+}++pub fn copy_texture_to_buffer_command(+ device: &wgpu::Device,+ texture: &wgpu::Texture,+ encoder: &mut wgpu::CommandEncoder,+) -> wgpu::Buffer {+ let bytes_per_px = texture.format().block_copy_size(None).unwrap();+ let output_buffer = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("Output Buffer"),+ size: (texture.width() * texture.height() * bytes_per_px) as u64,+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,+ mapped_at_creation: false,+ });++ let bytes_per_row = texture.width() * bytes_per_px;++ encoder.copy_texture_to_buffer(+ wgpu::ImageCopyTexture {+ texture,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ wgpu::ImageCopyBuffer {+ buffer: &output_buffer,+ layout: wgpu::ImageDataLayout {+ offset: 0,+ bytes_per_row: Some(bytes_per_row),+ rows_per_image: Some(texture.height()),+ },+ },+ wgpu::Extent3d {+ width: texture.width(),+ height: texture.height(),+ depth_or_array_layers: 1,+ },+ );++ output_buffer+}diff --git a/crates/gpu-converters/src/uyvy.rs b/crates/gpu-converters/src/uyvy.rsnew file mode 100644index 000000000..d86fac459--- /dev/null+++ b/crates/gpu-converters/src/uyvy.rs@@ -0,0 +1,29 @@+use wgpu::util::DeviceExt;++pub fn create_input_texture(+ device: &wgpu::Device,+ queue: &wgpu::Queue,+ data: &[u8],+ width: u32,+ height: u32,+) -> wgpu::Texture {+ device.create_texture_with_data(+ queue,+ &wgpu::TextureDescriptor {+ label: Some("UYVY Texture"),+ size: wgpu::Extent3d {+ width: width / 2,+ height,+ depth_or_array_layers: 1,+ },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::Rgba8Uint,+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,+ view_formats: &[],+ },+ wgpu::util::TextureDataOrder::MipMajor,+ data,+ )+}diff --git a/crates/gpu-converters/src/uyvy_nv12/mod.rs b/crates/gpu-converters/src/uyvy_nv12/mod.rsnew file mode 100644index 000000000..f544837a3--- /dev/null+++ b/crates/gpu-converters/src/uyvy_nv12/mod.rs@@ -0,0 +1,224 @@+use wgpu::{self, util::DeviceExt};++use crate::{util::read_buffer_to_vec, uyvy};++pub struct UYVYToNV12 {+ device: wgpu::Device,+ queue: wgpu::Queue,+ pipeline: wgpu::ComputePipeline,+ bind_group_layout: wgpu::BindGroupLayout,+}++impl UYVYToNV12 {+ pub async fn new() -> Self {+ todo!("implement UV downsampling for UYVYToNV12");++ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default());++ let adapter = instance+ .request_adapter(&wgpu::RequestAdapterOptions {+ power_preference: wgpu::PowerPreference::HighPerformance,+ force_fallback_adapter: false,+ compatible_surface: None,+ })+ .await+ .unwrap();++ let (device, queue) = adapter+ .request_device(+ &wgpu::DeviceDescriptor {+ required_features: wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES,+ ..Default::default()+ },+ None,+ )+ .await+ .unwrap();++ // Shader for YUYV to RGBA conversion+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("YUYV to RGBA Converter"),+ source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!(+ "./shader.wgsl"+ ))),+ });++ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("YUYV Converter Bind Group Layout"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Uint,+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Storage { read_only: false },+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 2,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Storage { read_only: false },+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 3,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ },+ ],+ });++ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("YUYV Converter Pipeline Layout"),+ bind_group_layouts: &[&bind_group_layout],+ push_constant_ranges: &[],+ });++ let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {+ label: Some("YUYV Converter Pipeline"),+ layout: Some(&pipeline_layout),+ module: &shader,+ entry_point: "main",+ compilation_options: Default::default(),+ cache: None,+ });++ Self {+ device,+ queue,+ pipeline,+ bind_group_layout,+ }+ }++ pub fn convert(&self, uyvy_data: &[u8], width: u32, height: u32) -> (Vec<u8>, Vec<u8>) {+ let uyvy_texture =+ uyvy::create_input_texture(&self.device, &self.queue, uyvy_data, width, height);++ let y_write_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {+ label: None,+ size: (width * height) as u64,+ usage: wgpu::BufferUsages::STORAGE+ | wgpu::BufferUsages::COPY_SRC+ | wgpu::BufferUsages::INDEX,+ mapped_at_creation: false,+ });++ let uv_write_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {+ label: None,+ size: (width * height) as u64 / 2,+ usage: wgpu::BufferUsages::STORAGE+ | wgpu::BufferUsages::COPY_SRC+ | wgpu::BufferUsages::INDEX,+ mapped_at_creation: false,+ });++ // Create bind group+ let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("UYVY Converter Bind Group"),+ layout: &self.bind_group_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: wgpu::BindingResource::TextureView(+ &uyvy_texture.create_view(&Default::default()),+ ),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: wgpu::BindingResource::Buffer(+ y_write_buffer.as_entire_buffer_binding(),+ ),+ },+ wgpu::BindGroupEntry {+ binding: 2,+ resource: wgpu::BindingResource::Buffer(+ uv_write_buffer.as_entire_buffer_binding(),+ ),+ },+ wgpu::BindGroupEntry {+ binding: 3,+ resource: wgpu::BindingResource::Buffer(+ self.device+ .create_buffer_init(&wgpu::util::BufferInitDescriptor {+ label: None,+ contents: [width.to_ne_bytes(), height.to_ne_bytes()]+ .as_flattened(),+ usage: wgpu::BufferUsages::UNIFORM,+ })+ .as_entire_buffer_binding(),+ ),+ },+ ],+ });++ // Create command encoder and dispatch compute shader+ let mut encoder = self+ .device+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {+ label: Some("YUYV Conversion Encoder"),+ });++ {+ let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {+ label: Some("YUYV Conversion Pass"),+ ..Default::default()+ });+ compute_pass.set_pipeline(&self.pipeline);+ compute_pass.set_bind_group(0, &bind_group, &[]);+ compute_pass.dispatch_workgroups((width + 3) / 4, (height + 7) / 8, 1);+ }++ let y_read_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {+ label: None,+ size: y_write_buffer.size(),+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,+ mapped_at_creation: false,+ });++ let uv_read_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {+ label: None,+ size: uv_write_buffer.size(),+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,+ mapped_at_creation: false,+ });++ encoder.copy_buffer_to_buffer(&y_write_buffer, 0, &y_read_buffer, 0, y_write_buffer.size());+ encoder.copy_buffer_to_buffer(+ &uv_write_buffer,+ 0,+ &uv_read_buffer,+ 0,+ uv_write_buffer.size(),+ );++ // Submit commands+ self.queue.submit(std::iter::once(encoder.finish()));++ (+ read_buffer_to_vec(&y_read_buffer, &self.device),+ read_buffer_to_vec(&uv_read_buffer, &self.device),+ )+ }+}diff --git a/crates/gpu-converters/src/uyvy_nv12/shader.wgsl b/crates/gpu-converters/src/uyvy_nv12/shader.wgslnew file mode 100644index 000000000..74441762c--- /dev/null+++ b/crates/gpu-converters/src/uyvy_nv12/shader.wgsl@@ -0,0 +1,46 @@+@group(0) @binding(0) var uyvy_input: texture_2d<u32>;++@group(0) @binding(1) var<storage, read_write> y_plane: array<u32>;+@group(0) @binding(2) var<storage, read_write> uv_plane: array<u32>;++@group(0) @binding(3) var<uniform> size: vec2<u32>;++@compute+@workgroup_size(8, 8)+fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {+ let coords = global_id.xy;++ // Each UYVY pixel contains 2 luma samples and shared UV samples+ let x = global_id.x / 4;+ let y = global_id.y / 4;++ let uyvy = textureLoad(uyvy_input, coords, 0).rgba;++ // Extract UYVY components+ let u = uyvy.r;+ let y1 = uyvy.g;+ let v = uyvy.b;+ let y2 = uyvy.a;++ // Write Y samples (one per actual pixel)+ let y_offset = y * size.x + (x * 2);+ y_plane[y_offset] = y1;+ y_plane[y_offset + 1] = y2;++ // this don't work :(++ // Handle UV downsampling+ // We only want to write UV values for every 2x2 block of pixels+ // This means we process UV on every other row+ if ((y % 2) == 0) {+ // Calculate the UV plane offset+ // UV plane is half the size in both dimensions+ let uv_row_stride = size.x; // Width of the UV plane in bytes+ let uv_offset = (y / 2) * uv_row_stride + x;++ // Write interleaved UV samples+ // Note: For every 2x2 block of pixels, we write one U and one V sample+ uv_plane[uv_offset] = u; // U sample+ uv_plane[uv_offset + 1] = v; // V sample+ }+}diff --git a/crates/gpu-converters/src/uyvy_rgba/mod.rs b/crates/gpu-converters/src/uyvy_rgba/mod.rsnew file mode 100644index 000000000..49bfcf05a--- /dev/null+++ b/crates/gpu-converters/src/uyvy_rgba/mod.rs@@ -0,0 +1,155 @@+use wgpu::{self, util::DeviceExt};++use crate::{+ util::{copy_texture_to_buffer_command, read_buffer_to_vec},+ uyvy,+};++pub struct UYVYToRGBA {+ device: wgpu::Device,+ queue: wgpu::Queue,+ pipeline: wgpu::ComputePipeline,+ bind_group_layout: wgpu::BindGroupLayout,+}++impl UYVYToRGBA {+ pub async fn new() -> Self {+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default());++ let adapter = instance+ .request_adapter(&wgpu::RequestAdapterOptions {+ power_preference: wgpu::PowerPreference::HighPerformance,+ force_fallback_adapter: false,+ compatible_surface: None,+ })+ .await+ .unwrap();++ let (device, queue) = adapter+ .request_device(&wgpu::DeviceDescriptor::default(), None)+ .await+ .unwrap();++ // Shader for YUYV to RGBA conversion+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("YUYV to RGBA Converter"),+ source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!(+ "./shader.wgsl"+ ))),+ });++ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("YUYV Converter Bind Group Layout"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Uint,+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::StorageTexture {+ access: wgpu::StorageTextureAccess::WriteOnly,+ format: wgpu::TextureFormat::Rgba8Unorm,+ view_dimension: wgpu::TextureViewDimension::D2,+ },+ count: None,+ },+ ],+ });++ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("YUYV Converter Pipeline Layout"),+ bind_group_layouts: &[&bind_group_layout],+ push_constant_ranges: &[],+ });++ let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {+ label: Some("YUYV Converter Pipeline"),+ layout: Some(&pipeline_layout),+ module: &shader,+ entry_point: "main",+ compilation_options: Default::default(),+ cache: None,+ });++ Self {+ device,+ queue,+ pipeline,+ bind_group_layout,+ }+ }++ pub fn convert(&self, uyvy_data: &[u8], width: u32, height: u32) -> Vec<u8> {+ let uyvy_texture =+ uyvy::create_input_texture(&self.device, &self.queue, uyvy_data, width, height);++ // Create output texture+ let output_texture = self.device.create_texture(&wgpu::TextureDescriptor {+ label: Some("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::COPY_SRC,+ view_formats: &[],+ });++ // Create bind group+ let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("YUYV Converter Bind Group"),+ layout: &self.bind_group_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: wgpu::BindingResource::TextureView(+ &uyvy_texture.create_view(&Default::default()),+ ),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: wgpu::BindingResource::TextureView(+ &output_texture.create_view(&Default::default()),+ ),+ },+ ],+ });++ // Create command encoder and dispatch compute shader+ let mut encoder = self+ .device+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {+ label: Some("YUYV Conversion Encoder"),+ });++ {+ let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {+ label: Some("YUYV Conversion Pass"),+ ..Default::default()+ });+ compute_pass.set_pipeline(&self.pipeline);+ compute_pass.set_bind_group(0, &bind_group, &[]);+ compute_pass.dispatch_workgroups((width + 7) / 8, (height + 7) / 8, 1);+ }++ let output_buffer =+ copy_texture_to_buffer_command(&self.device, &output_texture, &mut encoder);++ // Submit commands+ self.queue.submit(std::iter::once(encoder.finish()));++ read_buffer_to_vec(&output_buffer, &self.device)+ }+}diff --git a/crates/gpu-converters/src/uyvy_rgba/shader.wgsl b/crates/gpu-converters/src/uyvy_rgba/shader.wgslnew file mode 100644index 000000000..3812db800--- /dev/null+++ b/crates/gpu-converters/src/uyvy_rgba/shader.wgsl@@ -0,0 +1,35 @@+@group(0) @binding(0)+var uyvy_input: texture_2d<u32>;++@group(0) @binding(1)+var rgba_output: texture_storage_2d<rgba8unorm, write>;++@compute+@workgroup_size(8, 8)+fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {+ let coords = global_id.xy;++ let x = global_id.x;+ let y = global_id.y;++ let uyvy = textureLoad(uyvy_input, coords, 0).rgba;++ let u = f32(uyvy.r) / 255.0;+ let y1 = f32(uyvy.g) / 255.0;+ let v = f32(uyvy.b) / 255.0;+ let y2 = f32(uyvy.a) / 255.0;++ let r = clamp(y1 + 1.403 * (v - 0.5), 0.0, 1.0);+ let g = clamp(y1 - 0.344 * (u - 0.5) - 0.714 * (v - 0.5), 0.0, 1.0);+ let b = clamp(y1 + 1.770 * (u - 0.5), 0.0, 1.0);++ let output_coords = coords * vec2<u32>(2, 1);++ textureStore(rgba_output, output_coords, vec4<f32>(r, g, b, 1.0));++ let r2 = clamp(y2 + 1.403 * (v - 0.5), 0.0, 1.0);+ let g2 = clamp(y2 - 0.344 * (u - 0.5) - 0.714 * (v - 0.5), 0.0, 1.0);+ let b2 = clamp(y2 + 1.770 * (u - 0.5), 0.0, 1.0);++ textureStore(rgba_output, output_coords + vec2<u32>(1, 0), vec4<f32>(r2, g2, b2, 1.0));+}diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.tomlindex 0968af3a9..4e3182d83 100644--- a/crates/media/Cargo.toml+++ b/crates/media/Cargo.toml@@ -8,24 +8,26 @@ rust-version = "1.80"[dependencies]anyhow.workspace = truecap-project = { path = "../project" }+cap-flags = { path = "../flags" }+cap-gpu-converters = { path = "../gpu-converters" }cpal = "0.15.3"ffmpeg.workspace = trueffmpeg-sys-next.workspace = trueffmpeg-hw-device = { path = "../ffmpeg-hw-device" }flume = "0.11.0"indexmap = "2.5.0"-nokhwa = { git = "https://github.com/capsoftware/nokhwa", rev = "6ce1e8270d57", features = [- "input-native",- "serialize",-] }scap.workspace = true+nokhwa = { workspace = true, features = ["input-native", "serialize"] }serde = { version = "1", features = ["derive"] }specta.workspace = truetempfile = "3.12.0"thiserror = "1.0"tracing = "0.1"-cap-flags = { path = "../flags" }-windows = { version = "0.52", features = ["Win32_Media_MediaFoundation", "Win32_System_Com"] }+windows = { version = "0.52", features = [+ "Win32_Media_MediaFoundation",+ "Win32_System_Com",+] }+futures = "0.3.31"[target.'cfg(target_os = "macos")'.dependencies]cocoa = "0.26.0"@@ -34,7 +36,7 @@ core-foundation = "0.10.0"objc = "0.2.7"objc-foundation = "0.1.1"objc2-foundation = { version = "0.2.2", features = ["NSValue"] }-nokhwa-bindings-macos = { git = "https://github.com/capsoftware/nokhwa", rev = "6ce1e8270d57" }+nokhwa-bindings-macos.workspace = true[target.'cfg(target_os = "windows")'.dependencies]windows = { version = "0.52.0", features = [diff --git a/crates/media/src/data.rs b/crates/media/src/data.rsindex 5099319bf..f594bb2a5 100644--- a/crates/media/src/data.rs+++ b/crates/media/src/data.rs@@ -26,6 +26,7 @@ pub enum RawVideoFormat {RawRgb,Nv12,Gray,+ YUYV420,}impl From<RawAudioFormat> for Sample {@@ -116,6 +117,7 @@ impl VideoInfo {RawVideoFormat::RawRgb => Pixel::RGB24,RawVideoFormat::Nv12 => Pixel::NV12,RawVideoFormat::Gray => Pixel::GRAY8,+ RawVideoFormat::YUYV420 => Pixel::YUV420P,},width,height,@@ -137,7 +139,7 @@ impl VideoInfo {};Self {- pixel_format: Pixel::YUV420P,+ pixel_format: Pixel::NV12,width,height,time_base: self.time_base,diff --git a/crates/media/src/encoders/h264.rs b/crates/media/src/encoders/h264.rsindex 22a058bbf..9b327f9d0 100644--- a/crates/media/src/encoders/h264.rs+++ b/crates/media/src/encoders/h264.rs@@ -16,6 +16,7 @@ pub struct H264Encoder {tag: &'static str,encoder: encoder::Video,output_ctx: format::context::Output,+ last_pts: Option<i64>,}impl H264Encoder {@@ -35,6 +36,8 @@ impl H264Encoder {encoder.set_height(config.height);encoder.set_format(config.pixel_format);encoder.set_time_base(config.frame_rate.invert());+ encoder.set_frame_rate(Some(config.frame_rate));+ encoder.set_bit_rate(5_000_000);let video_encoder = encoder.open_with(options)?;@@ -48,6 +51,7 @@ impl H264Encoder {tag,encoder: video_encoder,output_ctx,+ last_pts: None,})}@@ -103,7 +107,14 @@ impl PipelineSinkTask for H264Encoder {}fn get_codec_and_options(config: &VideoInfo) -> Result<(Codec, Dictionary), MediaError> {- if let Some(codec) = encoder::find_by_name("libx264") {+ let encoder_name = {+ if cfg!(target_os = "macos") {+ "h264_videotoolbox"+ } else {+ "h264"+ }+ };+ if let Some(codec) = encoder::find_by_name(encoder_name) {let mut options = Dictionary::new();let keyframe_interval_secs = 2;diff --git a/crates/media/src/feeds/camera.rs b/crates/media/src/feeds/camera.rsindex c7bb8b2d4..10122efe6 100644--- a/crates/media/src/feeds/camera.rs+++ b/crates/media/src/feeds/camera.rs@@ -1,6 +1,7 @@+use cap_gpu_converters::{NV12Input, NV12ToRGBA, UYVYToNV12, UYVYToRGBA};use ffmpeg::software::scaling;use flume::{Receiver, Sender, TryRecvError};-use nokhwa::{pixel_format::*, utils::*, Camera};+use nokhwa::{utils::*, Camera};use std::{thread::{self, JoinHandle},time::Instant,@@ -82,7 +83,7 @@ impl CameraFeed {{use windows::Win32::Media::MediaFoundation::{MFStartup, MFSTARTUP_FULL};use windows::Win32::System::Com::{CoInitializeEx, COINIT_MULTITHREADED};-+// On Windows, wrap the entire operation in a catch_unwind to prevent crashesmatch std::panic::catch_unwind(|| {// Initialize COM and Media Foundation@@ -178,13 +179,16 @@ fn create_camera(info: &CameraInfo) -> Result<Camera, MediaError> {// TODO: Make selected format more flexible// let format = RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestResolution);- let format = RequestedFormat::new::<RgbAFormat>(RequestedFormatType::ClosestIgnoringFormat {- resolution: Resolution {- width_x: 1920,- height_y: 1080,+ let format = RequestedFormat::with_formats(+ RequestedFormatType::ClosestIgnoringFormat {+ resolution: Resolution {+ width_x: 1920,+ height_y: 1080,+ },+ frame_rate: 30,},- frame_rate: 30,- });+ &[FrameFormat::NV12],+ );let index = info.index().clone();@@ -367,6 +371,12 @@ struct FrameConverter {video_info: VideoInfo,context: scaling::Context,pub format: FrameFormat,+ hw_converter: Option<HwConverter>,+}++pub enum HwConverter {+ NV12(NV12ToRGBA),+ UYVY(UYVYToRGBA),}impl FrameConverter {@@ -394,22 +404,45 @@ impl FrameConverter {).unwrap();+ let hw_converter = match camera_format.format() {+ FrameFormat::NV12 => Some(HwConverter::NV12(futures::executor::block_on(+ NV12ToRGBA::new(),+ ))),+ FrameFormat::YUYV => Some(HwConverter::UYVY(futures::executor::block_on(+ UYVYToRGBA::new(),+ ))),+ _ => None,+ };+Self {video_info,context,format: camera_format.format(),+ hw_converter,}}fn rgba(&mut self, buffer: &nokhwa::Buffer) -> Vec<u8> {let resolution = buffer.resolution();- let input_frame = self.video_info.wrap_frame(buffer.buffer(), 0);- let mut rgba_frame = FFVideo::empty();+ let mut data = match &self.hw_converter {+ Some(HwConverter::NV12(converter)) => converter.convert(+ NV12Input::from_buffer(buffer.buffer(), resolution.width(), resolution.height()),+ resolution.width(),+ resolution.height(),+ ),+ Some(HwConverter::UYVY(converter)) => {+ converter.convert(buffer.buffer(), resolution.width(), resolution.height())+ }+ None => {+ let input_frame = self.video_info.wrap_frame(buffer.buffer(), 0);+ let mut rgba_frame = FFVideo::empty();- self.context.run(&input_frame, &mut rgba_frame).unwrap();+ self.context.run(&input_frame, &mut rgba_frame).unwrap();- let mut data = rgba_frame.data(0).to_vec();+ rgba_frame.data(0).to_vec()+ }+ };data.extend_from_slice(&resolution.height().to_le_bytes());data.extend_from_slice(&resolution.width().to_le_bytes());diff --git a/crates/media/src/filters/video.rs b/crates/media/src/filters/video.rsindex 192426b21..34b6e8dc8 100644--- a/crates/media/src/filters/video.rs+++ b/crates/media/src/filters/video.rs@@ -31,6 +31,8 @@ impl VideoFilter {filter_graph.add(&filter::find("buffer").unwrap(), "in", &input_args)?;filter_graph.add(&filter::find("buffersink").unwrap(), "out", "")?;+ dbg!(input_config.pixel_format, output_config.pixel_format);+let mut input = filter_graph.get("in").unwrap();input.set_pixel_format(input_config.pixel_format);diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rsindex 34582330e..0282de5ec 100644--- a/crates/media/src/sources/screen_capture.rs+++ b/crates/media/src/sources/screen_capture.rs@@ -2,7 +2,7 @@ use cap_flags::FLAGS;use flume::Sender;use scap::{capturer::{get_output_frame_size, Area, Capturer, Options, Point, Resolution, Size},- frame::{Frame, FrameType},+ frame::FrameType,Target,};use serde::{Deserialize, Serialize};@@ -88,7 +88,8 @@ impl ScreenCaptureSource {true}_ => false,- }).cloned()+ })+ .cloned().collect();let (crop_area, bounds) = match capture_target {@@ -126,7 +127,7 @@ impl ScreenCaptureSource {show_cursor: !FLAGS.zoom,show_highlight: true,excluded_targets: Some(excluded_targets),- output_type: FrameType::BGRAFrame,+ output_type: FrameType::YUVFrame,output_resolution,crop_area,target,@@ -139,7 +140,7 @@ impl ScreenCaptureSource {options,target: capture_target.clone(),bounds,- video_info: VideoInfo::from_raw(RawVideoFormat::Bgra, frame_width, frame_height, fps),+ video_info: VideoInfo::from_raw(RawVideoFormat::Nv12, frame_width, frame_height, fps),}}@@ -241,66 +242,47 @@ impl PipelineSourceTask for ScreenCaptureSource {println!("Screen recording started.");}- match capturer.get_next_frame() {- Ok(Frame::BGRA(frame)) => {- if frame.height == 0 || frame.width == 0 {+ match capturer.raw().get_next_pixel_buffer() {+ Ok(pixel_buffer) => {+ if pixel_buffer.height() == 0 || pixel_buffer.width() == 0 {continue;}- let raw_timestamp = RawNanoseconds(frame.display_time);+ let raw_timestamp = RawNanoseconds(pixel_buffer.display_time());match clock.timestamp_for(raw_timestamp) {None => {eprintln!("Clock is currently stopped. Dropping frames.");}Some(timestamp) => {- let mut buffer = FFVideo::new(+ let mut frame = FFVideo::new(self.video_info.pixel_format,self.video_info.width,self.video_info.height,);- buffer.set_pts(Some(timestamp));-- let bytes_per_pixel = 4;- let width_in_bytes = frame.width as usize * bytes_per_pixel;- let height = frame.height as usize;+ frame.set_pts(Some(timestamp));- let src_data = &frame.data;+ let planes = pixel_buffer.planes();- let src_stride = src_data.len() / height;- let dst_stride = buffer.stride(0);+ for (i, plane) in planes.into_iter().enumerate() {+ let data = plane.data();- if src_data.len() < src_stride * height {- eprintln!("Frame data size mismatch.");- continue;- }-- if src_stride < width_in_bytes {- eprintln!(- "Source stride is less than expected width in bytes."- );- continue;- }-- if buffer.data(0).len() < dst_stride * height {- eprintln!("Destination data size mismatch.");- continue;- }+ for y in 0..plane.height() {+ let buffer_y_offset = y * plane.bytes_per_row();+ let frame_y_offset = y * frame.stride(i);- {- let dst_data = buffer.data_mut(0);+ let num_bytes =+ frame.stride(i).min(plane.bytes_per_row());- for y in 0..height {- let src_offset = y * src_stride;- let dst_offset = y * dst_stride;- dst_data[dst_offset..dst_offset + width_in_bytes]+ frame.data_mut(i)+ [frame_y_offset..frame_y_offset + num_bytes].copy_from_slice(- &src_data- [src_offset..src_offset + width_in_bytes],+ &data[buffer_y_offset+ ..buffer_y_offset + num_bytes],);}}- if let Err(_) = output.send(buffer) {+ if let Err(_) = output.send(frame) {eprintln!("Pipeline is unreachable. Shutting down recording.");@@ -309,7 +291,6 @@ impl PipelineSourceTask for ScreenCaptureSource {}};}- Ok(_) => unreachable!(),Err(error) => {eprintln!("Capture error: {error}");break;diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.tomlindex 3f1ec0461..b0c66b46a 100644--- a/crates/rendering/Cargo.toml+++ b/crates/rendering/Cargo.toml@@ -9,7 +9,7 @@ bytemuck = { version = "1.7", features = ["derive"] }futures-intrusive = "0.5.0"serde = "1.0.209"specta.workspace = true-wgpu = "22.1.0"+wgpu.workspace = trueimage = "0.25.2"cap-ffmpeg-cli = { path = "../ffmpeg-cli" }diff --git a/crates/rendering/src/decoder.rs b/crates/rendering/src/decoder.rsindex 9eefed428..996e1065f 100644--- a/crates/rendering/src/decoder.rs+++ b/crates/rendering/src/decoder.rs@@ -47,10 +47,17 @@ impl AsyncVideoDecoder {let mut context = codec::context::Context::new_with_codec(decoder_codec);context.set_parameters(input_stream.parameters()).unwrap();+ let input_stream_index = input_stream.index();+ let time_base = input_stream.time_base();+ let frame_rate = input_stream.rate();++ // Create a decoder for the video stream+ let mut decoder = context.decoder().video().unwrap();+let hw_device: Option<HwDevice> = {#[cfg(target_os = "macos")]{- context+ decoder.try_use_hw_device(AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX,Pixel::NV12,@@ -62,13 +69,6 @@ impl AsyncVideoDecoder {None};- let input_stream_index = input_stream.index();- let time_base = input_stream.time_base();- let frame_rate = input_stream.rate();-- // Create a decoder for the video stream- let mut decoder = context.decoder().video().unwrap();-use ffmpeg::format::Pixel;use ffmpeg::software::scaling::{context::Context, flag::Flags};diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex f4eb341a1..4b024b0d7 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -12,7 +12,7 @@ use wgpu::util::DeviceExt;use wgpu::{CommandEncoder, COPY_BYTES_PER_ROW_ALIGNMENT};use cap_project::{- AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Crop, CursorClickEvent,+ AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Crop,CursorData, CursorMoveEvent, ProjectConfiguration, XY,};@@ -433,7 +433,7 @@ impl ProjectUniforms {let output_size = Self::get_output_size(options, project);let output_size = XY::new(output_size.0 as f64, output_size.1 as f64);- let output_aspect = output_size.x as f64 / output_size.y as f64;+ let output_aspect = output_size.x / output_size.y;let crop = Self::get_crop(options, project);@@ -629,7 +629,7 @@ impl ProjectUniforms {// Calculate camera motion blur based on zoom transitionlet camera_motion_blur = {- let base_blur = project.motion_blur.unwrap_or(0.2) as f32;+ let base_blur = project.motion_blur.unwrap_or(0.2);let zoom_delta = (current_zoom - prev_zoom).abs() as f32;// Calculate a smooth transition factor