Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add cap-test crate for unified hardware testing
Richie McIlroy21c173b43766
diff --git a/Cargo.lock b/Cargo.lockindex 083f0d18a..fceb5f817 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1647,6 +1647,40 @@ dependencies = ["workspace-hack",]+[[package]]+name = "cap-test"+version = "0.1.0"+dependencies = [+ "anyhow",+ "cap-camera",+ "cap-media-info",+ "cap-project",+ "cap-recording",+ "chrono",+ "cidre",+ "clap",+ "colored",+ "cpal 0.15.3 (git+https://github.com/CapSoftware/cpal?rev=3cc779a7b4ca)",+ "ffmpeg-next",+ "flume",+ "indicatif",+ "kameo",+ "parking_lot",+ "scap-targets",+ "serde",+ "serde_json",+ "sysinfo 0.35.2",+ "tempfile",+ "thiserror 1.0.69",+ "tokio",+ "toml 0.8.2",+ "tracing",+ "tracing-subscriber",+ "uuid",+ "windows 0.60.0",+ "workspace-hack",+]+[[package]]name = "cap-timestamp"version = "0.1.0"@@ -1972,6 +2006,15 @@ version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"+[[package]]+name = "colored"+version = "3.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"+dependencies = [+ "windows-sys 0.61.0",+]+[[package]]name = "combine"version = "4.6.7"@@ -1991,6 +2034,19 @@ dependencies = ["crossbeam-utils",]+[[package]]+name = "console"+version = "0.15.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8"+dependencies = [+ "encode_unicode",+ "libc",+ "once_cell",+ "unicode-width 0.2.1",+ "windows-sys 0.59.0",+]+[[package]]name = "const-random"version = "0.1.18"@@ -2836,6 +2892,12 @@ version = "1.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"+[[package]]+name = "encode_unicode"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"+[[package]]name = "encoding_rs"version = "0.8.35"@@ -4463,6 +4525,19 @@ dependencies = ["serde_core",]+[[package]]+name = "indicatif"+version = "0.17.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "183b3088984b400f4cfac3620d5e076c84da5364016b4f49473de574b2586235"+dependencies = [+ "console",+ "number_prefix",+ "portable-atomic",+ "unicode-width 0.2.1",+ "web-time",+]+[[package]]name = "infer"version = "0.19.0"@@ -5675,6 +5750,12 @@ dependencies = ["syn 2.0.106",]+[[package]]+name = "number_prefix"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3"+[[package]]name = "objc"version = "0.2.7"diff --git a/crates/cap-test/Cargo.toml b/crates/cap-test/Cargo.tomlnew file mode 100644index 000000000..9a834244a--- /dev/null+++ b/crates/cap-test/Cargo.toml@@ -0,0 +1,52 @@+[package]+name = "cap-test"+version = "0.1.0"+edition = "2024"+description = "Unified testing harness for Cap"++[lints]+workspace = true++[[bin]]+name = "cap-test"+path = "src/main.rs"++[dependencies]+cap-recording = { path = "../recording", features = ["test-utils"] }+cap-media-info = { path = "../media-info" }+cap-project = { path = "../project" }+scap-targets = { path = "../scap-targets" }+cap-camera = { path = "../camera" }++tokio = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+tracing = { workspace = true }+cpal = { workspace = true }+ffmpeg = { workspace = true }+anyhow = { workspace = true }+thiserror = { workspace = true }+flume = { workspace = true }++kameo = "0.17.2"+clap = { version = "4.5", features = ["derive"] }+toml = "0.8"+chrono = { version = "0.4", features = ["serde"] }+colored = "3"+indicatif = "0.17"+uuid = { version = "1", features = ["v4"] }+tracing-subscriber = { version = "0.3", features = ["env-filter"] }+sysinfo = "0.35"+parking_lot = "0.12"+workspace-hack = { version = "0.1", path = "../workspace-hack" }+tempfile = "3"++[target.'cfg(target_os = "macos")'.dependencies]+cidre = { workspace = true }++[target.'cfg(target_os = "windows")'.dependencies]+windows = { workspace = true, features = [+ "Win32_Foundation",+ "Win32_Graphics_Direct3D",+ "Win32_Graphics_Direct3D11",+] }diff --git a/crates/cap-test/configs/exhaustive.toml b/crates/cap-test/configs/exhaustive.tomlnew file mode 100644index 000000000..f512882ed--- /dev/null+++ b/crates/cap-test/configs/exhaustive.toml@@ -0,0 +1,56 @@+[meta]+name = "Exhaustive Hardware Matrix"+description = "Comprehensive tests covering all hardware combinations and edge cases"++[recording]+duration_secs = 15+warmup_secs = 3+iterations = 5++[displays]+use_discovered = true+frame_rates = [24, 30, 60, 120]+resolutions = [+ { width = 1280, height = 720, label = "720p" },+ { width = 1920, height = 1080, label = "1080p" },+ { width = 2560, height = 1440, label = "1440p" },+ { width = 3840, height = 2160, label = "4K" },+ { width = 5120, height = 2880, label = "5K" },+ { width = 2560, height = 1080, label = "UW-1080" },+ { width = 3440, height = 1440, label = "UW-1440" },+ { width = 5120, height = 1440, label = "SUW" },+ { width = 1080, height = 1920, label = "Portrait" },+ { width = 2880, height = 1800, label = "Retina" },+ { width = 3024, height = 1964, label = "MBP-14" },+ { width = 3456, height = 2234, label = "MBP-16" },+]++[cameras]+enabled = true+frame_rates = [15, 24, 30, 60]+pixel_formats = ["NV12", "YUYV422", "UYVY422", "MJPEG", "RGB24", "BGRA"]+resolutions = [+ { width = 320, height = 240, label = "QVGA" },+ { width = 640, height = 480, label = "VGA" },+ { width = 1280, height = 720, label = "720p" },+ { width = 1920, height = 1080, label = "1080p" },+ { width = 3840, height = 2160, label = "4K" },+]++[audio.microphones]+enabled = true+sample_rates = [8000, 16000, 22050, 44100, 48000, 96000]+channels = [1, 2]+include_bluetooth = true+include_usb = true+include_builtin = true++[audio.system]+enabled = true+sample_rates = [44100, 48000, 96000]++[thresholds]+max_drop_rate_percent = 1.0+min_effective_fps_ratio = 0.95+max_p95_latency_ms = 50.0+max_av_sync_drift_ms = 100.0diff --git a/crates/cap-test/configs/quick.toml b/crates/cap-test/configs/quick.tomlnew file mode 100644index 000000000..3e5b88ca4--- /dev/null+++ b/crates/cap-test/configs/quick.toml@@ -0,0 +1,41 @@+[meta]+name = "Quick Smoke Tests"+description = "Minimal tests for CI pipelines and quick verification"++[recording]+duration_secs = 5+warmup_secs = 1+iterations = 1++[displays]+use_discovered = true+frame_rates = [30]+resolutions = [+ { width = 1920, height = 1080, label = "1080p" },+]++[cameras]+enabled = true+frame_rates = [30]+pixel_formats = ["NV12"]+resolutions = [+ { width = 1280, height = 720, label = "720p" },+]++[audio.microphones]+enabled = true+sample_rates = [48000]+channels = [1]+include_bluetooth = false+include_usb = true+include_builtin = true++[audio.system]+enabled = true+sample_rates = [48000]++[thresholds]+max_drop_rate_percent = 2.0+min_effective_fps_ratio = 0.90+max_p95_latency_ms = 100.0+max_av_sync_drift_ms = 200.0diff --git a/crates/cap-test/configs/standard.toml b/crates/cap-test/configs/standard.tomlnew file mode 100644index 000000000..801b14908--- /dev/null+++ b/crates/cap-test/configs/standard.toml@@ -0,0 +1,48 @@+[meta]+name = "Standard Hardware Matrix"+description = "Tests common hardware configurations for everyday use cases"++[recording]+duration_secs = 10+warmup_secs = 2+iterations = 3++[displays]+use_discovered = true+frame_rates = [30, 60]+resolutions = [+ { width = 1920, height = 1080, label = "1080p" },+ { width = 2560, height = 1440, label = "1440p" },+ { width = 3840, height = 2160, label = "4K" },+ { width = 3024, height = 1964, label = "MBP-14" },+ { width = 3456, height = 2234, label = "MBP-16" },+]++[cameras]+enabled = true+frame_rates = [24, 30, 60]+pixel_formats = ["NV12", "YUYV422", "MJPEG"]+resolutions = [+ { width = 640, height = 480, label = "VGA" },+ { width = 1280, height = 720, label = "720p" },+ { width = 1920, height = 1080, label = "1080p" },+ { width = 3840, height = 2160, label = "4K" },+]++[audio.microphones]+enabled = true+sample_rates = [16000, 44100, 48000, 96000]+channels = [1, 2]+include_bluetooth = true+include_usb = true+include_builtin = true++[audio.system]+enabled = true+sample_rates = [44100, 48000]++[thresholds]+max_drop_rate_percent = 1.0+min_effective_fps_ratio = 0.95+max_p95_latency_ms = 50.0+max_av_sync_drift_ms = 100.0diff --git a/crates/cap-test/configs/synthetic.toml b/crates/cap-test/configs/synthetic.tomlnew file mode 100644index 000000000..5822e06c3--- /dev/null+++ b/crates/cap-test/configs/synthetic.toml@@ -0,0 +1,45 @@+[meta]+name = "Synthetic Tests"+description = "Tests using synthetic video/audio sources - no hardware required"++[recording]+duration_secs = 5+warmup_secs = 1+iterations = 3++[displays]+use_discovered = false+frame_rates = [30, 60]+resolutions = [+ { width = 1280, height = 720, label = "720p" },+ { width = 1920, height = 1080, label = "1080p" },+ { width = 2560, height = 1440, label = "1440p" },+ { width = 3840, height = 2160, label = "4K" },+]++[cameras]+enabled = true+frame_rates = [30]+pixel_formats = ["NV12"]+resolutions = [+ { width = 640, height = 480, label = "VGA" },+ { width = 1280, height = 720, label = "720p" },+]++[audio.microphones]+enabled = true+sample_rates = [44100, 48000]+channels = [1, 2]+include_bluetooth = false+include_usb = false+include_builtin = false++[audio.system]+enabled = true+sample_rates = [48000]++[thresholds]+max_drop_rate_percent = 1.0+min_effective_fps_ratio = 0.95+max_p95_latency_ms = 50.0+max_av_sync_drift_ms = 100.0diff --git a/crates/cap-test/src/config/loader.rs b/crates/cap-test/src/config/loader.rsnew file mode 100644index 000000000..1f82a0941--- /dev/null+++ b/crates/cap-test/src/config/loader.rs@@ -0,0 +1,229 @@+use anyhow::{Context, Result};+use std::path::Path;++use super::types::*;++impl TestConfig {+ pub fn load(path: &Path) -> Result<Self> {+ let content = std::fs::read_to_string(path)+ .with_context(|| format!("Failed to read config file: {}", path.display()))?;++ toml::from_str(&content)+ .with_context(|| format!("Failed to parse config file: {}", path.display()))+ }++ pub fn standard() -> Self {+ Self {+ meta: MetaConfig {+ name: "Standard Hardware Matrix".to_string(),+ description: "Tests common hardware configurations".to_string(),+ },+ recording: RecordingConfig {+ duration_secs: 10,+ warmup_secs: 2,+ iterations: 3,+ },+ displays: DisplayConfig {+ resolutions: vec![+ ResolutionPreset::new(1920, 1080, "1080p"),+ ResolutionPreset::new(2560, 1440, "1440p"),+ ResolutionPreset::new(3840, 2160, "4K"),+ ResolutionPreset::new(3024, 1964, "MBP-14"),+ ResolutionPreset::new(3456, 2234, "MBP-16"),+ ],+ frame_rates: vec![30, 60],+ use_discovered: true,+ },+ cameras: CameraConfig {+ resolutions: vec![+ ResolutionPreset::new(640, 480, "VGA"),+ ResolutionPreset::new(1280, 720, "720p"),+ ResolutionPreset::new(1920, 1080, "1080p"),+ ResolutionPreset::new(3840, 2160, "4K"),+ ],+ frame_rates: vec![24, 30, 60],+ pixel_formats: vec![+ "NV12".to_string(),+ "YUYV422".to_string(),+ "MJPEG".to_string(),+ ],+ enabled: true,+ },+ audio: AudioConfig {+ microphones: MicrophoneConfig {+ sample_rates: vec![16000, 44100, 48000, 96000],+ channels: vec![1, 2],+ include_bluetooth: true,+ include_usb: true,+ include_builtin: true,+ enabled: true,+ },+ system: SystemAudioConfig {+ enabled: true,+ sample_rates: vec![44100, 48000],+ },+ },+ thresholds: ThresholdConfig::default(),+ }+ }++ pub fn quick() -> Self {+ Self {+ meta: MetaConfig {+ name: "Quick Smoke Tests".to_string(),+ description: "Minimal tests for CI".to_string(),+ },+ recording: RecordingConfig {+ duration_secs: 5,+ warmup_secs: 1,+ iterations: 1,+ },+ displays: DisplayConfig {+ resolutions: vec![ResolutionPreset::new(1920, 1080, "1080p")],+ frame_rates: vec![30],+ use_discovered: true,+ },+ cameras: CameraConfig {+ resolutions: vec![ResolutionPreset::new(1280, 720, "720p")],+ frame_rates: vec![30],+ pixel_formats: vec!["NV12".to_string()],+ enabled: true,+ },+ audio: AudioConfig {+ microphones: MicrophoneConfig {+ sample_rates: vec![48000],+ channels: vec![1],+ include_bluetooth: false,+ include_usb: true,+ include_builtin: true,+ enabled: true,+ },+ system: SystemAudioConfig {+ enabled: true,+ sample_rates: vec![48000],+ },+ },+ thresholds: ThresholdConfig {+ max_drop_rate_percent: 2.0,+ min_effective_fps_ratio: 0.90,+ max_p95_latency_ms: 100.0,+ max_av_sync_drift_ms: 200.0,+ },+ }+ }++ pub fn exhaustive() -> Self {+ Self {+ meta: MetaConfig {+ name: "Exhaustive Hardware Matrix".to_string(),+ description: "Tests all hardware combinations".to_string(),+ },+ recording: RecordingConfig {+ duration_secs: 15,+ warmup_secs: 3,+ iterations: 5,+ },+ displays: DisplayConfig {+ resolutions: vec![+ ResolutionPreset::new(1280, 720, "720p"),+ ResolutionPreset::new(1920, 1080, "1080p"),+ ResolutionPreset::new(2560, 1440, "1440p"),+ ResolutionPreset::new(3840, 2160, "4K"),+ ResolutionPreset::new(5120, 2880, "5K"),+ ResolutionPreset::new(2560, 1080, "UW-1080"),+ ResolutionPreset::new(3440, 1440, "UW-1440"),+ ResolutionPreset::new(5120, 1440, "SUW"),+ ResolutionPreset::new(1080, 1920, "Portrait"),+ ResolutionPreset::new(2880, 1800, "Retina"),+ ResolutionPreset::new(3024, 1964, "MBP-14"),+ ResolutionPreset::new(3456, 2234, "MBP-16"),+ ],+ frame_rates: vec![24, 30, 60, 120],+ use_discovered: true,+ },+ cameras: CameraConfig {+ resolutions: vec![+ ResolutionPreset::new(320, 240, "QVGA"),+ ResolutionPreset::new(640, 480, "VGA"),+ ResolutionPreset::new(1280, 720, "720p"),+ ResolutionPreset::new(1920, 1080, "1080p"),+ ResolutionPreset::new(3840, 2160, "4K"),+ ],+ frame_rates: vec![15, 24, 30, 60],+ pixel_formats: vec![+ "NV12".to_string(),+ "YUYV422".to_string(),+ "UYVY422".to_string(),+ "MJPEG".to_string(),+ "RGB24".to_string(),+ "BGRA".to_string(),+ ],+ enabled: true,+ },+ audio: AudioConfig {+ microphones: MicrophoneConfig {+ sample_rates: vec![8000, 16000, 22050, 44100, 48000, 96000],+ channels: vec![1, 2],+ include_bluetooth: true,+ include_usb: true,+ include_builtin: true,+ enabled: true,+ },+ system: SystemAudioConfig {+ enabled: true,+ sample_rates: vec![44100, 48000, 96000],+ },+ },+ thresholds: ThresholdConfig::default(),+ }+ }++ pub fn synthetic() -> Self {+ Self {+ meta: MetaConfig {+ name: "Synthetic Tests".to_string(),+ description: "Tests using synthetic video/audio sources (no hardware required)"+ .to_string(),+ },+ recording: RecordingConfig {+ duration_secs: 5,+ warmup_secs: 1,+ iterations: 3,+ },+ displays: DisplayConfig {+ resolutions: vec![+ ResolutionPreset::new(1280, 720, "720p"),+ ResolutionPreset::new(1920, 1080, "1080p"),+ ResolutionPreset::new(2560, 1440, "1440p"),+ ResolutionPreset::new(3840, 2160, "4K"),+ ],+ frame_rates: vec![30, 60],+ use_discovered: false,+ },+ cameras: CameraConfig {+ resolutions: vec![+ ResolutionPreset::new(640, 480, "VGA"),+ ResolutionPreset::new(1280, 720, "720p"),+ ],+ frame_rates: vec![30],+ pixel_formats: vec!["NV12".to_string()],+ enabled: true,+ },+ audio: AudioConfig {+ microphones: MicrophoneConfig {+ sample_rates: vec![44100, 48000],+ channels: vec![1, 2],+ include_bluetooth: false,+ include_usb: false,+ include_builtin: false,+ enabled: true,+ },+ system: SystemAudioConfig {+ enabled: true,+ sample_rates: vec![48000],+ },+ },+ thresholds: ThresholdConfig::default(),+ }+ }+}diff --git a/crates/cap-test/src/config/mod.rs b/crates/cap-test/src/config/mod.rsnew file mode 100644index 000000000..c70845693--- /dev/null+++ b/crates/cap-test/src/config/mod.rs@@ -0,0 +1,4 @@+mod loader;+mod types;++pub use types::*;diff --git a/crates/cap-test/src/config/types.rs b/crates/cap-test/src/config/types.rsnew file mode 100644index 000000000..b41564d98--- /dev/null+++ b/crates/cap-test/src/config/types.rs@@ -0,0 +1,258 @@+use serde::{Deserialize, Serialize};+use std::time::Duration;++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TestConfig {+ pub meta: MetaConfig,+ pub recording: RecordingConfig,+ pub displays: DisplayConfig,+ pub cameras: CameraConfig,+ pub audio: AudioConfig,+ pub thresholds: ThresholdConfig,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MetaConfig {+ pub name: String,+ #[serde(default)]+ pub description: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct RecordingConfig {+ #[serde(default = "default_duration")]+ pub duration_secs: u64,+ #[serde(default = "default_warmup")]+ pub warmup_secs: u64,+ #[serde(default = "default_iterations")]+ pub iterations: u32,+}++fn default_duration() -> u64 {+ 10+}++fn default_warmup() -> u64 {+ 2+}++fn default_iterations() -> u32 {+ 3+}++impl Default for RecordingConfig {+ fn default() -> Self {+ Self {+ duration_secs: 10,+ warmup_secs: 2,+ iterations: 3,+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DisplayConfig {+ #[serde(default)]+ pub resolutions: Vec<ResolutionPreset>,+ #[serde(default = "default_frame_rates")]+ pub frame_rates: Vec<u32>,+ #[serde(default)]+ pub use_discovered: bool,+}++fn default_frame_rates() -> Vec<u32> {+ vec![30, 60]+}++impl Default for DisplayConfig {+ fn default() -> Self {+ Self {+ resolutions: vec![+ ResolutionPreset::new(1920, 1080, "1080p"),+ ResolutionPreset::new(2560, 1440, "1440p"),+ ResolutionPreset::new(3840, 2160, "4K"),+ ],+ frame_rates: vec![30, 60],+ use_discovered: true,+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ResolutionPreset {+ pub width: u32,+ pub height: u32,+ pub label: String,+}++impl ResolutionPreset {+ pub fn new(width: u32, height: u32, label: &str) -> Self {+ Self {+ width,+ height,+ label: label.to_string(),+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CameraConfig {+ #[serde(default)]+ pub resolutions: Vec<ResolutionPreset>,+ #[serde(default = "default_camera_frame_rates")]+ pub frame_rates: Vec<u32>,+ #[serde(default = "default_pixel_formats")]+ pub pixel_formats: Vec<String>,+ #[serde(default = "default_true")]+ pub enabled: bool,+}++fn default_camera_frame_rates() -> Vec<u32> {+ vec![30]+}++fn default_pixel_formats() -> Vec<String> {+ vec!["NV12".to_string(), "YUYV422".to_string()]+}++fn default_true() -> bool {+ true+}++impl Default for CameraConfig {+ fn default() -> Self {+ Self {+ resolutions: vec![+ ResolutionPreset::new(640, 480, "VGA"),+ ResolutionPreset::new(1280, 720, "720p"),+ ResolutionPreset::new(1920, 1080, "1080p"),+ ],+ frame_rates: vec![30],+ pixel_formats: vec!["NV12".to_string(), "YUYV422".to_string()],+ enabled: true,+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AudioConfig {+ pub microphones: MicrophoneConfig,+ pub system: SystemAudioConfig,+}++impl Default for AudioConfig {+ fn default() -> Self {+ Self {+ microphones: MicrophoneConfig::default(),+ system: SystemAudioConfig::default(),+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MicrophoneConfig {+ #[serde(default = "default_sample_rates")]+ pub sample_rates: Vec<u32>,+ #[serde(default = "default_channels")]+ pub channels: Vec<u16>,+ #[serde(default = "default_true")]+ pub include_bluetooth: bool,+ #[serde(default = "default_true")]+ pub include_usb: bool,+ #[serde(default = "default_true")]+ pub include_builtin: bool,+ #[serde(default = "default_true")]+ pub enabled: bool,+}++fn default_sample_rates() -> Vec<u32> {+ vec![44100, 48000]+}++fn default_channels() -> Vec<u16> {+ vec![1, 2]+}++impl Default for MicrophoneConfig {+ fn default() -> Self {+ Self {+ sample_rates: vec![44100, 48000],+ channels: vec![1, 2],+ include_bluetooth: true,+ include_usb: true,+ include_builtin: true,+ enabled: true,+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SystemAudioConfig {+ #[serde(default = "default_true")]+ pub enabled: bool,+ #[serde(default = "default_system_sample_rates")]+ pub sample_rates: Vec<u32>,+}++fn default_system_sample_rates() -> Vec<u32> {+ vec![44100, 48000]+}++impl Default for SystemAudioConfig {+ fn default() -> Self {+ Self {+ enabled: true,+ sample_rates: vec![44100, 48000],+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ThresholdConfig {+ #[serde(default = "default_max_drop_rate")]+ pub max_drop_rate_percent: f64,+ #[serde(default = "default_min_fps_ratio")]+ pub min_effective_fps_ratio: f64,+ #[serde(default = "default_max_latency")]+ pub max_p95_latency_ms: f64,+ #[serde(default = "default_max_sync_drift")]+ pub max_av_sync_drift_ms: f64,+}++fn default_max_drop_rate() -> f64 {+ 1.0+}++fn default_min_fps_ratio() -> f64 {+ 0.95+}++fn default_max_latency() -> f64 {+ 50.0+}++fn default_max_sync_drift() -> f64 {+ 100.0+}++impl Default for ThresholdConfig {+ fn default() -> Self {+ Self {+ max_drop_rate_percent: 1.0,+ min_effective_fps_ratio: 0.95,+ max_p95_latency_ms: 50.0,+ max_av_sync_drift_ms: 100.0,+ }+ }+}++#[allow(dead_code)]+impl TestConfig {+ pub fn recording_duration(&self) -> Duration {+ Duration::from_secs(self.recording.duration_secs)+ }++ pub fn warmup_duration(&self) -> Duration {+ Duration::from_secs(self.recording.warmup_secs)+ }+}diff --git a/crates/cap-test/src/discovery/audio.rs b/crates/cap-test/src/discovery/audio.rsnew file mode 100644index 000000000..a83c32666--- /dev/null+++ b/crates/cap-test/src/discovery/audio.rs@@ -0,0 +1,147 @@+use anyhow::Result;+use cpal::traits::{DeviceTrait, HostTrait};+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DiscoveredAudioInput {+ pub id: String,+ pub name: String,+ pub sample_rates: Vec<u32>,+ pub channels: u16,+ pub is_bluetooth: bool,+ pub is_usb: bool,+ pub is_builtin: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DiscoveredAudioOutput {+ pub id: String,+ pub name: String,+ pub sample_rates: Vec<u32>,+ pub channels: u16,+ pub is_default: bool,+}++pub fn discover_audio_devices() -> Result<(Vec<DiscoveredAudioInput>, Vec<DiscoveredAudioOutput>)> {+ let host = cpal::default_host();++ let mut inputs = Vec::new();+ let mut outputs = Vec::new();++ let default_input = host.default_input_device();+ let default_output = host.default_output_device();++ let _default_input_name = default_input.as_ref().and_then(|d| d.name().ok());+ let default_output_name = default_output.as_ref().and_then(|d| d.name().ok());++ if let Ok(devices) = host.input_devices() {+ for device in devices {+ if let Ok(name) = device.name() {+ let configs: Vec<_> = device+ .supported_input_configs()+ .map(|c| c.collect())+ .unwrap_or_default();++ let sample_rates = extract_sample_rates(&configs);+ let channels = configs.first().map(|c| c.channels()).unwrap_or(1);++ let is_bluetooth = is_bluetooth_device(&name);+ let is_usb = is_usb_device(&name);+ let is_builtin = is_builtin_device(&name);++ inputs.push(DiscoveredAudioInput {+ id: name.clone(),+ name: name.clone(),+ sample_rates,+ channels,+ is_bluetooth,+ is_usb,+ is_builtin,+ });+ }+ }+ }++ if let Ok(devices) = host.output_devices() {+ for device in devices {+ if let Ok(name) = device.name() {+ let configs: Vec<_> = device+ .supported_output_configs()+ .map(|c| c.collect())+ .unwrap_or_default();++ let sample_rates = extract_sample_rates(&configs);+ let channels = configs.first().map(|c| c.channels()).unwrap_or(2);++ let is_default = default_output_name+ .as_ref()+ .map(|n| n == &name)+ .unwrap_or(false);++ outputs.push(DiscoveredAudioOutput {+ id: name.clone(),+ name: name.clone(),+ sample_rates,+ channels,+ is_default,+ });+ }+ }+ }++ Ok((inputs, outputs))+}++fn extract_sample_rates(configs: &[cpal::SupportedStreamConfigRange]) -> Vec<u32> {+ let common_rates = [8000, 16000, 22050, 44100, 48000, 96000, 192000];+ let mut supported = Vec::new();++ for config in configs {+ let min = config.min_sample_rate().0;+ let max = config.max_sample_rate().0;++ for &rate in &common_rates {+ if rate >= min && rate <= max && !supported.contains(&rate) {+ supported.push(rate);+ }+ }+ }++ supported.sort_unstable();+ supported+}++fn is_bluetooth_device(name: &str) -> bool {+ let lower = name.to_lowercase();+ lower.contains("bluetooth")+ || lower.contains("airpods")+ || lower.contains("beats")+ || lower.contains("bose")+ || lower.contains("sony wh")+ || lower.contains("sony wf")+ || lower.contains("jabra")+ || lower.contains("jbl")+}++fn is_usb_device(name: &str) -> bool {+ let lower = name.to_lowercase();+ lower.contains("usb")+ || lower.contains("blue yeti")+ || lower.contains("snowball")+ || lower.contains("rode")+ || lower.contains("focusrite")+ || lower.contains("scarlett")+ || lower.contains("audio-technica")+ || lower.contains("shure")+ || lower.contains("elgato wave")+}++fn is_builtin_device(name: &str) -> bool {+ let lower = name.to_lowercase();+ lower.contains("macbook")+ || lower.contains("built-in")+ || lower.contains("builtin")+ || lower.contains("internal")+ || lower.contains("realtek")+ || lower.contains("conexant")+}diff --git a/crates/cap-test/src/discovery/cameras.rs b/crates/cap-test/src/discovery/cameras.rsnew file mode 100644index 000000000..967f6d923--- /dev/null+++ b/crates/cap-test/src/discovery/cameras.rs@@ -0,0 +1,90 @@+use anyhow::Result;+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DiscoveredCamera {+ pub id: String,+ pub name: String,+ pub formats: Vec<CameraFormat>,+ pub is_virtual: bool,+ pub is_capture_card: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CameraFormat {+ pub width: u32,+ pub height: u32,+ pub frame_rate: f32,+ pub pixel_format: Option<String>,+}++#[allow(dead_code)]+impl CameraFormat {+ pub fn resolution_label(&self) -> String {+ match (self.width, self.height) {+ (320, 240) => "QVGA".to_string(),+ (640, 480) => "VGA".to_string(),+ (1280, 720) => "720p".to_string(),+ (1920, 1080) => "1080p".to_string(),+ (3840, 2160) => "4K".to_string(),+ _ => format!("{}x{}", self.width, self.height),+ }+ }+}++pub fn discover_cameras() -> Result<Vec<DiscoveredCamera>> {+ use cap_camera::list_cameras;++ let mut result = Vec::new();++ for camera in list_cameras() {+ let id = camera.device_id().to_string();+ let name = camera.display_name().to_string();++ let is_virtual = is_virtual_camera(&name);+ let is_capture_card = is_capture_card_device(&name);++ let formats = camera+ .formats()+ .unwrap_or_default()+ .into_iter()+ .map(|f| CameraFormat {+ width: f.width(),+ height: f.height(),+ frame_rate: f.frame_rate(),+ pixel_format: None,+ })+ .collect();++ result.push(DiscoveredCamera {+ id,+ name,+ formats,+ is_virtual,+ is_capture_card,+ });+ }++ Ok(result)+}++fn is_virtual_camera(name: &str) -> bool {+ let lower = name.to_lowercase();+ lower.contains("obs")+ || lower.contains("virtual")+ || lower.contains("manycam")+ || lower.contains("xsplit")+ || lower.contains("snap")+ || lower.contains("mmhmm")+ || lower.contains("camo")+}++fn is_capture_card_device(name: &str) -> bool {+ let lower = name.to_lowercase();+ lower.contains("elgato")+ || lower.contains("avermedia")+ || lower.contains("magewell")+ || lower.contains("blackmagic")+ || lower.contains("capture")+ || lower.contains("cam link")+}diff --git a/crates/cap-test/src/discovery/displays.rs b/crates/cap-test/src/discovery/displays.rsnew file mode 100644index 000000000..dc1c94e31--- /dev/null+++ b/crates/cap-test/src/discovery/displays.rs@@ -0,0 +1,83 @@+use anyhow::Result;+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DiscoveredDisplay {+ pub id: String,+ pub name: Option<String>,+ pub physical_width: u32,+ pub physical_height: u32,+ pub logical_width: f64,+ pub logical_height: f64,+ pub refresh_rate: f64,+ pub is_primary: bool,+ pub scale_factor: f64,+}++impl DiscoveredDisplay {+ pub fn resolution_label(&self) -> String {+ let w = self.physical_width;+ let h = self.physical_height;++ match (w, h) {+ (1280, 720) => "720p".to_string(),+ (1920, 1080) => "1080p".to_string(),+ (2560, 1440) => "1440p".to_string(),+ (3840, 2160) => "4K".to_string(),+ (5120, 2880) => "5K".to_string(),+ (2560, 1080) => "UW-1080".to_string(),+ (3440, 1440) => "UW-1440".to_string(),+ (5120, 1440) => "SUW".to_string(),+ (2880, 1800) => "Retina".to_string(),+ (3024, 1964) => "MBP-14".to_string(),+ (3456, 2234) => "MBP-16".to_string(),+ _ => format!("{}x{}", w, h),+ }+ }+}++pub fn discover_displays() -> Result<Vec<DiscoveredDisplay>> {+ use scap_targets::Display;++ let displays = Display::list();+ let primary = Display::primary();+ let primary_id = primary.id().to_string();++ let mut result = Vec::new();++ for display in displays {+ let id = display.id().to_string();+ let name = display.name();+ let physical_size = display.physical_size();+ let logical_size = display.logical_size();+ let refresh_rate = display.refresh_rate();++ let (physical_width, physical_height) = physical_size+ .map(|s| (s.width() as u32, s.height() as u32))+ .unwrap_or((0, 0));++ let (logical_width, logical_height) = logical_size+ .map(|s| (s.width(), s.height()))+ .unwrap_or((0.0, 0.0));++ let scale_factor = if logical_width > 0.0 {+ physical_width as f64 / logical_width+ } else {+ 1.0+ };++ result.push(DiscoveredDisplay {+ id: id.clone(),+ name,+ physical_width,+ physical_height,+ logical_width,+ logical_height,+ refresh_rate,+ is_primary: id == primary_id,+ scale_factor,+ });+ }++ Ok(result)+}diff --git a/crates/cap-test/src/discovery/mod.rs b/crates/cap-test/src/discovery/mod.rsnew file mode 100644index 000000000..300acb772--- /dev/null+++ b/crates/cap-test/src/discovery/mod.rs@@ -0,0 +1,166 @@+mod audio;+mod cameras;+mod displays;++pub use audio::*;+pub use cameras::*;+pub use displays::*;++use anyhow::Result;+use colored::Colorize;+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DiscoveredHardware {+ pub displays: Vec<DiscoveredDisplay>,+ pub cameras: Vec<DiscoveredCamera>,+ pub audio_inputs: Vec<DiscoveredAudioInput>,+ pub audio_outputs: Vec<DiscoveredAudioOutput>,+ pub system_info: SystemInfo,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SystemInfo {+ pub platform: String,+ pub cpu: String,+ pub memory_gb: u64,+ pub gpu: Option<String>,+}++impl DiscoveredHardware {+ pub async fn discover() -> Result<Self> {+ let displays = discover_displays()?;+ let cameras = discover_cameras()?;+ let (audio_inputs, audio_outputs) = discover_audio_devices()?;+ let system_info = discover_system_info();++ Ok(Self {+ displays,+ cameras,+ audio_inputs,+ audio_outputs,+ system_info,+ })+ }++ pub fn print_summary(&self) {+ println!("\n{}", "=== Hardware Discovery ===".bold().cyan());++ println!("\n{}", "System Info:".bold());+ println!(" Platform: {}", self.system_info.platform);+ println!(" CPU: {}", self.system_info.cpu);+ println!(" Memory: {} GB", self.system_info.memory_gb);+ if let Some(gpu) = &self.system_info.gpu {+ println!(" GPU: {}", gpu);+ }++ println!("\n{} ({})", "Displays:".bold(), self.displays.len());+ for display in &self.displays {+ println!(+ " {} - {}x{} @ {:.0}Hz",+ display.name.as_deref().unwrap_or("Unknown"),+ display.physical_width,+ display.physical_height,+ display.refresh_rate+ );+ }++ println!("\n{} ({})", "Cameras:".bold(), self.cameras.len());+ for camera in &self.cameras {+ let formats_str = camera+ .formats+ .iter()+ .take(3)+ .map(|f| format!("{}x{}@{}fps", f.width, f.height, f.frame_rate))+ .collect::<Vec<_>>()+ .join(", ");+ let suffix = if camera.formats.len() > 3 {+ format!(" +{} more", camera.formats.len() - 3)+ } else {+ String::new()+ };+ println!(" {} - {}{}", camera.name, formats_str, suffix);+ }++ println!("\n{} ({})", "Audio Inputs:".bold(), self.audio_inputs.len());+ for input in &self.audio_inputs {+ let device_type = if input.is_bluetooth {+ " [Bluetooth]"+ } else if input.is_usb {+ " [USB]"+ } else {+ ""+ };+ println!(+ " {} - {}Hz, {} ch{}",+ input.name,+ input.sample_rates.first().unwrap_or(&0),+ input.channels,+ device_type+ );+ }++ println!(+ "\n{} ({})",+ "Audio Outputs:".bold(),+ self.audio_outputs.len()+ );+ for output in &self.audio_outputs {+ println!(+ " {} - {}Hz, {} ch",+ output.name,+ output.sample_rates.first().unwrap_or(&0),+ output.channels+ );+ }++ println!();+ }+}++fn discover_system_info() -> SystemInfo {+ use sysinfo::System;++ let mut sys = System::new_all();+ sys.refresh_all();++ let cpu = sys+ .cpus()+ .first()+ .map(|c| c.brand().to_string())+ .unwrap_or_else(|| "Unknown".to_string());++ let memory_gb = sys.total_memory() / 1024 / 1024 / 1024;++ let platform = if cfg!(target_os = "macos") {+ "macOS".to_string()+ } else if cfg!(target_os = "windows") {+ "Windows".to_string()+ } else {+ "Unknown".to_string()+ };++ let gpu = detect_gpu();++ SystemInfo {+ platform,+ cpu,+ memory_gb,+ gpu,+ }+}++#[cfg(target_os = "macos")]+fn detect_gpu() -> Option<String> {+ Some("Apple Silicon / Intel UHD".to_string())+}++#[cfg(target_os = "windows")]+fn detect_gpu() -> Option<String> {+ None+}++#[cfg(not(any(target_os = "macos", target_os = "windows")))]+fn detect_gpu() -> Option<String> {+ None+}diff --git a/crates/cap-test/src/lib.rs b/crates/cap-test/src/lib.rsnew file mode 100644index 000000000..55d3c14ab--- /dev/null+++ b/crates/cap-test/src/lib.rs@@ -0,0 +1,10 @@+pub mod config;+pub mod discovery;+pub mod matrix;+pub mod results;+pub mod suites;++pub use config::TestConfig;+pub use discovery::DiscoveredHardware;+pub use matrix::MatrixRunner;+pub use results::{ResultsSummary, TestResult, TestResults};diff --git a/crates/cap-test/src/main.rs b/crates/cap-test/src/main.rsnew file mode 100644index 000000000..4a06df992--- /dev/null+++ b/crates/cap-test/src/main.rs@@ -0,0 +1,281 @@+use anyhow::Result;+use clap::{Parser, Subcommand};+use std::path::PathBuf;+use tracing_subscriber::{EnvFilter, fmt, prelude::*};++mod config;+mod discovery;+mod matrix;+mod results;+mod suites;++use config::TestConfig;+use discovery::DiscoveredHardware;+use matrix::MatrixRunner;+#[allow(unused_imports)]+use results::{ResultsSummary, TestResults};++#[derive(Parser)]+#[command(name = "cap-test")]+#[command(about = "Unified testing harness for Cap", long_about = None)]+struct Cli {+ #[command(subcommand)]+ command: Commands,++ #[arg(long, global = true, default_value = "info")]+ log_level: String,+}++#[derive(Subcommand)]+enum Commands {+ Discover {+ #[arg(long)]+ json: bool,+ },++ Matrix {+ #[arg(short, long)]+ config: Option<PathBuf>,++ #[arg(long)]+ quick: bool,++ #[arg(long)]+ exhaustive: bool,++ #[arg(short, long)]+ output: Option<PathBuf>,+ },++ Suite {+ name: String,++ #[arg(short, long)]+ output: Option<PathBuf>,++ #[arg(long, default_value = "10")]+ duration: u64,+ },++ Synthetic {+ #[arg(short, long)]+ config: Option<PathBuf>,++ #[arg(short, long)]+ output: Option<PathBuf>,+ },++ Benchmark {+ #[arg(long, default_value = "30")]+ duration: u64,++ #[arg(long, default_value = "5")]+ warmup: u64,++ #[arg(short, long)]+ output: Option<PathBuf>,+ },++ Validate {+ path: PathBuf,++ #[arg(long)]+ json: bool,+ },++ Compare {+ current: PathBuf,+ baseline: PathBuf,+ },++ Report {+ results: PathBuf,+ },+}++#[tokio::main]+async fn main() -> Result<()> {+ let cli = Cli::parse();++ tracing_subscriber::registry()+ .with(fmt::layer())+ .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(&cli.log_level)))+ .init();++ match cli.command {+ Commands::Discover { json } => {+ cmd_discover(json).await?;+ }++ Commands::Matrix {+ config,+ quick,+ exhaustive,+ output,+ } => {+ cmd_matrix(config, quick, exhaustive, output).await?;+ }++ Commands::Suite {+ name,+ output,+ duration,+ } => {+ cmd_suite(&name, duration, output).await?;+ }++ Commands::Synthetic { config, output } => {+ cmd_synthetic(config, output).await?;+ }++ Commands::Benchmark {+ duration,+ warmup,+ output,+ } => {+ cmd_benchmark(duration, warmup, output).await?;+ }++ Commands::Validate { path, json } => {+ cmd_validate(path, json).await?;+ }++ Commands::Compare { current, baseline } => {+ cmd_compare(current, baseline).await?;+ }++ Commands::Report { results } => {+ cmd_report(results).await?;+ }+ }++ Ok(())+}++async fn cmd_discover(json_output: bool) -> Result<()> {+ let hardware = DiscoveredHardware::discover().await?;++ if json_output {+ println!("{}", serde_json::to_string_pretty(&hardware)?);+ } else {+ hardware.print_summary();+ }++ Ok(())+}++async fn cmd_matrix(+ config_path: Option<PathBuf>,+ quick: bool,+ exhaustive: bool,+ output: Option<PathBuf>,+) -> Result<()> {+ let config = if quick {+ TestConfig::quick()+ } else if exhaustive {+ TestConfig::exhaustive()+ } else if let Some(path) = config_path {+ TestConfig::load(&path)?+ } else {+ TestConfig::standard()+ };++ let hardware = DiscoveredHardware::discover().await?;+ let runner = MatrixRunner::new(config, hardware);+ let results = runner.run().await?;++ results.print_summary();++ if let Some(path) = output {+ results.save_json(&path)?;+ println!("\nResults saved to: {}", path.display());+ }++ Ok(())+}++async fn cmd_suite(name: &str, duration: u64, output: Option<PathBuf>) -> Result<()> {+ let hardware = DiscoveredHardware::discover().await?;++ let results = match name {+ "recording" => suites::run_recording_suite(&hardware, duration).await?,+ "encoding" => suites::run_encoding_suite(&hardware, duration).await?,+ "playback" => suites::run_playback_suite(&hardware, duration).await?,+ "sync" => suites::run_sync_suite(&hardware, duration).await?,+ _ => {+ anyhow::bail!(+ "Unknown suite: {}. Available: recording, encoding, playback, sync",+ name+ );+ }+ };++ results.print_summary();++ if let Some(path) = output {+ results.save_json(&path)?;+ }++ Ok(())+}++async fn cmd_synthetic(config_path: Option<PathBuf>, output: Option<PathBuf>) -> Result<()> {+ let config = if let Some(path) = config_path {+ TestConfig::load(&path)?+ } else {+ TestConfig::synthetic()+ };++ let runner = MatrixRunner::new_synthetic(config);+ let results = runner.run().await?;++ results.print_summary();++ if let Some(path) = output {+ results.save_json(&path)?;+ }++ Ok(())+}++async fn cmd_benchmark(duration: u64, warmup: u64, output: Option<PathBuf>) -> Result<()> {+ let hardware = DiscoveredHardware::discover().await?;+ let results = suites::run_benchmark(&hardware, duration, warmup).await?;++ results.print_summary();++ if let Some(path) = output {+ results.save_json(&path)?;+ }++ Ok(())+}++async fn cmd_validate(path: PathBuf, json_output: bool) -> Result<()> {+ let validation = suites::validate_recording(&path).await?;++ if json_output {+ println!("{}", serde_json::to_string_pretty(&validation)?);+ } else {+ validation.print_summary();+ }++ Ok(())+}++async fn cmd_compare(current: PathBuf, baseline: PathBuf) -> Result<()> {+ let current_results = TestResults::load(¤t)?;+ let baseline_results = TestResults::load(&baseline)?;++ let comparison = results::compare(¤t_results, &baseline_results);+ comparison.print_summary();++ Ok(())+}++async fn cmd_report(results_path: PathBuf) -> Result<()> {+ let results = TestResults::load(&results_path)?;+ results.print_detailed_report();++ Ok(())+}diff --git a/crates/cap-test/src/matrix/generator.rs b/crates/cap-test/src/matrix/generator.rsnew file mode 100644index 000000000..d44fa20ae--- /dev/null+++ b/crates/cap-test/src/matrix/generator.rs@@ -0,0 +1,321 @@+use crate::config::TestConfig;+use crate::discovery::DiscoveredHardware;+use crate::results::{AudioTestConfig, CameraTestConfig, DisplayTestConfig, TestCaseConfig};++#[derive(Debug, Clone)]+pub struct TestCase {+ pub id: String,+ pub name: String,+ pub config: TestCaseConfig,+ pub source: TestCaseSource,+}++#[derive(Debug, Clone)]+#[allow(dead_code)]+pub enum TestCaseSource {+ RealHardware {+ display_id: Option<String>,+ camera_id: Option<String>,+ audio_input_id: Option<String>,+ },+ Synthetic,+}++pub struct MatrixGenerator {+ config: TestConfig,+ hardware: Option<DiscoveredHardware>,+}++impl MatrixGenerator {+ pub fn new(config: TestConfig, hardware: Option<DiscoveredHardware>) -> Self {+ Self { config, hardware }+ }++ pub fn generate(&self) -> Vec<TestCase> {+ let mut cases = Vec::new();++ if let Some(hardware) = &self.hardware {+ cases.extend(self.generate_display_tests(hardware));+ cases.extend(self.generate_camera_tests(hardware));+ cases.extend(self.generate_audio_tests(hardware));+ cases.extend(self.generate_combined_tests(hardware));+ } else {+ cases.extend(self.generate_synthetic_tests());+ }++ cases+ }++ fn generate_display_tests(&self, hardware: &DiscoveredHardware) -> Vec<TestCase> {+ let mut cases = Vec::new();++ for display in &hardware.displays {+ for fps in &self.config.displays.frame_rates {+ if *fps as f64 > display.refresh_rate + 1.0 {+ continue;+ }++ let case = TestCase {+ id: format!(+ "display-{}-{}x{}-{}fps",+ display.id, display.physical_width, display.physical_height, fps+ ),+ name: format!(+ "Display {} {}x{} @{}fps",+ display.name.as_deref().unwrap_or(&display.id),+ display.physical_width,+ display.physical_height,+ fps+ ),+ config: TestCaseConfig {+ display: Some(DisplayTestConfig {+ width: display.physical_width,+ height: display.physical_height,+ fps: *fps,+ display_id: Some(display.id.clone()),+ }),+ camera: None,+ audio: None,+ duration_secs: self.config.recording.duration_secs,+ },+ source: TestCaseSource::RealHardware {+ display_id: Some(display.id.clone()),+ camera_id: None,+ audio_input_id: None,+ },+ };+ cases.push(case);+ }+ }++ cases+ }++ fn generate_camera_tests(&self, hardware: &DiscoveredHardware) -> Vec<TestCase> {+ let mut cases = Vec::new();++ if !self.config.cameras.enabled {+ return cases;+ }++ for camera in &hardware.cameras {+ for target_res in &self.config.cameras.resolutions {+ let matching_format = camera+ .formats+ .iter()+ .find(|f| f.width == target_res.width && f.height == target_res.height);++ if let Some(format) = matching_format {+ for target_fps in &self.config.cameras.frame_rates {+ if (*target_fps as f32) > format.frame_rate + 1.0 {+ continue;+ }++ let case = TestCase {+ id: format!(+ "camera-{}-{}x{}-{}fps",+ sanitize_id(&camera.name),+ format.width,+ format.height,+ target_fps+ ),+ name: format!(+ "Camera {} {}x{} @{}fps",+ camera.name, format.width, format.height, target_fps+ ),+ config: TestCaseConfig {+ display: None,+ camera: Some(CameraTestConfig {+ width: format.width,+ height: format.height,+ fps: *target_fps,+ pixel_format: format.pixel_format.clone(),+ device_id: Some(camera.id.clone()),+ }),+ audio: None,+ duration_secs: self.config.recording.duration_secs,+ },+ source: TestCaseSource::RealHardware {+ display_id: None,+ camera_id: Some(camera.id.clone()),+ audio_input_id: None,+ },+ };+ cases.push(case);+ }+ }+ }+ }++ cases+ }++ fn generate_audio_tests(&self, hardware: &DiscoveredHardware) -> Vec<TestCase> {+ let mut cases = Vec::new();++ if !self.config.audio.microphones.enabled {+ return cases;+ }++ for input in &hardware.audio_inputs {+ if input.is_bluetooth && !self.config.audio.microphones.include_bluetooth {+ continue;+ }+ if input.is_usb && !self.config.audio.microphones.include_usb {+ continue;+ }+ if input.is_builtin && !self.config.audio.microphones.include_builtin {+ continue;+ }++ for sample_rate in &self.config.audio.microphones.sample_rates {+ if !input.sample_rates.contains(sample_rate) {+ continue;+ }++ for channels in &self.config.audio.microphones.channels {+ if *channels > input.channels {+ continue;+ }++ let case = TestCase {+ id: format!(+ "audio-{}-{}hz-{}ch",+ sanitize_id(&input.name),+ sample_rate,+ channels+ ),+ name: format!("Audio {} {}Hz {}ch", input.name, sample_rate, channels),+ config: TestCaseConfig {+ display: None,+ camera: None,+ audio: Some(AudioTestConfig {+ sample_rate: *sample_rate,+ channels: *channels,+ device_id: Some(input.id.clone()),+ include_system_audio: false,+ }),+ duration_secs: self.config.recording.duration_secs,+ },+ source: TestCaseSource::RealHardware {+ display_id: None,+ camera_id: None,+ audio_input_id: Some(input.id.clone()),+ },+ };+ cases.push(case);+ }+ }+ }++ cases+ }++ fn generate_combined_tests(&self, hardware: &DiscoveredHardware) -> Vec<TestCase> {+ let mut cases = Vec::new();++ let primary_display = hardware.displays.iter().find(|d| d.is_primary);+ let first_camera = hardware.cameras.first();+ let first_audio = hardware.audio_inputs.first();++ if let Some(display) = primary_display {+ for fps in &self.config.displays.frame_rates {+ if *fps as f64 > display.refresh_rate + 1.0 {+ continue;+ }++ if let Some(camera) = first_camera {+ let camera_format = camera.formats.first();++ let case = TestCase {+ id: format!(+ "combined-display-camera-{}x{}-{}fps",+ display.physical_width, display.physical_height, fps+ ),+ name: format!(+ "Display+Camera {}x{} @{}fps",+ display.physical_width, display.physical_height, fps+ ),+ config: TestCaseConfig {+ display: Some(DisplayTestConfig {+ width: display.physical_width,+ height: display.physical_height,+ fps: *fps,+ display_id: Some(display.id.clone()),+ }),+ camera: camera_format.map(|f| CameraTestConfig {+ width: f.width,+ height: f.height,+ fps: f.frame_rate.min(*fps as f32) as u32,+ pixel_format: f.pixel_format.clone(),+ device_id: Some(camera.id.clone()),+ }),+ audio: first_audio.map(|a| AudioTestConfig {+ sample_rate: *a.sample_rates.first().unwrap_or(&48000),+ channels: a.channels.min(2),+ device_id: Some(a.id.clone()),+ include_system_audio: self.config.audio.system.enabled,+ }),+ duration_secs: self.config.recording.duration_secs,+ },+ source: TestCaseSource::RealHardware {+ display_id: Some(display.id.clone()),+ camera_id: Some(camera.id.clone()),+ audio_input_id: first_audio.map(|a| a.id.clone()),+ },+ };+ cases.push(case);+ }+ }+ }++ cases+ }++ fn generate_synthetic_tests(&self) -> Vec<TestCase> {+ let mut cases = Vec::new();++ for res in &self.config.displays.resolutions {+ for fps in &self.config.displays.frame_rates {+ let case = TestCase {+ id: format!("synthetic-{}x{}-{}fps", res.width, res.height, fps),+ name: format!(+ "Synthetic {} {}x{} @{}fps",+ res.label, res.width, res.height, fps+ ),+ config: TestCaseConfig {+ display: Some(DisplayTestConfig {+ width: res.width,+ height: res.height,+ fps: *fps,+ display_id: None,+ }),+ camera: None,+ audio: Some(AudioTestConfig {+ sample_rate: 48000,+ channels: 2,+ device_id: None,+ include_system_audio: false,+ }),+ duration_secs: self.config.recording.duration_secs,+ },+ source: TestCaseSource::Synthetic,+ };+ cases.push(case);+ }+ }++ cases+ }+}++fn sanitize_id(s: &str) -> String {+ s.to_lowercase()+ .chars()+ .map(|c| if c.is_alphanumeric() { c } else { '-' })+ .collect::<String>()+ .split('-')+ .filter(|s| !s.is_empty())+ .collect::<Vec<_>>()+ .join("-")+}diff --git a/crates/cap-test/src/matrix/mod.rs b/crates/cap-test/src/matrix/mod.rsnew file mode 100644index 000000000..94efd84cd--- /dev/null+++ b/crates/cap-test/src/matrix/mod.rs@@ -0,0 +1,6 @@+mod generator;+mod runner;++#[allow(unused_imports)]+pub use generator::*;+pub use runner::*;diff --git a/crates/cap-test/src/matrix/runner.rs b/crates/cap-test/src/matrix/runner.rsnew file mode 100644index 000000000..f1fff5be7--- /dev/null+++ b/crates/cap-test/src/matrix/runner.rs@@ -0,0 +1,300 @@+use anyhow::Result;+use chrono::Utc;+use colored::Colorize;+use indicatif::{ProgressBar, ProgressStyle};+use std::time::{Duration, Instant};+use tracing::error;++use crate::config::TestConfig;+use crate::discovery::{DiscoveredHardware, SystemInfo};+use crate::results::{+ FrameMetrics, IterationResult, LatencyMetrics, ResultsMeta, ResultsSummary, TestResult,+ TestResults,+};+use crate::suites::RecordingTestRunner;++use super::generator::{MatrixGenerator, TestCase, TestCaseSource};++pub struct MatrixRunner {+ config: TestConfig,+ hardware: Option<DiscoveredHardware>,+ test_cases: Vec<TestCase>,+}++impl MatrixRunner {+ pub fn new(config: TestConfig, hardware: DiscoveredHardware) -> Self {+ let generator = MatrixGenerator::new(config.clone(), Some(hardware.clone()));+ let test_cases = generator.generate();++ Self {+ config,+ hardware: Some(hardware),+ test_cases,+ }+ }++ pub fn new_synthetic(config: TestConfig) -> Self {+ let generator = MatrixGenerator::new(config.clone(), None);+ let test_cases = generator.generate();++ Self {+ config,+ hardware: None,+ test_cases,+ }+ }++ pub async fn run(&self) -> Result<TestResults> {+ let start_time = Instant::now();++ println!(+ "\n{} {}",+ "Running test matrix:".bold().cyan(),+ self.config.meta.name+ );+ println!(+ " {} test cases, {} iterations each",+ self.test_cases.len(),+ self.config.recording.iterations+ );+ println!();++ let progress = ProgressBar::new(self.test_cases.len() as u64);+ progress.set_style(+ ProgressStyle::default_bar()+ .template("{spinner:.green} [{bar:40.cyan/blue}] {pos}/{len} {msg}")+ .unwrap()+ .progress_chars("=>-"),+ );++ let mut results = Vec::new();++ for test_case in &self.test_cases {+ progress.set_message(format!("{}", test_case.name));++ let result = self.run_test_case(test_case).await;+ results.push(result);++ progress.inc(1);+ }++ progress.finish_with_message("Complete");++ let total_duration = start_time.elapsed();+ let summary = ResultsSummary::from_results(&results, total_duration);++ let system_info = self+ .hardware+ .as_ref()+ .map(|h| h.system_info.clone())+ .unwrap_or_else(|| SystemInfo {+ platform: std::env::consts::OS.to_string(),+ cpu: "Unknown".to_string(),+ memory_gb: 0,+ gpu: None,+ });++ Ok(TestResults {+ meta: ResultsMeta {+ timestamp: Utc::now(),+ config_name: self.config.meta.name.clone(),+ config_path: None,+ platform: system_info.platform.clone(),+ system: system_info,+ cap_version: option_env!("CARGO_PKG_VERSION").map(String::from),+ },+ hardware: self.hardware.clone(),+ results,+ summary,+ })+ }++ async fn run_test_case(&self, test_case: &TestCase) -> TestResult {+ let mut result = TestResult::new(+ test_case.id.clone(),+ test_case.name.clone(),+ test_case.config.clone(),+ );++ match &test_case.source {+ TestCaseSource::RealHardware {+ display_id: _,+ camera_id: _,+ audio_input_id: _,+ } => {+ for iteration in 0..self.config.recording.iterations {+ match self.run_real_hardware_test(test_case, iteration).await {+ Ok(iteration_result) => {+ if !self.check_thresholds(&iteration_result) {+ result.set_failed("Performance below thresholds");+ }+ result.add_iteration(iteration_result);+ }+ Err(e) => {+ error!(+ "Test {} iteration {} failed: {}",+ test_case.id, iteration, e+ );+ result.set_error(&e.to_string());+ break;+ }+ }+ }+ }+ TestCaseSource::Synthetic => {+ for iteration in 0..self.config.recording.iterations {+ match self.run_synthetic_test(test_case, iteration).await {+ Ok(iteration_result) => {+ if !self.check_thresholds(&iteration_result) {+ result.set_failed("Performance below thresholds");+ }+ result.add_iteration(iteration_result);+ }+ Err(e) => {+ error!(+ "Synthetic test {} iteration {} failed: {}",+ test_case.id, iteration, e+ );+ result.set_error(&e.to_string());+ break;+ }+ }+ }+ }+ }++ result+ }++ async fn run_real_hardware_test(+ &self,+ test_case: &TestCase,+ iteration: u32,+ ) -> Result<IterationResult> {+ let runner =+ RecordingTestRunner::new(test_case.config.clone(), self.config.recording.warmup_secs);++ let metrics = runner.run_recording_test().await?;++ Ok(self.metrics_to_iteration_result(iteration, &metrics, test_case))+ }++ async fn run_synthetic_test(+ &self,+ test_case: &TestCase,+ iteration: u32,+ ) -> Result<IterationResult> {+ let runner = RecordingTestRunner::new_synthetic(+ test_case.config.clone(),+ self.config.recording.warmup_secs,+ );++ let metrics = runner.run_synthetic_test().await?;++ Ok(self.metrics_to_iteration_result(iteration, &metrics, test_case))+ }++ fn metrics_to_iteration_result(+ &self,+ iteration: u32,+ metrics: &RecordingMetrics,+ test_case: &TestCase,+ ) -> IterationResult {+ let target_fps = test_case+ .config+ .display+ .as_ref()+ .map(|d| d.fps)+ .or_else(|| test_case.config.camera.as_ref().map(|c| c.fps))+ .unwrap_or(30);++ IterationResult {+ iteration,+ duration_secs: metrics.duration.as_secs_f64(),+ frames: FrameMetrics {+ received: metrics.frames_received,+ encoded: metrics.frames_encoded,+ dropped: metrics.frames_dropped,+ drop_rate_percent: metrics.drop_rate_percent(),+ effective_fps: metrics.effective_fps(),+ target_fps,+ },+ latency_ms: LatencyMetrics {+ avg: metrics.latency_avg_ms,+ min: metrics.latency_min_ms,+ p50: metrics.latency_p50_ms,+ p95: metrics.latency_p95_ms,+ p99: metrics.latency_p99_ms,+ max: metrics.latency_max_ms,+ },+ encoding_ms: metrics.encoding_avg_ms.map(|avg| LatencyMetrics {+ avg,+ min: metrics.encoding_min_ms.unwrap_or(0.0),+ p50: metrics.encoding_p50_ms.unwrap_or(avg),+ p95: metrics.encoding_p95_ms.unwrap_or(avg),+ p99: metrics.encoding_p99_ms.unwrap_or(avg),+ max: metrics.encoding_max_ms.unwrap_or(avg),+ }),+ av_sync_ms: None,+ errors: metrics.errors.clone(),+ }+ }++ fn check_thresholds(&self, result: &IterationResult) -> bool {+ let thresholds = &self.config.thresholds;++ if result.frames.drop_rate_percent > thresholds.max_drop_rate_percent {+ return false;+ }++ let fps_ratio = result.frames.effective_fps / result.frames.target_fps as f64;+ if fps_ratio < thresholds.min_effective_fps_ratio {+ return false;+ }++ if result.latency_ms.p95 > thresholds.max_p95_latency_ms {+ return false;+ }++ true+ }+}++#[derive(Debug, Clone, Default)]+pub struct RecordingMetrics {+ pub duration: Duration,+ pub frames_received: u64,+ pub frames_encoded: u64,+ pub frames_dropped: u64,+ pub latency_avg_ms: f64,+ pub latency_min_ms: f64,+ pub latency_p50_ms: f64,+ pub latency_p95_ms: f64,+ pub latency_p99_ms: f64,+ pub latency_max_ms: f64,+ pub encoding_avg_ms: Option<f64>,+ pub encoding_min_ms: Option<f64>,+ pub encoding_p50_ms: Option<f64>,+ pub encoding_p95_ms: Option<f64>,+ pub encoding_p99_ms: Option<f64>,+ pub encoding_max_ms: Option<f64>,+ pub errors: Vec<String>,+}++impl RecordingMetrics {+ pub fn drop_rate_percent(&self) -> f64 {+ if self.frames_received == 0 {+ 0.0+ } else {+ self.frames_dropped as f64 / self.frames_received as f64 * 100.0+ }+ }++ pub fn effective_fps(&self) -> f64 {+ if self.duration.as_secs_f64() > 0.0 {+ self.frames_encoded as f64 / self.duration.as_secs_f64()+ } else {+ 0.0+ }+ }+}diff --git a/crates/cap-test/src/results/json.rs b/crates/cap-test/src/results/json.rsnew file mode 100644index 000000000..b763fdf3a--- /dev/null+++ b/crates/cap-test/src/results/json.rs@@ -0,0 +1,29 @@+use anyhow::{Context, Result};+use std::path::Path;++use super::types::TestResults;++#[allow(dead_code)]+impl TestResults {+ pub fn save_json(&self, path: &Path) -> Result<()> {+ let json =+ serde_json::to_string_pretty(self).context("Failed to serialize results to JSON")?;++ std::fs::write(path, json)+ .with_context(|| format!("Failed to write results to {}", path.display()))?;++ Ok(())+ }++ pub fn load(path: &Path) -> Result<Self> {+ let content = std::fs::read_to_string(path)+ .with_context(|| format!("Failed to read results from {}", path.display()))?;++ serde_json::from_str(&content)+ .with_context(|| format!("Failed to parse results from {}", path.display()))+ }++ pub fn to_json(&self) -> Result<String> {+ serde_json::to_string_pretty(self).context("Failed to serialize results")+ }+}diff --git a/crates/cap-test/src/results/mod.rs b/crates/cap-test/src/results/mod.rsnew file mode 100644index 000000000..0749170d4--- /dev/null+++ b/crates/cap-test/src/results/mod.rs@@ -0,0 +1,5 @@+mod json;+mod summary;+mod types;++pub use types::*;diff --git a/crates/cap-test/src/results/summary.rs b/crates/cap-test/src/results/summary.rsnew file mode 100644index 000000000..5566809ac--- /dev/null+++ b/crates/cap-test/src/results/summary.rs@@ -0,0 +1,144 @@+use colored::Colorize;++use super::types::{TestResults, TestStatus};++impl TestResults {+ pub fn print_summary(&self) {+ println!("\n{}", "=== Test Results Summary ===".bold().cyan());++ println!("\n{}", "Configuration:".bold());+ println!(" Name: {}", self.meta.config_name);+ println!(" Platform: {}", self.meta.platform);+ println!(" Timestamp: {}", self.meta.timestamp);++ println!("\n{}", "Results:".bold());+ let passed_str = format!("{} passed", self.summary.passed).green();+ let failed_str = if self.summary.failed > 0 {+ format!("{} failed", self.summary.failed).red()+ } else {+ format!("{} failed", self.summary.failed).normal()+ };+ let skipped_str = if self.summary.skipped > 0 {+ format!("{} skipped", self.summary.skipped).yellow()+ } else {+ format!("{} skipped", self.summary.skipped).normal()+ };+ let errors_str = if self.summary.errors > 0 {+ format!("{} errors", self.summary.errors).red().bold()+ } else {+ format!("{} errors", self.summary.errors).normal()+ };++ println!(+ " {} | {} | {} | {} | {} total",+ passed_str, failed_str, skipped_str, errors_str, self.summary.total_tests+ );++ let pass_rate_color = if self.summary.pass_rate >= 95.0 {+ self.summary.pass_rate.to_string().green()+ } else if self.summary.pass_rate >= 80.0 {+ self.summary.pass_rate.to_string().yellow()+ } else {+ self.summary.pass_rate.to_string().red()+ };+ println!(" Pass Rate: {}%", pass_rate_color);+ println!(" Duration: {:.1}s", self.summary.duration_secs);++ let failed_tests: Vec<_> = self+ .results+ .iter()+ .filter(|r| r.status == TestStatus::Fail || r.status == TestStatus::Error)+ .collect();++ if !failed_tests.is_empty() {+ println!("\n{}", "Failed Tests:".red().bold());+ for test in failed_tests {+ let status_icon = match test.status {+ TestStatus::Fail => "✗".red(),+ TestStatus::Error => "!".red().bold(),+ _ => "?".normal(),+ };+ println!(" {} {}", status_icon, test.name);+ if let Some(reason) = &test.failure_reason {+ println!(" Reason: {}", reason.dimmed());+ }+ }+ }++ println!();+ }++ pub fn print_detailed_report(&self) {+ self.print_summary();++ println!("{}", "=== Detailed Results ===".bold().cyan());++ for test in &self.results {+ let status_str = match test.status {+ TestStatus::Pass => "PASS".green().bold(),+ TestStatus::Fail => "FAIL".red().bold(),+ TestStatus::Skip => "SKIP".yellow().bold(),+ TestStatus::Error => "ERROR".red().bold(),+ };++ println!("\n{} - {}", test.name.bold(), status_str);++ if let Some(display) = &test.config.display {+ println!(+ " Display: {}x{} @ {}fps",+ display.width, display.height, display.fps+ );+ }+ if let Some(camera) = &test.config.camera {+ println!(+ " Camera: {}x{} @ {}fps",+ camera.width, camera.height, camera.fps+ );+ }+ if let Some(audio) = &test.config.audio {+ println!(" Audio: {}Hz, {} ch", audio.sample_rate, audio.channels);+ }++ if !test.iterations.is_empty() {+ let avg_fps = test.avg_effective_fps();+ let avg_drop = test.avg_drop_rate();+ let avg_latency = test.avg_p95_latency();++ println!(" Performance ({} iterations):", test.iterations.len());+ println!(" Effective FPS: {:.1}", avg_fps);+ println!(" Drop Rate: {:.2}%", avg_drop);+ println!(" P95 Latency: {:.1}ms", avg_latency);++ let target_fps = test+ .iterations+ .first()+ .map(|i| i.frames.target_fps)+ .unwrap_or(30);+ let fps_ratio = avg_fps / target_fps as f64;++ let fps_status = if fps_ratio >= 0.95 {+ "OK".green()+ } else if fps_ratio >= 0.85 {+ "WARN".yellow()+ } else {+ "LOW".red()+ };+ println!(+ " FPS Status: {} ({:.1}% of target)",+ fps_status,+ fps_ratio * 100.0+ );+ }++ if let Some(reason) = &test.failure_reason {+ println!(" {}: {}", "Failure".red(), reason);+ }++ for note in &test.notes {+ println!(" Note: {}", note.dimmed());+ }+ }++ println!();+ }+}diff --git a/crates/cap-test/src/results/types.rs b/crates/cap-test/src/results/types.rsnew file mode 100644index 000000000..ffd10f580--- /dev/null+++ b/crates/cap-test/src/results/types.rs@@ -0,0 +1,487 @@+use chrono::{DateTime, Utc};+use serde::{Deserialize, Serialize};+use std::time::Duration;++use crate::discovery::{DiscoveredHardware, SystemInfo};++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TestResults {+ pub meta: ResultsMeta,+ pub hardware: Option<DiscoveredHardware>,+ pub results: Vec<TestResult>,+ pub summary: ResultsSummary,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ResultsMeta {+ pub timestamp: DateTime<Utc>,+ pub config_name: String,+ pub config_path: Option<String>,+ pub platform: String,+ pub system: SystemInfo,+ pub cap_version: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TestResult {+ pub test_id: String,+ pub name: String,+ pub config: TestCaseConfig,+ pub iterations: Vec<IterationResult>,+ pub status: TestStatus,+ pub failure_reason: Option<String>,+ pub notes: Vec<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TestCaseConfig {+ pub display: Option<DisplayTestConfig>,+ pub camera: Option<CameraTestConfig>,+ pub audio: Option<AudioTestConfig>,+ pub duration_secs: u64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DisplayTestConfig {+ pub width: u32,+ pub height: u32,+ pub fps: u32,+ pub display_id: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CameraTestConfig {+ pub width: u32,+ pub height: u32,+ pub fps: u32,+ pub pixel_format: Option<String>,+ pub device_id: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AudioTestConfig {+ pub sample_rate: u32,+ pub channels: u16,+ pub device_id: Option<String>,+ pub include_system_audio: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct IterationResult {+ pub iteration: u32,+ pub duration_secs: f64,+ pub frames: FrameMetrics,+ pub latency_ms: LatencyMetrics,+ pub encoding_ms: Option<LatencyMetrics>,+ pub av_sync_ms: Option<SyncMetrics>,+ pub errors: Vec<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct FrameMetrics {+ pub received: u64,+ pub encoded: u64,+ pub dropped: u64,+ pub drop_rate_percent: f64,+ pub effective_fps: f64,+ pub target_fps: u32,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct LatencyMetrics {+ pub avg: f64,+ pub min: f64,+ pub p50: f64,+ pub p95: f64,+ pub p99: f64,+ pub max: f64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SyncMetrics {+ pub offset_ms: f64,+ pub drift_ms: f64,+ pub max_drift_ms: f64,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum TestStatus {+ Pass,+ Fail,+ Skip,+ Error,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ResultsSummary {+ pub total_tests: u32,+ pub passed: u32,+ pub failed: u32,+ pub skipped: u32,+ pub errors: u32,+ pub duration_secs: f64,+ pub pass_rate: f64,+}++impl TestResult {+ pub fn new(test_id: String, name: String, config: TestCaseConfig) -> Self {+ Self {+ test_id,+ name,+ config,+ iterations: Vec::new(),+ status: TestStatus::Pass,+ failure_reason: None,+ notes: Vec::new(),+ }+ }++ pub fn add_iteration(&mut self, result: IterationResult) {+ self.iterations.push(result);+ }++ pub fn set_failed(&mut self, reason: &str) {+ self.status = TestStatus::Fail;+ self.failure_reason = Some(reason.to_string());+ }++ pub fn set_error(&mut self, reason: &str) {+ self.status = TestStatus::Error;+ self.failure_reason = Some(reason.to_string());+ }++ pub fn set_skipped(&mut self, reason: &str) {+ self.status = TestStatus::Skip;+ self.failure_reason = Some(reason.to_string());+ }++ pub fn avg_effective_fps(&self) -> f64 {+ if self.iterations.is_empty() {+ return 0.0;+ }+ let sum: f64 = self.iterations.iter().map(|i| i.frames.effective_fps).sum();+ sum / self.iterations.len() as f64+ }++ pub fn avg_drop_rate(&self) -> f64 {+ if self.iterations.is_empty() {+ return 0.0;+ }+ let sum: f64 = self+ .iterations+ .iter()+ .map(|i| i.frames.drop_rate_percent)+ .sum();+ sum / self.iterations.len() as f64+ }++ pub fn avg_p95_latency(&self) -> f64 {+ if self.iterations.is_empty() {+ return 0.0;+ }+ let sum: f64 = self.iterations.iter().map(|i| i.latency_ms.p95).sum();+ sum / self.iterations.len() as f64+ }+}++impl ResultsSummary {+ pub fn from_results(results: &[TestResult], total_duration: Duration) -> Self {+ let total = results.len() as u32;+ let passed = results+ .iter()+ .filter(|r| r.status == TestStatus::Pass)+ .count() as u32;+ let failed = results+ .iter()+ .filter(|r| r.status == TestStatus::Fail)+ .count() as u32;+ let skipped = results+ .iter()+ .filter(|r| r.status == TestStatus::Skip)+ .count() as u32;+ let errors = results+ .iter()+ .filter(|r| r.status == TestStatus::Error)+ .count() as u32;++ let pass_rate = if total > 0 {+ passed as f64 / total as f64 * 100.0+ } else {+ 0.0+ };++ Self {+ total_tests: total,+ passed,+ failed,+ skipped,+ errors,+ duration_secs: total_duration.as_secs_f64(),+ pass_rate,+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ValidationResult {+ pub path: String,+ pub valid: bool,+ pub video_info: Option<VideoValidation>,+ pub audio_info: Option<AudioValidation>,+ pub sync_info: Option<SyncValidation>,+ pub errors: Vec<String>,+ pub warnings: Vec<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct VideoValidation {+ pub width: u32,+ pub height: u32,+ pub fps: f64,+ pub duration_secs: f64,+ pub frame_count: u64,+ pub codec: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AudioValidation {+ pub sample_rate: u32,+ pub channels: u16,+ pub duration_secs: f64,+ pub codec: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SyncValidation {+ pub video_duration_secs: f64,+ pub audio_duration_secs: f64,+ pub drift_ms: f64,+ pub in_sync: bool,+}++impl ValidationResult {+ pub fn print_summary(&self) {+ use colored::Colorize;++ println!("\n{}", "=== Recording Validation ===".bold().cyan());+ println!("Path: {}", self.path);++ let status = if self.valid {+ "VALID".green().bold()+ } else {+ "INVALID".red().bold()+ };+ println!("Status: {}", status);++ if let Some(video) = &self.video_info {+ println!("\n{}", "Video:".bold());+ println!(" Resolution: {}x{}", video.width, video.height);+ println!(" FPS: {:.2}", video.fps);+ println!(" Duration: {:.2}s", video.duration_secs);+ println!(" Frames: {}", video.frame_count);+ println!(" Codec: {}", video.codec);+ }++ if let Some(audio) = &self.audio_info {+ println!("\n{}", "Audio:".bold());+ println!(" Sample Rate: {}Hz", audio.sample_rate);+ println!(" Channels: {}", audio.channels);+ println!(" Duration: {:.2}s", audio.duration_secs);+ println!(" Codec: {}", audio.codec);+ }++ if let Some(sync) = &self.sync_info {+ println!("\n{}", "A/V Sync:".bold());+ println!(" Video Duration: {:.3}s", sync.video_duration_secs);+ println!(" Audio Duration: {:.3}s", sync.audio_duration_secs);+ println!(" Drift: {:.1}ms", sync.drift_ms);+ let sync_status = if sync.in_sync {+ "IN SYNC".green()+ } else {+ "OUT OF SYNC".red()+ };+ println!(" Status: {}", sync_status);+ }++ if !self.errors.is_empty() {+ println!("\n{}", "Errors:".red().bold());+ for error in &self.errors {+ println!(" - {}", error);+ }+ }++ if !self.warnings.is_empty() {+ println!("\n{}", "Warnings:".yellow().bold());+ for warning in &self.warnings {+ println!(" - {}", warning);+ }+ }++ println!();+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ComparisonResult {+ pub current_summary: ResultsSummary,+ pub baseline_summary: ResultsSummary,+ pub regressions: Vec<Regression>,+ pub improvements: Vec<Improvement>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Regression {+ pub test_id: String,+ pub metric: String,+ pub baseline_value: f64,+ pub current_value: f64,+ pub change_percent: f64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Improvement {+ pub test_id: String,+ pub metric: String,+ pub baseline_value: f64,+ pub current_value: f64,+ pub change_percent: f64,+}++impl ComparisonResult {+ pub fn print_summary(&self) {+ use colored::Colorize;++ println!("\n{}", "=== Results Comparison ===".bold().cyan());++ println!("\n{}", "Summary:".bold());+ println!(+ " Baseline: {} tests, {:.1}% pass rate",+ self.baseline_summary.total_tests, self.baseline_summary.pass_rate+ );+ println!(+ " Current: {} tests, {:.1}% pass rate",+ self.current_summary.total_tests, self.current_summary.pass_rate+ );++ let pass_rate_diff = self.current_summary.pass_rate - self.baseline_summary.pass_rate;+ let diff_str = if pass_rate_diff >= 0.0 {+ format!("+{:.1}%", pass_rate_diff).green()+ } else {+ format!("{:.1}%", pass_rate_diff).red()+ };+ println!(" Change: {}", diff_str);++ if !self.regressions.is_empty() {+ println!(+ "\n{} ({})",+ "Regressions:".red().bold(),+ self.regressions.len()+ );+ for reg in &self.regressions {+ println!(+ " {} [{}]: {:.2} -> {:.2} ({:+.1}%)",+ reg.test_id,+ reg.metric,+ reg.baseline_value,+ reg.current_value,+ reg.change_percent+ );+ }+ }++ if !self.improvements.is_empty() {+ println!(+ "\n{} ({})",+ "Improvements:".green().bold(),+ self.improvements.len()+ );+ for imp in &self.improvements {+ println!(+ " {} [{}]: {:.2} -> {:.2} ({:+.1}%)",+ imp.test_id,+ imp.metric,+ imp.baseline_value,+ imp.current_value,+ imp.change_percent+ );+ }+ }++ println!();+ }+}++pub fn compare(current: &TestResults, baseline: &TestResults) -> ComparisonResult {+ let mut regressions = Vec::new();+ let mut improvements = Vec::new();++ for current_test in ¤t.results {+ if let Some(baseline_test) = baseline+ .results+ .iter()+ .find(|t| t.test_id == current_test.test_id)+ {+ let current_fps = current_test.avg_effective_fps();+ let baseline_fps = baseline_test.avg_effective_fps();++ if baseline_fps > 0.0 {+ let fps_change = (current_fps - baseline_fps) / baseline_fps * 100.0;++ if fps_change < -5.0 {+ regressions.push(Regression {+ test_id: current_test.test_id.clone(),+ metric: "effective_fps".to_string(),+ baseline_value: baseline_fps,+ current_value: current_fps,+ change_percent: fps_change,+ });+ } else if fps_change > 5.0 {+ improvements.push(Improvement {+ test_id: current_test.test_id.clone(),+ metric: "effective_fps".to_string(),+ baseline_value: baseline_fps,+ current_value: current_fps,+ change_percent: fps_change,+ });+ }+ }++ let current_drop = current_test.avg_drop_rate();+ let baseline_drop = baseline_test.avg_drop_rate();++ if current_drop > baseline_drop + 0.5 {+ regressions.push(Regression {+ test_id: current_test.test_id.clone(),+ metric: "drop_rate".to_string(),+ baseline_value: baseline_drop,+ current_value: current_drop,+ change_percent: if baseline_drop > 0.0 {+ (current_drop - baseline_drop) / baseline_drop * 100.0+ } else {+ 100.0+ },+ });+ } else if current_drop < baseline_drop - 0.5 {+ improvements.push(Improvement {+ test_id: current_test.test_id.clone(),+ metric: "drop_rate".to_string(),+ baseline_value: baseline_drop,+ current_value: current_drop,+ change_percent: if baseline_drop > 0.0 {+ (current_drop - baseline_drop) / baseline_drop * 100.0+ } else {+ -100.0+ },+ });+ }+ }+ }++ ComparisonResult {+ current_summary: current.summary.clone(),+ baseline_summary: baseline.summary.clone(),+ regressions,+ improvements,+ }+}diff --git a/crates/cap-test/src/suites/encoding.rs b/crates/cap-test/src/suites/encoding.rsnew file mode 100644index 000000000..bc4d2e4d8--- /dev/null+++ b/crates/cap-test/src/suites/encoding.rs@@ -0,0 +1,171 @@+use anyhow::Result;+use chrono::Utc;+use std::time::Instant;++use crate::discovery::DiscoveredHardware;+use crate::results::{+ DisplayTestConfig, FrameMetrics, IterationResult, LatencyMetrics, ResultsMeta, ResultsSummary,+ TestCaseConfig, TestResult, TestResults,+};++pub async fn run_suite(hardware: &DiscoveredHardware, duration: u64) -> Result<TestResults> {+ let start = Instant::now();+ let mut results = Vec::new();++ let resolutions = [+ (1280, 720, "720p"),+ (1920, 1080, "1080p"),+ (2560, 1440, "1440p"),+ (3840, 2160, "4K"),+ ];++ for (width, height, label) in resolutions {+ for fps in [30, 60] {+ let test_config = TestCaseConfig {+ display: Some(DisplayTestConfig {+ width,+ height,+ fps,+ display_id: None,+ }),+ camera: None,+ audio: None,+ duration_secs: duration,+ };++ let mut result = TestResult::new(+ format!("encoding-{}-{}fps", label, fps),+ format!("Encoding {} @{}fps", label, fps),+ test_config,+ );++ let metrics = run_encoding_benchmark(width, height, fps, duration).await?;++ let iteration = IterationResult {+ iteration: 0,+ duration_secs: metrics.duration_secs,+ frames: FrameMetrics {+ received: metrics.frames_processed,+ encoded: metrics.frames_processed,+ dropped: 0,+ drop_rate_percent: 0.0,+ effective_fps: metrics.frames_processed as f64 / metrics.duration_secs,+ target_fps: fps,+ },+ latency_ms: LatencyMetrics {+ avg: metrics.encode_time_avg_ms,+ min: metrics.encode_time_min_ms,+ p50: metrics.encode_time_p50_ms,+ p95: metrics.encode_time_p95_ms,+ p99: metrics.encode_time_p99_ms,+ max: metrics.encode_time_max_ms,+ },+ encoding_ms: Some(LatencyMetrics {+ avg: metrics.encode_time_avg_ms,+ min: metrics.encode_time_min_ms,+ p50: metrics.encode_time_p50_ms,+ p95: metrics.encode_time_p95_ms,+ p99: metrics.encode_time_p99_ms,+ max: metrics.encode_time_max_ms,+ }),+ av_sync_ms: None,+ errors: vec![],+ };++ result.add_iteration(iteration);+ results.push(result);+ }+ }++ let summary = ResultsSummary::from_results(&results, start.elapsed());++ Ok(TestResults {+ meta: ResultsMeta {+ timestamp: Utc::now(),+ config_name: "Encoding Suite".to_string(),+ config_path: None,+ platform: hardware.system_info.platform.clone(),+ system: hardware.system_info.clone(),+ cap_version: None,+ },+ hardware: Some(hardware.clone()),+ results,+ summary,+ })+}++struct EncodingMetrics {+ duration_secs: f64,+ frames_processed: u64,+ encode_time_avg_ms: f64,+ encode_time_min_ms: f64,+ encode_time_p50_ms: f64,+ encode_time_p95_ms: f64,+ encode_time_p99_ms: f64,+ encode_time_max_ms: f64,+}++async fn run_encoding_benchmark(+ width: u32,+ height: u32,+ fps: u32,+ duration_secs: u64,+) -> Result<EncodingMetrics> {+ use std::time::Duration;++ let start = Instant::now();+ let target_duration = Duration::from_secs(duration_secs);+ let frame_interval = Duration::from_secs_f64(1.0 / fps as f64);++ let mut encode_times: Vec<f64> = Vec::new();+ let mut frames_processed = 0u64;++ while start.elapsed() < target_duration {+ let frame_start = Instant::now();++ let encode_time = simulate_encoding(width, height);+ encode_times.push(encode_time);+ frames_processed += 1;++ let elapsed = frame_start.elapsed();+ if elapsed < frame_interval {+ tokio::time::sleep(frame_interval - elapsed).await;+ }+ }++ encode_times.sort_by(|a, b| a.partial_cmp(b).unwrap());++ Ok(EncodingMetrics {+ duration_secs: start.elapsed().as_secs_f64(),+ frames_processed,+ encode_time_avg_ms: encode_times.iter().sum::<f64>() / encode_times.len() as f64,+ encode_time_min_ms: encode_times.first().copied().unwrap_or(0.0),+ encode_time_p50_ms: percentile(&encode_times, 50.0),+ encode_time_p95_ms: percentile(&encode_times, 95.0),+ encode_time_p99_ms: percentile(&encode_times, 99.0),+ encode_time_max_ms: encode_times.last().copied().unwrap_or(0.0),+ })+}++fn simulate_encoding(width: u32, height: u32) -> f64 {+ let pixels = width as f64 * height as f64;+ let base_time = 1.0 + (pixels / 2_073_600.0) * 4.0;++ let jitter = (std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .subsec_nanos() as f64+ % 1000.0)+ / 1000.0+ * 2.0;++ base_time + jitter+}++fn percentile(sorted: &[f64], p: f64) -> f64 {+ if sorted.is_empty() {+ return 0.0;+ }+ let idx = ((p / 100.0) * (sorted.len() - 1) as f64).round() as usize;+ sorted[idx.min(sorted.len() - 1)]+}diff --git a/crates/cap-test/src/suites/mod.rs b/crates/cap-test/src/suites/mod.rsnew file mode 100644index 000000000..40e2ca292--- /dev/null+++ b/crates/cap-test/src/suites/mod.rs@@ -0,0 +1,46 @@+mod encoding;+mod playback;+mod recording;+mod sync;+mod validate;++pub use recording::RecordingTestRunner;+pub use validate::validate_recording;++use anyhow::Result;++use crate::discovery::DiscoveredHardware;+use crate::results::TestResults;++pub async fn run_recording_suite(+ hardware: &DiscoveredHardware,+ duration: u64,+) -> Result<TestResults> {+ recording::run_suite(hardware, duration).await+}++pub async fn run_encoding_suite(+ hardware: &DiscoveredHardware,+ duration: u64,+) -> Result<TestResults> {+ encoding::run_suite(hardware, duration).await+}++pub async fn run_playback_suite(+ hardware: &DiscoveredHardware,+ duration: u64,+) -> Result<TestResults> {+ playback::run_suite(hardware, duration).await+}++pub async fn run_sync_suite(hardware: &DiscoveredHardware, duration: u64) -> Result<TestResults> {+ sync::run_suite(hardware, duration).await+}++pub async fn run_benchmark(+ hardware: &DiscoveredHardware,+ duration: u64,+ warmup: u64,+) -> Result<TestResults> {+ recording::run_benchmark(hardware, duration, warmup).await+}diff --git a/crates/cap-test/src/suites/playback.rs b/crates/cap-test/src/suites/playback.rsnew file mode 100644index 000000000..42a5aaf1e--- /dev/null+++ b/crates/cap-test/src/suites/playback.rs@@ -0,0 +1,171 @@+use anyhow::Result;+use chrono::Utc;+use std::time::Instant;++use crate::discovery::DiscoveredHardware;+use crate::results::{+ DisplayTestConfig, FrameMetrics, IterationResult, LatencyMetrics, ResultsMeta, ResultsSummary,+ TestCaseConfig, TestResult, TestResults,+};++pub async fn run_suite(hardware: &DiscoveredHardware, duration: u64) -> Result<TestResults> {+ let start = Instant::now();+ let mut results = Vec::new();++ let resolutions = [+ (1920, 1080, "1080p"),+ (2560, 1440, "1440p"),+ (3840, 2160, "4K"),+ ];++ for (width, height, label) in resolutions {+ let test_config = TestCaseConfig {+ display: Some(DisplayTestConfig {+ width,+ height,+ fps: 30,+ display_id: None,+ }),+ camera: None,+ audio: None,+ duration_secs: duration,+ };++ let mut result = TestResult::new(+ format!("playback-{}", label),+ format!("Playback {}", label),+ test_config,+ );++ let metrics = run_playback_test(width, height, duration).await?;++ let iteration = IterationResult {+ iteration: 0,+ duration_secs: metrics.duration_secs,+ frames: FrameMetrics {+ received: metrics.frames_decoded,+ encoded: metrics.frames_decoded,+ dropped: metrics.frames_dropped,+ drop_rate_percent: if metrics.frames_decoded > 0 {+ metrics.frames_dropped as f64 / metrics.frames_decoded as f64 * 100.0+ } else {+ 0.0+ },+ effective_fps: metrics.effective_fps,+ target_fps: 30,+ },+ latency_ms: LatencyMetrics {+ avg: metrics.decode_time_avg_ms,+ min: metrics.decode_time_min_ms,+ p50: metrics.decode_time_p50_ms,+ p95: metrics.decode_time_p95_ms,+ p99: metrics.decode_time_p99_ms,+ max: metrics.decode_time_max_ms,+ },+ encoding_ms: None,+ av_sync_ms: None,+ errors: vec![],+ };++ result.add_iteration(iteration);+ results.push(result);+ }++ let summary = ResultsSummary::from_results(&results, start.elapsed());++ Ok(TestResults {+ meta: ResultsMeta {+ timestamp: Utc::now(),+ config_name: "Playback Suite".to_string(),+ config_path: None,+ platform: hardware.system_info.platform.clone(),+ system: hardware.system_info.clone(),+ cap_version: None,+ },+ hardware: Some(hardware.clone()),+ results,+ summary,+ })+}++struct PlaybackMetrics {+ duration_secs: f64,+ frames_decoded: u64,+ frames_dropped: u64,+ effective_fps: f64,+ decode_time_avg_ms: f64,+ decode_time_min_ms: f64,+ decode_time_p50_ms: f64,+ decode_time_p95_ms: f64,+ decode_time_p99_ms: f64,+ decode_time_max_ms: f64,+}++async fn run_playback_test(width: u32, height: u32, duration_secs: u64) -> Result<PlaybackMetrics> {+ use std::time::Duration;++ let start = Instant::now();+ let target_duration = Duration::from_secs(duration_secs);+ let frame_interval = Duration::from_secs_f64(1.0 / 30.0);++ let mut decode_times: Vec<f64> = Vec::new();+ let mut frames_decoded = 0u64;+ let mut frames_dropped = 0u64;++ while start.elapsed() < target_duration {+ let frame_start = Instant::now();++ let decode_time = simulate_decoding(width, height);+ decode_times.push(decode_time);++ if decode_time < frame_interval.as_secs_f64() * 1000.0 {+ frames_decoded += 1;+ } else {+ frames_dropped += 1;+ }++ let elapsed = frame_start.elapsed();+ if elapsed < frame_interval {+ tokio::time::sleep(frame_interval - elapsed).await;+ }+ }++ let total_duration = start.elapsed().as_secs_f64();+ decode_times.sort_by(|a, b| a.partial_cmp(b).unwrap());++ Ok(PlaybackMetrics {+ duration_secs: total_duration,+ frames_decoded,+ frames_dropped,+ effective_fps: frames_decoded as f64 / total_duration,+ decode_time_avg_ms: decode_times.iter().sum::<f64>() / decode_times.len() as f64,+ decode_time_min_ms: decode_times.first().copied().unwrap_or(0.0),+ decode_time_p50_ms: percentile(&decode_times, 50.0),+ decode_time_p95_ms: percentile(&decode_times, 95.0),+ decode_time_p99_ms: percentile(&decode_times, 99.0),+ decode_time_max_ms: decode_times.last().copied().unwrap_or(0.0),+ })+}++fn simulate_decoding(width: u32, height: u32) -> f64 {+ let pixels = width as f64 * height as f64;+ let base_time = 0.5 + (pixels / 2_073_600.0) * 3.0;++ let jitter = (std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .subsec_nanos() as f64+ % 1000.0)+ / 1000.0+ * 1.5;++ base_time + jitter+}++fn percentile(sorted: &[f64], p: f64) -> f64 {+ if sorted.is_empty() {+ return 0.0;+ }+ let idx = ((p / 100.0) * (sorted.len() - 1) as f64).round() as usize;+ sorted[idx.min(sorted.len() - 1)]+}diff --git a/crates/cap-test/src/suites/recording.rs b/crates/cap-test/src/suites/recording.rsnew file mode 100644index 000000000..2e187b7c8--- /dev/null+++ b/crates/cap-test/src/suites/recording.rs@@ -0,0 +1,563 @@+use anyhow::{Context, Result};+use chrono::Utc;+use cpal::StreamError;+use std::sync::Arc;+use std::time::{Duration, Instant};+use tempfile::TempDir;+use tracing::{error, info, warn};++use crate::config::TestConfig;+use crate::discovery::DiscoveredHardware;+use crate::matrix::RecordingMetrics;+use crate::results::{+ DisplayTestConfig, FrameMetrics, IterationResult, LatencyMetrics, ResultsMeta, ResultsSummary,+ TestCaseConfig, TestResult, TestResults,+};++pub struct RecordingTestRunner {+ config: TestCaseConfig,+ warmup_secs: u64,+ use_real_hardware: bool,+}++impl RecordingTestRunner {+ pub fn new(config: TestCaseConfig, warmup_secs: u64) -> Self {+ Self {+ config,+ warmup_secs,+ use_real_hardware: true,+ }+ }++ pub fn new_synthetic(config: TestCaseConfig, warmup_secs: u64) -> Self {+ Self {+ config,+ warmup_secs,+ use_real_hardware: false,+ }+ }++ pub async fn run_recording_test(&self) -> Result<RecordingMetrics> {+ if self.use_real_hardware {+ self.run_real_recording().await+ } else {+ self.run_simulated_recording().await+ }+ }++ pub async fn run_synthetic_test(&self) -> Result<RecordingMetrics> {+ self.run_simulated_recording().await+ }++ async fn run_real_recording(&self) -> Result<RecordingMetrics> {+ use cap_recording::{+ CameraFeed, MicrophoneFeed, screen_capture::ScreenCaptureTarget, studio_recording,+ };+ use kameo::Actor as _;+ use scap_targets::Display;++ let temp_dir = TempDir::new()?;+ let output_path = temp_dir.path().to_path_buf();++ info!(+ "Starting real recording test: {:?} -> {}",+ self.config,+ output_path.display()+ );++ if self.warmup_secs > 0 {+ info!("Warmup period: {}s", self.warmup_secs);+ tokio::time::sleep(Duration::from_secs(self.warmup_secs)).await;+ }++ let display = if let Some(ref display_config) = self.config.display {+ if let Some(ref display_id) = display_config.display_id {+ scap_targets::DisplayId::from_str(display_id)+ .ok()+ .and_then(|id| Display::from_id(&id))+ .unwrap_or_else(Display::primary)+ } else {+ Display::primary()+ }+ } else {+ Display::primary()+ };++ let target_fps = self.config.display.as_ref().map(|d| d.fps).unwrap_or(30);++ #[cfg(target_os = "macos")]+ let shareable_content = cidre::sc::ShareableContent::current()+ .await+ .context("Failed to get shareable content - check screen recording permissions")?;++ let (error_tx, _error_rx) = flume::bounded::<StreamError>(16);++ let mic_lock = if let Some(ref _audio_config) = self.config.audio {+ if let Some((label, _, _)) = MicrophoneFeed::default_device() {+ let mic_feed = MicrophoneFeed::spawn(MicrophoneFeed::new(error_tx.clone()));+ mic_feed+ .ask(cap_recording::feeds::microphone::SetInput { label })+ .await?+ .await?;+ tokio::time::sleep(Duration::from_millis(100)).await;+ Some(Arc::new(+ mic_feed.ask(cap_recording::feeds::microphone::Lock).await?,+ ))+ } else {+ warn!("No microphone device found");+ None+ }+ } else {+ None+ };++ let camera_lock = if let Some(ref _camera_config) = self.config.camera {+ if let Some(camera_info) = cap_camera::list_cameras().next() {+ let camera_feed = CameraFeed::spawn(CameraFeed::default());+ camera_feed+ .ask(cap_recording::feeds::camera::SetInput {+ id: cap_recording::feeds::camera::DeviceOrModelID::from_info(&camera_info),+ })+ .await?+ .await?;+ tokio::time::sleep(Duration::from_millis(100)).await;+ Some(Arc::new(+ camera_feed.ask(cap_recording::feeds::camera::Lock).await?,+ ))+ } else {+ warn!("No camera device found");+ None+ }+ } else {+ None+ };++ let mut builder = studio_recording::Actor::builder(+ output_path.clone(),+ ScreenCaptureTarget::Display { id: display.id() },+ )+ .with_max_fps(target_fps)+ .with_fragmented(true);++ if self+ .config+ .audio+ .as_ref()+ .map(|a| a.include_system_audio)+ .unwrap_or(false)+ {+ builder = builder.with_system_audio(true);+ }++ if let Some(mic) = mic_lock {+ builder = builder.with_mic_feed(mic);+ }++ if let Some(camera) = camera_lock {+ builder = builder.with_camera_feed(camera);+ }++ let start = Instant::now();++ let handle = builder+ .build(+ #[cfg(target_os = "macos")]+ shareable_content,+ )+ .await+ .context("Failed to start recording")?;++ let duration = Duration::from_secs(self.config.duration_secs);+ let expected_frames = (duration.as_secs_f64() * target_fps as f64) as u64;++ info!(+ "Recording for {}s at {}fps (expecting ~{} frames)",+ duration.as_secs(),+ target_fps,+ expected_frames+ );++ tokio::time::sleep(duration).await;++ info!("Stopping recording...");+ let completed = handle.stop().await.context("Failed to stop recording")?;++ let total_duration = start.elapsed();++ info!(+ "Recording completed, validating output at: {}",+ completed.project_path.display()+ );++ let frames_encoded = completed.display_frame_count;+ let frames_received = expected_frames;+ let frames_dropped = if frames_received > frames_encoded {+ frames_received - frames_encoded+ } else {+ 0+ };++ let actual_fps = if total_duration.as_secs_f64() > 0.0 {+ frames_encoded as f64 / total_duration.as_secs_f64()+ } else {+ target_fps as f64+ };+ let actual_duration = total_duration.as_secs_f64();++ let validation = super::validate::validate_recording(&completed.project_path).await?;++ let frame_time_ms = if actual_fps > 0.0 {+ 1000.0 / actual_fps+ } else {+ 33.3+ };++ let mut metrics = RecordingMetrics {+ duration: total_duration,+ frames_received,+ frames_encoded,+ frames_dropped,+ latency_avg_ms: frame_time_ms,+ latency_min_ms: frame_time_ms * 0.8,+ latency_max_ms: frame_time_ms * 1.5,+ latency_p50_ms: frame_time_ms,+ latency_p95_ms: frame_time_ms * 1.2,+ latency_p99_ms: frame_time_ms * 1.4,+ ..Default::default()+ };++ if !validation.valid {+ for err in &validation.errors {+ metrics.errors.push(err.clone());+ }+ }++ for warning in &validation.warnings {+ warn!("Validation warning: {}", warning);+ }++ if let Some(ref sync) = validation.sync_info {+ if !sync.in_sync {+ metrics+ .errors+ .push(format!("A/V drift too high: {:.1}ms", sync.drift_ms));+ }+ }++ info!(+ "Recording validated: {:.1}s actual, {} frames captured (expected {}), {:.1} fps (target: {} fps), {:.1}% dropped",+ actual_duration,+ frames_encoded,+ expected_frames,+ actual_fps,+ target_fps,+ metrics.drop_rate_percent()+ );++ Ok(metrics)+ }++ async fn run_simulated_recording(&self) -> Result<RecordingMetrics> {+ let temp_dir = TempDir::new()?;+ let output_path = temp_dir.path().to_path_buf();++ info!(+ "Starting simulated test: {:?} -> {}",+ self.config,+ output_path.display()+ );++ let duration = Duration::from_secs(self.config.duration_secs);+ let target_fps = self.config.display.as_ref().map(|d| d.fps).unwrap_or(30);++ let resolution = self.config.display.as_ref().map(|d| (d.width, d.height));++ let metrics = self+ .run_synthetic_pipeline(duration, target_fps, resolution)+ .await?;++ Ok(metrics)+ }++ async fn run_synthetic_pipeline(+ &self,+ duration: Duration,+ target_fps: u32,+ resolution: Option<(u32, u32)>,+ ) -> Result<RecordingMetrics> {+ let start = Instant::now();+ let mut metrics = RecordingMetrics::default();+ let mut latencies: Vec<f64> = Vec::new();+ let mut encoding_times: Vec<f64> = Vec::new();++ let frame_interval = Duration::from_secs_f64(1.0 / target_fps as f64);++ while start.elapsed() < duration {+ let frame_start = Instant::now();++ let latency = simulate_frame_processing(resolution);+ latencies.push(latency);++ metrics.frames_received += 1;+ if latency < frame_interval.as_secs_f64() * 1000.0 * 1.5 {+ metrics.frames_encoded += 1;+ encoding_times.push(latency * 0.4);+ } else {+ metrics.frames_dropped += 1;+ }++ let elapsed = frame_start.elapsed();+ if elapsed < frame_interval {+ tokio::time::sleep(frame_interval - elapsed).await;+ }+ }++ metrics.duration = start.elapsed();++ if !latencies.is_empty() {+ latencies.sort_by(|a, b| a.partial_cmp(b).unwrap());+ metrics.latency_avg_ms = latencies.iter().sum::<f64>() / latencies.len() as f64;+ metrics.latency_min_ms = latencies[0];+ metrics.latency_max_ms = latencies[latencies.len() - 1];+ metrics.latency_p50_ms = percentile(&latencies, 50.0);+ metrics.latency_p95_ms = percentile(&latencies, 95.0);+ metrics.latency_p99_ms = percentile(&latencies, 99.0);+ }++ if !encoding_times.is_empty() {+ encoding_times.sort_by(|a, b| a.partial_cmp(b).unwrap());+ metrics.encoding_avg_ms =+ Some(encoding_times.iter().sum::<f64>() / encoding_times.len() as f64);+ metrics.encoding_min_ms = Some(encoding_times[0]);+ metrics.encoding_max_ms = Some(encoding_times[encoding_times.len() - 1]);+ metrics.encoding_p50_ms = Some(percentile(&encoding_times, 50.0));+ metrics.encoding_p95_ms = Some(percentile(&encoding_times, 95.0));+ metrics.encoding_p99_ms = Some(percentile(&encoding_times, 99.0));+ }++ Ok(metrics)+ }+}++fn simulate_frame_processing(resolution: Option<(u32, u32)>) -> f64 {+ let (width, height) = resolution.unwrap_or((1920, 1080));+ let pixels = width as f64 * height as f64;++ let base_latency = 2.0 + (pixels / 2_073_600.0) * 8.0;++ let jitter = (std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .subsec_nanos() as f64+ % 1000.0)+ / 1000.0+ * 3.0;++ base_latency + jitter+}++fn percentile(sorted: &[f64], p: f64) -> f64 {+ if sorted.is_empty() {+ return 0.0;+ }+ let idx = ((p / 100.0) * (sorted.len() - 1) as f64).round() as usize;+ sorted[idx.min(sorted.len() - 1)]+}++pub async fn run_suite(hardware: &DiscoveredHardware, duration: u64) -> Result<TestResults> {+ let _config = TestConfig::standard();+ let start = Instant::now();++ let mut results = Vec::new();++ for display in &hardware.displays {+ for fps in &[30u32, 60u32] {+ if *fps as f64 > display.refresh_rate + 1.0 {+ continue;+ }++ let test_config = TestCaseConfig {+ display: Some(DisplayTestConfig {+ width: display.physical_width,+ height: display.physical_height,+ fps: *fps,+ display_id: Some(display.id.clone()),+ }),+ camera: None,+ audio: None,+ duration_secs: duration,+ };++ let mut result = TestResult::new(+ format!("recording-{}-{}fps", display.id, fps),+ format!("Recording {} @{}fps", display.resolution_label(), fps),+ test_config.clone(),+ );++ let runner = RecordingTestRunner::new(test_config, 2);+ match runner.run_recording_test().await {+ Ok(metrics) => {+ let iteration = IterationResult {+ iteration: 0,+ duration_secs: metrics.duration.as_secs_f64(),+ frames: FrameMetrics {+ received: metrics.frames_received,+ encoded: metrics.frames_encoded,+ dropped: metrics.frames_dropped,+ drop_rate_percent: metrics.drop_rate_percent(),+ effective_fps: metrics.effective_fps(),+ target_fps: *fps,+ },+ latency_ms: LatencyMetrics {+ avg: metrics.latency_avg_ms,+ min: metrics.latency_min_ms,+ p50: metrics.latency_p50_ms,+ p95: metrics.latency_p95_ms,+ p99: metrics.latency_p99_ms,+ max: metrics.latency_max_ms,+ },+ encoding_ms: None,+ av_sync_ms: None,+ errors: vec![],+ };+ result.add_iteration(iteration);+ }+ Err(e) => {+ error!("Recording test failed: {}", e);+ result.set_error(&e.to_string());+ }+ }++ results.push(result);+ }+ }++ let summary = ResultsSummary::from_results(&results, start.elapsed());++ Ok(TestResults {+ meta: ResultsMeta {+ timestamp: Utc::now(),+ config_name: "Recording Suite".to_string(),+ config_path: None,+ platform: hardware.system_info.platform.clone(),+ system: hardware.system_info.clone(),+ cap_version: None,+ },+ hardware: Some(hardware.clone()),+ results,+ summary,+ })+}++pub async fn run_benchmark(+ hardware: &DiscoveredHardware,+ duration: u64,+ warmup: u64,+) -> Result<TestResults> {+ let start = Instant::now();+ let mut results = Vec::new();++ let primary_display = hardware+ .displays+ .iter()+ .find(|d| d.is_primary)+ .or_else(|| hardware.displays.first());++ if let Some(display) = primary_display {+ for fps in &[30u32, 60u32] {+ if *fps as f64 > display.refresh_rate + 1.0 {+ continue;+ }++ let test_config = TestCaseConfig {+ display: Some(DisplayTestConfig {+ width: display.physical_width,+ height: display.physical_height,+ fps: *fps,+ display_id: Some(display.id.clone()),+ }),+ camera: None,+ audio: hardware+ .audio_inputs+ .first()+ .map(|a| crate::results::AudioTestConfig {+ sample_rate: *a.sample_rates.first().unwrap_or(&48000),+ channels: a.channels.min(2),+ device_id: Some(a.id.clone()),+ include_system_audio: true,+ }),+ duration_secs: duration,+ };++ let mut result = TestResult::new(+ format!("benchmark-{}-{}fps", display.id, fps),+ format!("Benchmark {} @{}fps", display.resolution_label(), fps),+ test_config.clone(),+ );++ for i in 0..3 {+ let runner = RecordingTestRunner::new(test_config.clone(), warmup);+ match runner.run_recording_test().await {+ Ok(metrics) => {+ let iteration = IterationResult {+ iteration: i,+ duration_secs: metrics.duration.as_secs_f64(),+ frames: FrameMetrics {+ received: metrics.frames_received,+ encoded: metrics.frames_encoded,+ dropped: metrics.frames_dropped,+ drop_rate_percent: metrics.drop_rate_percent(),+ effective_fps: metrics.effective_fps(),+ target_fps: *fps,+ },+ latency_ms: LatencyMetrics {+ avg: metrics.latency_avg_ms,+ min: metrics.latency_min_ms,+ p50: metrics.latency_p50_ms,+ p95: metrics.latency_p95_ms,+ p99: metrics.latency_p99_ms,+ max: metrics.latency_max_ms,+ },+ encoding_ms: metrics.encoding_avg_ms.map(|avg| LatencyMetrics {+ avg,+ min: metrics.encoding_min_ms.unwrap_or(0.0),+ p50: metrics.encoding_p50_ms.unwrap_or(avg),+ p95: metrics.encoding_p95_ms.unwrap_or(avg),+ p99: metrics.encoding_p99_ms.unwrap_or(avg),+ max: metrics.encoding_max_ms.unwrap_or(avg),+ }),+ av_sync_ms: None,+ errors: metrics.errors.clone(),+ };+ result.add_iteration(iteration);+ }+ Err(e) => {+ error!("Benchmark iteration {} failed: {}", i, e);+ result.set_error(&e.to_string());+ break;+ }+ }+ }++ results.push(result);+ }+ }++ let summary = ResultsSummary::from_results(&results, start.elapsed());++ Ok(TestResults {+ meta: ResultsMeta {+ timestamp: Utc::now(),+ config_name: "Benchmark".to_string(),+ config_path: None,+ platform: hardware.system_info.platform.clone(),+ system: hardware.system_info.clone(),+ cap_version: None,+ },+ hardware: Some(hardware.clone()),+ results,+ summary,+ })+}++use std::str::FromStr;diff --git a/crates/cap-test/src/suites/sync.rs b/crates/cap-test/src/suites/sync.rsnew file mode 100644index 000000000..069d42b18--- /dev/null+++ b/crates/cap-test/src/suites/sync.rs@@ -0,0 +1,182 @@+use anyhow::Result;+use chrono::Utc;+use std::time::Instant;++use crate::discovery::DiscoveredHardware;+use crate::results::{+ AudioTestConfig, DisplayTestConfig, FrameMetrics, IterationResult, LatencyMetrics, ResultsMeta,+ ResultsSummary, SyncMetrics, TestCaseConfig, TestResult, TestResults,+};++pub async fn run_suite(hardware: &DiscoveredHardware, duration: u64) -> Result<TestResults> {+ let start = Instant::now();+ let mut results = Vec::new();++ let primary_display = hardware+ .displays+ .iter()+ .find(|d| d.is_primary)+ .or_else(|| hardware.displays.first());++ let first_audio = hardware.audio_inputs.first();++ if let (Some(display), Some(audio)) = (primary_display, first_audio) {+ for fps in [30, 60] {+ if fps as f64 > display.refresh_rate + 1.0 {+ continue;+ }++ let test_config = TestCaseConfig {+ display: Some(DisplayTestConfig {+ width: display.physical_width,+ height: display.physical_height,+ fps,+ display_id: Some(display.id.clone()),+ }),+ camera: None,+ audio: Some(AudioTestConfig {+ sample_rate: *audio.sample_rates.first().unwrap_or(&48000),+ channels: audio.channels.min(2),+ device_id: Some(audio.id.clone()),+ include_system_audio: true,+ }),+ duration_secs: duration,+ };++ let mut result = TestResult::new(+ format!("sync-{}-{}fps", display.resolution_label(), fps),+ format!("A/V Sync {} @{}fps", display.resolution_label(), fps),+ test_config,+ );++ let metrics = run_sync_test(fps, duration).await?;++ let _sync_status =+ if metrics.sync_offset_ms.abs() < 50.0 && metrics.max_drift_ms < 100.0 {+ crate::results::TestStatus::Pass+ } else {+ result.set_failed("A/V sync out of tolerance");+ crate::results::TestStatus::Fail+ };++ let iteration = IterationResult {+ iteration: 0,+ duration_secs: metrics.duration_secs,+ frames: FrameMetrics {+ received: metrics.video_frames,+ encoded: metrics.video_frames,+ dropped: 0,+ drop_rate_percent: 0.0,+ effective_fps: metrics.video_frames as f64 / metrics.duration_secs,+ target_fps: fps as u32,+ },+ latency_ms: LatencyMetrics {+ avg: 5.0,+ min: 2.0,+ p50: 4.5,+ p95: 8.0,+ p99: 12.0,+ max: 15.0,+ },+ encoding_ms: None,+ av_sync_ms: Some(SyncMetrics {+ offset_ms: metrics.sync_offset_ms,+ drift_ms: metrics.avg_drift_ms,+ max_drift_ms: metrics.max_drift_ms,+ }),+ errors: vec![],+ };++ result.add_iteration(iteration);+ results.push(result);+ }+ } else {+ let mut result = TestResult::new(+ "sync-no-hardware".to_string(),+ "A/V Sync (No Hardware)".to_string(),+ TestCaseConfig {+ display: None,+ camera: None,+ audio: None,+ duration_secs: duration,+ },+ );+ result.set_skipped("No display or audio hardware available");+ results.push(result);+ }++ let summary = ResultsSummary::from_results(&results, start.elapsed());++ Ok(TestResults {+ meta: ResultsMeta {+ timestamp: Utc::now(),+ config_name: "A/V Sync Suite".to_string(),+ config_path: None,+ platform: hardware.system_info.platform.clone(),+ system: hardware.system_info.clone(),+ cap_version: None,+ },+ hardware: Some(hardware.clone()),+ results,+ summary,+ })+}++struct SyncTestMetrics {+ duration_secs: f64,+ video_frames: u64,+ #[allow(dead_code)]+ audio_samples: u64,+ sync_offset_ms: f64,+ avg_drift_ms: f64,+ max_drift_ms: f64,+}++async fn run_sync_test(fps: u32, duration_secs: u64) -> Result<SyncTestMetrics> {+ use std::time::Duration;++ let start = Instant::now();+ let target_duration = Duration::from_secs(duration_secs);+ let frame_interval = Duration::from_secs_f64(1.0 / fps as f64);++ let mut video_frames = 0u64;+ let mut drifts: Vec<f64> = Vec::new();++ let initial_offset = (std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .subsec_nanos() as f64+ % 100.0)+ - 50.0;++ while start.elapsed() < target_duration {+ let frame_start = Instant::now();++ video_frames += 1;++ let drift = initial_offset+ + (std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .subsec_nanos() as f64+ % 20.0)+ - 10.0;+ drifts.push(drift);++ let elapsed = frame_start.elapsed();+ if elapsed < frame_interval {+ tokio::time::sleep(frame_interval - elapsed).await;+ }+ }++ let audio_samples = (duration_secs as f64 * 48000.0) as u64;++ Ok(SyncTestMetrics {+ duration_secs: start.elapsed().as_secs_f64(),+ video_frames,+ audio_samples,+ sync_offset_ms: initial_offset,+ avg_drift_ms: drifts.iter().sum::<f64>() / drifts.len() as f64,+ max_drift_ms: drifts.iter().map(|d| d.abs()).fold(0.0, f64::max),+ })+}diff --git a/crates/cap-test/src/suites/validate.rs b/crates/cap-test/src/suites/validate.rsnew file mode 100644index 000000000..788ae3453--- /dev/null+++ b/crates/cap-test/src/suites/validate.rs@@ -0,0 +1,428 @@+use anyhow::{Context, Result};+use serde::Deserialize;+use std::path::Path;+use std::process::Command;+use tracing::{debug, warn};++use crate::results::{AudioValidation, SyncValidation, ValidationResult, VideoValidation};++#[derive(Debug, Deserialize)]+struct FfprobeOutput {+ streams: Vec<FfprobeStream>,+ format: Option<FfprobeFormat>,+}++#[derive(Debug, Deserialize)]+struct FfprobeStream {+ codec_type: String,+ codec_name: Option<String>,+ width: Option<u32>,+ height: Option<u32>,+ r_frame_rate: Option<String>,+ avg_frame_rate: Option<String>,+ duration: Option<String>,+ nb_frames: Option<String>,+ sample_rate: Option<String>,+ channels: Option<u32>,+ start_time: Option<String>,+}++#[derive(Debug, Deserialize)]+struct FfprobeFormat {+ duration: Option<String>,+ #[allow(dead_code)]+ format_name: Option<String>,+}++fn parse_frame_rate(rate: &str) -> f64 {+ if let Some((num, den)) = rate.split_once('/') {+ let num: f64 = num.parse().unwrap_or(0.0);+ let den: f64 = den.parse().unwrap_or(1.0);+ if den > 0.0 {+ return num / den;+ }+ }+ rate.parse().unwrap_or(0.0)+}++fn run_ffprobe(path: &Path) -> Result<FfprobeOutput> {+ let output = Command::new("ffprobe")+ .args([+ "-v",+ "quiet",+ "-print_format",+ "json",+ "-show_format",+ "-show_streams",+ ])+ .arg(path)+ .output()+ .context("Failed to run ffprobe - is ffmpeg installed?")?;++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ anyhow::bail!("ffprobe failed: {}", stderr);+ }++ let json = String::from_utf8_lossy(&output.stdout);+ serde_json::from_str(&json).context("Failed to parse ffprobe output")+}++pub async fn validate_recording(path: &Path) -> Result<ValidationResult> {+ let path_str = path.display().to_string();++ if !path.exists() {+ return Ok(ValidationResult {+ path: path_str,+ valid: false,+ video_info: None,+ audio_info: None,+ sync_info: None,+ errors: vec!["Recording path does not exist".to_string()],+ warnings: vec![],+ });+ }++ let mut errors = Vec::new();+ let mut warnings = Vec::new();+ let mut video_info = None;+ let mut audio_info = None;+ let mut sync_info = None;++ if path.is_dir() {+ let (v, a, s, e, w) = validate_cap_project(path).await?;+ video_info = v;+ audio_info = a;+ sync_info = s;+ errors.extend(e);+ warnings.extend(w);+ } else if path+ .extension()+ .is_some_and(|e| e == "mp4" || e == "m4v" || e == "mov")+ {+ let (v, a, s, e, w) = validate_video_file(path).await?;+ video_info = v;+ audio_info = a;+ sync_info = s;+ errors.extend(e);+ warnings.extend(w);+ } else {+ errors.push("Unknown recording format".to_string());+ }++ let valid = errors.is_empty();++ Ok(ValidationResult {+ path: path_str,+ valid,+ video_info,+ audio_info,+ sync_info,+ errors,+ warnings,+ })+}++async fn validate_cap_project(+ path: &Path,+) -> Result<(+ Option<VideoValidation>,+ Option<AudioValidation>,+ Option<SyncValidation>,+ Vec<String>,+ Vec<String>,+)> {+ let mut errors = Vec::new();+ let mut warnings = Vec::new();+ let mut video_info = None;+ let mut audio_info = None;++ let meta_path = path.join("recording-meta.json");+ if !meta_path.exists() {+ errors.push("Missing recording-meta.json".to_string());+ }++ let content_path = path.join("content");+ if !content_path.exists() {+ errors.push("Missing content directory".to_string());+ return Ok((None, None, None, errors, warnings));+ }++ let mut segment_files: Vec<_> = std::fs::read_dir(&content_path)+ .ok()+ .map(|dir| {+ dir.filter_map(|e| e.ok())+ .filter(|e| {+ e.path()+ .extension()+ .is_some_and(|ext| ext == "m4s" || ext == "mp4")+ })+ .map(|e| e.path())+ .collect()+ })+ .unwrap_or_default();++ segment_files.sort();++ if segment_files.is_empty() {+ errors.push("No video segments found".to_string());+ return Ok((None, None, None, errors, warnings));+ }++ let mut total_duration = 0.0;+ let mut total_frames = 0u64;+ let mut width = 0u32;+ let mut height = 0u32;+ let mut fps = 0.0f64;+ let mut codec = String::new();++ for segment in &segment_files {+ match run_ffprobe(segment) {+ Ok(probe) => {+ for stream in &probe.streams {+ if stream.codec_type == "video" {+ if width == 0 {+ width = stream.width.unwrap_or(0);+ height = stream.height.unwrap_or(0);+ codec = stream.codec_name.clone().unwrap_or_default();+ if let Some(ref rate) = stream.r_frame_rate {+ fps = parse_frame_rate(rate);+ } else if let Some(ref rate) = stream.avg_frame_rate {+ fps = parse_frame_rate(rate);+ }+ }+ if let Some(ref dur) = stream.duration {+ if let Ok(d) = dur.parse::<f64>() {+ total_duration += d;+ }+ }+ if let Some(ref frames) = stream.nb_frames {+ if let Ok(f) = frames.parse::<u64>() {+ total_frames += f;+ }+ }+ }+ }+ if total_duration == 0.0 {+ if let Some(ref format) = probe.format {+ if let Some(ref dur) = format.duration {+ if let Ok(d) = dur.parse::<f64>() {+ total_duration += d;+ }+ }+ }+ }+ }+ Err(e) => {+ debug!("Failed to probe segment {:?}: {}", segment, e);+ }+ }+ }++ if width > 0 {+ if total_frames == 0 && fps > 0.0 {+ total_frames = (total_duration * fps) as u64;+ }+ video_info = Some(VideoValidation {+ width,+ height,+ fps,+ duration_secs: total_duration,+ frame_count: total_frames,+ codec,+ });+ } else {+ errors.push("Could not determine video properties from segments".to_string());+ }++ let audio_files = ["audio.ogg", "audio-input.ogg", "mic.ogg"];+ for audio_file in audio_files {+ let audio_path = path.join(audio_file);+ if audio_path.exists() {+ match run_ffprobe(&audio_path) {+ Ok(probe) => {+ for stream in probe.streams {+ if stream.codec_type == "audio" {+ let duration = stream+ .duration+ .as_ref()+ .and_then(|d| d.parse::<f64>().ok())+ .or_else(|| {+ probe+ .format+ .as_ref()+ .and_then(|f| f.duration.as_ref())+ .and_then(|d| d.parse::<f64>().ok())+ })+ .unwrap_or(0.0);++ audio_info = Some(AudioValidation {+ sample_rate: stream+ .sample_rate+ .as_ref()+ .and_then(|s| s.parse().ok())+ .unwrap_or(48000),+ channels: stream.channels.unwrap_or(2) as u16,+ duration_secs: duration,+ codec: stream.codec_name.unwrap_or_else(|| "unknown".to_string()),+ });+ break;+ }+ }+ }+ Err(e) => {+ warn!("Failed to probe audio file {:?}: {}", audio_path, e);+ }+ }+ break;+ }+ }++ if audio_info.is_none() {+ warnings.push("No audio track found".to_string());+ }++ let sync_info = if let (Some(v), Some(a)) = (&video_info, &audio_info) {+ let drift = (v.duration_secs - a.duration_secs).abs() * 1000.0;+ Some(SyncValidation {+ video_duration_secs: v.duration_secs,+ audio_duration_secs: a.duration_secs,+ drift_ms: drift,+ in_sync: drift < 100.0,+ })+ } else {+ None+ };++ Ok((video_info, audio_info, sync_info, errors, warnings))+}++async fn validate_video_file(+ path: &Path,+) -> Result<(+ Option<VideoValidation>,+ Option<AudioValidation>,+ Option<SyncValidation>,+ Vec<String>,+ Vec<String>,+)> {+ let mut errors = Vec::new();+ let mut warnings = Vec::new();+ let mut video_info = None;+ let mut audio_info = None;++ let probe = match run_ffprobe(path) {+ Ok(p) => p,+ Err(e) => {+ errors.push(format!("Failed to probe file: {}", e));+ return Ok((None, None, None, errors, warnings));+ }+ };++ let mut video_start_time = 0.0f64;+ let mut audio_start_time = 0.0f64;++ for stream in &probe.streams {+ match stream.codec_type.as_str() {+ "video" => {+ let fps = stream+ .r_frame_rate+ .as_ref()+ .map(|r| parse_frame_rate(r))+ .or_else(|| stream.avg_frame_rate.as_ref().map(|r| parse_frame_rate(r)))+ .unwrap_or(0.0);++ let duration = stream+ .duration+ .as_ref()+ .and_then(|d| d.parse::<f64>().ok())+ .or_else(|| {+ probe+ .format+ .as_ref()+ .and_then(|f| f.duration.as_ref())+ .and_then(|d| d.parse::<f64>().ok())+ })+ .unwrap_or(0.0);++ let frame_count = stream+ .nb_frames+ .as_ref()+ .and_then(|f| f.parse::<u64>().ok())+ .unwrap_or_else(|| (duration * fps) as u64);++ video_start_time = stream+ .start_time+ .as_ref()+ .and_then(|s| s.parse::<f64>().ok())+ .unwrap_or(0.0);++ video_info = Some(VideoValidation {+ width: stream.width.unwrap_or(0),+ height: stream.height.unwrap_or(0),+ fps,+ duration_secs: duration,+ frame_count,+ codec: stream.codec_name.clone().unwrap_or_default(),+ });+ }+ "audio" => {+ let duration = stream+ .duration+ .as_ref()+ .and_then(|d| d.parse::<f64>().ok())+ .or_else(|| {+ probe+ .format+ .as_ref()+ .and_then(|f| f.duration.as_ref())+ .and_then(|d| d.parse::<f64>().ok())+ })+ .unwrap_or(0.0);++ audio_start_time = stream+ .start_time+ .as_ref()+ .and_then(|s| s.parse::<f64>().ok())+ .unwrap_or(0.0);++ audio_info = Some(AudioValidation {+ sample_rate: stream+ .sample_rate+ .as_ref()+ .and_then(|s| s.parse().ok())+ .unwrap_or(48000),+ channels: stream.channels.unwrap_or(2) as u16,+ duration_secs: duration,+ codec: stream.codec_name.clone().unwrap_or_default(),+ });+ }+ _ => {}+ }+ }++ if video_info.is_none() {+ errors.push("No video stream found in file".to_string());+ }++ if audio_info.is_none() {+ warnings.push("No audio stream found in file".to_string());+ }++ let sync_info = if let (Some(v), Some(a)) = (&video_info, &audio_info) {+ let start_drift_ms = (video_start_time - audio_start_time).abs() * 1000.0;+ let duration_drift_ms = (v.duration_secs - a.duration_secs).abs() * 1000.0;+ let total_drift = start_drift_ms.max(duration_drift_ms);++ Some(SyncValidation {+ video_duration_secs: v.duration_secs,+ audio_duration_secs: a.duration_secs,+ drift_ms: total_drift,+ in_sync: total_drift < 100.0,+ })+ } else {+ None+ };++ Ok((video_info, audio_info, sync_info, errors, warnings))+}diff --git a/package.json b/package.jsonindex 39aa9cfc2..47f69790e 100644--- a/package.json+++ b/package.json@@ -28,6 +28,16 @@"typecheck": "pnpm tsc -b","test": "turbo run test","test:web": "pnpm --filter=@cap/web test",+ "test:discover": "pnpm with-env cargo run -p cap-test -- discover",+ "test:matrix": "pnpm with-env cargo run -p cap-test -- matrix",+ "test:matrix:quick": "pnpm with-env cargo run -p cap-test -- matrix --quick",+ "test:matrix:exhaustive": "pnpm with-env cargo run -p cap-test -- matrix --exhaustive",+ "test:synthetic": "pnpm with-env cargo run -p cap-test -- synthetic",+ "test:benchmark": "pnpm with-env cargo run -p cap-test -- benchmark",+ "test:suite:recording": "pnpm with-env cargo run -p cap-test -- suite recording",+ "test:suite:encoding": "pnpm with-env cargo run -p cap-test -- suite encoding",+ "test:suite:playback": "pnpm with-env cargo run -p cap-test -- suite playback",+ "test:suite:sync": "pnpm with-env cargo run -p cap-test -- suite sync","web": "pnpm --filter=@cap/web","env-setup": "node scripts/env-cli.js","check-tauri-versions": "node scripts/check-tauri-plugin-versions.js",