Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add recording and encoding benchmark examples
Richie McIlroyc973966fd5c8
diff --git a/crates/recording/examples/camera-benchmark.rs b/crates/recording/examples/camera-benchmark.rsnew file mode 100644index 000000000..05f00ff41--- /dev/null+++ b/crates/recording/examples/camera-benchmark.rs@@ -0,0 +1,415 @@+use cap_camera::CameraInfo;+use cap_recording::{+ CameraFeed,+ benchmark::{BenchmarkConfig, EncoderInfo, PipelineMetrics},+ feeds::camera::{self, DeviceOrModelID},+};+use ffmpeg::format::Pixel;+use kameo::Actor;+use std::{+ fmt::Display,+ time::{Duration, Instant},+};+use tracing::{info, warn};++struct CameraSelection(CameraInfo);++impl Display for CameraSelection {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ let model_id = self+ .0+ .model_id()+ .map(|m| m.to_string())+ .unwrap_or_else(|| "unknown".to_string());+ write!(f, "{} ({})", self.0.display_name(), model_id)+ }+}++fn print_camera_info(info: &CameraInfo) {+ println!("\nCamera: {}", info.display_name());+ println!("Model ID: {:?}", info.model_id());++ if let Some(formats) = info.formats() {+ println!("\nAvailable formats:");+ for (i, format) in formats.into_iter().take(10).enumerate() {+ println!(+ " {}. {}x{} @ {:.1} fps",+ i + 1,+ format.width(),+ format.height(),+ format.frame_rate()+ );+ }+ }+}++async fn run_camera_frame_rate_test(+ camera_info: &CameraInfo,+ duration_secs: u64,+) -> (u64, f64, Vec<Duration>) {+ let feed = CameraFeed::spawn(CameraFeed::default());++ feed.ask(camera::SetInput {+ id: DeviceOrModelID::from_info(camera_info),+ })+ .await+ .expect("Failed to send SetInput")+ .await+ .expect("SetInput failed");++ let (tx, rx) = flume::bounded(256);+ feed.ask(camera::AddSender(tx))+ .await+ .expect("Failed to add sender");++ tokio::time::sleep(Duration::from_millis(100)).await;++ let start = Instant::now();+ let deadline = start + Duration::from_secs(duration_secs);+ let mut frame_count = 0u64;+ let mut inter_frame_times = Vec::new();+ let mut last_frame_time = Instant::now();++ info!("Measuring camera frame rate for {}s...", duration_secs);++ while Instant::now() < deadline {+ match rx.recv_timeout(Duration::from_millis(100)) {+ Ok(_frame) => {+ let now = Instant::now();+ if frame_count > 0 {+ inter_frame_times.push(now.duration_since(last_frame_time));+ }+ last_frame_time = now;+ frame_count += 1;+ }+ Err(flume::RecvTimeoutError::Timeout) => continue,+ Err(flume::RecvTimeoutError::Disconnected) => break,+ }+ }++ let elapsed = start.elapsed();+ let fps = frame_count as f64 / elapsed.as_secs_f64();++ (frame_count, fps, inter_frame_times)+}++async fn run_camera_encoding_benchmark(+ camera_info: &CameraInfo,+ config: &BenchmarkConfig,+) -> cap_recording::benchmark::MetricsSnapshot {+ use cap_frame_converter::{+ AsyncConverterPool, ConversionConfig, ConverterPoolConfig, DropStrategy,+ };++ let metrics = PipelineMetrics::new();++ let feed = CameraFeed::spawn(CameraFeed::default());++ feed.ask(camera::SetInput {+ id: DeviceOrModelID::from_info(camera_info),+ })+ .await+ .expect("Failed to send SetInput")+ .await+ .expect("SetInput failed");++ let (tx, rx) = flume::bounded(256);+ feed.ask(camera::AddSender(tx))+ .await+ .expect("Failed to add sender");++ tokio::time::sleep(Duration::from_millis(500)).await;++ let first_frame = rx+ .recv_timeout(Duration::from_secs(2))+ .expect("No frame from camera");+ let input_format = first_frame.inner.format();+ let width = first_frame.inner.width();+ let height = first_frame.inner.height();++ println!(+ "\nCamera frame format: {:?} {}x{}",+ input_format, width, height+ );++ let output_format = Pixel::NV12;+ let needs_conversion = input_format != output_format;++ let pool = if needs_conversion {+ let conversion_config =+ ConversionConfig::new(input_format, width, height, output_format, width, height);++ let pool_config = ConverterPoolConfig {+ worker_count: 4,+ input_capacity: 120,+ output_capacity: 90,+ drop_strategy: DropStrategy::DropOldest,+ };++ let pool = AsyncConverterPool::from_config(conversion_config, pool_config)+ .expect("Failed to create converter pool");++ Some(pool)+ } else {+ println!("No conversion needed (passthrough)");+ None+ };++ let mut output =+ ffmpeg::format::output_as("/dev/null", "mp4").expect("Failed to create dummy output");+ let video_info = cap_media_info::VideoInfo {+ width,+ height,+ pixel_format: input_format,+ frame_rate: (30, 1).into(),+ time_base: (1, 30).into(),+ };++ let mut encoder = cap_enc_ffmpeg::h264::H264Encoder::builder(video_info)+ .with_external_conversion()+ .build(&mut output)+ .expect("Failed to create encoder");++ output.write_header().ok();++ info!("Warming up for {}s...", config.warmup_secs);+ let warmup_deadline = Instant::now() + Duration::from_secs(config.warmup_secs);+ let mut warmup_submitted = 0u64;++ while Instant::now() < warmup_deadline {+ if let Ok(frame) = rx.recv_timeout(Duration::from_millis(50)) {+ if let Some(ref pool) = pool {+ let _ = pool.submit(frame.inner, 0);+ warmup_submitted += 1;+ while let Some(converted) = pool.try_recv() {+ let _ = encoder.queue_preconverted_frame(+ converted.frame,+ Duration::ZERO,+ &mut output,+ );+ }+ } else {+ let _ = encoder.queue_frame(frame.inner, Duration::ZERO, &mut output);+ }+ }+ }++ if let Some(ref pool) = pool {+ let drain_start = Instant::now();+ loop {+ let stats = pool.stats();+ let pending =+ warmup_submitted.saturating_sub(stats.frames_converted + stats.frames_dropped);+ if pending == 0 || drain_start.elapsed() > Duration::from_secs(1) {+ break;+ }+ if let Some(converted) = pool.try_recv() {+ let _ =+ encoder.queue_preconverted_frame(converted.frame, Duration::ZERO, &mut output);+ } else {+ std::thread::sleep(Duration::from_millis(5));+ }+ }+ while pool.try_recv().is_some() {}+ }++ info!("Running benchmark for {}s...", config.duration_secs);+ metrics.start();++ let benchmark_deadline = Instant::now() + Duration::from_secs(config.duration_secs);+ let mut sequence = 1u64;++ while Instant::now() < benchmark_deadline {+ match rx.recv_timeout(Duration::from_millis(50)) {+ Ok(frame) => {+ metrics.record_frame_received();++ if let Some(ref pool) = pool {+ match pool.submit(frame.inner, sequence) {+ Ok(()) => {}+ Err(_) => {+ metrics.record_dropped_input();+ continue;+ }+ }++ while let Some(converted) = pool.try_recv() {+ if converted.sequence == 0 {+ continue;+ }++ metrics.record_frame_converted(converted.conversion_duration);++ let encode_start = Instant::now();+ let timestamp =+ Duration::from_micros(converted.frame.pts().unwrap_or(0) as u64);++ match encoder.queue_preconverted_frame(+ converted.frame,+ timestamp,+ &mut output,+ ) {+ Ok(()) => {+ let encode_duration = encode_start.elapsed();+ let pipeline_latency = converted.submit_time.elapsed();+ metrics.record_frame_encoded(encode_duration, pipeline_latency);+ }+ Err(e) => {+ warn!("Encode error: {}", e);+ metrics.record_dropped_output();+ }+ }+ }+ } else {+ let encode_start = Instant::now();+ let timestamp = Duration::from_micros(sequence * 33333);++ match encoder.queue_frame(frame.inner, timestamp, &mut output) {+ Ok(()) => {+ let encode_duration = encode_start.elapsed();+ metrics.record_frame_encoded(encode_duration, encode_duration);+ }+ Err(e) => {+ warn!("Encode error: {}", e);+ metrics.record_dropped_output();+ }+ }+ }++ sequence += 1;+ }+ Err(flume::RecvTimeoutError::Timeout) => continue,+ Err(flume::RecvTimeoutError::Disconnected) => break,+ }+ }++ if let Some(pool) = pool {+ let drain_deadline = Instant::now() + Duration::from_secs(2);+ while Instant::now() < drain_deadline {+ if let Some(converted) = pool.recv_timeout(Duration::from_millis(50)) {+ if converted.sequence == 0 {+ continue;+ }++ metrics.record_frame_converted(converted.conversion_duration);++ let encode_start = Instant::now();+ let timestamp = Duration::from_micros(converted.frame.pts().unwrap_or(0) as u64);+ match encoder.queue_preconverted_frame(converted.frame, timestamp, &mut output) {+ Ok(()) => {+ let encode_duration = encode_start.elapsed();+ let pipeline_latency = converted.submit_time.elapsed();+ metrics.record_frame_encoded(encode_duration, pipeline_latency);+ }+ Err(_) => {}+ }+ } else {+ break;+ }+ }+ }++ metrics.stop();+ let _ = encoder.flush(&mut output);+ let _ = output.write_trailer();++ metrics.snapshot()+}++#[tokio::main]+async fn main() {+ ffmpeg::init().expect("Failed to init ffmpeg");+ tracing_subscriber::fmt::init();++ println!("=== Cap Camera Encoding Benchmark ===\n");++ let encoder_info = EncoderInfo::detect();+ encoder_info.print_info();++ println!(+ "\nCPU Cores: {}",+ std::thread::available_parallelism()+ .map(|p| p.get())+ .unwrap_or(1)+ );+ println!("Platform: {}\n", std::env::consts::OS);++ let cameras: Vec<_> = cap_camera::list_cameras().map(CameraSelection).collect();++ if cameras.is_empty() {+ println!("No cameras found!");+ return;+ }++ println!("Available cameras:");+ for (i, cam) in cameras.iter().enumerate() {+ println!(" {}. {}", i + 1, cam);+ }++ let args: Vec<String> = std::env::args().collect();++ let camera_index = args+ .iter()+ .position(|a| a == "--camera")+ .and_then(|i| args.get(i + 1))+ .and_then(|s| s.parse::<usize>().ok())+ .map(|i| i.saturating_sub(1))+ .unwrap_or(0);++ let camera = cameras.get(camera_index).expect("Invalid camera index");+ print_camera_info(&camera.0);++ let config = BenchmarkConfig {+ duration_secs: args+ .iter()+ .position(|a| a == "--duration")+ .and_then(|i| args.get(i + 1))+ .and_then(|s| s.parse().ok())+ .unwrap_or(10),+ warmup_secs: 2,+ target_fps: 30,+ camera_resolution: None,+ output_json: args.contains(&"--json".to_string()),+ };++ println!("\n=== Frame Rate Test ===");+ let (frames, fps, inter_frame_times) = run_camera_frame_rate_test(&camera.0, 3).await;+ println!("Frames captured: {}", frames);+ println!("Average FPS: {:.1}", fps);++ if !inter_frame_times.is_empty() {+ let avg_interval: Duration =+ inter_frame_times.iter().sum::<Duration>() / inter_frame_times.len() as u32;+ let max_interval = inter_frame_times.iter().max().unwrap();+ let min_interval = inter_frame_times.iter().min().unwrap();++ println!("Inter-frame timing:");+ println!(" Average: {:?}", avg_interval);+ println!(" Min: {:?}", min_interval);+ println!(" Max: {:?}", max_interval);++ let mut sorted = inter_frame_times.clone();+ sorted.sort();+ let p99_idx = (sorted.len() as f64 * 0.99) as usize;+ if p99_idx < sorted.len() {+ println!(" P99: {:?}", sorted[p99_idx]);+ }++ let jitter: f64 = inter_frame_times+ .iter()+ .map(|d| (d.as_secs_f64() - avg_interval.as_secs_f64()).powi(2))+ .sum::<f64>()+ / inter_frame_times.len() as f64;+ println!(" Jitter (stddev): {:.2}ms", jitter.sqrt() * 1000.0);+ }++ println!("\n=== Full Encoding Pipeline Benchmark ===");+ let result = run_camera_encoding_benchmark(&camera.0, &config).await;++ result.print_report();++ if config.output_json {+ println!("\n--- JSON Output ---");+ println!("{}", result.to_json());+ }+}diff --git a/crates/recording/examples/encoding-benchmark.rs b/crates/recording/examples/encoding-benchmark.rsnew file mode 100644index 000000000..6b1219566--- /dev/null+++ b/crates/recording/examples/encoding-benchmark.rs@@ -0,0 +1,420 @@+use cap_frame_converter::{+ AsyncConverterPool, ConversionConfig, ConverterPoolConfig, DropStrategy,+};+use cap_recording::benchmark::{BenchmarkConfig, EncoderInfo, MetricsSnapshot, PipelineMetrics};+use ffmpeg::format::Pixel;+use std::{+ sync::{+ Arc,+ atomic::{AtomicU64, Ordering},+ },+ time::{Duration, Instant},+};+use tracing::info;++fn create_test_frame(+ format: Pixel,+ width: u32,+ height: u32,+ frame_num: u64,+) -> 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+ .wrapping_mul(17)+ .wrapping_add(plane_idx * 31)+ .wrapping_add(frame_num as usize))+ % 256) as u8;+ }+ }+ frame.set_pts(Some((frame_num * 33333) as i64));+ frame+}++struct MockEncoder {+ encode_time: Duration,+ frames_encoded: AtomicU64,+}++impl MockEncoder {+ fn new(encode_time: Duration) -> Self {+ Self {+ encode_time,+ frames_encoded: AtomicU64::new(0),+ }+ }++ fn encode(&self, _frame: ffmpeg::frame::Video) -> Duration {+ let start = Instant::now();+ std::thread::sleep(self.encode_time);+ self.frames_encoded.fetch_add(1, Ordering::Relaxed);+ start.elapsed()+ }+}++fn run_synthetic_benchmark(+ config: &BenchmarkConfig,+ input_format: Pixel,+ output_format: Pixel,+ width: u32,+ height: u32,+ simulated_encode_time: Duration,+ worker_count: usize,+) -> MetricsSnapshot {+ let metrics = PipelineMetrics::new();+ let conversion_config =+ ConversionConfig::new(input_format, width, height, output_format, width, height);++ let pool_config = ConverterPoolConfig {+ worker_count,+ input_capacity: 120,+ output_capacity: 90,+ drop_strategy: DropStrategy::DropOldest,+ };++ let pool = AsyncConverterPool::from_config(conversion_config, pool_config)+ .expect("Failed to create converter pool");++ let encoder = Arc::new(MockEncoder::new(simulated_encode_time));++ let frame_interval = Duration::from_secs_f64(1.0 / config.target_fps as f64);+ let total_frames = config.duration_secs * config.target_fps as u64;+ let warmup_frames = config.warmup_secs * config.target_fps as u64;++ info!(+ "Running synthetic benchmark: {}x{} {:?} -> {:?}",+ width, height, input_format, output_format+ );+ info!(+ "Duration: {}s, Target FPS: {}, Simulated encode time: {:?}",+ config.duration_secs, config.target_fps, simulated_encode_time+ );++ if config.warmup_secs > 0 {+ info!("Warmup: {} frames...", warmup_frames);+ for i in 0..warmup_frames {+ let frame = create_test_frame(input_format, width, height, i);+ let _ = pool.submit(frame, i);+ std::thread::sleep(frame_interval);+ while let Some(converted) = pool.try_recv() {+ let _ = encoder.encode(converted.frame);+ }+ }+ std::thread::sleep(Duration::from_millis(100));+ while pool.try_recv().is_some() {}+ }++ metrics.start();++ let start = Instant::now();+ let mut next_frame_time = start;+ let mut frame_sequence = 0u64;++ for _ 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 frame = create_test_frame(input_format, width, height, frame_sequence);+ let receive_time = Instant::now();+ metrics.record_frame_received();++ match pool.submit(frame, frame_sequence) {+ Ok(()) => {}+ Err(_) => {+ metrics.record_dropped_input();+ }+ }++ while let Some(converted) = pool.try_recv() {+ let conversion_end = Instant::now();+ let conversion_duration = conversion_end.duration_since(receive_time);+ metrics.record_frame_converted(conversion_duration);++ let encode_start = Instant::now();+ let encode_duration = encoder.encode(converted.frame);+ let pipeline_latency = encode_start.elapsed() + conversion_duration;+ metrics.record_frame_encoded(encode_duration, pipeline_latency);+ }++ frame_sequence += 1;+ }++ let drain_deadline = Instant::now() + Duration::from_secs(5);+ while Instant::now() < drain_deadline {+ if let Some(converted) = pool.recv_timeout(Duration::from_millis(100)) {+ let encode_start = Instant::now();+ let encode_duration = encoder.encode(converted.frame);+ metrics.record_frame_converted(Duration::from_millis(1));+ metrics.record_frame_encoded(encode_duration, encode_start.elapsed());+ } else {+ let stats = pool.stats();+ let pending = stats+ .frames_received+ .saturating_sub(stats.frames_converted + stats.frames_dropped);+ if pending == 0 {+ break;+ }+ }+ }++ metrics.stop();+ let pool_stats = pool.stats();++ let snapshot = metrics.snapshot();++ info!(+ "Pool stats: received={}, converted={}, dropped={}",+ pool_stats.frames_received, pool_stats.frames_converted, pool_stats.frames_dropped+ );++ snapshot+}++fn benchmark_conversion_formats(config: &BenchmarkConfig) {+ let formats = [+ (+ Pixel::UYVY422,+ Pixel::NV12,+ "UYVY422 -> NV12 (macOS camera typical)",+ ),+ (+ Pixel::YUYV422,+ Pixel::NV12,+ "YUYV422 -> NV12 (Windows camera typical)",+ ),+ (Pixel::BGRA, Pixel::NV12, "BGRA -> NV12 (screen capture)"),+ (Pixel::NV12, Pixel::NV12, "NV12 -> NV12 (passthrough)"),+ (Pixel::YUV420P, Pixel::NV12, "YUV420P -> NV12"),+ ];++ println!("\n=== Format Conversion Benchmarks ===\n");++ for (input, output, name) in formats {+ println!("Testing: {}", name);++ let mut cfg = config.clone();+ cfg.duration_secs = 5;++ let result = run_synthetic_benchmark(+ &cfg,+ input,+ output,+ 1920,+ 1080,+ Duration::from_micros(500),+ 4,+ );++ println!(+ " FPS: {:.1}, Dropped: {} ({:.2}%), Avg Conv: {:?}",+ result.effective_fps(),+ result.total_frames_dropped(),+ result.drop_rate(),+ result.avg_conversion_time().unwrap_or_default()+ );+ println!();+ }+}++fn benchmark_encode_times(config: &BenchmarkConfig) {+ let encode_times = [+ Duration::from_micros(100),+ Duration::from_micros(500),+ Duration::from_millis(1),+ Duration::from_millis(2),+ Duration::from_millis(5),+ Duration::from_millis(10),+ Duration::from_millis(16),+ Duration::from_millis(33),+ ];++ println!("\n=== Encode Time Impact Analysis ===\n");+ println!("Testing how different encode times affect frame drops at 30 FPS");+ println!("(Frame budget at 30 FPS = 33.3ms)\n");++ for encode_time in encode_times {+ let mut cfg = config.clone();+ cfg.duration_secs = 5;++ let result = run_synthetic_benchmark(+ &cfg,+ Pixel::UYVY422,+ Pixel::NV12,+ 1920,+ 1080,+ encode_time,+ 4,+ );++ let status = if result.drop_rate() < 1.0 {+ "✓"+ } else {+ "✗"+ };++ println!(+ " {:>6?} encode: FPS {:.1}, Drops {:.1}% {}",+ encode_time,+ result.effective_fps(),+ result.drop_rate(),+ status+ );+ }+}++fn benchmark_worker_counts(config: &BenchmarkConfig) {+ let worker_counts = [1, 2, 4, 6, 8];++ println!("\n=== Worker Count Optimization ===\n");+ println!("Testing conversion pool with different worker counts\n");++ for workers in worker_counts {+ let mut cfg = config.clone();+ cfg.duration_secs = 5;++ let result = run_synthetic_benchmark(+ &cfg,+ Pixel::UYVY422,+ Pixel::NV12,+ 1920,+ 1080,+ Duration::from_millis(2),+ workers,+ );++ println!(+ " {} workers: FPS {:.1}, Drops {:.1}%, Avg Conv {:?}",+ workers,+ result.effective_fps(),+ result.drop_rate(),+ result.avg_conversion_time().unwrap_or_default()+ );+ }+}++fn benchmark_resolutions(config: &BenchmarkConfig) {+ let resolutions = [+ (640, 480, "480p"),+ (1280, 720, "720p"),+ (1920, 1080, "1080p"),+ (2560, 1440, "1440p"),+ (3840, 2160, "4K"),+ ];++ println!("\n=== Resolution Impact ===\n");++ for (width, height, name) in resolutions {+ let mut cfg = config.clone();+ cfg.duration_secs = 5;++ let result = run_synthetic_benchmark(+ &cfg,+ Pixel::UYVY422,+ Pixel::NV12,+ width,+ height,+ Duration::from_millis(2),+ 4,+ );++ println!(+ " {} ({}x{}): FPS {:.1}, Drops {:.1}%, Conv {:?}",+ name,+ width,+ height,+ result.effective_fps(),+ result.drop_rate(),+ result.avg_conversion_time().unwrap_or_default()+ );+ }+}++fn run_full_benchmark(config: &BenchmarkConfig) {+ println!("\n=== Full Production Simulation ===\n");++ let encoder_info = EncoderInfo::detect();+ encoder_info.print_info();+ println!();++ let result = run_synthetic_benchmark(+ config,+ Pixel::UYVY422,+ Pixel::NV12,+ 1920,+ 1080,+ Duration::from_millis(2),+ 4,+ );++ result.print_report();++ if config.output_json {+ println!("\n--- JSON Output ---");+ println!("{}", result.to_json());+ }+}++fn main() {+ ffmpeg::init().expect("Failed to init ffmpeg");+ tracing_subscriber::fmt::init();++ println!("=== Cap Encoding Pipeline Benchmark ===\n");++ let encoder_info = EncoderInfo::detect();+ encoder_info.print_info();++ println!("\nSystem Info:");+ println!(+ " CPU Cores: {}",+ std::thread::available_parallelism()+ .map(|p| p.get())+ .unwrap_or(1)+ );+ println!(" Platform: {}", std::env::consts::OS);+ println!();++ let args: Vec<String> = std::env::args().collect();++ let config = BenchmarkConfig {+ duration_secs: args+ .iter()+ .position(|a| a == "--duration")+ .and_then(|i| args.get(i + 1))+ .and_then(|s| s.parse().ok())+ .unwrap_or(10),+ warmup_secs: 2,+ target_fps: args+ .iter()+ .position(|a| a == "--fps")+ .and_then(|i| args.get(i + 1))+ .and_then(|s| s.parse().ok())+ .unwrap_or(30),+ camera_resolution: None,+ output_json: args.contains(&"--json".to_string()),+ };++ let mode = args+ .iter()+ .position(|a| a == "--mode")+ .and_then(|i| args.get(i + 1).map(|s| s.as_str()))+ .unwrap_or("full");++ match mode {+ "formats" => benchmark_conversion_formats(&config),+ "encode" => benchmark_encode_times(&config),+ "workers" => benchmark_worker_counts(&config),+ "resolutions" => benchmark_resolutions(&config),+ "full" | _ => {+ benchmark_conversion_formats(&config);+ benchmark_encode_times(&config);+ benchmark_worker_counts(&config);+ benchmark_resolutions(&config);+ run_full_benchmark(&config);+ }+ }+}diff --git a/crates/recording/examples/recording-benchmark.rs b/crates/recording/examples/recording-benchmark.rsnew file mode 100644index 000000000..75cf11576--- /dev/null+++ b/crates/recording/examples/recording-benchmark.rs@@ -0,0 +1,290 @@+use cap_recording::{+ CameraFeed,+ benchmark::{BenchmarkConfig, EncoderInfo},+ feeds::camera::{self, DeviceOrModelID},+ screen_capture::ScreenCaptureTarget,+};+use kameo::Actor;+use scap_targets::Display;+use std::{+ sync::Arc,+ time::{Duration, Instant},+};+use tracing::info;++async fn run_recording_benchmark(+ config: &BenchmarkConfig,+ include_camera: bool,+) -> Result<(), Box<dyn std::error::Error>> {+ let encoder_info = EncoderInfo::detect();+ encoder_info.print_info();++ let dir = tempfile::tempdir()?;+ info!("Recording to: {}", dir.path().display());++ let mut builder = cap_recording::studio_recording::Actor::builder(+ dir.path().into(),+ ScreenCaptureTarget::Display {+ id: Display::primary().id(),+ },+ );++ if include_camera {+ if let Some(camera_info) = cap_camera::list_cameras().next() {+ println!("\nUsing camera: {}", camera_info.display_name());++ let feed = CameraFeed::spawn(CameraFeed::default());++ feed.ask(camera::SetInput {+ id: DeviceOrModelID::from_info(&camera_info),+ })+ .await?+ .await?;++ tokio::time::sleep(Duration::from_millis(500)).await;++ let lock = feed.ask(camera::Lock).await?;+ builder = builder.with_camera_feed(Arc::new(lock));+ } else {+ println!("\nNo camera found, running without camera");+ }+ }++ println!("\nStarting recording...");+ let start = Instant::now();++ let handle = builder+ .build(+ #[cfg(target_os = "macos")]+ cidre::sc::ShareableContent::current().await?,+ )+ .await?;++ tokio::time::sleep(Duration::from_secs(config.duration_secs)).await;++ println!("Stopping recording...");+ let stop_start = Instant::now();++ let result = handle.stop().await?;+ let stop_duration = stop_start.elapsed();+ let total_duration = start.elapsed();++ println!("\n=== Recording Benchmark Results ===\n");+ println!("Recording duration: {:.2}s", config.duration_secs);+ println!("Stop/finalize time: {:?}", stop_duration);+ println!("Total time: {:?}", total_duration);+ println!("Output path: {}", result.project_path.display());++ let content_dir = result+ .project_path+ .join("content")+ .join("segments")+ .join("segment-0");++ if let Ok(metadata) = std::fs::metadata(content_dir.join("display.mp4")) {+ let size_mb = metadata.len() as f64 / (1024.0 * 1024.0);+ let bitrate_mbps = size_mb * 8.0 / config.duration_secs as f64;+ println!("\nScreen recording:");+ println!(" Size: {:.2} MB", size_mb);+ println!(" Bitrate: {:.2} Mbps", bitrate_mbps);+ }++ if include_camera {+ if let Ok(metadata) = std::fs::metadata(content_dir.join("camera.mp4")) {+ let size_mb = metadata.len() as f64 / (1024.0 * 1024.0);+ let bitrate_mbps = size_mb * 8.0 / config.duration_secs as f64;+ println!("\nCamera recording:");+ println!(" Size: {:.2} MB", size_mb);+ println!(" Bitrate: {:.2} Mbps", bitrate_mbps);+ }+ }++ std::mem::forget(dir);++ Ok(())+}++async fn run_pause_resume_benchmark(duration_secs: u64) -> Result<(), Box<dyn std::error::Error>> {+ println!("\n=== Pause/Resume Benchmark ===\n");++ let dir = tempfile::tempdir()?;++ let handle = cap_recording::studio_recording::Actor::builder(+ dir.path().into(),+ ScreenCaptureTarget::Display {+ id: Display::primary().id(),+ },+ )+ .build(+ #[cfg(target_os = "macos")]+ cidre::sc::ShareableContent::current().await?,+ )+ .await?;++ let segment_duration = duration_secs / 4;++ println!("Recording segment 1...");+ tokio::time::sleep(Duration::from_secs(segment_duration)).await;++ println!("Pausing...");+ let pause_start = Instant::now();+ handle.pause().await?;+ println!("Pause took: {:?}", pause_start.elapsed());++ tokio::time::sleep(Duration::from_secs(1)).await;++ println!("Resuming...");+ let resume_start = Instant::now();+ handle.resume().await?;+ println!("Resume took: {:?}", resume_start.elapsed());++ println!("Recording segment 2...");+ tokio::time::sleep(Duration::from_secs(segment_duration)).await;++ println!("Stopping...");+ let stop_start = Instant::now();+ let _ = handle.stop().await?;+ println!("Stop took: {:?}", stop_start.elapsed());++ std::mem::forget(dir);++ Ok(())+}++async fn stress_test_recording(+ cycles: u32,+ cycle_duration_secs: u64,+) -> Result<(), Box<dyn std::error::Error>> {+ println!("\n=== Recording Stress Test ===\n");+ println!(+ "Running {} cycles of {}s recordings\n",+ cycles, cycle_duration_secs+ );++ let mut start_times = Vec::new();+ let mut stop_times = Vec::new();++ for i in 0..cycles {+ println!("Cycle {}/{}...", i + 1, cycles);++ let dir = tempfile::tempdir()?;++ let start = Instant::now();+ let handle = cap_recording::studio_recording::Actor::builder(+ dir.path().into(),+ ScreenCaptureTarget::Display {+ id: Display::primary().id(),+ },+ )+ .build(+ #[cfg(target_os = "macos")]+ cidre::sc::ShareableContent::current().await?,+ )+ .await?;+ start_times.push(start.elapsed());++ tokio::time::sleep(Duration::from_secs(cycle_duration_secs)).await;++ let stop_start = Instant::now();+ let _ = handle.stop().await?;+ stop_times.push(stop_start.elapsed());++ std::mem::forget(dir);+ }++ println!("\n=== Stress Test Results ===\n");++ let avg_start: Duration = start_times.iter().sum::<Duration>() / cycles;+ let max_start = start_times.iter().max().unwrap();+ let min_start = start_times.iter().min().unwrap();++ println!("Start times:");+ println!(" Average: {:?}", avg_start);+ println!(" Min: {:?}", min_start);+ println!(" Max: {:?}", max_start);++ let avg_stop: Duration = stop_times.iter().sum::<Duration>() / cycles;+ let max_stop = stop_times.iter().max().unwrap();+ let min_stop = stop_times.iter().min().unwrap();++ println!("\nStop times:");+ println!(" Average: {:?}", avg_stop);+ println!(" Min: {:?}", min_stop);+ println!(" Max: {:?}", max_stop);++ Ok(())+}++#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ unsafe { std::env::set_var("RUST_LOG", "info") };+ tracing_subscriber::fmt::init();++ println!("=== Cap Recording Benchmark ===\n");++ let args: Vec<String> = std::env::args().collect();++ let config = BenchmarkConfig {+ duration_secs: args+ .iter()+ .position(|a| a == "--duration")+ .and_then(|i| args.get(i + 1))+ .and_then(|s| s.parse().ok())+ .unwrap_or(10),+ warmup_secs: 0,+ target_fps: 30,+ camera_resolution: None,+ output_json: args.contains(&"--json".to_string()),+ };++ let mode = args+ .iter()+ .position(|a| a == "--mode")+ .and_then(|i| args.get(i + 1).map(|s| s.as_str()))+ .unwrap_or("full");++ let include_camera = args.contains(&"--camera".to_string());++ match mode {+ "screen" => {+ println!("Mode: Screen only recording");+ run_recording_benchmark(&config, false).await?;+ }+ "camera" => {+ println!("Mode: Screen + Camera recording");+ run_recording_benchmark(&config, true).await?;+ }+ "pause" => {+ println!("Mode: Pause/Resume test");+ run_pause_resume_benchmark(config.duration_secs).await?;+ }+ "stress" => {+ println!("Mode: Stress test");+ let cycles = args+ .iter()+ .position(|a| a == "--cycles")+ .and_then(|i| args.get(i + 1))+ .and_then(|s| s.parse().ok())+ .unwrap_or(5);+ stress_test_recording(cycles, config.duration_secs).await?;+ }+ "full" | _ => {+ println!("Mode: Full benchmark suite\n");++ println!("--- Screen Recording ---");+ run_recording_benchmark(&config, false).await?;++ if include_camera {+ println!("\n--- Screen + Camera Recording ---");+ run_recording_benchmark(&config, true).await?;+ }++ println!("\n--- Pause/Resume Test ---");+ run_pause_resume_benchmark(8).await?;+ }+ }++ println!("\n=== Benchmark Complete ===");++ Ok(())+}