Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(cap-test): add av-alignment, drift and kill9 crash-test suites

Richie McIlroy129550ee7b6a
diff --git a/crates/cap-test/Cargo.toml b/crates/cap-test/Cargo.toml
index 4209f5056..2c38071d7 100644
--- a/crates/cap-test/Cargo.toml
+++ b/crates/cap-test/Cargo.toml
@@ -44,6 +44,9 @@ parking_lot = "0.12"
workspace-hack = { version = "0.1", path = "../workspace-hack" }
tempfile = "3"
+[target.'cfg(unix)'.dependencies]
+libc = "0.2"
+
[target.'cfg(target_os = "macos")'.dependencies]
cidre = { workspace = true }
diff --git a/crates/cap-test/src/main.rs b/crates/cap-test/src/main.rs
index 054c314c5..c92ff0f77 100644
--- a/crates/cap-test/src/main.rs
+++ b/crates/cap-test/src/main.rs
@@ -111,6 +111,29 @@ enum Commands {
Report {
results: PathBuf,
},
+
+ RecordHarness {
+ #[arg(long)]
+ output: PathBuf,
+
+ #[arg(long)]
+ ready_file: Option<PathBuf>,
+
+ #[arg(long)]
+ display: Option<String>,
+
+ #[arg(long, default_value = "30")]
+ fps: u32,
+
+ #[arg(long, default_value = "600")]
+ max_duration: u64,
+
+ #[arg(long, default_value = "true")]
+ include_mic: bool,
+
+ #[arg(long, default_value = "false")]
+ include_system_audio: bool,
+ },
}
#[tokio::main]
@@ -181,6 +204,27 @@ async fn main() -> Result<()> {
Commands::Report { results } => {
cmd_report(results).await?;
}
+
+ Commands::RecordHarness {
+ output,
+ ready_file,
+ display,
+ fps,
+ max_duration,
+ include_mic,
+ include_system_audio,
+ } => {
+ suites::kill9::run_record_harness(suites::kill9::RecordHarnessArgs {
+ output,
+ ready_file,
+ display_id: display,
+ fps,
+ max_duration_secs: max_duration,
+ include_mic,
+ include_system_audio,
+ })
+ .await?;
+ }
}
Ok(())
@@ -246,9 +290,12 @@ async fn cmd_suite(
suites::run_performance_suite(&hardware, &recording_path, duration).await?
}
"sync" => suites::run_sync_suite(&hardware, duration).await?,
+ "av-alignment" => suites::run_av_alignment_suite(&hardware, duration).await?,
+ "drift" => suites::run_drift_suite(&hardware, duration).await?,
+ "kill9-crash-test" | "kill9" => suites::run_kill9_crash_suite(&hardware, duration).await?,
_ => {
anyhow::bail!(
- "Unknown suite: {}. Available: recording, encoding, playback, performance, sync",
+ "Unknown suite: {}. Available: recording, encoding, playback, performance, sync, av-alignment, drift, kill9-crash-test",
name
);
}
diff --git a/crates/cap-test/src/suites/av_alignment.rs b/crates/cap-test/src/suites/av_alignment.rs
new file mode 100644
index 000000000..db3bae26b
--- /dev/null
+++ b/crates/cap-test/src/suites/av_alignment.rs
@@ -0,0 +1,242 @@
+use anyhow::Result;
+use chrono::Utc;
+use std::path::Path;
+use std::time::{Duration, Instant};
+use tracing::{error, info, warn};
+
+use crate::discovery::DiscoveredHardware;
+use crate::results::{
+ AudioTestConfig, DisplayTestConfig, FrameMetrics, IterationResult, LatencyMetrics, ResultsMeta,
+ ResultsSummary, SyncMetrics, TestCaseConfig, TestResult, TestResults,
+};
+
+use super::ffprobe_ext::{AvAlignmentReading, probe_stream_stats};
+use super::recording_helpers::{StudioRecordingOptions, record_studio_for_duration};
+
+const TARGET_OFFSET_MS: f64 = 21.5;
+
+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();
+
+ let Some(display) = primary_display else {
+ warn!("No display available - skipping AV alignment suite");
+ return Ok(empty_results(hardware, start.elapsed()));
+ };
+
+ let target_fps = 30u32;
+ let duration_secs = duration.max(5);
+
+ let test_config = TestCaseConfig {
+ display: Some(DisplayTestConfig {
+ width: display.physical_width,
+ height: display.physical_height,
+ fps: target_fps,
+ display_id: Some(display.id.clone()),
+ }),
+ camera: None,
+ 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: false,
+ }),
+ duration_secs,
+ };
+
+ let mut result = TestResult::new(
+ format!("av-alignment-{}-{}fps", display.id, target_fps),
+ format!(
+ "AV first-frame alignment {} @{}fps",
+ display.resolution_label(),
+ target_fps
+ ),
+ test_config,
+ );
+
+ match run_single_measurement(display.id.clone(), target_fps, duration_secs).await {
+ Ok(reading) => {
+ let offset_abs_ms = reading.offset_ms.abs();
+ let sync = SyncMetrics {
+ offset_ms: reading.offset_ms,
+ drift_ms: reading.offset_ms,
+ max_drift_ms: offset_abs_ms,
+ };
+
+ if offset_abs_ms > TARGET_OFFSET_MS {
+ result.set_failed(&format!(
+ "First-frame AV offset {:.2}ms exceeds {:.2}ms target (video first={:.4}s audio first={:.4}s)",
+ reading.offset_ms,
+ TARGET_OFFSET_MS,
+ reading.video_first_secs,
+ reading.audio_first_secs,
+ ));
+ } else {
+ info!(
+ "AV alignment pass: offset={:.2}ms (|Δ|={:.2}ms <= {:.2}ms target)",
+ reading.offset_ms, offset_abs_ms, TARGET_OFFSET_MS,
+ );
+ }
+
+ let iteration = IterationResult {
+ iteration: 0,
+ duration_secs: duration_secs as f64,
+ frames: FrameMetrics {
+ received: 0,
+ encoded: 0,
+ dropped: 0,
+ drop_rate_percent: 0.0,
+ effective_fps: 0.0,
+ target_fps,
+ },
+ latency_ms: LatencyMetrics {
+ avg: 0.0,
+ min: 0.0,
+ p50: 0.0,
+ p95: 0.0,
+ p99: 0.0,
+ max: 0.0,
+ },
+ encoding_ms: None,
+ av_sync_ms: Some(sync),
+ errors: vec![],
+ };
+ result.add_iteration(iteration);
+ }
+ Err(e) => {
+ error!("AV alignment measurement failed: {e}");
+ result.set_error(&e.to_string());
+ }
+ }
+
+ results.push(result);
+
+ Ok(TestResults {
+ meta: ResultsMeta {
+ timestamp: Utc::now(),
+ config_name: "AV Alignment Suite".to_string(),
+ config_path: None,
+ platform: hardware.system_info.platform.clone(),
+ system: hardware.system_info.clone(),
+ cap_version: None,
+ },
+ hardware: Some(hardware.clone()),
+ summary: ResultsSummary::from_results(&results, start.elapsed()),
+ results,
+ })
+}
+
+async fn run_single_measurement(
+ display_id: String,
+ target_fps: u32,
+ duration_secs: u64,
+) -> Result<AvAlignmentReading> {
+ let opts = StudioRecordingOptions {
+ display_id: Some(display_id),
+ target_fps,
+ duration: Duration::from_secs(duration_secs),
+ include_mic: true,
+ include_system_audio: true,
+ fragmented: true,
+ };
+
+ let artifacts = record_studio_for_duration(opts).await?;
+
+ let candidate = artifacts
+ .display_outputs
+ .first()
+ .cloned()
+ .ok_or_else(|| anyhow::anyhow!("no display.mp4 produced after recording"))?;
+
+ let stats = probe_stream_stats(&candidate)?;
+ info!(
+ "Probed display output {}: video_frames={:?} video_duration={:?} audio_samples={:?} audio_duration={:?}",
+ candidate.display(),
+ stats.video_frame_count,
+ stats.video_duration_secs,
+ stats.audio_sample_count,
+ stats.audio_duration_secs,
+ );
+
+ let reading = measure_cross_track_av_alignment(&artifacts.project_path)?;
+ drop(artifacts);
+ Ok(reading)
+}
+
+fn measure_cross_track_av_alignment(project_path: &Path) -> Result<AvAlignmentReading> {
+ let meta_path = project_path.join("recording-meta.json");
+ let raw = std::fs::read_to_string(&meta_path)
+ .with_context(|| format!("reading {}", meta_path.display()))?;
+ let meta: serde_json::Value =
+ serde_json::from_str(&raw).context("parsing recording-meta.json")?;
+
+ info!(
+ "recording-meta.json for diagnostic inspection:\n{}",
+ serde_json::to_string_pretty(&meta).unwrap_or_else(|_| raw.clone())
+ );
+
+ let segments = meta
+ .get("segments")
+ .and_then(|v| v.as_array())
+ .ok_or_else(|| anyhow::anyhow!("recording-meta.json missing segments array"))?;
+
+ let segment = segments
+ .first()
+ .ok_or_else(|| anyhow::anyhow!("segments is empty"))?;
+
+ let display_start = read_start_time(segment, "display").unwrap_or(0.0);
+ let system_audio_start = read_start_time(segment, "system_audio");
+ let mic_start = read_start_time(segment, "mic");
+
+ let audio_start = system_audio_start.or(mic_start).ok_or_else(|| {
+ anyhow::anyhow!(
+ "neither system_audio nor mic start_time present — cannot measure AV alignment"
+ )
+ })?;
+
+ let audio_source = if system_audio_start.is_some() {
+ "system_audio"
+ } else {
+ "mic"
+ };
+
+ info!(
+ "Track start_times (secs since recording start): display={display_start:.6} {audio_source}={audio_start:.6}"
+ );
+
+ Ok(AvAlignmentReading {
+ video_first_secs: display_start,
+ audio_first_secs: audio_start,
+ offset_ms: (audio_start - display_start) * 1000.0,
+ })
+}
+
+fn read_start_time(segment: &serde_json::Value, key: &str) -> Option<f64> {
+ segment.get(key)?.get("start_time")?.as_f64()
+}
+
+use anyhow::Context;
+
+fn empty_results(hardware: &DiscoveredHardware, elapsed: Duration) -> TestResults {
+ TestResults {
+ meta: ResultsMeta {
+ timestamp: Utc::now(),
+ config_name: "AV Alignment 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: Vec::new(),
+ summary: ResultsSummary::from_results(&[], elapsed),
+ }
+}
diff --git a/crates/cap-test/src/suites/drift.rs b/crates/cap-test/src/suites/drift.rs
new file mode 100644
index 000000000..9829f9806
--- /dev/null
+++ b/crates/cap-test/src/suites/drift.rs
@@ -0,0 +1,280 @@
+use anyhow::Result;
+use chrono::Utc;
+use std::time::{Duration, Instant};
+use tracing::{error, info, warn};
+
+use crate::discovery::DiscoveredHardware;
+use crate::results::{
+ AudioTestConfig, DisplayTestConfig, FrameMetrics, IterationResult, LatencyMetrics, ResultsMeta,
+ ResultsSummary, SyncMetrics, TestCaseConfig, TestResult, TestResults,
+};
+
+use super::ffprobe_ext::{StreamStats, probe_stream_stats};
+use super::recording_helpers::{StudioRecordingOptions, record_studio_for_duration};
+
+pub const TARGET_DRIFT_MS_PER_MINUTE: f64 = 50.0;
+
+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();
+
+ let Some(display) = primary_display else {
+ warn!("No display available - skipping drift suite");
+ return Ok(empty_results(hardware, start.elapsed()));
+ };
+
+ let target_fps = 30u32;
+ let duration_secs = duration.max(60);
+
+ let test_config = TestCaseConfig {
+ display: Some(DisplayTestConfig {
+ width: display.physical_width,
+ height: display.physical_height,
+ fps: target_fps,
+ display_id: Some(display.id.clone()),
+ }),
+ camera: None,
+ 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: false,
+ }),
+ duration_secs,
+ };
+
+ let mut result = TestResult::new(
+ format!("drift-{}-{}fps-{}s", display.id, target_fps, duration_secs),
+ format!(
+ "A/V drift over {}s {} @{}fps",
+ duration_secs,
+ display.resolution_label(),
+ target_fps
+ ),
+ test_config,
+ );
+
+ match run_drift_measurement(display.id.clone(), target_fps, duration_secs).await {
+ Ok(reading) => {
+ let minutes = duration_secs as f64 / 60.0;
+ let drift_per_minute = if minutes > 0.0 {
+ reading.drift_ms / minutes
+ } else {
+ reading.drift_ms
+ };
+
+ info!(
+ "Drift reading: video_duration={:.3}s audio_duration={:.3}s drift={:.2}ms ({:.2}ms/min)",
+ reading.video_duration_secs,
+ reading.audio_duration_secs,
+ reading.drift_ms,
+ drift_per_minute,
+ );
+
+ if drift_per_minute.abs() > TARGET_DRIFT_MS_PER_MINUTE {
+ result.set_failed(&format!(
+ "Drift {:.2}ms over {:.2}min ({:.2}ms/min) exceeds {:.2}ms/min target",
+ reading.drift_ms, minutes, drift_per_minute, TARGET_DRIFT_MS_PER_MINUTE,
+ ));
+ }
+
+ let iteration = IterationResult {
+ iteration: 0,
+ duration_secs: duration_secs as f64,
+ frames: FrameMetrics {
+ received: reading.video_frame_count.unwrap_or(0),
+ encoded: reading.video_frame_count.unwrap_or(0),
+ dropped: 0,
+ drop_rate_percent: 0.0,
+ effective_fps: reading
+ .video_frame_count
+ .map(|f| f as f64 / duration_secs.max(1) as f64)
+ .unwrap_or(0.0),
+ target_fps,
+ },
+ latency_ms: LatencyMetrics {
+ avg: 0.0,
+ min: 0.0,
+ p50: 0.0,
+ p95: 0.0,
+ p99: 0.0,
+ max: 0.0,
+ },
+ encoding_ms: None,
+ av_sync_ms: Some(SyncMetrics {
+ offset_ms: reading.drift_ms,
+ drift_ms: drift_per_minute,
+ max_drift_ms: reading.drift_ms.abs(),
+ }),
+ errors: vec![],
+ };
+ result.add_iteration(iteration);
+ }
+ Err(e) => {
+ error!("Drift measurement failed: {e}");
+ result.set_error(&e.to_string());
+ }
+ }
+
+ results.push(result);
+
+ Ok(TestResults {
+ meta: ResultsMeta {
+ timestamp: Utc::now(),
+ config_name: "Drift Suite".to_string(),
+ config_path: None,
+ platform: hardware.system_info.platform.clone(),
+ system: hardware.system_info.clone(),
+ cap_version: None,
+ },
+ hardware: Some(hardware.clone()),
+ summary: ResultsSummary::from_results(&results, start.elapsed()),
+ results,
+ })
+}
+
+struct DriftReading {
+ video_duration_secs: f64,
+ audio_duration_secs: f64,
+ drift_ms: f64,
+ video_frame_count: Option<u64>,
+}
+
+async fn run_drift_measurement(
+ display_id: String,
+ target_fps: u32,
+ duration_secs: u64,
+) -> Result<DriftReading> {
+ let opts = StudioRecordingOptions {
+ display_id: Some(display_id),
+ target_fps,
+ duration: Duration::from_secs(duration_secs),
+ include_mic: true,
+ include_system_audio: false,
+ fragmented: true,
+ };
+
+ let artifacts = record_studio_for_duration(opts).await?;
+
+ let mut video_stats_total = StreamStats::default();
+ let mut video_segments = 0u32;
+ for path in &artifacts.display_outputs {
+ match probe_stream_stats(path) {
+ Ok(stats) => {
+ video_stats_total.video_frame_count = Some(
+ video_stats_total.video_frame_count.unwrap_or(0)
+ + stats.video_frame_count.unwrap_or(0),
+ );
+ video_stats_total.video_duration_secs = Some(
+ video_stats_total.video_duration_secs.unwrap_or(0.0)
+ + stats.video_duration_secs.unwrap_or(0.0),
+ );
+ video_stats_total.video_fps = video_stats_total.video_fps.or(stats.video_fps);
+ video_segments += 1;
+ }
+ Err(err) => warn!(
+ "Failed to probe display segment {}: {}",
+ path.display(),
+ err
+ ),
+ }
+ }
+
+ if video_segments == 0 {
+ anyhow::bail!("no playable display outputs produced for drift measurement");
+ }
+
+ let mut audio_duration = 0.0f64;
+ let mut audio_samples_total = 0u64;
+ let mut audio_sample_rate = None;
+ for audio_path in find_audio_track_files(&artifacts.project_path) {
+ match probe_stream_stats(&audio_path) {
+ Ok(stats) => {
+ audio_duration += stats.audio_duration_secs.unwrap_or(0.0);
+ audio_samples_total += stats.audio_sample_count.unwrap_or(0);
+ audio_sample_rate = audio_sample_rate.or(stats.audio_sample_rate);
+ }
+ Err(err) => warn!(
+ "Failed to probe audio file {}: {}",
+ audio_path.display(),
+ err
+ ),
+ }
+ }
+
+ if audio_duration <= 0.0 {
+ warn!(
+ "No audio durations measured across {} display segment(s) — drift will compare video-only",
+ video_segments
+ );
+ }
+
+ let video_duration = video_stats_total.video_duration_secs.unwrap_or(0.0);
+ let drift_ms = (video_duration - audio_duration) * 1000.0;
+
+ info!(
+ "Drift inputs: video_segments={video_segments} audio_samples={audio_samples_total} audio_rate={:?}",
+ audio_sample_rate
+ );
+
+ Ok(DriftReading {
+ video_duration_secs: video_duration,
+ audio_duration_secs: audio_duration,
+ drift_ms,
+ video_frame_count: video_stats_total.video_frame_count,
+ })
+}
+
+fn find_audio_track_files(project_path: &std::path::Path) -> Vec<std::path::PathBuf> {
+ use std::fs;
+ let mut tracks = Vec::new();
+
+ let segments_root = project_path.join("content").join("segments");
+ let Ok(segments) = fs::read_dir(&segments_root) else {
+ return tracks;
+ };
+
+ for segment_entry in segments.flatten() {
+ let segment_dir = segment_entry.path();
+ if !segment_dir.is_dir() {
+ continue;
+ }
+ for candidate in [
+ "audio-input.ogg",
+ "audio-input.m4a",
+ "system_audio.ogg",
+ "system_audio.m4a",
+ ] {
+ let path = segment_dir.join(candidate);
+ if path.exists() {
+ tracks.push(path);
+ }
+ }
+ }
+
+ tracks
+}
+
+fn empty_results(hardware: &DiscoveredHardware, elapsed: Duration) -> TestResults {
+ TestResults {
+ meta: ResultsMeta {
+ timestamp: Utc::now(),
+ config_name: "Drift 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: Vec::new(),
+ summary: ResultsSummary::from_results(&[], elapsed),
+ }
+}
diff --git a/crates/cap-test/src/suites/ffprobe_ext.rs b/crates/cap-test/src/suites/ffprobe_ext.rs
new file mode 100644
index 000000000..81528ef4f
--- /dev/null
+++ b/crates/cap-test/src/suites/ffprobe_ext.rs
@@ -0,0 +1,154 @@
+use anyhow::{Context, Result};
+use serde::Deserialize;
+use std::path::Path;
+use std::process::Command;
+
+#[derive(Debug, Deserialize)]
+struct StreamsEnvelope {
+ streams: Vec<StreamEntry>,
+ format: Option<FormatEntry>,
+}
+
+#[derive(Debug, Deserialize)]
+struct StreamEntry {
+ codec_type: String,
+ nb_frames: Option<String>,
+ nb_read_packets: Option<String>,
+ sample_rate: Option<String>,
+ duration: Option<String>,
+ r_frame_rate: Option<String>,
+ avg_frame_rate: Option<String>,
+ channels: Option<u32>,
+}
+
+#[derive(Debug, Deserialize)]
+struct FormatEntry {
+ duration: Option<String>,
+}
+
+#[derive(Debug, Clone)]
+pub struct AvAlignmentReading {
+ pub video_first_secs: f64,
+ pub audio_first_secs: f64,
+ pub offset_ms: f64,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct StreamStats {
+ pub video_frame_count: Option<u64>,
+ pub video_duration_secs: Option<f64>,
+ pub video_fps: Option<f64>,
+ pub audio_sample_count: Option<u64>,
+ pub audio_sample_rate: Option<u32>,
+ pub audio_channels: Option<u32>,
+ pub audio_duration_secs: Option<f64>,
+ pub container_duration_secs: Option<f64>,
+}
+
+fn parse_frame_rate(rate: &str) -> Option<f64> {
+ if let Some((num, den)) = rate.split_once('/') {
+ let num: f64 = num.parse().ok()?;
+ let den: f64 = den.parse().ok()?;
+ if den > 0.0 {
+ return Some(num / den);
+ }
+ }
+ rate.parse().ok()
+}
+
+pub fn probe_stream_stats(path: &Path) -> Result<StreamStats> {
+ let output = Command::new("ffprobe")
+ .args([
+ "-v",
+ "quiet",
+ "-print_format",
+ "json",
+ "-show_format",
+ "-show_streams",
+ "-count_packets",
+ ])
+ .arg(path)
+ .output()
+ .context("Failed to run ffprobe for stream stats")?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ anyhow::bail!("ffprobe stream stats failed: {stderr}");
+ }
+
+ let json = String::from_utf8_lossy(&output.stdout);
+ let parsed: StreamsEnvelope =
+ serde_json::from_str(&json).context("Failed to parse ffprobe streams envelope")?;
+
+ let mut stats = StreamStats {
+ container_duration_secs: parsed
+ .format
+ .as_ref()
+ .and_then(|f| f.duration.as_deref())
+ .and_then(|d| d.parse::<f64>().ok()),
+ ..Default::default()
+ };
+
+ for stream in parsed.streams {
+ match stream.codec_type.as_str() {
+ "video" => {
+ stats.video_frame_count = stream
+ .nb_frames
+ .as_deref()
+ .and_then(|s| s.parse::<u64>().ok())
+ .or_else(|| {
+ stream
+ .nb_read_packets
+ .as_deref()
+ .and_then(|s| s.parse::<u64>().ok())
+ });
+ stats.video_duration_secs = stream
+ .duration
+ .as_deref()
+ .and_then(|d| d.parse::<f64>().ok())
+ .or(stats.container_duration_secs);
+ stats.video_fps = stream
+ .r_frame_rate
+ .as_deref()
+ .and_then(parse_frame_rate)
+ .or_else(|| stream.avg_frame_rate.as_deref().and_then(parse_frame_rate))
+ .filter(|f| *f > 0.0 && *f < 1000.0);
+ }
+ "audio" => {
+ stats.audio_sample_rate = stream
+ .sample_rate
+ .as_deref()
+ .and_then(|s| s.parse::<u32>().ok());
+ stats.audio_channels = stream.channels;
+ stats.audio_duration_secs = stream
+ .duration
+ .as_deref()
+ .and_then(|d| d.parse::<f64>().ok())
+ .or(stats.container_duration_secs);
+ if let (Some(rate), Some(dur)) =
+ (stats.audio_sample_rate, stats.audio_duration_secs)
+ {
+ stats.audio_sample_count = Some((dur * rate as f64).round() as u64);
+ }
+ }
+ _ => {}
+ }
+ }
+
+ Ok(stats)
+}
+
+pub fn verify_playable(path: &Path) -> Result<()> {
+ let output = Command::new("ffprobe")
+ .args(["-v", "error", "-show_streams", "-show_format"])
+ .arg(path)
+ .output()
+ .context("Failed to run ffprobe for playability check")?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ anyhow::bail!("ffprobe playability check failed: {stderr}");
+ }
+
+ Ok(())
+}
diff --git a/crates/cap-test/src/suites/kill9.rs b/crates/cap-test/src/suites/kill9.rs
new file mode 100644
index 000000000..3c640e1f3
--- /dev/null
+++ b/crates/cap-test/src/suites/kill9.rs
@@ -0,0 +1,360 @@
+use anyhow::{Context, Result};
+use chrono::Utc;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+use tempfile::TempDir;
+use tracing::{info, warn};
+
+use crate::discovery::DiscoveredHardware;
+use crate::results::{
+ DisplayTestConfig, FrameMetrics, IterationResult, LatencyMetrics, ResultsMeta, ResultsSummary,
+ TestCaseConfig, TestResult, TestResults,
+};
+
+use super::ffprobe_ext::verify_playable;
+use super::recording_helpers::materialize_display_outputs;
+
+const READY_POLL_INTERVAL: Duration = Duration::from_millis(200);
+const READY_WAIT_TIMEOUT: Duration = Duration::from_secs(30);
+
+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 Some(display) = primary_display else {
+ warn!("No display available - skipping kill9 crash test suite");
+ return Ok(empty_results(hardware, start.elapsed()));
+ };
+
+ let target_fps = 30u32;
+ let duration_secs = duration.max(5);
+
+ let test_config = TestCaseConfig {
+ display: Some(DisplayTestConfig {
+ width: display.physical_width,
+ height: display.physical_height,
+ fps: target_fps,
+ display_id: Some(display.id.clone()),
+ }),
+ camera: None,
+ audio: None,
+ duration_secs,
+ };
+
+ let mut result = TestResult::new(
+ format!("kill9-crash-{}-{}s", display.id, duration_secs),
+ format!(
+ "SIGKILL mid-recording crash recovery {} @{}fps",
+ display.resolution_label(),
+ target_fps
+ ),
+ test_config,
+ );
+
+ match run_single_kill9(&display.id, target_fps, duration_secs).await {
+ Ok(report) => {
+ info!(
+ "Kill9 scenario: recovered_segments={} total_duration_secs={:.2} playable={}",
+ report.recovered_segment_count, report.total_duration_secs, report.playable,
+ );
+
+ if !report.playable {
+ result.set_failed(&format!(
+ "Recovered recording not playable: {}",
+ report.failure_reason.unwrap_or_default()
+ ));
+ } else if report.total_duration_secs < (duration_secs as f64 * 0.5) {
+ result.set_failed(&format!(
+ "Recovered duration {:.2}s below 50% of wall-clock {}s",
+ report.total_duration_secs, duration_secs
+ ));
+ }
+
+ let iteration = IterationResult {
+ iteration: 0,
+ duration_secs: report.total_duration_secs,
+ frames: FrameMetrics {
+ received: 0,
+ encoded: 0,
+ dropped: 0,
+ drop_rate_percent: 0.0,
+ effective_fps: 0.0,
+ target_fps,
+ },
+ latency_ms: LatencyMetrics {
+ avg: 0.0,
+ min: 0.0,
+ p50: 0.0,
+ p95: 0.0,
+ p99: 0.0,
+ max: 0.0,
+ },
+ encoding_ms: None,
+ av_sync_ms: None,
+ errors: vec![],
+ };
+ result.add_iteration(iteration);
+ }
+ Err(err) => {
+ warn!("kill9 scenario harness failed: {err}");
+ result.set_error(&err.to_string());
+ }
+ }
+
+ results.push(result);
+
+ Ok(TestResults {
+ meta: ResultsMeta {
+ timestamp: Utc::now(),
+ config_name: "Kill9 Crash Suite".to_string(),
+ config_path: None,
+ platform: hardware.system_info.platform.clone(),
+ system: hardware.system_info.clone(),
+ cap_version: None,
+ },
+ hardware: Some(hardware.clone()),
+ summary: ResultsSummary::from_results(&results, start.elapsed()),
+ results,
+ })
+}
+
+struct Kill9Report {
+ recovered_segment_count: usize,
+ total_duration_secs: f64,
+ playable: bool,
+ failure_reason: Option<String>,
+}
+
+async fn run_single_kill9(
+ display_id: &str,
+ target_fps: u32,
+ kill_after_secs: u64,
+) -> Result<Kill9Report> {
+ let temp_dir = TempDir::new()?;
+ let project_path = temp_dir.path().join("kill9-project");
+ std::fs::create_dir_all(&project_path)?;
+
+ let ready_file = temp_dir.path().join("harness-ready.flag");
+ let cap_test_bin = std::env::current_exe().context("failed to resolve current exe path")?;
+
+ let mut child = Command::new(&cap_test_bin)
+ .arg("record-harness")
+ .arg("--output")
+ .arg(&project_path)
+ .arg("--ready-file")
+ .arg(&ready_file)
+ .arg("--display")
+ .arg(display_id)
+ .arg("--fps")
+ .arg(target_fps.to_string())
+ .arg("--max-duration")
+ .arg((kill_after_secs * 10).to_string())
+ .stdin(Stdio::null())
+ .stdout(Stdio::inherit())
+ .stderr(Stdio::inherit())
+ .spawn()
+ .context("failed to spawn record-harness child process")?;
+
+ let child_pid = child.id() as i32;
+ info!(
+ "Spawned record-harness child pid={child_pid} at {}",
+ project_path.display()
+ );
+
+ let ready = wait_for_ready(&ready_file, READY_WAIT_TIMEOUT).await;
+
+ if !ready {
+ let _ = child.kill();
+ let _ = child.wait();
+ anyhow::bail!(
+ "record-harness child never signaled ready within {:?}",
+ READY_WAIT_TIMEOUT
+ );
+ }
+
+ tokio::time::sleep(Duration::from_secs(kill_after_secs)).await;
+
+ info!("Sending SIGKILL to record-harness child pid={child_pid}");
+ send_sigkill(child_pid)?;
+
+ let exit_status = child
+ .wait()
+ .context("failed waiting for record-harness child")?;
+ info!("record-harness child exited: {exit_status:?}");
+
+ let outputs = materialize_display_outputs(&project_path)?;
+ if outputs.is_empty() {
+ return Ok(Kill9Report {
+ recovered_segment_count: 0,
+ total_duration_secs: 0.0,
+ playable: false,
+ failure_reason: Some("no display.mp4 produced after recovery".to_string()),
+ });
+ }
+
+ let mut total_duration = 0.0f64;
+ let mut playable = true;
+ let mut failure_reason: Option<String> = None;
+
+ for output in &outputs {
+ match verify_playable(output) {
+ Ok(()) => {
+ if let Ok(stats) = super::ffprobe_ext::probe_stream_stats(output) {
+ total_duration += stats
+ .video_duration_secs
+ .or(stats.container_duration_secs)
+ .unwrap_or(0.0);
+ }
+ }
+ Err(err) => {
+ playable = false;
+ failure_reason = Some(format!("{}: {}", output.display(), err));
+ }
+ }
+ }
+
+ Ok(Kill9Report {
+ recovered_segment_count: outputs.len(),
+ total_duration_secs: total_duration,
+ playable,
+ failure_reason,
+ })
+}
+
+async fn wait_for_ready(ready_file: &Path, timeout: Duration) -> bool {
+ let start = Instant::now();
+ while start.elapsed() < timeout {
+ if ready_file.exists() {
+ return true;
+ }
+ tokio::time::sleep(READY_POLL_INTERVAL).await;
+ }
+ false
+}
+
+#[cfg(unix)]
+fn send_sigkill(pid: i32) -> Result<()> {
+ let result = unsafe { libc::kill(pid, libc::SIGKILL) };
+ if result != 0 {
+ let err = std::io::Error::last_os_error();
+ anyhow::bail!("kill(pid={pid}, SIGKILL) failed: {err}");
+ }
+ Ok(())
+}
+
+#[cfg(windows)]
+fn send_sigkill(pid: i32) -> Result<()> {
+ let output = Command::new("taskkill")
+ .args(["/F", "/T", "/PID"])
+ .arg(pid.to_string())
+ .output()
+ .context("failed to invoke taskkill")?;
+ if !output.status.success() {
+ anyhow::bail!(
+ "taskkill /F failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+ Ok(())
+}
+
+fn empty_results(hardware: &DiscoveredHardware, elapsed: Duration) -> TestResults {
+ TestResults {
+ meta: ResultsMeta {
+ timestamp: Utc::now(),
+ config_name: "Kill9 Crash 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: Vec::new(),
+ summary: ResultsSummary::from_results(&[], elapsed),
+ }
+}
+
+pub struct RecordHarnessArgs {
+ pub output: PathBuf,
+ pub ready_file: Option<PathBuf>,
+ pub display_id: Option<String>,
+ pub fps: u32,
+ pub max_duration_secs: u64,
+ pub include_mic: bool,
+ pub include_system_audio: bool,
+}
+
+pub async fn run_record_harness(args: RecordHarnessArgs) -> Result<()> {
+ use super::recording_helpers::{StudioRecordingOptions, record_studio_at_path};
+
+ if !args.output.exists() {
+ std::fs::create_dir_all(&args.output)?;
+ }
+
+ if let Some(ready_file) = args.ready_file.as_ref() {
+ spawn_ready_signal_writer(ready_file.clone(), args.output.clone());
+ }
+
+ let opts = StudioRecordingOptions {
+ display_id: args.display_id,
+ target_fps: args.fps,
+ duration: Duration::from_secs(args.max_duration_secs),
+ include_mic: args.include_mic,
+ include_system_audio: args.include_system_audio,
+ fragmented: true,
+ };
+
+ info!(
+ "record-harness: recording to {} for up to {}s",
+ args.output.display(),
+ args.max_duration_secs
+ );
+
+ let _ = record_studio_at_path(opts, args.output).await?;
+ Ok(())
+}
+
+fn spawn_ready_signal_writer(ready_file: PathBuf, output_path: PathBuf) {
+ tokio::spawn(async move {
+ let segments_dir = output_path.join("content").join("segments");
+ let start = Instant::now();
+ loop {
+ if start.elapsed() > Duration::from_secs(60) {
+ warn!("record-harness: ready signal timed out waiting for segments dir");
+ return;
+ }
+
+ if segments_dir.is_dir() {
+ let has_fragment = std::fs::read_dir(&segments_dir)
+ .map(|entries| {
+ entries.filter_map(|e| e.ok()).any(|e| {
+ let path = e.path();
+ path.is_dir()
+ && path
+ .join("display")
+ .read_dir()
+ .map(|frag_entries| frag_entries.count() > 0)
+ .unwrap_or(false)
+ })
+ })
+ .unwrap_or(false);
+
+ if has_fragment && let Err(err) = std::fs::write(&ready_file, b"ready") {
+ warn!("record-harness: failed to write ready file: {err}");
+ }
+ if has_fragment {
+ return;
+ }
+ }
+
+ tokio::time::sleep(Duration::from_millis(250)).await;
+ }
+ });
+}
diff --git a/crates/cap-test/src/suites/mod.rs b/crates/cap-test/src/suites/mod.rs
index c5e751fac..9cf3f0561 100644
--- a/crates/cap-test/src/suites/mod.rs
+++ b/crates/cap-test/src/suites/mod.rs
@@ -1,7 +1,12 @@
+mod av_alignment;
+mod drift;
mod encoding;
+pub mod ffprobe_ext;
+pub mod kill9;
mod performance;
mod playback;
mod recording;
+pub(crate) mod recording_helpers;
pub mod scenarios;
mod sync;
pub(crate) mod validate;
@@ -48,6 +53,24 @@ pub async fn run_sync_suite(hardware: &DiscoveredHardware, duration: u64) -> Res
sync::run_suite(hardware, duration).await
}
+pub async fn run_av_alignment_suite(
+ hardware: &DiscoveredHardware,
+ duration: u64,
+) -> Result<TestResults> {
+ av_alignment::run_suite(hardware, duration).await
+}
+
+pub async fn run_drift_suite(hardware: &DiscoveredHardware, duration: u64) -> Result<TestResults> {
+ drift::run_suite(hardware, duration).await
+}
+
+pub async fn run_kill9_crash_suite(
+ hardware: &DiscoveredHardware,
+ duration: u64,
+) -> Result<TestResults> {
+ kill9::run_suite(hardware, duration).await
+}
+
pub async fn run_benchmark(
hardware: &DiscoveredHardware,
duration: u64,
diff --git a/crates/cap-test/src/suites/recording_helpers.rs b/crates/cap-test/src/suites/recording_helpers.rs
new file mode 100644
index 000000000..ab023b6ea
--- /dev/null
+++ b/crates/cap-test/src/suites/recording_helpers.rs
@@ -0,0 +1,175 @@
+use anyhow::{Context, Result};
+use cpal::StreamError;
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use std::time::Duration;
+use tempfile::TempDir;
+use tracing::{info, warn};
+
+pub struct RecordedArtifacts {
+ #[allow(dead_code)]
+ pub project_path: PathBuf,
+ pub display_outputs: Vec<PathBuf>,
+ #[allow(dead_code)]
+ pub held_temp_dir: Option<TempDir>,
+}
+
+pub struct StudioRecordingOptions {
+ pub display_id: Option<String>,
+ pub target_fps: u32,
+ pub duration: Duration,
+ pub include_mic: bool,
+ pub include_system_audio: bool,
+ pub fragmented: bool,
+}
+
+impl Default for StudioRecordingOptions {
+ fn default() -> Self {
+ Self {
+ display_id: None,
+ target_fps: 30,
+ duration: Duration::from_secs(10),
+ include_mic: true,
+ include_system_audio: true,
+ fragmented: true,
+ }
+ }
+}
+
+pub async fn record_studio_for_duration(opts: StudioRecordingOptions) -> Result<RecordedArtifacts> {
+ let temp_dir = TempDir::new()?;
+ let project_path = temp_dir.path().to_path_buf();
+ let completed_path = record_studio_at_path(opts, project_path).await?;
+
+ let display_outputs = materialize_display_outputs(&completed_path)?;
+
+ Ok(RecordedArtifacts {
+ project_path: completed_path,
+ display_outputs,
+ held_temp_dir: Some(temp_dir),
+ })
+}
+
+pub async fn record_studio_at_path(
+ mut opts: StudioRecordingOptions,
+ project_path: PathBuf,
+) -> Result<PathBuf> {
+ use cap_recording::{MicrophoneFeed, screen_capture::ScreenCaptureTarget, studio_recording};
+ use kameo::Actor as _;
+ use scap_targets::Display;
+
+ let display = if let Some(ref id) = opts.display_id {
+ use std::str::FromStr;
+ scap_targets::DisplayId::from_str(id)
+ .ok()
+ .and_then(|id| Display::from_id(&id))
+ .unwrap_or_else(Display::primary)
+ } else {
+ Display::primary()
+ };
+
+ #[cfg(target_os = "macos")]
+ let shareable_content = cidre::sc::ShareableContent::current()
+ .await
+ .context("Failed to get shareable content - check screen recording permissions")
+ .map(cap_recording::SendableShareableContent::from)?;
+
+ let (error_tx, _error_rx) = flume::bounded::<StreamError>(16);
+
+ let mic_lock = if opts.include_mic {
+ 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
+ };
+
+ opts.include_mic = mic_lock.is_some();
+
+ let mut builder = studio_recording::Actor::builder(
+ project_path.clone(),
+ ScreenCaptureTarget::Display { id: display.id() },
+ )
+ .with_max_fps(opts.target_fps)
+ .with_fragmented(opts.fragmented);
+
+ if opts.include_system_audio {
+ builder = builder.with_system_audio(true);
+ }
+
+ if let Some(mic) = mic_lock {
+ builder = builder.with_mic_feed(mic);
+ }
+
+ let handle = builder
+ .build(
+ #[cfg(target_os = "macos")]
+ Some(shareable_content),
+ )
+ .await
+ .context("Failed to start recording")?;
+
+ info!(
+ "Recording for {}s at {}fps -> {}",
+ opts.duration.as_secs(),
+ opts.target_fps,
+ project_path.display()
+ );
+
+ tokio::time::sleep(opts.duration).await;
+
+ let completed = handle.stop().await.context("Failed to stop recording")?;
+ Ok(completed.project_path)
+}
+
+pub fn materialize_display_outputs(project_path: &Path) -> Result<Vec<PathBuf>> {
+ use cap_recording::recovery::RecoveryManager;
+
+ if let Some(incomplete) = RecoveryManager::inspect_recording(project_path) {
+ match RecoveryManager::recover(&incomplete) {
+ Ok(_) => {}
+ Err(err) => {
+ warn!(
+ "Recovery attempt on recorded project returned: {}. \
+ Continuing with any existing display.mp4 files.",
+ err
+ );
+ }
+ }
+ }
+
+ let mut outputs = Vec::new();
+ let content_dir = project_path.join("content");
+ let segments_dir = content_dir.join("segments");
+ if segments_dir.is_dir() {
+ let mut entries: Vec<_> = std::fs::read_dir(&segments_dir)?
+ .filter_map(|r| r.ok())
+ .map(|e| e.path())
+ .filter(|p| p.is_dir())
+ .collect();
+ entries.sort();
+ for entry in entries {
+ let candidate = entry.join("display.mp4");
+ if candidate.exists() {
+ outputs.push(candidate);
+ }
+ }
+ }
+ let legacy = content_dir.join("display.mp4");
+ if legacy.exists() {
+ outputs.push(legacy);
+ }
+
+ Ok(outputs)
+}