Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add frame-converter crate with GPU and CPU backends
Richie McIlroyf4414b2ac3ef
diff --git a/crates/frame-converter/Cargo.toml b/crates/frame-converter/Cargo.tomlnew file mode 100644index 000000000..a69a81dbb--- /dev/null+++ b/crates/frame-converter/Cargo.toml@@ -0,0 +1,30 @@+[package]+name = "cap-frame-converter"+version = "0.1.0"+edition = "2024"++[lints]+workspace = true++[dependencies]+cap-media-info = { path = "../media-info" }++ffmpeg.workspace = true+thiserror.workspace = true+tracing.workspace = true+flume.workspace = true+crossbeam-channel = "0.5"+parking_lot = "0.12"+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[target.'cfg(target_os = "macos")'.dependencies]++[target.'cfg(target_os = "windows")'.dependencies]+windows = { workspace = true, features = [+ "Win32_Foundation",+ "Win32_Graphics_Direct3D",+ "Win32_Graphics_Direct3D11",+ "Win32_Graphics_Dxgi_Common",+ "Win32_Media_MediaFoundation",+] }+diff --git a/crates/frame-converter/build.rs b/crates/frame-converter/build.rsnew file mode 100644index 000000000..2f12dbcee--- /dev/null+++ b/crates/frame-converter/build.rs@@ -0,0 +1,8 @@+fn main() {+ #[cfg(target_os = "macos")]+ {+ println!("cargo:rustc-link-lib=framework=VideoToolbox");+ println!("cargo:rustc-link-lib=framework=CoreVideo");+ println!("cargo:rustc-link-lib=framework=CoreFoundation");+ }+}diff --git a/crates/frame-converter/examples/benchmark.rs b/crates/frame-converter/examples/benchmark.rsnew file mode 100644index 000000000..c65c783c1--- /dev/null+++ b/crates/frame-converter/examples/benchmark.rs@@ -0,0 +1,274 @@+use cap_frame_converter::{+ AsyncConverterPool, ConversionConfig, ConverterPoolConfig, DropStrategy, FrameConverter,+ SwscaleConverter,+};+use ffmpeg::format::Pixel;+use std::sync::Arc;+use std::sync::atomic::{AtomicU64, Ordering};+use std::time::{Duration, Instant};++fn create_test_frame(format: Pixel, width: u32, height: u32) -> ffmpeg::frame::Video {+ let mut frame = ffmpeg::frame::Video::new(format, width, height);+ for plane_idx in 0..frame.planes() {+ let data = frame.data_mut(plane_idx);+ for (i, byte) in data.iter_mut().enumerate() {+ *byte = ((i * 17 + plane_idx * 31) % 256) as u8;+ }+ }+ frame.set_pts(Some(0));+ frame+}++fn benchmark_single_threaded(iterations: u32, config: &ConversionConfig) -> Duration {+ let converter = SwscaleConverter::new(config.clone()).expect("Failed to create converter");++ let mut total_time = Duration::ZERO;+ let mut first_frame = true;++ for i in 0..iterations {+ let frame = create_test_frame(config.input_format, config.input_width, config.input_height);+ let start = Instant::now();+ let _output = converter.convert(frame).expect("Conversion failed");+ let elapsed = start.elapsed();++ if first_frame {+ println!(" First frame: {:?}", elapsed);+ first_frame = false;+ }+ total_time += elapsed;+ }++ total_time+}++fn benchmark_pool(+ frame_count: u32,+ config: &ConversionConfig,+ worker_count: usize,+) -> (Duration, u64, u64) {+ let pool_config = ConverterPoolConfig {+ worker_count,+ input_capacity: 120,+ output_capacity: 120,+ drop_strategy: DropStrategy::DropOldest,+ };++ let pool = AsyncConverterPool::from_config(config.clone(), pool_config)+ .expect("Failed to create pool");++ let start = Instant::now();++ for i in 0..frame_count {+ let mut frame =+ create_test_frame(config.input_format, config.input_width, config.input_height);+ frame.set_pts(Some(i as i64 * 33333));+ pool.submit(frame, i as u64).expect("Submit failed");+ }++ let mut received = 0u64;+ let deadline = Instant::now() + Duration::from_secs(30);++ while received < frame_count as u64 && Instant::now() < deadline {+ if let Some(_converted) = pool.recv_timeout(Duration::from_millis(100)) {+ received += 1;+ }+ let stats = pool.stats();+ if stats.frames_converted >= frame_count as u64 {+ while let Some(_) = pool.try_recv() {+ received += 1;+ }+ break;+ }+ }++ let elapsed = start.elapsed();+ let stats = pool.stats();++ (elapsed, stats.frames_converted, stats.frames_dropped)+}++fn main() {+ ffmpeg::init().expect("Failed to init ffmpeg");++ println!("=== Camera Frame Conversion Benchmark ===\n");++ let config = ConversionConfig::new(Pixel::UYVY422, 1920, 1080, Pixel::NV12, 1920, 1080);++ println!(+ "Conversion: {:?} {}x{} -> {:?} {}x{}\n",+ config.input_format,+ config.input_width,+ config.input_height,+ config.output_format,+ config.output_width,+ config.output_height+ );++ println!("--- Single-threaded SwScale ---");+ let warmup_iterations = 10;+ let test_iterations = 100;++ println!("Warmup ({} frames)...", warmup_iterations);+ let _ = benchmark_single_threaded(warmup_iterations, &config);++ println!("Benchmark ({} frames)...", test_iterations);+ let single_time = benchmark_single_threaded(test_iterations, &config);+ let avg_per_frame = single_time / test_iterations;+ let max_fps = 1.0 / avg_per_frame.as_secs_f64();+ println!(" Total time: {:?}", single_time);+ println!(" Avg per frame: {:?}", avg_per_frame);+ println!(" Max theoretical FPS: {:.1}", max_fps);+ println!(+ " Can sustain 30fps: {}",+ if max_fps >= 30.0 { "YES" } else { "NO" }+ );+ println!();++ let frame_count = 300;++ for worker_count in [1, 2, 4, 6, 8] {+ println!(+ "--- Pool with {} workers ({} frames) ---",+ worker_count, frame_count+ );+ let (elapsed, converted, dropped) = benchmark_pool(frame_count, &config, worker_count);++ let conversion_fps = converted as f64 / elapsed.as_secs_f64();+ println!(" Total time: {:?}", elapsed);+ println!(" Converted: {}, Dropped: {}", converted, dropped);+ println!(" Throughput: {:.1} fps", conversion_fps);+ println!(+ " Can sustain 30fps: {}",+ if conversion_fps >= 30.0 { "YES" } else { "NO" }+ );+ println!();+ }++ println!("--- Alternative Format Tests ---");++ let formats_to_test = [+ (Pixel::UYVY422, Pixel::YUV420P, "UYVY422 -> YUV420P"),+ (Pixel::YUYV422, Pixel::NV12, "YUYV422 -> NV12"),+ (Pixel::BGRA, Pixel::NV12, "BGRA -> NV12"),+ ];++ for (input_format, output_format, name) in formats_to_test {+ let alt_config = ConversionConfig::new(input_format, 1920, 1080, output_format, 1920, 1080);++ if SwscaleConverter::new(alt_config.clone()).is_ok() {+ let time = benchmark_single_threaded(50, &alt_config);+ let avg = time / 50;+ let fps = 1.0 / avg.as_secs_f64();+ println!(" {}: {:.1} fps ({:?}/frame)", name, fps, avg);+ }+ }++ println!("\n--- Real-time Simulations ---");++ for encode_time_ms in [0.1, 1.0, 5.0, 10.0, 20.0] {+ println!("\n Encode time: {}ms", encode_time_ms);+ simulate_realtime_pipeline(+ &config,+ 30.0,+ Duration::from_secs(10),+ Duration::from_secs_f64(encode_time_ms / 1000.0),+ );+ }++ println!("\n=== Benchmark Complete ===");+}++fn simulate_realtime_pipeline(+ config: &ConversionConfig,+ target_fps: f64,+ duration: Duration,+ encode_time_per_frame: Duration,+) {+ let frame_interval = Duration::from_secs_f64(1.0 / target_fps);+ let total_frames = (duration.as_secs_f64() * target_fps) as u32;++ let pool_config = ConverterPoolConfig {+ worker_count: 4,+ input_capacity: 60,+ output_capacity: 30,+ drop_strategy: DropStrategy::DropOldest,+ };++ let pool = AsyncConverterPool::from_config(config.clone(), pool_config)+ .expect("Failed to create pool");++ let start = Instant::now();+ let mut next_frame_time = start;+ let mut submitted = 0u32;+ let mut converted = 0u64;+ let mut encode_time_total = Duration::ZERO;++ println!(+ " Simulating {} frames at {:.1} fps over {:?}",+ total_frames, target_fps, duration+ );++ for i in 0..total_frames {+ let now = Instant::now();+ if now < next_frame_time {+ std::thread::sleep(next_frame_time - now);+ }+ next_frame_time += frame_interval;++ let mut frame =+ create_test_frame(config.input_format, config.input_width, config.input_height);+ frame.set_pts(Some(i as i64 * 33333));++ if pool.submit(frame, i as u64).is_ok() {+ submitted += 1;+ }++ while let Some(_converted_frame) = pool.try_recv() {+ converted += 1;+ let encode_start = Instant::now();+ std::thread::sleep(encode_time_per_frame);+ encode_time_total += encode_start.elapsed();+ }+ }++ let drain_deadline = Instant::now() + Duration::from_secs(5);+ while Instant::now() < drain_deadline {+ if let Some(_) = pool.recv_timeout(Duration::from_millis(100)) {+ converted += 1;+ } else {+ break;+ }+ }++ let elapsed = start.elapsed();+ let stats = pool.stats();++ println!(" Elapsed: {:?}", elapsed);+ println!(+ " Submitted: {}, Converted: {}, Dropped: {}",+ submitted, converted, stats.frames_dropped+ );+ println!(+ " Drop rate: {:.1}%",+ (stats.frames_dropped as f64 / total_frames as f64) * 100.0+ );+ println!(" Total encode time: {:?}", encode_time_total);++ let expected_duration = Duration::from_secs_f64(total_frames as f64 / target_fps);+ let overhead = if elapsed > expected_duration {+ elapsed - expected_duration+ } else {+ Duration::ZERO+ };+ println!(" Processing overhead: {:?}", overhead);++ if stats.frames_dropped == 0 {+ println!(" Result: SUCCESS - No frames dropped!");+ } else {+ println!(+ " Result: FAILED - {} frames dropped ({:.1}%)",+ stats.frames_dropped,+ (stats.frames_dropped as f64 / total_frames as f64) * 100.0+ );+ }+}diff --git a/crates/frame-converter/src/d3d11.rs b/crates/frame-converter/src/d3d11.rsnew file mode 100644index 000000000..4fa7bc344--- /dev/null+++ b/crates/frame-converter/src/d3d11.rs@@ -0,0 +1,574 @@+use crate::{ConversionConfig, ConvertError, ConverterBackend, FrameConverter};+use ffmpeg::{format::Pixel, frame};+use parking_lot::Mutex;+use std::{+ ptr,+ sync::atomic::{AtomicBool, AtomicU64, Ordering},+};+use windows::{+ Win32::Graphics::{+ Direct3D::D3D_DRIVER_TYPE_HARDWARE,+ Direct3D11::{+ D3D11_BIND_RENDER_TARGET, D3D11_CPU_ACCESS_READ, D3D11_CPU_ACCESS_WRITE,+ D3D11_CREATE_DEVICE_VIDEO_SUPPORT, D3D11_MAP_READ, D3D11_MAP_WRITE, D3D11_SDK_VERSION,+ D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING,+ D3D11_VIDEO_PROCESSOR_CONTENT_DESC, D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC,+ D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC, D3D11_VIDEO_PROCESSOR_STREAM,+ D3D11_VPIV_DIMENSION_TEXTURE2D, D3D11_VPOV_DIMENSION_TEXTURE2D, D3D11CreateDevice,+ ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D, ID3D11VideoContext,+ ID3D11VideoDevice, ID3D11VideoProcessor, ID3D11VideoProcessorEnumerator,+ ID3D11VideoProcessorInputView, ID3D11VideoProcessorOutputView,+ },+ Dxgi::{+ Common::{DXGI_FORMAT, DXGI_FORMAT_NV12, DXGI_FORMAT_YUY2},+ IDXGIAdapter, IDXGIDevice,+ },+ },+ core::Interface,+};++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum GpuVendor {+ Nvidia,+ Amd,+ Intel,+ Qualcomm,+ Arm,+ Microsoft,+ Unknown(u32),+}++impl GpuVendor {+ pub fn from_id(vendor_id: u32) -> Self {+ match vendor_id {+ 0x10DE => GpuVendor::Nvidia,+ 0x1002 | 0x1022 => GpuVendor::Amd,+ 0x8086 => GpuVendor::Intel,+ 0x5143 => GpuVendor::Qualcomm,+ 0x13B5 => GpuVendor::Arm,+ 0x1414 => GpuVendor::Microsoft,+ _ => GpuVendor::Unknown(vendor_id),+ }+ }+}++#[derive(Debug, Clone)]+pub struct GpuInfo {+ pub vendor: GpuVendor,+ pub vendor_id: u32,+ pub device_id: u32,+ pub description: String,+ pub dedicated_video_memory: u64,+}++impl GpuInfo {+ pub fn vendor_name(&self) -> &'static str {+ match self.vendor {+ GpuVendor::Nvidia => "NVIDIA",+ GpuVendor::Amd => "AMD",+ GpuVendor::Intel => "Intel",+ GpuVendor::Qualcomm => "Qualcomm",+ GpuVendor::Arm => "ARM",+ GpuVendor::Microsoft => "Microsoft",+ GpuVendor::Unknown(_) => "Unknown",+ }+ }+}++struct D3D11Resources {+ #[allow(dead_code)]+ device: ID3D11Device,+ context: ID3D11DeviceContext,+ video_device: ID3D11VideoDevice,+ video_context: ID3D11VideoContext,+ processor: ID3D11VideoProcessor,+ enumerator: ID3D11VideoProcessorEnumerator,+ input_texture: ID3D11Texture2D,+ output_texture: ID3D11Texture2D,+ staging_input: ID3D11Texture2D,+ staging_output: ID3D11Texture2D,+}++pub struct D3D11Converter {+ resources: Mutex<D3D11Resources>,+ #[allow(dead_code)]+ input_format: Pixel,+ output_format: Pixel,+ #[allow(dead_code)]+ input_width: u32,+ #[allow(dead_code)]+ input_height: u32,+ output_width: u32,+ output_height: u32,+ gpu_info: GpuInfo,+ conversion_count: AtomicU64,+ verified_gpu_usage: AtomicBool,+}++fn get_gpu_info(device: &ID3D11Device) -> Result<GpuInfo, ConvertError> {+ unsafe {+ let dxgi_device: IDXGIDevice = device.cast().map_err(|e| {+ ConvertError::HardwareUnavailable(format!("Failed to get DXGI device: {:?}", e))+ })?;++ let adapter: IDXGIAdapter = dxgi_device.GetAdapter().map_err(|e| {+ ConvertError::HardwareUnavailable(format!("Failed to get adapter: {:?}", e))+ })?;++ let desc = adapter.GetDesc().map_err(|e| {+ ConvertError::HardwareUnavailable(format!("Failed to get adapter description: {:?}", e))+ })?;++ let description = String::from_utf16_lossy(+ &desc+ .Description+ .iter()+ .take_while(|&&c| c != 0)+ .copied()+ .collect::<Vec<_>>(),+ );++ Ok(GpuInfo {+ vendor: GpuVendor::from_id(desc.VendorId),+ vendor_id: desc.VendorId,+ device_id: desc.DeviceId,+ description,+ dedicated_video_memory: desc.DedicatedVideoMemory as u64,+ })+ }+}++impl D3D11Converter {+ pub fn new(config: ConversionConfig) -> Result<Self, ConvertError> {+ let input_dxgi = pixel_to_dxgi(config.input_format)?;+ let output_dxgi = pixel_to_dxgi(config.output_format)?;++ let (device, context) = unsafe {+ let mut device = None;+ let mut context = None;++ D3D11CreateDevice(+ None,+ D3D_DRIVER_TYPE_HARDWARE,+ None,+ D3D11_CREATE_DEVICE_VIDEO_SUPPORT,+ None,+ D3D11_SDK_VERSION,+ Some(&mut device),+ None,+ Some(&mut context),+ )+ .map_err(|e| {+ ConvertError::HardwareUnavailable(format!(+ "D3D11CreateDevice failed (no hardware GPU available?): {:?}",+ e+ ))+ })?;++ let device = device.ok_or_else(|| {+ ConvertError::HardwareUnavailable("D3D11 device was null".to_string())+ })?;+ let context = context.ok_or_else(|| {+ ConvertError::HardwareUnavailable("D3D11 context was null".to_string())+ })?;++ (device, context)+ };++ let gpu_info = get_gpu_info(&device)?;++ tracing::debug!(+ "D3D11 GPU detected: {} (Vendor: {}, VendorID: 0x{:04X}, DeviceID: 0x{:04X}, VRAM: {} MB)",+ gpu_info.description,+ gpu_info.vendor_name(),+ gpu_info.vendor_id,+ gpu_info.device_id,+ gpu_info.dedicated_video_memory / (1024 * 1024)+ );++ let video_device: ID3D11VideoDevice = device.cast().map_err(|e| {+ ConvertError::HardwareUnavailable(format!(+ "GPU does not support D3D11 Video API (ID3D11VideoDevice): {:?}",+ e+ ))+ })?;++ let video_context: ID3D11VideoContext = context.cast().map_err(|e| {+ ConvertError::HardwareUnavailable(format!("Failed to get ID3D11VideoContext: {:?}", e))+ })?;++ let content_desc = D3D11_VIDEO_PROCESSOR_CONTENT_DESC {+ InputFrameFormat:+ windows::Win32::Graphics::Direct3D11::D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE,+ InputFrameRate: windows::Win32::Graphics::Dxgi::Common::DXGI_RATIONAL {+ Numerator: 30,+ Denominator: 1,+ },+ InputWidth: config.input_width,+ InputHeight: config.input_height,+ OutputFrameRate: windows::Win32::Graphics::Dxgi::Common::DXGI_RATIONAL {+ Numerator: 30,+ Denominator: 1,+ },+ OutputWidth: config.output_width,+ OutputHeight: config.output_height,+ Usage: windows::Win32::Graphics::Direct3D11::D3D11_VIDEO_USAGE_PLAYBACK_NORMAL,+ };++ let enumerator = unsafe {+ video_device+ .CreateVideoProcessorEnumerator(&content_desc)+ .map_err(|e| {+ ConvertError::HardwareUnavailable(format!(+ "CreateVideoProcessorEnumerator failed (format {:?}->{:?} not supported by GPU?): {:?}",+ config.input_format, config.output_format, e+ ))+ })?+ };++ let processor = unsafe {+ video_device+ .CreateVideoProcessor(&enumerator, 0)+ .map_err(|e| {+ ConvertError::HardwareUnavailable(format!(+ "CreateVideoProcessor failed: {:?}",+ e+ ))+ })?+ };++ let input_texture = create_texture(+ &device,+ config.input_width,+ config.input_height,+ input_dxgi,+ D3D11_USAGE_DEFAULT,+ D3D11_BIND_RENDER_TARGET.0,+ 0,+ )?;++ let output_texture = create_texture(+ &device,+ config.output_width,+ config.output_height,+ output_dxgi,+ D3D11_USAGE_DEFAULT,+ D3D11_BIND_RENDER_TARGET.0,+ 0,+ )?;++ let staging_input = create_texture(+ &device,+ config.input_width,+ config.input_height,+ input_dxgi,+ D3D11_USAGE_STAGING,+ 0,+ D3D11_CPU_ACCESS_WRITE.0,+ )?;++ let staging_output = create_texture(+ &device,+ config.output_width,+ config.output_height,+ output_dxgi,+ D3D11_USAGE_STAGING,+ 0,+ D3D11_CPU_ACCESS_READ.0,+ )?;++ let resources = D3D11Resources {+ device,+ context,+ video_device,+ video_context,+ processor,+ enumerator,+ input_texture,+ output_texture,+ staging_input,+ staging_output,+ };++ tracing::debug!(+ "D3D11 converter created: {:?} {}x{} -> {:?} {}x{} on {}",+ config.input_format,+ config.input_width,+ config.input_height,+ config.output_format,+ config.output_width,+ config.output_height,+ gpu_info.description+ );++ Ok(Self {+ resources: Mutex::new(resources),+ input_format: config.input_format,+ output_format: config.output_format,+ input_width: config.input_width,+ input_height: config.input_height,+ output_width: config.output_width,+ output_height: config.output_height,+ gpu_info,+ conversion_count: AtomicU64::new(0),+ verified_gpu_usage: AtomicBool::new(false),+ })+ }++ pub fn gpu_info(&self) -> &GpuInfo {+ &self.gpu_info+ }+}++impl FrameConverter for D3D11Converter {+ fn convert(&self, input: frame::Video) -> Result<frame::Video, ConvertError> {+ let count = self.conversion_count.fetch_add(1, Ordering::Relaxed);++ if count == 0 {+ tracing::info!(+ "D3D11 converter first frame: converting on GPU {} ({})",+ self.gpu_info.description,+ self.gpu_info.vendor_name()+ );+ }++ let pts = input.pts();+ let mut resources = self.resources.lock();++ unsafe {+ let mapped = resources+ .context+ .Map(&resources.staging_input, 0, D3D11_MAP_WRITE, 0)+ .map_err(|e| {+ ConvertError::ConversionFailed(format!("Map input failed: {:?}", e))+ })?;++ copy_frame_to_mapped(&input, mapped.pData as *mut u8, mapped.RowPitch as usize);++ resources.context.Unmap(&resources.staging_input, 0);++ resources+ .context+ .CopyResource(&resources.input_texture, &resources.staging_input);++ let input_view_desc = D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC {+ FourCC: 0,+ ViewDimension: D3D11_VPIV_DIMENSION_TEXTURE2D,+ Anonymous:+ windows::Win32::Graphics::Direct3D11::D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC_0 {+ Texture2D: windows::Win32::Graphics::Direct3D11::D3D11_TEX2D_VPIV {+ MipSlice: 0,+ ArraySlice: 0,+ },+ },+ };++ let input_view: ID3D11VideoProcessorInputView = resources+ .video_device+ .CreateVideoProcessorInputView(+ &resources.input_texture,+ &resources.enumerator,+ &input_view_desc,+ )+ .map_err(|e| {+ ConvertError::ConversionFailed(format!("CreateInputView failed: {:?}", e))+ })?;++ let output_view_desc = D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC {+ ViewDimension: D3D11_VPOV_DIMENSION_TEXTURE2D,+ Anonymous:+ windows::Win32::Graphics::Direct3D11::D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC_0 {+ Texture2D: windows::Win32::Graphics::Direct3D11::D3D11_TEX2D_VPOV {+ MipSlice: 0,+ },+ },+ };++ let output_view: ID3D11VideoProcessorOutputView = resources+ .video_device+ .CreateVideoProcessorOutputView(+ &resources.output_texture,+ &resources.enumerator,+ &output_view_desc,+ )+ .map_err(|e| {+ ConvertError::ConversionFailed(format!("CreateOutputView failed: {:?}", e))+ })?;++ let stream = D3D11_VIDEO_PROCESSOR_STREAM {+ Enable: true.into(),+ OutputIndex: 0,+ InputFrameOrField: 0,+ PastFrames: 0,+ FutureFrames: 0,+ ppPastSurfaces: ptr::null_mut(),+ pInputSurface: std::mem::transmute_copy(&input_view),+ ppFutureSurfaces: ptr::null_mut(),+ ppPastSurfacesRight: ptr::null_mut(),+ pInputSurfaceRight: None,+ ppFutureSurfacesRight: ptr::null_mut(),+ };++ resources+ .video_context+ .VideoProcessorBlt(&resources.processor, &output_view, 0, &[stream])+ .map_err(|e| {+ ConvertError::ConversionFailed(format!("VideoProcessorBlt failed: {:?}", e))+ })?;++ if !self.verified_gpu_usage.swap(true, Ordering::Relaxed) {+ tracing::info!(+ "D3D11 VideoProcessorBlt succeeded - confirmed GPU hardware acceleration on {}",+ self.gpu_info.description+ );+ }++ resources+ .context+ .CopyResource(&resources.staging_output, &resources.output_texture);++ let mapped = resources+ .context+ .Map(&resources.staging_output, 0, D3D11_MAP_READ, 0)+ .map_err(|e| {+ ConvertError::ConversionFailed(format!("Map output failed: {:?}", e))+ })?;++ let mut output =+ frame::Video::new(self.output_format, self.output_width, self.output_height);+ copy_mapped_to_frame(+ mapped.pData as *const u8,+ mapped.RowPitch as usize,+ &mut output,+ );++ resources.context.Unmap(&resources.staging_output, 0);++ output.set_pts(pts);+ Ok(output)+ }+ }++ fn name(&self) -> &'static str {+ "d3d11"+ }++ fn backend(&self) -> ConverterBackend {+ ConverterBackend::D3D11+ }++ fn conversion_count(&self) -> u64 {+ self.conversion_count.load(Ordering::Relaxed)+ }++ fn verify_hardware_usage(&self) -> Option<bool> {+ Some(self.verified_gpu_usage.load(Ordering::Relaxed))+ }+}++fn pixel_to_dxgi(pixel: Pixel) -> Result<DXGI_FORMAT, ConvertError> {+ match pixel {+ Pixel::NV12 => Ok(DXGI_FORMAT_NV12),+ Pixel::YUYV422 => Ok(DXGI_FORMAT_YUY2),+ _ => Err(ConvertError::UnsupportedFormat(pixel, Pixel::NV12)),+ }+}++fn create_texture(+ device: &ID3D11Device,+ width: u32,+ height: u32,+ format: DXGI_FORMAT,+ usage: windows::Win32::Graphics::Direct3D11::D3D11_USAGE,+ bind_flags: u32,+ cpu_access: u32,+) -> Result<ID3D11Texture2D, ConvertError> {+ let desc = D3D11_TEXTURE2D_DESC {+ Width: width,+ Height: height,+ MipLevels: 1,+ ArraySize: 1,+ Format: format,+ SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC {+ Count: 1,+ Quality: 0,+ },+ Usage: usage,+ BindFlags: windows::Win32::Graphics::Direct3D11::D3D11_BIND_FLAG(bind_flags as i32),+ CPUAccessFlags: windows::Win32::Graphics::Direct3D11::D3D11_CPU_ACCESS_FLAG(+ cpu_access as i32,+ ),+ MiscFlags: windows::Win32::Graphics::Direct3D11::D3D11_RESOURCE_MISC_FLAG(0),+ };++ unsafe {+ device.CreateTexture2D(&desc, None).map_err(|e| {+ ConvertError::HardwareUnavailable(format!("CreateTexture2D failed: {:?}", e))+ })+ }+}++unsafe fn copy_frame_to_mapped(frame: &frame::Video, dst: *mut u8, dst_stride: usize) {+ let height = frame.height() as usize;+ let format = frame.format();++ match format {+ Pixel::NV12 => {+ for y in 0..height {+ ptr::copy_nonoverlapping(+ frame.data(0).as_ptr().add(y * frame.stride(0)),+ dst.add(y * dst_stride),+ frame.width() as usize,+ );+ }+ let uv_offset = height * dst_stride;+ for y in 0..height / 2 {+ ptr::copy_nonoverlapping(+ frame.data(1).as_ptr().add(y * frame.stride(1)),+ dst.add(uv_offset + y * dst_stride),+ frame.width() as usize,+ );+ }+ }+ Pixel::YUYV422 | Pixel::UYVY422 => {+ let row_bytes = frame.width() as usize * 2;+ for y in 0..height {+ ptr::copy_nonoverlapping(+ frame.data(0).as_ptr().add(y * frame.stride(0)),+ dst.add(y * dst_stride),+ row_bytes,+ );+ }+ }+ _ => {}+ }+}++unsafe fn copy_mapped_to_frame(src: *const u8, src_stride: usize, frame: &mut frame::Video) {+ let height = frame.height() as usize;+ let format = frame.format();++ match format {+ Pixel::NV12 => {+ for y in 0..height {+ ptr::copy_nonoverlapping(+ src.add(y * src_stride),+ frame.data_mut(0).as_mut_ptr().add(y * frame.stride(0)),+ frame.width() as usize,+ );+ }+ let uv_offset = height * src_stride;+ for y in 0..height / 2 {+ ptr::copy_nonoverlapping(+ src.add(uv_offset + y * src_stride),+ frame.data_mut(1).as_mut_ptr().add(y * frame.stride(1)),+ frame.width() as usize,+ );+ }+ }+ _ => {}+ }+}++unsafe impl Send for D3D11Converter {}+unsafe impl Sync for D3D11Converter {}diff --git a/crates/frame-converter/src/lib.rs b/crates/frame-converter/src/lib.rsnew file mode 100644index 000000000..ed3664692--- /dev/null+++ b/crates/frame-converter/src/lib.rs@@ -0,0 +1,253 @@+mod swscale;+pub use swscale::*;++mod pool;+pub use pool::*;++#[cfg(target_os = "macos")]+mod videotoolbox;+#[cfg(target_os = "macos")]+pub use videotoolbox::*;++#[cfg(target_os = "windows")]+mod d3d11;+#[cfg(target_os = "windows")]+pub use d3d11::*;++use std::sync::Arc;++#[derive(Debug, Clone, thiserror::Error)]+pub enum ConvertError {+ #[error("Conversion failed: {0}")]+ ConversionFailed(String),+ #[error("Unsupported format: {0:?} -> {1:?}")]+ UnsupportedFormat(ffmpeg::format::Pixel, ffmpeg::format::Pixel),+ #[error("Hardware unavailable: {0}")]+ HardwareUnavailable(String),+ #[error("Channel closed")]+ ChannelClosed,+ #[error("Pool shutdown")]+ PoolShutdown,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ConverterBackend {+ #[cfg(target_os = "macos")]+ VideoToolbox,+ #[cfg(target_os = "windows")]+ D3D11,+ Swscale,+ Passthrough,+}++impl std::fmt::Display for ConverterBackend {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ #[cfg(target_os = "macos")]+ ConverterBackend::VideoToolbox => write!(f, "VideoToolbox (hardware)"),+ #[cfg(target_os = "windows")]+ ConverterBackend::D3D11 => write!(f, "D3D11 (GPU)"),+ ConverterBackend::Swscale => write!(f, "swscale (CPU)"),+ ConverterBackend::Passthrough => write!(f, "passthrough"),+ }+ }+}++pub trait FrameConverter: Send + Sync + 'static {+ fn convert(&self, input: ffmpeg::frame::Video) -> Result<ffmpeg::frame::Video, ConvertError>;++ fn name(&self) -> &'static str;++ fn backend(&self) -> ConverterBackend;++ fn is_hardware_accelerated(&self) -> bool {+ match self.backend() {+ #[cfg(target_os = "macos")]+ ConverterBackend::VideoToolbox => true,+ #[cfg(target_os = "windows")]+ ConverterBackend::D3D11 => true,+ ConverterBackend::Swscale => false,+ ConverterBackend::Passthrough => false,+ }+ }++ fn conversion_count(&self) -> u64 {+ 0+ }++ fn verify_hardware_usage(&self) -> Option<bool> {+ None+ }+}++#[derive(Clone)]+pub struct ConversionConfig {+ pub input_format: ffmpeg::format::Pixel,+ pub input_width: u32,+ pub input_height: u32,+ pub output_format: ffmpeg::format::Pixel,+ pub output_width: u32,+ pub output_height: u32,+}++impl ConversionConfig {+ pub fn new(+ input_format: ffmpeg::format::Pixel,+ input_width: u32,+ input_height: u32,+ output_format: ffmpeg::format::Pixel,+ output_width: u32,+ output_height: u32,+ ) -> Self {+ Self {+ input_format,+ input_width,+ input_height,+ output_format,+ output_width,+ output_height,+ }+ }++ pub fn needs_conversion(&self) -> bool {+ self.input_format != self.output_format+ || self.input_width != self.output_width+ || self.input_height != self.output_height+ }++ pub fn needs_scaling(&self) -> bool {+ self.input_width != self.output_width || self.input_height != self.output_height+ }+}++pub struct ConverterSelectionResult {+ pub converter: Arc<dyn FrameConverter>,+ pub backend: ConverterBackend,+ pub fallback_reason: Option<String>,+}++impl ConverterSelectionResult {+ pub fn log_selection(&self) {+ if let Some(reason) = &self.fallback_reason {+ tracing::warn!("Using {} converter (fallback: {})", self.backend, reason);+ } else {+ tracing::info!("Using {} converter", self.backend);+ }+ }+}++pub fn create_converter(config: ConversionConfig) -> Result<Arc<dyn FrameConverter>, ConvertError> {+ let result = create_converter_with_details(config)?;+ result.log_selection();+ Ok(result.converter)+}++pub fn create_converter_with_details(+ config: ConversionConfig,+) -> Result<ConverterSelectionResult, ConvertError> {+ if !config.needs_conversion() {+ tracing::info!(+ "No conversion needed ({:?} {}x{} -> {:?} {}x{}), using passthrough",+ config.input_format,+ config.input_width,+ config.input_height,+ config.output_format,+ config.output_width,+ config.output_height+ );+ return Ok(ConverterSelectionResult {+ converter: Arc::new(PassthroughConverter),+ backend: ConverterBackend::Passthrough,+ fallback_reason: None,+ });+ }++ tracing::info!(+ "Creating converter: {:?} {}x{} -> {:?} {}x{}",+ config.input_format,+ config.input_width,+ config.input_height,+ config.output_format,+ config.output_width,+ config.output_height+ );++ let mut fallback_reasons: Vec<String> = Vec::new();++ #[cfg(target_os = "macos")]+ {+ match VideoToolboxConverter::new(config.clone()) {+ Ok(converter) => {+ tracing::info!(+ "✓ Created VideoToolbox converter - hardware accelerated pixel transfer"+ );+ return Ok(ConverterSelectionResult {+ converter: Arc::new(converter),+ backend: ConverterBackend::VideoToolbox,+ fallback_reason: None,+ });+ }+ Err(e) => {+ let reason = format!("VideoToolbox: {}", e);+ tracing::debug!("{}", reason);+ fallback_reasons.push(reason);+ }+ }+ }++ #[cfg(target_os = "windows")]+ {+ match D3D11Converter::new(config.clone()) {+ Ok(converter) => {+ let gpu_info = converter.gpu_info();+ tracing::info!(+ "✓ Created D3D11 hardware converter - GPU: {} ({})",+ gpu_info.description,+ gpu_info.vendor_name()+ );+ return Ok(ConverterSelectionResult {+ converter: Arc::new(converter),+ backend: ConverterBackend::D3D11,+ fallback_reason: None,+ });+ }+ Err(e) => {+ let reason = format!("D3D11: {}", e);+ tracing::debug!("{}", reason);+ fallback_reasons.push(reason);+ }+ }+ }++ let converter = SwscaleConverter::new(config.clone())?;++ let fallback_reason = if fallback_reasons.is_empty() {+ None+ } else {+ Some(fallback_reasons.join("; "))+ };++ tracing::info!("✓ Created swscale software converter (CPU-based, SIMD optimized)");++ Ok(ConverterSelectionResult {+ converter: Arc::new(converter),+ backend: ConverterBackend::Swscale,+ fallback_reason,+ })+}++struct PassthroughConverter;++impl FrameConverter for PassthroughConverter {+ fn convert(&self, input: ffmpeg::frame::Video) -> Result<ffmpeg::frame::Video, ConvertError> {+ Ok(input)+ }++ fn name(&self) -> &'static str {+ "passthrough"+ }++ fn backend(&self) -> ConverterBackend {+ ConverterBackend::Passthrough+ }+}diff --git a/crates/frame-converter/src/pool.rs b/crates/frame-converter/src/pool.rsnew file mode 100644index 000000000..a4ebdcb5b--- /dev/null+++ b/crates/frame-converter/src/pool.rs@@ -0,0 +1,363 @@+use crate::{ConversionConfig, ConvertError, FrameConverter, create_converter};+use ffmpeg::frame;+use std::{+ sync::{+ Arc,+ atomic::{AtomicBool, AtomicU64, Ordering},+ },+ thread::{self, JoinHandle},+ time::{Duration, Instant},+};+use tracing::{debug, info, warn};++pub struct ConvertedFrame {+ pub frame: frame::Video,+ pub sequence: u64,+ pub submit_time: Instant,+ pub conversion_duration: Duration,+}++pub struct InputFrame {+ pub frame: frame::Video,+ pub sequence: u64,+ pub submit_time: Instant,+}++pub struct ConverterPoolConfig {+ pub worker_count: usize,+ pub input_capacity: usize,+ pub output_capacity: usize,+ pub drop_strategy: DropStrategy,+}++impl Default for ConverterPoolConfig {+ fn default() -> Self {+ Self {+ worker_count: 2,+ input_capacity: 8,+ output_capacity: 8,+ drop_strategy: DropStrategy::DropOldest,+ }+ }+}++#[derive(Clone, Copy, Debug)]+pub enum DropStrategy {+ DropOldest,+ DropNewest,+}++pub struct ConverterPoolStats {+ pub frames_received: u64,+ pub frames_converted: u64,+ pub frames_dropped: u64,+ pub current_queue_depth: usize,+}++pub struct AsyncConverterPool {+ input_tx: Option<flume::Sender<InputFrame>>,+ output_rx: flume::Receiver<ConvertedFrame>,+ workers: Vec<JoinHandle<()>>,+ shutdown: Arc<AtomicBool>,+ stats: Arc<PoolStats>,+}++struct PoolStats {+ frames_received: AtomicU64,+ frames_converted: AtomicU64,+ frames_dropped: AtomicU64,+}++impl Default for PoolStats {+ fn default() -> Self {+ Self {+ frames_received: AtomicU64::new(0),+ frames_converted: AtomicU64::new(0),+ frames_dropped: AtomicU64::new(0),+ }+ }+}++impl AsyncConverterPool {+ pub fn new(converter: Arc<dyn FrameConverter>, config: ConverterPoolConfig) -> Self {+ let converter_name = converter.name().to_string();+ Self::new_with_factory(move |_| Ok(Arc::clone(&converter)), &converter_name, config)+ .expect("Factory using pre-created converter should not fail")+ }++ pub fn from_config(+ conversion_config: ConversionConfig,+ pool_config: ConverterPoolConfig,+ ) -> Result<Self, ConvertError> {+ let first_converter = create_converter(conversion_config.clone())?;+ let converter_name = first_converter.name().to_string();++ Self::new_with_factory(+ move |worker_id| {+ if worker_id == 0 {+ Ok(Arc::clone(&first_converter))+ } else {+ create_converter(conversion_config.clone())+ }+ },+ &converter_name,+ pool_config,+ )+ }++ fn new_with_factory<F>(+ factory: F,+ converter_name: &str,+ config: ConverterPoolConfig,+ ) -> Result<Self, ConvertError>+ where+ F: Fn(usize) -> Result<Arc<dyn FrameConverter>, ConvertError> + Send + Sync + 'static,+ {+ let (input_tx, input_rx) = flume::bounded(config.input_capacity);+ let (output_tx, output_rx) = flume::bounded(config.output_capacity);+ let shutdown = Arc::new(AtomicBool::new(false));+ let stats = Arc::new(PoolStats::default());++ let mut workers = Vec::with_capacity(config.worker_count);+ let factory = Arc::new(factory);++ for worker_id in 0..config.worker_count {+ let factory = Arc::clone(&factory);+ let input_rx = input_rx.clone();+ let output_tx = output_tx.clone();+ let shutdown = Arc::clone(&shutdown);+ let stats = Arc::clone(&stats);+ let drop_strategy = config.drop_strategy;++ let handle = thread::Builder::new()+ .name(format!("converter-worker-{}", worker_id))+ .spawn(move || {+ let converter = match factory(worker_id) {+ Ok(c) => c,+ Err(e) => {+ warn!("Worker {} failed to create converter: {}", worker_id, e);+ return;+ }+ };+ worker_loop(+ worker_id,+ converter,+ input_rx,+ output_tx,+ shutdown,+ stats,+ drop_strategy,+ );+ })+ .expect("Failed to spawn converter worker thread");++ workers.push(handle);+ }++ info!(+ "AsyncConverterPool started with {} workers using {} converter",+ config.worker_count, converter_name+ );++ Ok(Self {+ input_tx: Some(input_tx),+ output_rx,+ workers,+ shutdown,+ stats,+ })+ }++ pub fn submit(&self, frame: frame::Video, sequence: u64) -> Result<(), ConvertError> {+ let Some(input_tx) = &self.input_tx else {+ return Err(ConvertError::PoolShutdown);+ };++ self.stats.frames_received.fetch_add(1, Ordering::Relaxed);+ let submit_time = Instant::now();++ match input_tx.try_send(InputFrame {+ frame,+ sequence,+ submit_time,+ }) {+ Ok(()) => Ok(()),+ Err(flume::TrySendError::Full(_)) => {+ self.stats.frames_dropped.fetch_add(1, Ordering::Relaxed);+ let dropped = self.stats.frames_dropped.load(Ordering::Relaxed);+ if dropped % 30 == 0 {+ warn!(+ "Converter pool input full, dropped {} frames so far",+ dropped+ );+ }+ Ok(())+ }+ Err(flume::TrySendError::Disconnected(_)) => Err(ConvertError::PoolShutdown),+ }+ }++ pub fn try_recv(&self) -> Option<ConvertedFrame> {+ self.output_rx.try_recv().ok()+ }++ pub fn recv(&self) -> Result<ConvertedFrame, ConvertError> {+ self.output_rx+ .recv()+ .map_err(|_| ConvertError::PoolShutdown)+ }++ pub fn recv_timeout(&self, timeout: Duration) -> Option<ConvertedFrame> {+ self.output_rx.recv_timeout(timeout).ok()+ }++ pub fn output_receiver(&self) -> flume::Receiver<ConvertedFrame> {+ self.output_rx.clone()+ }++ pub fn stats(&self) -> ConverterPoolStats {+ ConverterPoolStats {+ frames_received: self.stats.frames_received.load(Ordering::Relaxed),+ frames_converted: self.stats.frames_converted.load(Ordering::Relaxed),+ frames_dropped: self.stats.frames_dropped.load(Ordering::Relaxed),+ current_queue_depth: self.input_tx.as_ref().map(|tx| tx.len()).unwrap_or(0),+ }+ }++ pub fn drain_with_timeout(+ &mut self,+ mut frame_handler: impl FnMut(ConvertedFrame),+ timeout: Duration,+ ) -> usize {+ self.input_tx.take();++ let deadline = std::time::Instant::now() + timeout;+ let mut drained = 0;++ while std::time::Instant::now() < deadline {+ match self.output_rx.recv_timeout(Duration::from_millis(50)) {+ Ok(frame) => {+ frame_handler(frame);+ drained += 1;+ }+ Err(flume::RecvTimeoutError::Timeout) => {+ let stats = self.stats();+ let pending = stats+ .frames_received+ .saturating_sub(stats.frames_converted + stats.frames_dropped);+ if pending == 0 {+ break;+ }+ }+ Err(flume::RecvTimeoutError::Disconnected) => break,+ }+ }++ self.shutdown.store(true, Ordering::SeqCst);+ for worker in self.workers.drain(..) {+ let _ = worker.join();+ }++ while let Ok(frame) = self.output_rx.try_recv() {+ frame_handler(frame);+ drained += 1;+ }++ let stats = self.stats();+ info!(+ "Converter pool drained: {} frames collected, {} received, {} converted, {} dropped",+ drained, stats.frames_received, stats.frames_converted, stats.frames_dropped+ );++ drained+ }++ fn do_shutdown(&mut self) {+ self.shutdown.store(true, Ordering::SeqCst);+ self.input_tx.take();++ for worker in self.workers.drain(..) {+ let _ = worker.join();+ }++ let stats = self.stats();+ info!(+ "Converter pool shutdown: {} received, {} converted, {} dropped",+ stats.frames_received, stats.frames_converted, stats.frames_dropped+ );+ }+}++fn worker_loop(+ worker_id: usize,+ converter: Arc<dyn FrameConverter>,+ input_rx: flume::Receiver<InputFrame>,+ output_tx: flume::Sender<ConvertedFrame>,+ shutdown: Arc<AtomicBool>,+ stats: Arc<PoolStats>,+ drop_strategy: DropStrategy,+) {+ debug!("Converter worker {} started", worker_id);+ let mut local_converted = 0u64;+ let mut local_errors = 0u64;++ while !shutdown.load(Ordering::Relaxed) {+ match input_rx.recv_timeout(Duration::from_millis(100)) {+ Ok(input) => {+ let sequence = input.sequence;+ let submit_time = input.submit_time;+ let convert_start = Instant::now();+ match converter.convert(input.frame) {+ Ok(converted) => {+ let conversion_duration = convert_start.elapsed();+ local_converted += 1;+ stats.frames_converted.fetch_add(1, Ordering::Relaxed);++ match output_tx.try_send(ConvertedFrame {+ frame: converted,+ sequence,+ submit_time,+ conversion_duration,+ }) {+ Ok(()) => {}+ Err(flume::TrySendError::Full(_frame)) => match drop_strategy {+ DropStrategy::DropOldest | DropStrategy::DropNewest => {+ stats.frames_dropped.fetch_add(1, Ordering::Relaxed);+ }+ },+ Err(flume::TrySendError::Disconnected(_)) => {+ break;+ }+ }+ }+ Err(e) => {+ local_errors += 1;+ if local_errors % 10 == 1 {+ warn!(+ "Worker {}: conversion error (#{} total): {}",+ worker_id, local_errors, e+ );+ }+ }+ }+ }+ Err(flume::RecvTimeoutError::Timeout) => {+ continue;+ }+ Err(flume::RecvTimeoutError::Disconnected) => {+ break;+ }+ }+ }++ debug!(+ "Converter worker {} finished: {} converted, {} errors",+ worker_id, local_converted, local_errors+ );+}++impl Drop for AsyncConverterPool {+ fn drop(&mut self) {+ self.do_shutdown();+ }+}diff --git a/crates/frame-converter/src/swscale.rs b/crates/frame-converter/src/swscale.rsnew file mode 100644index 000000000..eb07b0d7a--- /dev/null+++ b/crates/frame-converter/src/swscale.rs@@ -0,0 +1,65 @@+use crate::{ConversionConfig, ConvertError, ConverterBackend, FrameConverter};+use ffmpeg::{format::Pixel, frame, software::scaling};+use parking_lot::Mutex;++pub struct SwscaleConverter {+ context: Mutex<scaling::Context>,+ output_format: Pixel,+ output_width: u32,+ output_height: u32,+}++impl SwscaleConverter {+ pub fn new(config: ConversionConfig) -> Result<Self, ConvertError> {+ let flags = if config.needs_scaling() {+ scaling::flag::Flags::BICUBIC+ } else {+ scaling::flag::Flags::FAST_BILINEAR+ };++ let context = scaling::Context::get(+ config.input_format,+ config.input_width,+ config.input_height,+ config.output_format,+ config.output_width,+ config.output_height,+ flags,+ )+ .map_err(|_| ConvertError::UnsupportedFormat(config.input_format, config.output_format))?;++ Ok(Self {+ context: Mutex::new(context),+ output_format: config.output_format,+ output_width: config.output_width,+ output_height: config.output_height,+ })+ }+}++impl FrameConverter for SwscaleConverter {+ fn convert(&self, input: frame::Video) -> Result<frame::Video, ConvertError> {+ let pts = input.pts();+ let mut output =+ frame::Video::new(self.output_format, self.output_width, self.output_height);++ self.context+ .lock()+ .run(&input, &mut output)+ .map_err(|e| ConvertError::ConversionFailed(e.to_string()))?;++ output.set_pts(pts);+ Ok(output)+ }++ fn name(&self) -> &'static str {+ "swscale"+ }++ fn backend(&self) -> ConverterBackend {+ ConverterBackend::Swscale+ }+}++unsafe impl Send for SwscaleConverter {}+unsafe impl Sync for SwscaleConverter {}diff --git a/crates/frame-converter/src/videotoolbox.rs b/crates/frame-converter/src/videotoolbox.rsnew file mode 100644index 000000000..560059e0d--- /dev/null+++ b/crates/frame-converter/src/videotoolbox.rs@@ -0,0 +1,331 @@+use crate::{ConversionConfig, ConvertError, ConverterBackend, FrameConverter};+use ffmpeg::{format::Pixel, frame};+use std::{+ ffi::c_void,+ ptr,+ sync::atomic::{AtomicBool, AtomicU64, Ordering},+};++type CFAllocatorRef = *const c_void;+type CFDictionaryRef = *const c_void;+type CVPixelBufferRef = *mut c_void;+type VTPixelTransferSessionRef = *mut c_void;+type OSStatus = i32;++const K_CV_RETURN_SUCCESS: i32 = 0;++const K_CV_PIXEL_FORMAT_TYPE_422_YP_CB_YP_CR8: u32 = 0x79757679;+const K_CV_PIXEL_FORMAT_TYPE_420_YP_CB_CR8_BI_PLANAR_VIDEO_RANGE: u32 = 0x34323076;+const K_CV_PIXEL_FORMAT_TYPE_2VUY: u32 = 0x32767579;++#[link(name = "CoreFoundation", kind = "framework")]+unsafe extern "C" {+ fn CFRelease(cf: *const c_void);+}++#[link(name = "CoreVideo", kind = "framework")]+unsafe extern "C" {+ fn CVPixelBufferCreate(+ allocator: CFAllocatorRef,+ width: usize,+ height: usize,+ pixel_format_type: u32,+ pixel_buffer_attributes: CFDictionaryRef,+ pixel_buffer_out: *mut CVPixelBufferRef,+ ) -> i32;++ fn CVPixelBufferCreateWithBytes(+ allocator: CFAllocatorRef,+ width: usize,+ height: usize,+ pixel_format_type: u32,+ base_address: *mut c_void,+ bytes_per_row: usize,+ release_callback: *const c_void,+ release_ref_con: *const c_void,+ pixel_buffer_attributes: CFDictionaryRef,+ pixel_buffer_out: *mut CVPixelBufferRef,+ ) -> i32;++ fn CVPixelBufferRelease(pixel_buffer: CVPixelBufferRef);++ fn CVPixelBufferLockBaseAddress(pixel_buffer: CVPixelBufferRef, lock_flags: u64) -> i32;+ fn CVPixelBufferUnlockBaseAddress(pixel_buffer: CVPixelBufferRef, lock_flags: u64) -> i32;++ fn CVPixelBufferGetBaseAddressOfPlane(pixel_buffer: CVPixelBufferRef, plane: usize) -> *mut u8;+ fn CVPixelBufferGetBytesPerRowOfPlane(pixel_buffer: CVPixelBufferRef, plane: usize) -> usize;+ fn CVPixelBufferGetHeightOfPlane(pixel_buffer: CVPixelBufferRef, plane: usize) -> usize;+ fn CVPixelBufferGetPlaneCount(pixel_buffer: CVPixelBufferRef) -> usize;+}++#[link(name = "VideoToolbox", kind = "framework")]+unsafe extern "C" {+ fn VTPixelTransferSessionCreate(+ allocator: CFAllocatorRef,+ pixel_transfer_session_out: *mut VTPixelTransferSessionRef,+ ) -> OSStatus;++ fn VTPixelTransferSessionInvalidate(session: VTPixelTransferSessionRef);++ fn VTPixelTransferSessionTransferImage(+ session: VTPixelTransferSessionRef,+ source_buffer: CVPixelBufferRef,+ destination_buffer: CVPixelBufferRef,+ ) -> OSStatus;+}++fn pixel_to_cv_format(pixel: Pixel) -> Option<u32> {+ match pixel {+ Pixel::YUYV422 => Some(K_CV_PIXEL_FORMAT_TYPE_422_YP_CB_YP_CR8),+ Pixel::UYVY422 => Some(K_CV_PIXEL_FORMAT_TYPE_2VUY),+ Pixel::NV12 => Some(K_CV_PIXEL_FORMAT_TYPE_420_YP_CB_CR8_BI_PLANAR_VIDEO_RANGE),+ _ => None,+ }+}++pub struct VideoToolboxConverter {+ session: VTPixelTransferSessionRef,+ input_format: Pixel,+ input_cv_format: u32,+ output_format: Pixel,+ output_cv_format: u32,+ input_width: u32,+ input_height: u32,+ output_width: u32,+ output_height: u32,+ conversion_count: AtomicU64,+ verified_hardware: AtomicBool,+}++impl VideoToolboxConverter {+ pub fn new(config: ConversionConfig) -> Result<Self, ConvertError> {+ let input_cv_format = pixel_to_cv_format(config.input_format).ok_or_else(|| {+ ConvertError::UnsupportedFormat(config.input_format, config.output_format)+ })?;++ let output_cv_format = pixel_to_cv_format(config.output_format).ok_or_else(|| {+ ConvertError::UnsupportedFormat(config.input_format, config.output_format)+ })?;++ let mut session: VTPixelTransferSessionRef = ptr::null_mut();+ let status = unsafe { VTPixelTransferSessionCreate(ptr::null(), &mut session) };++ if status != 0 {+ return Err(ConvertError::HardwareUnavailable(format!(+ "VTPixelTransferSessionCreate failed with status: {}",+ status+ )));+ }++ if session.is_null() {+ return Err(ConvertError::HardwareUnavailable(+ "VTPixelTransferSessionCreate returned null session".to_string(),+ ));+ }++ tracing::debug!(+ "VideoToolbox converter initialized: {:?} {}x{} -> {:?} {}x{}",+ config.input_format,+ config.input_width,+ config.input_height,+ config.output_format,+ config.output_width,+ config.output_height+ );++ Ok(Self {+ session,+ input_format: config.input_format,+ input_cv_format,+ output_format: config.output_format,+ output_cv_format,+ input_width: config.input_width,+ input_height: config.input_height,+ output_width: config.output_width,+ output_height: config.output_height,+ conversion_count: AtomicU64::new(0),+ verified_hardware: AtomicBool::new(false),+ })+ }++ fn create_input_pixel_buffer(+ &self,+ input: &frame::Video,+ ) -> Result<CVPixelBufferRef, ConvertError> {+ let mut pixel_buffer: CVPixelBufferRef = ptr::null_mut();++ let base_address = input.data(0).as_ptr() as *mut c_void;+ let bytes_per_row = input.stride(0);++ let status = unsafe {+ CVPixelBufferCreateWithBytes(+ ptr::null(),+ self.input_width as usize,+ self.input_height as usize,+ self.input_cv_format,+ base_address,+ bytes_per_row,+ ptr::null(),+ ptr::null(),+ ptr::null(),+ &mut pixel_buffer,+ )+ };++ if status != K_CV_RETURN_SUCCESS {+ return Err(ConvertError::ConversionFailed(format!(+ "CVPixelBufferCreateWithBytes failed: {}",+ status+ )));+ }++ Ok(pixel_buffer)+ }++ fn create_output_pixel_buffer(&self) -> Result<CVPixelBufferRef, ConvertError> {+ let mut pixel_buffer: CVPixelBufferRef = ptr::null_mut();++ let status = unsafe {+ CVPixelBufferCreate(+ ptr::null(),+ self.output_width as usize,+ self.output_height as usize,+ self.output_cv_format,+ ptr::null(),+ &mut pixel_buffer,+ )+ };++ if status != K_CV_RETURN_SUCCESS {+ return Err(ConvertError::ConversionFailed(format!(+ "CVPixelBufferCreate failed: {}",+ status+ )));+ }++ Ok(pixel_buffer)+ }++ fn copy_output_to_frame(+ &self,+ pixel_buffer: CVPixelBufferRef,+ ) -> Result<frame::Video, ConvertError> {+ unsafe {+ let lock_status = CVPixelBufferLockBaseAddress(pixel_buffer, 0);+ if lock_status != K_CV_RETURN_SUCCESS {+ return Err(ConvertError::ConversionFailed(format!(+ "CVPixelBufferLockBaseAddress failed: {}",+ lock_status+ )));+ }+ }++ let mut output =+ frame::Video::new(self.output_format, self.output_width, self.output_height);++ unsafe {+ let plane_count = CVPixelBufferGetPlaneCount(pixel_buffer);++ for plane in 0..plane_count {+ let src_ptr = CVPixelBufferGetBaseAddressOfPlane(pixel_buffer, plane);+ let src_stride = CVPixelBufferGetBytesPerRowOfPlane(pixel_buffer, plane);+ let height = CVPixelBufferGetHeightOfPlane(pixel_buffer, plane);+ let dst_stride = output.stride(plane);++ let dst_data = output.data_mut(plane);+ let dst_ptr = dst_data.as_mut_ptr();++ for row in 0..height {+ let src_row = src_ptr.add(row * src_stride);+ let dst_row = dst_ptr.add(row * dst_stride);+ let copy_len = src_stride.min(dst_stride);+ ptr::copy_nonoverlapping(src_row, dst_row, copy_len);+ }+ }++ CVPixelBufferUnlockBaseAddress(pixel_buffer, 0);+ }++ Ok(output)+ }+}++impl Drop for VideoToolboxConverter {+ fn drop(&mut self) {+ if !self.session.is_null() {+ unsafe {+ VTPixelTransferSessionInvalidate(self.session);+ CFRelease(self.session as *const c_void);+ }+ }+ }+}++impl FrameConverter for VideoToolboxConverter {+ fn convert(&self, input: frame::Video) -> Result<frame::Video, ConvertError> {+ let count = self.conversion_count.fetch_add(1, Ordering::Relaxed);++ if count == 0 {+ tracing::info!(+ "VideoToolbox converter first frame: {:?} -> {:?}",+ self.input_format,+ self.output_format+ );+ }++ let input_buffer = self.create_input_pixel_buffer(&input)?;+ let output_buffer = self.create_output_pixel_buffer()?;++ let status = unsafe {+ VTPixelTransferSessionTransferImage(self.session, input_buffer, output_buffer)+ };++ unsafe {+ CVPixelBufferRelease(input_buffer);+ }++ if status != 0 {+ unsafe {+ CVPixelBufferRelease(output_buffer);+ }+ return Err(ConvertError::ConversionFailed(format!(+ "VTPixelTransferSessionTransferImage failed: {}",+ status+ )));+ }++ if !self.verified_hardware.swap(true, Ordering::Relaxed) {+ tracing::info!(+ "VideoToolbox VTPixelTransferSession succeeded - hardware acceleration confirmed"+ );+ }++ let mut result = self.copy_output_to_frame(output_buffer)?;+ result.set_pts(input.pts());++ unsafe {+ CVPixelBufferRelease(output_buffer);+ }++ Ok(result)+ }++ fn name(&self) -> &'static str {+ "videotoolbox"+ }++ fn backend(&self) -> ConverterBackend {+ ConverterBackend::VideoToolbox+ }++ fn conversion_count(&self) -> u64 {+ self.conversion_count.load(Ordering::Relaxed)+ }++ fn verify_hardware_usage(&self) -> Option<bool> {+ Some(self.verified_hardware.load(Ordering::Relaxed))+ }+}++unsafe impl Send for VideoToolboxConverter {}+unsafe impl Sync for VideoToolboxConverter {}