Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add playback and device test runners on Windows

Richie McIlroy8668815ee963
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index d8dec93d6..75320936e 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -72,7 +72,20 @@
"Bash(sysctl:*)",
"Bash(CAP_VIDEO_SOURCE_BUFFER_SIZE=4800 CAP_MUXER_BUFFER_SIZE=4800 RUST_LOG=warn cargo run:*)",
"Bash(RUST_LOG=cap_enc_ffmpeg::video::h264=debug cargo run:*)",
- "Bash(CAP_VIDEO_SOURCE_BUFFER_SIZE=5400 CAP_MUXER_BUFFER_SIZE=5400 RUST_LOG=info cargo run:*)"
+ "Bash(CAP_VIDEO_SOURCE_BUFFER_SIZE=5400 CAP_MUXER_BUFFER_SIZE=5400 RUST_LOG=info cargo run:*)",
+ "Bash(target\\release\\examples\\real-device-test-runner.exe:*)",
+ "Bash(./target/release/examples/real-device-test-runner.exe:*)",
+ "Bash(.\\target\\release\\examples\\real-device-test-runner.exe:*)",
+ "Bash(for dir in /c/Users/Richie/AppData/Local/Temp/cap-real-device-tests/*/)",
+ "Bash(for segment in \"$dir\"content/segments/*/)",
+ "Bash(do if [ -d \"$segment\" ])",
+ "Bash(if [ -f \"$segment/output.mp4\" ])",
+ "Bash(then ffprobe -v error -show_entries format=duration -of default=nw=1 \"$segment/output.mp4\")",
+ "Bash(fi)",
+ "Bash(if [ -f \"$segment/audio.ogg\" ])",
+ "Bash(then ffprobe -v error -show_entries format=duration -of default=nw=1 \"$segment/audio.ogg\")",
+ "Bash(done)",
+ "Bash(./target/release/examples/real-device-test-runner:*)"
],
"deny": [],
"ask": []
diff --git a/Cargo.lock b/Cargo.lock
index 76275d6f4..590617b7d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1679,6 +1679,7 @@ dependencies = [
"ffmpeg-hw-device",
"ffmpeg-next",
"num_cpus",
+ "tempfile",
"tokio",
"tracing",
"windows 0.60.0",
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index b14f88498..40623119e 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -372,6 +372,7 @@ uploadProgressEvent: "upload-progress-event"
/** user-defined types **/
+export type AllGpusInfo = { gpus: GpuInfoDiag[]; primaryGpuIndex: number | null; isMultiGpuSystem: boolean; hasDiscreteGpu: boolean }
export type Annotation = { id: string; type: AnnotationType; x: number; y: number; width: number; height: number; strokeColor: string; strokeWidth: number; fillColor: string; opacity: number; rotation: number; text: string | null; maskType?: MaskType | null; maskLevel?: number | null }
export type AnnotationType = "arrow" | "circle" | "rectangle" | "text" | "mask"
export type AppTheme = "system" | "light" | "dark"
@@ -440,6 +441,7 @@ quality: number | null;
* Whether to prioritize speed over quality (default: false)
*/
fast: boolean | null }
+export type GpuInfoDiag = { vendor: string; description: string; dedicatedVideoMemoryMb: number; adapterIndex: number; isSoftwareAdapter: boolean; isBasicRenderDriver: boolean; supportsHardwareEncoding: boolean }
export type HapticPattern = "alignment" | "levelChange" | "generic"
export type HapticPerformanceTime = "default" | "now" | "drawCompleted"
export type Hotkey = { code: string; meta: boolean; ctrl: boolean; alt: boolean; shift: boolean }
@@ -452,7 +454,6 @@ export type JsonValue<T> = [T]
export type LogicalBounds = { position: LogicalPosition; size: LogicalSize }
export type LogicalPosition = { x: number; y: number }
export type LogicalSize = { width: number; height: number }
-export type MacOSVersionInfo = { displayName: string }
export type MainWindowRecordingStartBehaviour = "close" | "minimise"
export type MaskKeyframes = { position?: MaskVectorKeyframe[]; size?: MaskVectorKeyframe[]; intensity?: MaskScalarKeyframe[] }
export type MaskKind = "sensitive" | "highlight"
@@ -495,6 +496,7 @@ export type RecordingStatus = "pending" | "recording"
export type RecordingStopped = null
export type RecordingTargetMode = "display" | "window" | "area"
export type RenderFrameEvent = { frame_number: number; fps: number; resolution_base: XY<number> }
+export type RenderingStatus = { isUsingSoftwareRendering: boolean; isUsingBasicRenderDriver: boolean; hardwareEncodingAvailable: boolean; warningMessage: string | null }
export type RequestOpenRecordingPicker = { target_mode: RecordingTargetMode | null }
export type RequestOpenSettings = { page: string }
export type RequestScreenCapturePrewarm = { force?: boolean }
@@ -515,7 +517,7 @@ export type StartRecordingInputs = { capture_target: ScreenCaptureTarget; captur
export type StereoMode = "stereo" | "monoL" | "monoR"
export type StudioRecordingMeta = { segment: SingleSegment } | { inner: MultipleSegments }
export type StudioRecordingStatus = { status: "InProgress" } | { status: "NeedsRemux" } | { status: "Failed"; error: string } | { status: "Complete" }
-export type SystemDiagnostics = { macosVersion: MacOSVersionInfo | null; availableEncoders: string[]; screenCaptureSupported: boolean }
+export type SystemDiagnostics = { windowsVersion: WindowsVersionInfo | null; gpuInfo: GpuInfoDiag | null; allGpus: AllGpusInfo | null; renderingStatus: RenderingStatus; availableEncoders: string[]; graphicsCaptureSupported: boolean; d3D11VideoProcessorAvailable: boolean }
export type TargetUnderCursor = { display_id: DisplayId | null; window: WindowUnderCursor | null }
export type TextSegment = { start: number; end: number; enabled?: boolean; content?: string; center?: XY<number>; size?: XY<number>; fontFamily?: string; fontSize?: number; fontWeight?: number; italic?: boolean; color?: string; fadeDuration?: number }
export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[]; sceneSegments?: SceneSegment[]; maskSegments?: MaskSegment[]; textSegments?: TextSegment[] }
@@ -532,6 +534,7 @@ export type VideoUploadInfo = { id: string; link: string; config: S3UploadMeta }
export type WindowExclusion = { bundleIdentifier?: string | null; ownerName?: string | null; windowTitle?: string | null }
export type WindowId = string
export type WindowUnderCursor = { id: WindowId; app_name: string; bounds: LogicalBounds }
+export type WindowsVersionInfo = { major: number; minor: number; build: number; displayName: string; meetsRequirements: boolean; isWindows11: boolean }
export type XY<T> = { x: T; y: T }
export type ZoomMode = "auto" | { manual: { x: number; y: number } }
export type ZoomSegment = { start: number; end: number; amount: number; mode: ZoomMode }
diff --git a/crates/enc-ffmpeg/src/mux/segmented_stream.rs b/crates/enc-ffmpeg/src/mux/segmented_stream.rs
index 78b678634..52218dc68 100644
--- a/crates/enc-ffmpeg/src/mux/segmented_stream.rs
+++ b/crates/enc-ffmpeg/src/mux/segmented_stream.rs
@@ -336,89 +336,53 @@ impl SegmentedVideoEncoder {
frame: frame::Video,
timestamp: Duration,
) -> Result<(), QueueFrameError> {
- if self.segment_start_time.is_none() {
- self.segment_start_time = Some(timestamp);
- }
+ let segment_start = match self.segment_start_time {
+ Some(start) => start,
+ None => {
+ self.segment_start_time = Some(timestamp);
+ timestamp
+ }
+ };
self.last_frame_timestamp = Some(timestamp);
- let prev_segment_index = self.detect_current_segment_index();
-
self.encoder
.queue_frame(frame, timestamp, &mut self.output)?;
self.frames_in_segment += 1;
- let new_segment_index = self.detect_current_segment_index();
-
- if new_segment_index > prev_segment_index {
- self.on_segment_completed(prev_segment_index, timestamp)?;
+ let elapsed_in_segment = timestamp.saturating_sub(segment_start);
+ if elapsed_in_segment >= self.segment_duration {
+ self.on_segment_boundary(self.current_index, timestamp);
}
Ok(())
}
- fn detect_current_segment_index(&self) -> u32 {
- let next_segment_path = self
- .base_path
- .join(format!("segment_{:03}.m4s", self.current_index + 1));
- if next_segment_path.exists() {
- self.current_index + 1
- } else {
- self.current_index
- }
- }
+ fn on_segment_boundary(&mut self, completed_index: u32, timestamp: Duration) {
+ let segment_start = self.segment_start_time.unwrap_or(Duration::ZERO);
+ let segment_duration = timestamp.saturating_sub(segment_start);
- fn on_segment_completed(
- &mut self,
- completed_index: u32,
- timestamp: Duration,
- ) -> Result<(), QueueFrameError> {
let segment_path = self
.base_path
.join(format!("segment_{completed_index:03}.m4s"));
- if segment_path.exists() {
- sync_file(&segment_path);
-
- let segment_start = self.segment_start_time.unwrap_or(Duration::ZERO);
- let segment_duration = timestamp.saturating_sub(segment_start);
-
- let file_size = std::fs::metadata(&segment_path).ok().map(|m| m.len());
-
- tracing::debug!(
- segment_index = completed_index,
- duration_secs = segment_duration.as_secs_f64(),
- file_size = ?file_size,
- frames = self.frames_in_segment,
- "Segment completed"
- );
-
- self.completed_segments.push(VideoSegmentInfo {
- path: segment_path,
- index: completed_index,
- duration: segment_duration,
- file_size,
- });
-
- self.current_index = completed_index + 1;
- self.segment_start_time = Some(timestamp);
- self.frames_in_segment = 0;
-
- if !self.init_segment_validated && self.init_segment_path().exists() {
- self.init_segment_validated = true;
- tracing::debug!(
- segment = completed_index,
- "init.mp4 now exists after segment completion"
- );
- }
-
- self.write_manifest();
- self.write_in_progress_manifest();
+ tracing::debug!(
+ segment_index = completed_index,
+ duration_secs = segment_duration.as_secs_f64(),
+ frames = self.frames_in_segment,
+ "Segment boundary reached (time-based)"
+ );
- self.check_disk_space();
- }
+ self.completed_segments.push(VideoSegmentInfo {
+ path: segment_path,
+ index: completed_index,
+ duration: segment_duration,
+ file_size: None,
+ });
- Ok(())
+ self.current_index = completed_index + 1;
+ self.segment_start_time = Some(timestamp);
+ self.frames_in_segment = 0;
}
fn current_segment_path(&self) -> PathBuf {
diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.toml
index 245c46a88..cbc4837e3 100644
--- a/crates/recording/Cargo.toml
+++ b/crates/recording/Cargo.toml
@@ -99,6 +99,9 @@ tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
[target.'cfg(target_os = "macos")'.dev-dependencies]
libproc = "0.14"
+[target.'cfg(target_os = "windows")'.dev-dependencies]
+windows = { workspace = true, features = ["Win32_UI_HiDpi"] }
+
[[test]]
name = "synthetic_recording"
required-features = ["test-utils"]
@@ -106,3 +109,9 @@ required-features = ["test-utils"]
[[example]]
name = "synthetic-test-runner"
required-features = ["test-utils"]
+
+[[example]]
+name = "playback-test-runner"
+
+[[example]]
+name = "real-device-test-runner"
diff --git a/crates/recording/examples/playback-test-runner.rs b/crates/recording/examples/playback-test-runner.rs
new file mode 100644
index 000000000..7c6d83e45
--- /dev/null
+++ b/crates/recording/examples/playback-test-runner.rs
@@ -0,0 +1,992 @@
+use anyhow::bail;
+use cap_audio::{AudioData, SyncAnalyzer};
+use cap_project::{RecordingMeta, RecordingMetaInner, StudioRecordingMeta};
+use cap_rendering::decoder::spawn_decoder;
+use clap::{Parser, Subcommand};
+use std::{
+ path::{Path, PathBuf},
+ time::{Duration, Instant},
+};
+use tracing_subscriber::{EnvFilter, fmt, prelude::*};
+
+#[cfg(windows)]
+fn default_input_dir() -> PathBuf {
+ std::env::temp_dir().join("cap-real-device-tests")
+}
+
+#[cfg(not(windows))]
+fn default_input_dir() -> PathBuf {
+ PathBuf::from("/tmp/cap-real-device-tests")
+}
+
+#[derive(Parser)]
+#[command(name = "playback-test-runner")]
+#[command(about = "Run playback validation tests on existing Cap recordings")]
+struct Cli {
+ #[command(subcommand)]
+ command: Option<Commands>,
+
+ #[arg(long, global = true, default_value_os_t = default_input_dir())]
+ input_dir: PathBuf,
+
+ #[arg(long, global = true)]
+ recording_path: Option<PathBuf>,
+
+ #[arg(long, global = true, default_value = "30")]
+ fps: u32,
+
+ #[arg(long, global = true)]
+ verbose: bool,
+}
+
+#[derive(Subcommand)]
+enum Commands {
+ Full,
+ Decoder,
+ Playback,
+ AudioSync,
+ CameraSync,
+ List,
+}
+
+const FPS_TOLERANCE: f64 = 2.0;
+const DECODE_LATENCY_WARNING_MS: f64 = 50.0;
+const AUDIO_VIDEO_SYNC_TOLERANCE_MS: f64 = 100.0;
+const CAMERA_SYNC_TOLERANCE_MS: f64 = 100.0;
+
+#[derive(Debug, Clone, Default)]
+struct DecoderTestResult {
+ passed: bool,
+ decoder_type: String,
+ init_time_ms: f64,
+ video_width: u32,
+ video_height: u32,
+ is_hardware_accelerated: bool,
+ fallback_reason: Option<String>,
+ errors: Vec<String>,
+}
+
+#[derive(Debug, Clone, Default)]
+struct PlaybackTestResult {
+ passed: bool,
+ segment_index: usize,
+ total_frames: usize,
+ decoded_frames: usize,
+ failed_frames: usize,
+ avg_decode_time_ms: f64,
+ min_decode_time_ms: f64,
+ max_decode_time_ms: f64,
+ p50_decode_time_ms: f64,
+ p95_decode_time_ms: f64,
+ p99_decode_time_ms: f64,
+ effective_fps: f64,
+ expected_fps: f64,
+ fps_ok: bool,
+ jitter_ms: f64,
+ decode_latency_ok: bool,
+ errors: Vec<String>,
+}
+
+#[derive(Debug, Clone, Default)]
+struct AudioSyncTestResult {
+ passed: bool,
+ segment_index: usize,
+ has_mic_audio: bool,
+ has_system_audio: bool,
+ mic_duration_secs: f64,
+ system_audio_duration_secs: f64,
+ video_duration_secs: f64,
+ mic_video_diff_ms: f64,
+ system_audio_video_diff_ms: f64,
+ mic_sync_ok: bool,
+ system_audio_sync_ok: bool,
+ detected_sync_offset_ms: Option<f64>,
+ sync_confidence: f64,
+ errors: Vec<String>,
+}
+
+#[derive(Debug, Clone, Default)]
+struct CameraSyncTestResult {
+ passed: bool,
+ segment_index: usize,
+ has_camera: bool,
+ camera_start_time: Option<f64>,
+ display_start_time: Option<f64>,
+ camera_display_drift_ms: Option<f64>,
+ drift_ok: bool,
+ camera_decoder_ok: bool,
+ camera_frame_count: usize,
+ display_frame_count: usize,
+ frame_count_diff: i32,
+ errors: Vec<String>,
+}
+
+#[derive(Debug, Clone, Default)]
+struct RecordingTestReport {
+ recording_path: PathBuf,
+ recording_name: String,
+ segment_count: usize,
+ is_fragmented: bool,
+ has_camera: bool,
+ has_mic: bool,
+ has_system_audio: bool,
+ decoder_results: Vec<DecoderTestResult>,
+ playback_results: Vec<PlaybackTestResult>,
+ audio_sync_results: Vec<AudioSyncTestResult>,
+ camera_sync_results: Vec<CameraSyncTestResult>,
+ overall_passed: bool,
+ elapsed: Duration,
+}
+
+impl RecordingTestReport {
+ fn print(&self) {
+ let status = if self.overall_passed { "PASS" } else { "FAIL" };
+ let format_type = if self.is_fragmented {
+ "fragmented"
+ } else {
+ "mp4"
+ };
+
+ println!("\n{}", "=".repeat(70));
+ println!("[{}] {} ({})", status, self.recording_name, format_type);
+ println!("{}", "=".repeat(70));
+ println!(" Path: {}", self.recording_path.display());
+ println!(" Segments: {}", self.segment_count);
+ println!(
+ " Features: camera={} mic={} system_audio={}",
+ self.has_camera, self.has_mic, self.has_system_audio
+ );
+
+ println!("\n DECODER TESTS:");
+ for (i, result) in self.decoder_results.iter().enumerate() {
+ let status = if result.passed { "OK" } else { "FAIL" };
+ println!(
+ " Segment {}: [{}] {} ({}x{}) init={:.1}ms hw={}",
+ i,
+ status,
+ result.decoder_type,
+ result.video_width,
+ result.video_height,
+ result.init_time_ms,
+ result.is_hardware_accelerated
+ );
+ if let Some(reason) = &result.fallback_reason {
+ println!(" Fallback: {}", reason);
+ }
+ for err in &result.errors {
+ println!(" ERROR: {}", err);
+ }
+ }
+
+ println!("\n PLAYBACK TESTS:");
+ for result in &self.playback_results {
+ let status = if result.passed { "OK" } else { "FAIL" };
+ println!(
+ " Segment {}: [{}] frames={}/{} fps={:.1}/{:.1} avg={:.1}ms",
+ result.segment_index,
+ status,
+ result.decoded_frames,
+ result.total_frames,
+ result.effective_fps,
+ result.expected_fps,
+ result.avg_decode_time_ms
+ );
+ println!(
+ " Latency: min={:.1}ms avg={:.1}ms max={:.1}ms p95={:.1}ms p99={:.1}ms",
+ result.min_decode_time_ms,
+ result.avg_decode_time_ms,
+ result.max_decode_time_ms,
+ result.p95_decode_time_ms,
+ result.p99_decode_time_ms
+ );
+ if !result.fps_ok {
+ println!(" WARN: FPS outside tolerance!");
+ }
+ if !result.decode_latency_ok {
+ println!(
+ " WARN: Decode latency exceeds {}ms!",
+ DECODE_LATENCY_WARNING_MS
+ );
+ }
+ for err in &result.errors {
+ println!(" ERROR: {}", err);
+ }
+ }
+
+ if !self.audio_sync_results.is_empty() {
+ println!("\n AUDIO SYNC TESTS:");
+ for result in &self.audio_sync_results {
+ let status = if result.passed { "OK" } else { "FAIL" };
+ println!(
+ " Segment {}: [{}] mic={} sys_audio={}",
+ result.segment_index, status, result.has_mic_audio, result.has_system_audio
+ );
+ if result.has_mic_audio {
+ println!(
+ " Mic: {:.2}s diff={:.1}ms ({})",
+ result.mic_duration_secs,
+ result.mic_video_diff_ms,
+ if result.mic_sync_ok { "OK" } else { "FAIL" }
+ );
+ }
+ if result.has_system_audio {
+ println!(
+ " System: {:.2}s diff={:.1}ms ({})",
+ result.system_audio_duration_secs,
+ result.system_audio_video_diff_ms,
+ if result.system_audio_sync_ok {
+ "OK"
+ } else {
+ "FAIL"
+ }
+ );
+ }
+ if let Some(offset) = result.detected_sync_offset_ms {
+ println!(
+ " Detected sync offset: {:.1}ms (confidence: {:.0}%)",
+ offset,
+ result.sync_confidence * 100.0
+ );
+ }
+ for err in &result.errors {
+ println!(" ERROR: {}", err);
+ }
+ }
+ }
+
+ if !self.camera_sync_results.is_empty() {
+ println!("\n CAMERA SYNC TESTS:");
+ for result in &self.camera_sync_results {
+ let status = if result.passed { "OK" } else { "FAIL" };
+ if result.has_camera {
+ let drift_str = result
+ .camera_display_drift_ms
+ .map(|d| format!("{:.1}ms", d))
+ .unwrap_or_else(|| "N/A".to_string());
+ println!(
+ " Segment {}: [{}] drift={} frames={}(cam)/{}(disp)",
+ result.segment_index,
+ status,
+ drift_str,
+ result.camera_frame_count,
+ result.display_frame_count
+ );
+ if !result.drift_ok {
+ println!(
+ " WARN: Camera-display drift exceeds {}ms!",
+ CAMERA_SYNC_TOLERANCE_MS
+ );
+ }
+ } else {
+ println!(" Segment {}: No camera", result.segment_index);
+ }
+ for err in &result.errors {
+ println!(" ERROR: {}", err);
+ }
+ }
+ }
+
+ println!("\n Elapsed: {:.2}s", self.elapsed.as_secs_f64());
+ }
+}
+
+fn percentile(data: &[f64], p: f64) -> f64 {
+ if data.is_empty() {
+ return 0.0;
+ }
+ let mut sorted: Vec<f64> = data.iter().copied().filter(|x| !x.is_nan()).collect();
+ if sorted.is_empty() {
+ return 0.0;
+ }
+ sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
+ let idx = ((p / 100.0) * (sorted.len() - 1) as f64).round() as usize;
+ sorted[idx.min(sorted.len() - 1)]
+}
+
+async fn test_decoder(video_path: &Path, fps: u32, is_camera: bool) -> DecoderTestResult {
+ let mut result = DecoderTestResult::default();
+ let name = if is_camera { "camera" } else { "display" };
+
+ let start = Instant::now();
+ match spawn_decoder(name, video_path.to_path_buf(), fps, 0.0).await {
+ Ok(decoder) => {
+ result.init_time_ms = start.elapsed().as_secs_f64() * 1000.0;
+ result.decoder_type = format!("{}", decoder.decoder_type());
+ result.is_hardware_accelerated = decoder.is_hardware_accelerated();
+ let (width, height) = decoder.video_dimensions();
+ result.video_width = width;
+ result.video_height = height;
+ result.fallback_reason = decoder.fallback_reason().map(String::from);
+ result.passed = true;
+ }
+ Err(e) => {
+ result.init_time_ms = start.elapsed().as_secs_f64() * 1000.0;
+ result.errors.push(format!("Decoder init failed: {}", e));
+ result.passed = false;
+ }
+ }
+
+ result
+}
+
+async fn test_playback(
+ recording_meta: &RecordingMeta,
+ meta: &StudioRecordingMeta,
+ segment_index: usize,
+ fps: u32,
+ verbose: bool,
+) -> PlaybackTestResult {
+ let mut result = PlaybackTestResult {
+ segment_index,
+ expected_fps: fps as f64,
+ ..Default::default()
+ };
+
+ let display_path = match meta {
+ StudioRecordingMeta::SingleSegment { segment } => {
+ recording_meta.path(&segment.display.path)
+ }
+ StudioRecordingMeta::MultipleSegments { inner } => {
+ recording_meta.path(&inner.segments[segment_index].display.path)
+ }
+ };
+
+ let decoder = match spawn_decoder("display", display_path.clone(), fps, 0.0).await {
+ Ok(d) => d,
+ Err(e) => {
+ result
+ .errors
+ .push(format!("Failed to create decoder: {}", e));
+ return result;
+ }
+ };
+
+ let duration_secs = get_video_duration(&display_path);
+ let total_frames = (duration_secs * fps as f64).ceil() as usize;
+ result.total_frames = total_frames;
+
+ let test_frame_count = total_frames.min(300);
+ let mut decode_times: Vec<f64> = Vec::with_capacity(test_frame_count);
+ let mut decoded_count = 0;
+ let mut failed_count = 0;
+
+ let overall_start = Instant::now();
+
+ for frame_num in 0..test_frame_count {
+ let time = frame_num as f32 / fps as f32;
+ let start = Instant::now();
+
+ match decoder.get_frame(time).await {
+ Some(frame) => {
+ let decode_time_ms = start.elapsed().as_secs_f64() * 1000.0;
+ decode_times.push(decode_time_ms);
+ decoded_count += 1;
+
+ if frame.width() == 0 || frame.height() == 0 {
+ result
+ .errors
+ .push(format!("Frame {} has zero dimensions", frame_num));
+ }
+
+ if verbose && frame_num % 30 == 0 {
+ println!(
+ " Frame {}/{}: {:.1}ms ({}x{})",
+ frame_num,
+ test_frame_count,
+ decode_time_ms,
+ frame.width(),
+ frame.height()
+ );
+ }
+ }
+ None => {
+ failed_count += 1;
+ if verbose {
+ println!(" Frame {}: FAILED", frame_num);
+ }
+ }
+ }
+ }
+
+ let overall_elapsed = overall_start.elapsed();
+ result.decoded_frames = decoded_count;
+ result.failed_frames = failed_count;
+
+ if !decode_times.is_empty() {
+ result.avg_decode_time_ms = decode_times.iter().sum::<f64>() / decode_times.len() as f64;
+ result.min_decode_time_ms = decode_times.iter().copied().fold(f64::INFINITY, f64::min);
+ result.max_decode_time_ms = decode_times
+ .iter()
+ .copied()
+ .fold(f64::NEG_INFINITY, f64::max);
+ result.p50_decode_time_ms = percentile(&decode_times, 50.0);
+ result.p95_decode_time_ms = percentile(&decode_times, 95.0);
+ result.p99_decode_time_ms = percentile(&decode_times, 99.0);
+
+ let mean = result.avg_decode_time_ms;
+ let variance: f64 = decode_times.iter().map(|t| (t - mean).powi(2)).sum::<f64>()
+ / decode_times.len() as f64;
+ result.jitter_ms = variance.sqrt();
+ }
+
+ if overall_elapsed.as_secs_f64() > 0.0 {
+ result.effective_fps = decoded_count as f64 / overall_elapsed.as_secs_f64();
+ }
+
+ result.fps_ok = (result.effective_fps - result.expected_fps).abs() <= FPS_TOLERANCE
+ || result.effective_fps >= result.expected_fps;
+ result.decode_latency_ok = result.p95_decode_time_ms <= DECODE_LATENCY_WARNING_MS;
+
+ result.passed = result.fps_ok
+ && result.decode_latency_ok
+ && result.failed_frames == 0
+ && result.decoded_frames > 0;
+
+ result
+}
+
+async fn test_audio_sync(
+ recording_meta: &RecordingMeta,
+ meta: &StudioRecordingMeta,
+ segment_index: usize,
+ fps: u32,
+) -> AudioSyncTestResult {
+ let mut result = AudioSyncTestResult {
+ segment_index,
+ ..Default::default()
+ };
+
+ let (display_path, mic_path, system_audio_path) = match meta {
+ StudioRecordingMeta::SingleSegment { segment } => (
+ recording_meta.path(&segment.display.path),
+ segment.audio.as_ref().map(|a| recording_meta.path(&a.path)),
+ None,
+ ),
+ StudioRecordingMeta::MultipleSegments { inner } => {
+ let seg = &inner.segments[segment_index];
+ (
+ recording_meta.path(&seg.display.path),
+ seg.mic.as_ref().map(|m| recording_meta.path(&m.path)),
+ seg.system_audio
+ .as_ref()
+ .map(|s| recording_meta.path(&s.path)),
+ )
+ }
+ };
+
+ result.video_duration_secs = get_video_duration(&display_path);
+
+ if let Some(mic_path) = mic_path {
+ result.has_mic_audio = true;
+ match AudioData::from_file(&mic_path) {
+ Ok(audio_data) => {
+ let duration = audio_data.sample_count() as f64 / AudioData::SAMPLE_RATE as f64;
+ result.mic_duration_secs = duration;
+ let diff = (result.mic_duration_secs - result.video_duration_secs).abs() * 1000.0;
+ result.mic_video_diff_ms = diff;
+ result.mic_sync_ok = diff <= AUDIO_VIDEO_SYNC_TOLERANCE_MS;
+
+ let mut analyzer = SyncAnalyzer::new(AudioData::SAMPLE_RATE, fps as f64);
+ let mono_samples: Vec<f32> = audio_data
+ .samples()
+ .chunks(audio_data.channels() as usize)
+ .map(|c| c.iter().sum::<f32>() / c.len() as f32)
+ .collect();
+ analyzer.add_audio_samples(&mono_samples, 0.0);
+
+ if let Some(sync_result) = analyzer.calculate_sync_offset() {
+ result.detected_sync_offset_ms = Some(sync_result.offset_secs * 1000.0);
+ result.sync_confidence = sync_result.confidence;
+ }
+ }
+ Err(e) => {
+ result
+ .errors
+ .push(format!("Failed to load mic audio: {}", e));
+ }
+ }
+ }
+
+ if let Some(sys_path) = system_audio_path {
+ result.has_system_audio = true;
+ match AudioData::from_file(&sys_path) {
+ Ok(audio_data) => {
+ let duration = audio_data.sample_count() as f64 / AudioData::SAMPLE_RATE as f64;
+ result.system_audio_duration_secs = duration;
+ let diff =
+ (result.system_audio_duration_secs - result.video_duration_secs).abs() * 1000.0;
+ result.system_audio_video_diff_ms = diff;
+ result.system_audio_sync_ok = diff <= AUDIO_VIDEO_SYNC_TOLERANCE_MS;
+ }
+ Err(e) => {
+ result
+ .errors
+ .push(format!("Failed to load system audio: {}", e));
+ }
+ }
+ }
+
+ let mic_ok = !result.has_mic_audio || result.mic_sync_ok;
+ let sys_ok = !result.has_system_audio || result.system_audio_sync_ok;
+ result.passed = mic_ok && sys_ok && result.errors.is_empty();
+
+ result
+}
+
+async fn test_camera_sync(
+ recording_meta: &RecordingMeta,
+ meta: &StudioRecordingMeta,
+ segment_index: usize,
+ fps: u32,
+) -> CameraSyncTestResult {
+ let mut result = CameraSyncTestResult {
+ segment_index,
+ ..Default::default()
+ };
+
+ let (display_path, camera_path, display_start_time, camera_start_time) = match meta {
+ StudioRecordingMeta::SingleSegment { segment } => (
+ recording_meta.path(&segment.display.path),
+ segment
+ .camera
+ .as_ref()
+ .map(|c| recording_meta.path(&c.path)),
+ segment.display.start_time,
+ segment.camera.as_ref().and_then(|c| c.start_time),
+ ),
+ StudioRecordingMeta::MultipleSegments { inner } => {
+ let seg = &inner.segments[segment_index];
+ (
+ recording_meta.path(&seg.display.path),
+ seg.camera.as_ref().map(|c| recording_meta.path(&c.path)),
+ seg.display.start_time,
+ seg.camera.as_ref().and_then(|c| c.start_time),
+ )
+ }
+ };
+
+ result.display_start_time = display_start_time;
+ result.camera_start_time = camera_start_time;
+
+ let camera_path = match camera_path {
+ Some(p) => {
+ result.has_camera = true;
+ p
+ }
+ None => {
+ result.passed = true;
+ return result;
+ }
+ };
+
+ if let (Some(disp_start), Some(cam_start)) = (display_start_time, camera_start_time) {
+ let drift_secs = (disp_start - cam_start).abs();
+ result.camera_display_drift_ms = Some(drift_secs * 1000.0);
+ result.drift_ok = drift_secs * 1000.0 <= CAMERA_SYNC_TOLERANCE_MS;
+ } else {
+ result.drift_ok = true;
+ }
+
+ let display_decoder = match spawn_decoder("display", display_path.clone(), fps, 0.0).await {
+ Ok(d) => d,
+ Err(e) => {
+ result
+ .errors
+ .push(format!("Failed to create display decoder: {}", e));
+ return result;
+ }
+ };
+
+ let camera_decoder = match spawn_decoder("camera", camera_path.clone(), fps, 0.0).await {
+ Ok(d) => {
+ result.camera_decoder_ok = true;
+ d
+ }
+ Err(e) => {
+ result
+ .errors
+ .push(format!("Failed to create camera decoder: {}", e));
+ result.camera_decoder_ok = false;
+ return result;
+ }
+ };
+
+ let test_duration_secs = 5.0f32;
+ let test_frame_count = (test_duration_secs * fps as f32) as usize;
+
+ let mut display_frames = 0;
+ let mut camera_frames = 0;
+
+ for frame_num in 0..test_frame_count {
+ let time = frame_num as f32 / fps as f32;
+
+ if display_decoder.get_frame(time).await.is_some() {
+ display_frames += 1;
+ }
+
+ if camera_decoder.get_frame(time).await.is_some() {
+ camera_frames += 1;
+ }
+ }
+
+ result.display_frame_count = display_frames;
+ result.camera_frame_count = camera_frames;
+ result.frame_count_diff = (display_frames as i32 - camera_frames as i32).abs();
+
+ result.passed = result.drift_ok && result.camera_decoder_ok && result.errors.is_empty();
+
+ result
+}
+
+fn get_video_duration(path: &Path) -> f64 {
+ if path.is_dir() {
+ let init_segment = path.join("init.mp4");
+ if !init_segment.exists() {
+ return 0.0;
+ }
+
+ let mut fragments: Vec<PathBuf> = std::fs::read_dir(path)
+ .ok()
+ .map(|entries| {
+ entries
+ .filter_map(|e| e.ok())
+ .map(|e| e.path())
+ .filter(|p| p.extension().is_some_and(|ext| ext == "m4s"))
+ .collect()
+ })
+ .unwrap_or_default();
+ fragments.sort();
+
+ if fragments.is_empty() {
+ return 0.0;
+ }
+
+ let combined_path = path.join("_combined_for_duration.mp4");
+ let mut combined_data = match std::fs::read(&init_segment) {
+ Ok(d) => d,
+ Err(_) => return 0.0,
+ };
+ for fragment in &fragments {
+ if let Ok(data) = std::fs::read(fragment) {
+ combined_data.extend(data);
+ }
+ }
+ if std::fs::write(&combined_path, &combined_data).is_err() {
+ return 0.0;
+ }
+
+ let duration = get_single_file_duration(&combined_path);
+ let _ = std::fs::remove_file(&combined_path);
+ duration
+ } else {
+ get_single_file_duration(path)
+ }
+}
+
+fn get_single_file_duration(path: &Path) -> f64 {
+ match ffmpeg::format::input(path) {
+ Ok(input) => {
+ let raw_duration = input.duration();
+ if raw_duration > 0 {
+ raw_duration as f64 / ffmpeg::ffi::AV_TIME_BASE as f64
+ } else {
+ for stream in input.streams() {
+ if stream.parameters().medium() == ffmpeg::media::Type::Video {
+ let time_base = stream.time_base();
+ if let Some(duration) = stream.duration().checked_mul(time_base.0 as i64) {
+ return (duration as f64 / time_base.1 as f64).max(0.0);
+ }
+ }
+ }
+ 0.0
+ }
+ }
+ Err(_) => 0.0,
+ }
+}
+
+fn discover_recordings(input_dir: &Path) -> Vec<PathBuf> {
+ let mut recordings = Vec::new();
+
+ if !input_dir.exists() {
+ return recordings;
+ }
+
+ if let Ok(entries) = std::fs::read_dir(input_dir) {
+ for entry in entries.filter_map(|e| e.ok()) {
+ let path = entry.path();
+ if path.is_dir() {
+ let meta_path = path.join("recording-meta.json");
+ if meta_path.exists() {
+ recordings.push(path);
+ }
+ }
+ }
+ }
+
+ recordings.sort();
+ recordings
+}
+
+async fn run_tests_on_recording(
+ recording_path: &Path,
+ fps: u32,
+ run_decoder: bool,
+ run_playback: bool,
+ run_audio_sync: bool,
+ run_camera_sync: bool,
+ verbose: bool,
+) -> anyhow::Result<RecordingTestReport> {
+ let start = Instant::now();
+
+ let meta = RecordingMeta::load_for_project(recording_path)
+ .map_err(|e| anyhow::anyhow!("Failed to load recording metadata: {}", e))?;
+
+ let RecordingMetaInner::Studio(studio_meta) = &meta.inner else {
+ bail!("Not a studio recording");
+ };
+
+ let segment_count = match studio_meta.as_ref() {
+ StudioRecordingMeta::SingleSegment { .. } => 1,
+ StudioRecordingMeta::MultipleSegments { inner } => inner.segments.len(),
+ };
+
+ let is_fragmented = match studio_meta.as_ref() {
+ StudioRecordingMeta::SingleSegment { segment } => meta.path(&segment.display.path).is_dir(),
+ StudioRecordingMeta::MultipleSegments { inner } => {
+ !inner.segments.is_empty() && meta.path(&inner.segments[0].display.path).is_dir()
+ }
+ };
+
+ let (has_camera, has_mic, has_system_audio) = match studio_meta.as_ref() {
+ StudioRecordingMeta::SingleSegment { segment } => {
+ (segment.camera.is_some(), segment.audio.is_some(), false)
+ }
+ StudioRecordingMeta::MultipleSegments { inner } => {
+ let has_cam = inner.segments.iter().any(|s| s.camera.is_some());
+ let has_mic = inner.segments.iter().any(|s| s.mic.is_some());
+ let has_sys = inner.segments.iter().any(|s| s.system_audio.is_some());
+ (has_cam, has_mic, has_sys)
+ }
+ };
+
+ let mut report = RecordingTestReport {
+ recording_path: recording_path.to_path_buf(),
+ recording_name: meta.pretty_name.clone(),
+ segment_count,
+ is_fragmented,
+ has_camera,
+ has_mic,
+ has_system_audio,
+ ..Default::default()
+ };
+
+ for segment_idx in 0..segment_count {
+ if run_decoder {
+ let display_path = match studio_meta.as_ref() {
+ StudioRecordingMeta::SingleSegment { segment } => meta.path(&segment.display.path),
+ StudioRecordingMeta::MultipleSegments { inner } => {
+ meta.path(&inner.segments[segment_idx].display.path)
+ }
+ };
+
+ if verbose {
+ println!(" Testing decoder for segment {} display...", segment_idx);
+ }
+ let decoder_result = test_decoder(&display_path, fps, false).await;
+ report.decoder_results.push(decoder_result);
+
+ let camera_path = match studio_meta.as_ref() {
+ StudioRecordingMeta::SingleSegment { segment } => {
+ segment.camera.as_ref().map(|c| meta.path(&c.path))
+ }
+ StudioRecordingMeta::MultipleSegments { inner } => inner.segments[segment_idx]
+ .camera
+ .as_ref()
+ .map(|c| meta.path(&c.path)),
+ };
+
+ if let Some(cam_path) = camera_path {
+ if verbose {
+ println!(" Testing decoder for segment {} camera...", segment_idx);
+ }
+ let cam_decoder_result = test_decoder(&cam_path, fps, true).await;
+ report.decoder_results.push(cam_decoder_result);
+ }
+ }
+
+ if run_playback {
+ if verbose {
+ println!(" Testing playback for segment {}...", segment_idx);
+ }
+ let playback_result =
+ test_playback(&meta, studio_meta.as_ref(), segment_idx, fps, verbose).await;
+ report.playback_results.push(playback_result);
+ }
+
+ if run_audio_sync {
+ if verbose {
+ println!(" Testing audio sync for segment {}...", segment_idx);
+ }
+ let audio_result = test_audio_sync(&meta, studio_meta.as_ref(), segment_idx, fps).await;
+ report.audio_sync_results.push(audio_result);
+ }
+
+ if run_camera_sync && has_camera {
+ if verbose {
+ println!(" Testing camera sync for segment {}...", segment_idx);
+ }
+ let camera_result =
+ test_camera_sync(&meta, studio_meta.as_ref(), segment_idx, fps).await;
+ report.camera_sync_results.push(camera_result);
+ }
+ }
+
+ report.elapsed = start.elapsed();
+
+ let decoder_ok = report.decoder_results.iter().all(|r| r.passed);
+ let playback_ok = report.playback_results.iter().all(|r| r.passed);
+ let audio_ok = report.audio_sync_results.iter().all(|r| r.passed);
+ let camera_ok = report.camera_sync_results.iter().all(|r| r.passed);
+
+ report.overall_passed = decoder_ok && playback_ok && audio_ok && camera_ok;
+
+ Ok(report)
+}
+
+fn print_summary(reports: &[RecordingTestReport]) {
+ println!("\n{}", "=".repeat(70));
+ println!("PLAYBACK TEST SUMMARY");
+ println!("{}", "=".repeat(70));
+
+ let passed = reports.iter().filter(|r| r.overall_passed).count();
+ let total = reports.len();
+
+ println!("\nResults: {}/{} recordings passed", passed, total);
+
+ if passed < total {
+ println!("\nFailed recordings:");
+ for report in reports.iter().filter(|r| !r.overall_passed) {
+ print!(" - {}", report.recording_name);
+
+ let decoder_failed = report.decoder_results.iter().any(|r| !r.passed);
+ let playback_failed = report.playback_results.iter().any(|r| !r.passed);
+ let audio_failed = report.audio_sync_results.iter().any(|r| !r.passed);
+ let camera_failed = report.camera_sync_results.iter().any(|r| !r.passed);
+
+ if decoder_failed {
+ print!(" [DECODER]");
+ }
+ if playback_failed {
+ print!(" [PLAYBACK]");
+ }
+ if audio_failed {
+ print!(" [AUDIO SYNC]");
+ }
+ if camera_failed {
+ print!(" [CAMERA SYNC]");
+ }
+ println!();
+ }
+ }
+
+ println!();
+}
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ tracing_subscriber::registry()
+ .with(fmt::layer())
+ .with(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
+ .init();
+
+ ffmpeg::init().map_err(|e| anyhow::anyhow!("Failed to initialize FFmpeg: {}", e))?;
+
+ let cli = Cli::parse();
+
+ match cli.command {
+ Some(Commands::List) => {
+ let recordings = discover_recordings(&cli.input_dir);
+ if recordings.is_empty() {
+ println!("No recordings found in {}", cli.input_dir.display());
+ } else {
+ println!("Found {} recordings:", recordings.len());
+ for recording in recordings {
+ if let Ok(meta) = RecordingMeta::load_for_project(&recording) {
+ println!(" - {} ({})", meta.pretty_name, recording.display());
+ } else {
+ println!(" - {}", recording.display());
+ }
+ }
+ }
+ return Ok(());
+ }
+ _ => {}
+ }
+
+ let recordings = if let Some(path) = cli.recording_path {
+ vec![path]
+ } else {
+ discover_recordings(&cli.input_dir)
+ };
+
+ if recordings.is_empty() {
+ println!("No recordings found to test.");
+ println!(
+ "Either specify --recording-path or ensure recordings exist in {}",
+ cli.input_dir.display()
+ );
+ println!("\nTip: Run real-device-test-runner first to create test recordings:");
+ println!(" cargo run --example real-device-test-runner -- --keep-outputs");
+ return Ok(());
+ }
+
+ let (run_decoder, run_playback, run_audio_sync, run_camera_sync) = match cli.command {
+ Some(Commands::Decoder) => (true, false, false, false),
+ Some(Commands::Playback) => (false, true, false, false),
+ Some(Commands::AudioSync) => (false, false, true, false),
+ Some(Commands::CameraSync) => (false, false, false, true),
+ Some(Commands::Full) | None => (true, true, true, true),
+ Some(Commands::List) => unreachable!(),
+ };
+
+ println!("\nCap Playback Test Runner");
+ println!("{}", "=".repeat(40));
+ println!(
+ "Testing {} recording(s) at {} FPS",
+ recordings.len(),
+ cli.fps
+ );
+ println!();
+
+ let mut reports = Vec::new();
+
+ for recording_path in &recordings {
+ println!("Testing: {}", recording_path.display());
+
+ match run_tests_on_recording(
+ recording_path,
+ cli.fps,
+ run_decoder,
+ run_playback,
+ run_audio_sync,
+ run_camera_sync,
+ cli.verbose,
+ )
+ .await
+ {
+ Ok(report) => {
+ report.print();
+ reports.push(report);
+ }
+ Err(e) => {
+ println!(" ERROR: {}", e);
+ }
+ }
+ }
+
+ print_summary(&reports);
+
+ let failed = reports.iter().filter(|r| !r.overall_passed).count();
+ std::process::exit(if failed > 0 { 1 } else { 0 });
+}
diff --git a/crates/recording/examples/real-device-test-runner.rs b/crates/recording/examples/real-device-test-runner.rs
index 33cc57034..9d80d4c4b 100644
--- a/crates/recording/examples/real-device-test-runner.rs
+++ b/crates/recording/examples/real-device-test-runner.rs
@@ -17,14 +17,24 @@ use std::{
};
use tracing_subscriber::{EnvFilter, fmt, prelude::*};
+#[cfg(windows)]
+fn default_output_dir() -> PathBuf {
+ std::env::temp_dir().join("cap-real-device-tests")
+}
+
+#[cfg(not(windows))]
+fn default_output_dir() -> PathBuf {
+ PathBuf::from("/tmp/cap-real-device-tests")
+}
+
#[derive(Parser)]
#[command(name = "real-device-test-runner")]
-#[command(about = "Run end-to-end recording tests with real hardware devices on macOS")]
+#[command(about = "Run end-to-end recording tests with real hardware devices")]
struct Cli {
#[command(subcommand)]
command: Option<Commands>,
- #[arg(long, global = true, default_value = "/tmp/cap-real-device-tests")]
+ #[arg(long, global = true, default_value_os_t = default_output_dir())]
output_dir: PathBuf,
#[arg(long, global = true)]
@@ -250,6 +260,65 @@ struct DurationValidation {
segment_results: Vec<SegmentDurationResult>,
}
+#[derive(Debug, Clone, Default)]
+struct FrameRateAnalysis {
+ valid: bool,
+ expected_fps: f64,
+ segments: Vec<SegmentFrameRateResult>,
+}
+
+#[derive(Debug, Clone, Default)]
+struct SegmentFrameRateResult {
+ index: usize,
+ actual_fps: f64,
+ frame_count: usize,
+ expected_frame_count: usize,
+ dropped_frames: usize,
+ avg_frame_interval_ms: f64,
+ max_frame_interval_ms: f64,
+ min_frame_interval_ms: f64,
+ jitter_ms: f64,
+ fps_ok: bool,
+ jitter_ok: bool,
+ dropped_ok: bool,
+}
+
+const FPS_TOLERANCE: f64 = 2.0;
+const JITTER_TOLERANCE_MS: f64 = 15.0;
+const MAX_DROPPED_FRAME_PERCENT: f64 = 2.0;
+
+#[derive(Debug, Clone, Default)]
+struct AudioTimingAnalysis {
+ valid: bool,
+ segments: Vec<SegmentAudioTimingResult>,
+}
+
+#[derive(Debug, Clone, Default)]
+struct SegmentAudioTimingResult {
+ index: usize,
+ mic: Option<AudioStreamMetrics>,
+ system_audio: Option<AudioStreamMetrics>,
+ mic_video_duration_diff_ms: Option<f64>,
+ system_audio_video_duration_diff_ms: Option<f64>,
+ mic_duration_ok: bool,
+ system_audio_duration_ok: bool,
+}
+
+#[derive(Debug, Clone, Default)]
+struct AudioStreamMetrics {
+ duration_secs: f64,
+ sample_rate: u32,
+ channels: u16,
+ total_samples: u64,
+ expected_samples: u64,
+ sample_deficit_percent: f64,
+ has_gaps: bool,
+ gap_count: usize,
+ total_gap_duration_ms: f64,
+}
+
+const AUDIO_VIDEO_DURATION_TOLERANCE_MS: f64 = 100.0;
+
#[derive(Debug, Clone, Default)]
struct SegmentDurationResult {
index: usize,
@@ -271,6 +340,8 @@ struct TestReport {
av_sync: AVSyncValidation,
camera_output: CameraOutputValidation,
duration_validation: DurationValidation,
+ frame_rate: FrameRateAnalysis,
+ audio_timing: AudioTimingAnalysis,
elapsed: Duration,
errors: Vec<String>,
}
@@ -394,6 +465,106 @@ impl TestReport {
);
}
+ println!(
+ " Frame Rate: {} (expected {:.0}fps, tolerance: ±{:.0}fps)",
+ if self.frame_rate.valid { "OK" } else { "FAIL" },
+ self.frame_rate.expected_fps,
+ FPS_TOLERANCE
+ );
+ for seg in &self.frame_rate.segments {
+ let drop_percent = if seg.expected_frame_count > 0 {
+ (seg.dropped_frames as f64 / seg.expected_frame_count as f64) * 100.0
+ } else {
+ 0.0
+ };
+ println!(
+ " Segment {}: {:.1}fps frames={} dropped={} ({:.1}%) jitter={:.1}ms interval=[{:.1}-{:.1}ms]",
+ seg.index,
+ seg.actual_fps,
+ seg.frame_count,
+ seg.dropped_frames,
+ drop_percent,
+ seg.jitter_ms,
+ seg.min_frame_interval_ms,
+ seg.max_frame_interval_ms
+ );
+ if !seg.fps_ok {
+ println!(" WARN: FPS outside tolerance!");
+ }
+ if !seg.jitter_ok {
+ println!(
+ " WARN: Frame jitter exceeds {}ms!",
+ JITTER_TOLERANCE_MS
+ );
+ }
+ if !seg.dropped_ok {
+ println!(
+ " WARN: Dropped frames exceed {}%!",
+ MAX_DROPPED_FRAME_PERCENT
+ );
+ }
+ }
+
+ println!(
+ " Audio Timing: {} (tolerance: ±{:.0}ms vs video)",
+ if self.audio_timing.valid {
+ "OK"
+ } else {
+ "FAIL"
+ },
+ AUDIO_VIDEO_DURATION_TOLERANCE_MS
+ );
+ for seg in &self.audio_timing.segments {
+ if let Some(ref mic) = seg.mic {
+ let diff_str = seg
+ .mic_video_duration_diff_ms
+ .map(|d| format!("{:.1}ms", d))
+ .unwrap_or_else(|| "N/A".to_string());
+ let gap_str = if mic.has_gaps {
+ format!(
+ " gaps={} ({:.1}ms total)",
+ mic.gap_count, mic.total_gap_duration_ms
+ )
+ } else {
+ String::new()
+ };
+ println!(
+ " Segment {} mic: {:.2}s diff={} {}Hz {}ch{}",
+ seg.index, mic.duration_secs, diff_str, mic.sample_rate, mic.channels, gap_str
+ );
+ if !seg.mic_duration_ok {
+ println!(" WARN: Mic duration differs from video!");
+ }
+ if mic.has_gaps {
+ println!(" WARN: Audio gaps detected!");
+ }
+ }
+ if let Some(ref sys) = seg.system_audio {
+ let diff_str = seg
+ .system_audio_video_duration_diff_ms
+ .map(|d| format!("{:.1}ms", d))
+ .unwrap_or_else(|| "N/A".to_string());
+ let gap_str = if sys.has_gaps {
+ format!(
+ " gaps={} ({:.1}ms total)",
+ sys.gap_count, sys.total_gap_duration_ms
+ )
+ } else {
+ String::new()
+ };
+ println!(
+ " Segment {} system: {:.2}s diff={} {}Hz {}ch{}",
+ seg.index, sys.duration_secs, diff_str, sys.sample_rate, sys.channels, gap_str
+ );
+ if !seg.system_audio_duration_ok {
+ println!(" WARN: System audio duration differs from video!");
+ }
+ if sys.has_gaps {
+ println!(" WARN: Audio gaps detected!");
+ }
+ }
+ }
+
if !self.errors.is_empty() {
println!(" Errors:");
for error in &self.errors {
@@ -678,6 +849,412 @@ async fn probe_single_file_duration(path: &Path) -> anyhow::Result<Duration> {
Ok(Duration::ZERO)
}
+fn analyze_frame_rate_for_file(
+ path: &Path,
+ expected_fps: f64,
+ expected_duration: Duration,
+) -> anyhow::Result<SegmentFrameRateResult> {
+ let mut result = SegmentFrameRateResult {
+ expected_frame_count: (expected_duration.as_secs_f64() * expected_fps) as usize,
+ ..Default::default()
+ };
+
+ let input = ffmpeg::format::input(path).context("Failed to open video file")?;
+
+ let video_stream = input
+ .streams()
+ .best(ffmpeg::media::Type::Video)
+ .context("No video stream found")?;
+
+ let stream_index = video_stream.index();
+ let time_base = video_stream.time_base();
+ let time_base_secs = time_base.0 as f64 / time_base.1 as f64;
+
+ let mut frame_timestamps: Vec<f64> = Vec::new();
+
+ let mut ictx = ffmpeg::format::input(path)?;
+ for (stream, packet) in ictx.packets() {
+ if stream.index() == stream_index {
+ if let Some(pts) = packet.pts() {
+ let timestamp_secs = pts as f64 * time_base_secs;
+ frame_timestamps.push(timestamp_secs);
+ }
+ }
+ }
+
+ frame_timestamps.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
+
+ result.frame_count = frame_timestamps.len();
+
+ if frame_timestamps.len() < 2 {
+ return Ok(result);
+ }
+
+ let mut intervals: Vec<f64> = Vec::with_capacity(frame_timestamps.len() - 1);
+ for i in 1..frame_timestamps.len() {
+ let interval = frame_timestamps[i] - frame_timestamps[i - 1];
+ if interval > 0.0 {
+ intervals.push(interval * 1000.0);
+ }
+ }
+
+ if intervals.is_empty() {
+ return Ok(result);
+ }
+
+ let total_interval: f64 = intervals.iter().sum();
+ result.avg_frame_interval_ms = total_interval / intervals.len() as f64;
+ result.max_frame_interval_ms = intervals.iter().cloned().fold(0.0, f64::max);
+ result.min_frame_interval_ms = intervals.iter().cloned().fold(f64::INFINITY, f64::min);
+
+ let duration_secs = frame_timestamps.last().unwrap() - frame_timestamps.first().unwrap();
+ if duration_secs > 0.0 {
+ result.actual_fps = (frame_timestamps.len() - 1) as f64 / duration_secs;
+ }
+
+ let mean_interval = result.avg_frame_interval_ms;
+ let variance: f64 = intervals
+ .iter()
+ .map(|i| (i - mean_interval).powi(2))
+ .sum::<f64>()
+ / intervals.len() as f64;
+ result.jitter_ms = variance.sqrt();
+
+ let expected_interval_ms = 1000.0 / expected_fps;
+ let drop_threshold_ms = expected_interval_ms * 1.8;
+
+ result.dropped_frames = intervals
+ .iter()
+ .filter(|&&interval| interval > drop_threshold_ms)
+ .map(|&interval| ((interval / expected_interval_ms).round() as usize).saturating_sub(1))
+ .sum();
+
+ result.fps_ok = (result.actual_fps - expected_fps).abs() <= FPS_TOLERANCE;
+ result.jitter_ok = result.jitter_ms <= JITTER_TOLERANCE_MS;
+
+ let drop_percent = if result.expected_frame_count > 0 {
+ (result.dropped_frames as f64 / result.expected_frame_count as f64) * 100.0
+ } else {
+ 0.0
+ };
+ result.dropped_ok = drop_percent <= MAX_DROPPED_FRAME_PERCENT;
+
+ Ok(result)
+}
+
+async fn analyze_frame_rate(
+ meta: &RecordingMeta,
+ scenario: &TestScenario,
+ expected_fps: f64,
+) -> FrameRateAnalysis {
+ let mut result = FrameRateAnalysis {
+ valid: true,
+ expected_fps,
+ segments: vec![],
+ };
+
+ let expected_durations = scenario.segment_durations();
+
+ let RecordingMetaInner::Studio(studio_meta) = &meta.inner else {
+ return result;
+ };
+
+ match studio_meta.as_ref() {
+ StudioRecordingMeta::SingleSegment { segment } => {
+ let display_path = meta.path(&segment.display.path);
+ let expected_dur = expected_durations.first().copied().unwrap_or_default();
+
+ let file_path = if display_path.is_dir() {
+ let combined = display_path.join("_combined_for_fps.mp4");
+ if let Ok(()) = combine_fragmented_to_file(&display_path, &combined) {
+ combined
+ } else {
+ return result;
+ }
+ } else {
+ display_path
+ };
+
+ match analyze_frame_rate_for_file(&file_path, expected_fps, expected_dur) {
+ Ok(mut seg_result) => {
+ seg_result.index = 0;
+ if !seg_result.fps_ok || !seg_result.jitter_ok || !seg_result.dropped_ok {
+ result.valid = false;
+ }
+ result.segments.push(seg_result);
+ }
+ Err(e) => {
+ tracing::warn!("Failed to analyze frame rate for segment 0: {}", e);
+ result.valid = false;
+ }
+ }
+
+ if file_path
+ .file_name()
+ .is_some_and(|n| n == "_combined_for_fps.mp4")
+ {
+ let _ = std::fs::remove_file(&file_path);
+ }
+ }
+ StudioRecordingMeta::MultipleSegments { inner } => {
+ for (idx, segment) in inner.segments.iter().enumerate() {
+ let display_path = meta.path(&segment.display.path);
+ let expected_dur = expected_durations.get(idx).copied().unwrap_or_default();
+
+ let file_path = if display_path.is_dir() {
+ let combined = display_path.join("_combined_for_fps.mp4");
+ if let Ok(()) = combine_fragmented_to_file(&display_path, &combined) {
+ combined
+ } else {
+ result.valid = false;
+ continue;
+ }
+ } else {
+ display_path
+ };
+
+ match analyze_frame_rate_for_file(&file_path, expected_fps, expected_dur) {
+ Ok(mut seg_result) => {
+ seg_result.index = idx;
+ if !seg_result.fps_ok || !seg_result.jitter_ok || !seg_result.dropped_ok {
+ result.valid = false;
+ }
+ result.segments.push(seg_result);
+ }
+ Err(e) => {
+ tracing::warn!("Failed to analyze frame rate for segment {}: {}", idx, e);
+ result.valid = false;
+ }
+ }
+
+ if file_path
+ .file_name()
+ .is_some_and(|n| n == "_combined_for_fps.mp4")
+ {
+ let _ = std::fs::remove_file(&file_path);
+ }
+ }
+ }
+ }
+
+ result
+}
+
+fn combine_fragmented_to_file(dir: &Path, output: &Path) -> anyhow::Result<()> {
+ let init_segment = dir.join("init.mp4");
+ if !init_segment.exists() {
+ bail!("Missing init.mp4");
+ }
+
+ let mut fragments: Vec<PathBuf> = std::fs::read_dir(dir)?
+ .filter_map(|e| e.ok())
+ .map(|e| e.path())
+ .filter(|p| p.extension().is_some_and(|ext| ext == "m4s"))
+ .collect();
+ fragments.sort();
+
+ let mut combined_data = std::fs::read(&init_segment)?;
+ for fragment in &fragments {
+ combined_data.extend(std::fs::read(fragment)?);
+ }
+ std::fs::write(output, combined_data)?;
+
+ Ok(())
+}
+
+fn analyze_audio_stream(
+ path: &Path,
+ video_duration_secs: f64,
+) -> anyhow::Result<AudioStreamMetrics> {
+ let mut metrics = AudioStreamMetrics::default();
+
+ let input = ffmpeg::format::input(path).context("Failed to open audio file")?;
+
+ let audio_stream = input
+ .streams()
+ .best(ffmpeg::media::Type::Audio)
+ .context("No audio stream found")?;
+
+ let codec_params = audio_stream.parameters();
+ metrics.sample_rate = unsafe { (*codec_params.as_ptr()).sample_rate as u32 };
+ metrics.channels = unsafe { (*codec_params.as_ptr()).ch_layout.nb_channels as u16 };
+
+ let time_base = audio_stream.time_base();
+ let time_base_secs = time_base.0 as f64 / time_base.1 as f64;
+ let stream_index = audio_stream.index();
+
+ let raw_duration = input.duration();
+ if raw_duration > 0 {
+ metrics.duration_secs = raw_duration as f64 / ffmpeg::ffi::AV_TIME_BASE as f64;
+ } else if let Some(stream_duration) = audio_stream.duration().checked_mul(time_base.0 as i64) {
+ metrics.duration_secs = stream_duration as f64 / time_base.1 as f64;
+ }
+
+ if metrics.sample_rate > 0 {
+ metrics.expected_samples = (video_duration_secs * metrics.sample_rate as f64) as u64;
+ }
+
+ let mut packet_timestamps: Vec<(f64, f64)> = Vec::new();
+ let mut ictx = ffmpeg::format::input(path)?;
+
+ for (stream, packet) in ictx.packets() {
+ if stream.index() == stream_index {
+ if let (Some(pts), Some(duration)) = (packet.pts(), Some(packet.duration())) {
+ let start_secs = pts as f64 * time_base_secs;
+ let dur_secs = duration as f64 * time_base_secs;
+ packet_timestamps.push((start_secs, dur_secs));
+ }
+ }
+ }
+
+ packet_timestamps.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
+
+ let gap_threshold_secs = 0.05;
+ for i in 1..packet_timestamps.len() {
+ let prev_end = packet_timestamps[i - 1].0 + packet_timestamps[i - 1].1;
+ let curr_start = packet_timestamps[i].0;
+ let gap = curr_start - prev_end;
+
+ if gap > gap_threshold_secs {
+ metrics.has_gaps = true;
+ metrics.gap_count += 1;
+ metrics.total_gap_duration_ms += gap * 1000.0;
+ }
+ }
+
+ if metrics.sample_rate > 0 && metrics.duration_secs > 0.0 {
+ metrics.total_samples = (metrics.duration_secs * metrics.sample_rate as f64) as u64;
+
+ if metrics.expected_samples > 0 {
+ let deficit = metrics
+ .expected_samples
+ .saturating_sub(metrics.total_samples);
+ metrics.sample_deficit_percent =
+ (deficit as f64 / metrics.expected_samples as f64) * 100.0;
+ }
+ }
+
+ Ok(metrics)
+}
+
+async fn analyze_audio_timing(
+ meta: &RecordingMeta,
+ scenario: &TestScenario,
+) -> AudioTimingAnalysis {
+ let mut result = AudioTimingAnalysis {
+ valid: true,
+ segments: vec![],
+ };
+
+ let expected_durations = scenario.segment_durations();
+
+ let RecordingMetaInner::Studio(studio_meta) = &meta.inner else {
+ return result;
+ };
+
+ match studio_meta.as_ref() {
+ StudioRecordingMeta::SingleSegment { segment } => {
+ let mut seg_result = SegmentAudioTimingResult {
+ index: 0,
+ mic_duration_ok: true,
+ system_audio_duration_ok: true,
+ ..Default::default()
+ };
+
+ let video_duration = expected_durations.first().copied().unwrap_or_default();
+ let video_duration_secs = video_duration.as_secs_f64();
+
+ if let Some(ref audio) = segment.audio {
+ let audio_path = meta.path(&audio.path);
+ match analyze_audio_stream(&audio_path, video_duration_secs) {
+ Ok(metrics) => {
+ let diff_ms = (metrics.duration_secs - video_duration_secs).abs() * 1000.0;
+ seg_result.mic_video_duration_diff_ms = Some(diff_ms);
+ seg_result.mic_duration_ok = diff_ms <= AUDIO_VIDEO_DURATION_TOLERANCE_MS;
+
+ if !seg_result.mic_duration_ok || metrics.has_gaps {
+ result.valid = false;
+ }
+ seg_result.mic = Some(metrics);
+ }
+ Err(e) => {
+ tracing::warn!("Failed to analyze audio: {}", e);
+ }
+ }
+ }
+
+ result.segments.push(seg_result);
+ }
+ StudioRecordingMeta::MultipleSegments { inner } => {
+ for (idx, segment) in inner.segments.iter().enumerate() {
+ let mut seg_result = SegmentAudioTimingResult {
+ index: idx,
+ mic_duration_ok: true,
+ system_audio_duration_ok: true,
+ ..Default::default()
+ };
+
+ let video_duration = expected_durations.get(idx).copied().unwrap_or_default();
+ let video_duration_secs = video_duration.as_secs_f64();
+
+ if let Some(ref mic) = segment.mic {
+ let mic_path = meta.path(&mic.path);
+ match analyze_audio_stream(&mic_path, video_duration_secs) {
+ Ok(metrics) => {
+ let diff_ms =
+ (metrics.duration_secs - video_duration_secs).abs() * 1000.0;
+ seg_result.mic_video_duration_diff_ms = Some(diff_ms);
+ seg_result.mic_duration_ok =
+ diff_ms <= AUDIO_VIDEO_DURATION_TOLERANCE_MS;
+
+ if !seg_result.mic_duration_ok || metrics.has_gaps {
+ result.valid = false;
+ }
+ seg_result.mic = Some(metrics);
+ }
+ Err(e) => {
+ tracing::warn!(
+ "Failed to analyze mic audio for segment {}: {}",
+ idx,
+ e
+ );
+ }
+ }
+ }
+
+ if let Some(ref sys_audio) = segment.system_audio {
+ let sys_path = meta.path(&sys_audio.path);
+ match analyze_audio_stream(&sys_path, video_duration_secs) {
+ Ok(metrics) => {
+ let diff_ms =
+ (metrics.duration_secs - video_duration_secs).abs() * 1000.0;
+ seg_result.system_audio_video_duration_diff_ms = Some(diff_ms);
+ seg_result.system_audio_duration_ok =
+ diff_ms <= AUDIO_VIDEO_DURATION_TOLERANCE_MS;
+
+ if !seg_result.system_audio_duration_ok || metrics.has_gaps {
+ result.valid = false;
+ }
+ seg_result.system_audio = Some(metrics);
+ }
+ Err(e) => {
+ tracing::warn!(
+ "Failed to analyze system audio for segment {}: {}",
+ idx,
+ e
+ );
+ }
+ }
+ }
+
+ result.segments.push(seg_result);
+ }
+ }
+ }
+
+ result
+}
+
async fn validate_duration(
meta: &RecordingMeta,
scenario: &TestScenario,
@@ -785,6 +1362,7 @@ async fn execute_recording(
None
};
+ #[cfg(target_os = "macos")]
let shareable_content = cidre::sc::ShareableContent::current().await?;
let mut builder = studio_recording::Actor::builder(
@@ -805,7 +1383,12 @@ async fn execute_recording(
builder = builder.with_camera_feed(camera);
}
- let handle = builder.build(shareable_content).await?;
+ let handle = builder
+ .build(
+ #[cfg(target_os = "macos")]
+ shareable_content,
+ )
+ .await?;
for action in &scenario.actions {
match action {
@@ -903,12 +1486,19 @@ async fn run_test(
}
}
+ let expected_fps = 30.0;
+ report.frame_rate = analyze_frame_rate(&meta, scenario, expected_fps).await;
+
+ report.audio_timing = analyze_audio_timing(&meta, scenario).await;
+
let av_sync_ok = !include_camera || report.av_sync.all_synced;
let camera_output_ok = !include_camera || !fragmented || report.camera_output.valid;
report.passed = report.segment_count_ok
&& report.segment_timing.all_valid
&& report.duration_validation.total_ok
+ && report.frame_rate.valid
+ && report.audio_timing.valid
&& av_sync_ok
&& camera_output_ok
&& report.errors.is_empty();
@@ -917,6 +1507,7 @@ async fn run_test(
report
}
+#[cfg(target_os = "macos")]
async fn check_permissions() -> anyhow::Result<()> {
println!("\nChecking macOS permissions...\n");
@@ -935,7 +1526,7 @@ async fn check_permissions() -> anyhow::Result<()> {
println!(" Microphone: NO DEVICE FOUND");
}
- if !cap_camera::list_cameras().next().is_none() {
+ if cap_camera::list_cameras().next().is_some() {
println!(" Camera: AVAILABLE (permission will be requested on first use)");
} else {
println!(" Camera: NO DEVICE FOUND");
@@ -945,6 +1536,28 @@ async fn check_permissions() -> anyhow::Result<()> {
Ok(())
}
+#[cfg(windows)]
+async fn check_permissions() -> anyhow::Result<()> {
+ println!("\nChecking Windows device availability...\n");
+
+ println!(" Screen Recording: Windows does not require explicit permission");
+
+ if MicrophoneFeed::default_device().is_some() {
+ println!(" Microphone: AVAILABLE");
+ } else {
+ println!(" Microphone: NO DEVICE FOUND");
+ }
+
+ if cap_camera::list_cameras().next().is_some() {
+ println!(" Camera: AVAILABLE");
+ } else {
+ println!(" Camera: NO DEVICE FOUND");
+ }
+
+ println!();
+ Ok(())
+}
+
fn print_summary(reports: &[TestReport]) {
println!("\n{}", "=".repeat(70));
println!("CAP REAL-DEVICE RECORDING TEST RESULTS");
@@ -980,6 +1593,12 @@ fn print_summary(reports: &[TestReport]) {
if !report.duration_validation.total_ok {
print!(" [DURATION]");
}
+ if !report.frame_rate.valid {
+ print!(" [FRAME RATE]");
+ }
+ if !report.audio_timing.valid {
+ print!(" [AUDIO TIMING]");
+ }
if report.include_camera && !report.av_sync.all_synced {
print!(" [A/V SYNC]");
}
@@ -996,6 +1615,12 @@ fn print_summary(reports: &[TestReport]) {
#[tokio::main]
async fn main() -> anyhow::Result<()> {
+ #[cfg(windows)]
+ {
+ use windows::Win32::UI::HiDpi::{PROCESS_PER_MONITOR_DPI_AWARE, SetProcessDpiAwareness};
+ unsafe { SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE).ok() };
+ }
+
tracing_subscriber::registry()
.with(fmt::layer())
.with(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
@@ -1017,6 +1642,7 @@ async fn main() -> anyhow::Result<()> {
let devices = AvailableDevices::discover()?;
+ #[cfg(target_os = "macos")]
if cidre::sc::ShareableContent::current().await.is_err() {
bail!(
"Screen Recording permission not granted. Run with 'check-permissions' to see details."
diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs
index 555da598f..7c5f64502 100644
--- a/crates/recording/src/output_pipeline/core.rs
+++ b/crates/recording/src/output_pipeline/core.rs
@@ -31,12 +31,17 @@ const LARGE_FORWARD_JUMP_SECS: f64 = 5.0;
struct AudioDriftTracker {
baseline_offset_secs: Option<f64>,
+ drift_warning_logged: bool,
}
+const AUDIO_WALL_CLOCK_TOLERANCE_SECS: f64 = 0.1;
+const VIDEO_WALL_CLOCK_TOLERANCE_SECS: f64 = 0.1;
+
impl AudioDriftTracker {
fn new() -> Self {
Self {
baseline_offset_secs: None,
+ drift_warning_logged: false,
}
}
@@ -46,58 +51,59 @@ impl AudioDriftTracker {
sample_rate: u32,
wall_clock_secs: f64,
total_input_duration_secs: f64,
- ) -> Duration {
+ ) -> Option<Duration> {
let sample_time_secs = samples_before_frame as f64 / sample_rate as f64;
- if wall_clock_secs < 2.0 || total_input_duration_secs < 2.0 {
- return Duration::from_secs_f64(sample_time_secs);
+ if sample_time_secs > wall_clock_secs + AUDIO_WALL_CLOCK_TOLERANCE_SECS {
+ return None;
}
- if self.baseline_offset_secs.is_none() {
- let offset = total_input_duration_secs - wall_clock_secs;
- debug!(
- wall_clock_secs,
- total_input_duration_secs,
- baseline_offset_secs = offset,
- "Capturing audio baseline offset after warmup"
- );
- self.baseline_offset_secs = Some(offset);
- }
-
- let baseline = self.baseline_offset_secs.unwrap_or(0.0);
- let adjusted_input_duration = total_input_duration_secs - baseline;
- let adjusted_sample_time_secs = (sample_time_secs - baseline).max(0.0);
+ if wall_clock_secs >= 2.0 && total_input_duration_secs >= 2.0 {
+ if self.baseline_offset_secs.is_none() {
+ let offset = total_input_duration_secs - wall_clock_secs;
+ debug!(
+ wall_clock_secs,
+ total_input_duration_secs,
+ baseline_offset_secs = offset,
+ "Capturing audio baseline offset after warmup"
+ );
+ self.baseline_offset_secs = Some(offset);
+ }
- let drift_ratio = if adjusted_input_duration > 0.0 {
- wall_clock_secs / adjusted_input_duration
- } else {
- 1.0
- };
+ let baseline = self.baseline_offset_secs.unwrap_or(0.0);
+ let adjusted_input_duration = total_input_duration_secs - baseline;
+ let drift_ratio = if adjusted_input_duration > 0.0 {
+ wall_clock_secs / adjusted_input_duration
+ } else {
+ 1.0
+ };
- if !(0.95..=1.05).contains(&drift_ratio) {
- warn!(
- drift_ratio,
- wall_clock_secs,
- adjusted_input_duration,
- baseline,
- "Extreme audio clock drift detected after baseline correction, clamping"
- );
- let clamped_ratio = drift_ratio.clamp(0.95, 1.05);
- Duration::from_secs_f64(adjusted_sample_time_secs * clamped_ratio)
- } else {
- Duration::from_secs_f64(adjusted_sample_time_secs * drift_ratio)
+ if !(0.90..=1.10).contains(&drift_ratio) && !self.drift_warning_logged {
+ warn!(
+ drift_ratio,
+ wall_clock_secs,
+ adjusted_input_duration,
+ baseline,
+ "Significant audio clock drift detected"
+ );
+ self.drift_warning_logged = true;
+ }
}
+
+ Some(Duration::from_secs_f64(sample_time_secs))
}
}
struct VideoDriftTracker {
baseline_offset_secs: Option<f64>,
+ capped_frame_count: u64,
}
impl VideoDriftTracker {
fn new() -> Self {
Self {
baseline_offset_secs: None,
+ capped_frame_count: 0,
}
}
@@ -108,9 +114,14 @@ impl VideoDriftTracker {
) -> Duration {
let camera_secs = camera_duration.as_secs_f64();
let wall_clock_secs = wall_clock_elapsed.as_secs_f64();
+ let max_allowed_secs = wall_clock_secs + VIDEO_WALL_CLOCK_TOLERANCE_SECS;
if wall_clock_secs < 2.0 || camera_secs < 2.0 {
- return camera_duration;
+ let result_secs = camera_secs.min(max_allowed_secs);
+ if result_secs < camera_secs {
+ self.capped_frame_count += 1;
+ }
+ return Duration::from_secs_f64(result_secs);
}
if self.baseline_offset_secs.is_none() {
@@ -133,7 +144,7 @@ impl VideoDriftTracker {
1.0
};
- if !(0.95..=1.05).contains(&drift_ratio) {
+ let corrected_secs = if !(0.95..=1.05).contains(&drift_ratio) {
warn!(
drift_ratio,
wall_clock_secs,
@@ -142,13 +153,24 @@ impl VideoDriftTracker {
"Extreme video clock drift detected after baseline correction, clamping"
);
let clamped_ratio = drift_ratio.clamp(0.95, 1.05);
- Duration::from_secs_f64(adjusted_camera_secs * clamped_ratio)
+ adjusted_camera_secs * clamped_ratio
} else {
- Duration::from_secs_f64(adjusted_camera_secs * drift_ratio)
+ adjusted_camera_secs * drift_ratio
+ };
+
+ let final_secs = corrected_secs.min(max_allowed_secs);
+ if final_secs < corrected_secs {
+ self.capped_frame_count += 1;
}
+
+ Duration::from_secs_f64(final_secs)
+ }
+
+ fn capped_frame_count(&self) -> u64 {
+ self.capped_frame_count
}
}
-const DEFAULT_VIDEO_SOURCE_CHANNEL_CAPACITY: usize = 128;
+const DEFAULT_VIDEO_SOURCE_CHANNEL_CAPACITY: usize = 300;
fn get_video_source_channel_capacity() -> usize {
std::env::var("CAP_VIDEO_SOURCE_BUFFER_SIZE")
@@ -599,6 +621,7 @@ impl<TVideo: VideoSource> OutputPipelineBuilder<HasVideo<TVideo>> {
build_ctx.done_tx,
None,
&path,
+ build_ctx.pause_flag.clone(),
)
.await?;
@@ -659,6 +682,7 @@ impl OutputPipelineBuilder<NoVideo> {
build_ctx.done_tx,
Some(first_tx),
&path,
+ build_ctx.pause_flag.clone(),
)
.await?;
@@ -713,6 +737,7 @@ async fn finish_build(
done_tx: oneshot::Sender<anyhow::Result<()>>,
first_tx: Option<oneshot::Sender<Timestamp>>,
path: &Path,
+ pause_flag: Arc<AtomicBool>,
) -> anyhow::Result<()> {
if let Some(audio) = audio {
audio.configure(
@@ -721,6 +746,7 @@ async fn finish_build(
stop_token.clone(),
timestamps,
first_tx,
+ pause_flag,
);
}
@@ -950,6 +976,12 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
}
anomaly_tracker.log_stats_if_notable();
+ if drift_tracker.capped_frame_count() > 0 {
+ debug!(
+ capped_frames = drift_tracker.capped_frame_count(),
+ "Video frames capped to wall clock + tolerance"
+ );
+ }
muxer.lock().await.stop();
if let Some(Err(e)) = res {
@@ -981,6 +1013,7 @@ impl PreparedAudioSources {
stop_token: CancellationToken,
timestamps: Timestamps,
mut first_tx: Option<oneshot::Sender<Timestamp>>,
+ pause_flag: Arc<AtomicBool>,
) {
let sample_rate = self.audio_info.sample_rate;
@@ -991,10 +1024,34 @@ impl PreparedAudioSources {
let mut anomaly_tracker = TimestampAnomalyTracker::new("audio");
let mut drift_tracker = AudioDriftTracker::new();
let mut total_samples: u64 = 0;
+ let mut dropped_during_pause: u64 = 0;
+ let mut pause_start: Option<std::time::Instant> = None;
+ let mut total_pause_duration = Duration::ZERO;
let res = stop_token
.run_until_cancelled(async {
while let Some(frame) = self.audio_rx.next().await {
+ let is_paused = pause_flag.load(Ordering::Acquire);
+
+ if is_paused {
+ if pause_start.is_none() {
+ pause_start = Some(std::time::Instant::now());
+ }
+ dropped_during_pause += 1;
+ continue;
+ }
+
+ if let Some(start) = pause_start.take() {
+ let pause_duration = start.elapsed();
+ total_pause_duration =
+ total_pause_duration.saturating_add(pause_duration);
+ debug!(
+ pause_duration_ms = pause_duration.as_millis(),
+ total_pause_duration_ms = total_pause_duration.as_millis(),
+ "Audio resumed after pause"
+ );
+ }
+
if let Some(first_tx) = first_tx.take() {
let _ = first_tx.send(frame.timestamp);
}
@@ -1005,7 +1062,10 @@ impl PreparedAudioSources {
let _ = anomaly_tracker.process_timestamp(frame.timestamp, timestamps);
- let wall_clock_secs = timestamps.instant().elapsed().as_secs_f64();
+ let raw_wall_clock = timestamps.instant().elapsed();
+ let effective_wall_clock =
+ raw_wall_clock.saturating_sub(total_pause_duration);
+ let wall_clock_secs = effective_wall_clock.as_secs_f64();
let total_input_duration_secs =
total_samples as f64 / sample_rate as f64;
@@ -1023,6 +1083,7 @@ impl PreparedAudioSources {
samples_before_frame,
total_samples,
baseline_offset = drift_tracker.baseline_offset_secs,
+ total_pause_ms = total_pause_duration.as_millis(),
"Audio drift correction status"
);
}
@@ -1034,14 +1095,26 @@ impl PreparedAudioSources {
total_input_duration_secs,
);
- if let Err(e) = muxer.lock().await.send_audio_frame(frame, timestamp) {
- error!("Audio encoder: {e}");
+ if let Some(timestamp) = timestamp {
+ if let Err(e) =
+ muxer.lock().await.send_audio_frame(frame, timestamp)
+ {
+ error!("Audio encoder: {e}");
+ }
}
}
Ok::<(), anyhow::Error>(())
})
.await;
+ if dropped_during_pause > 0 {
+ debug!(
+ dropped_during_pause,
+ total_pause_ms = total_pause_duration.as_millis(),
+ "Audio frames dropped during pause (not counted in samples)"
+ );
+ }
+
anomaly_tracker.log_stats_if_notable();
for source in &mut self.erased_audio_sources {
@@ -1418,14 +1491,16 @@ mod tests {
}
#[test]
- fn no_correction_during_warmup() {
+ fn returns_sample_based_time_during_warmup() {
let mut tracker = AudioDriftTracker::new();
- let samples = samples_for_duration(10.0);
- let result = tracker.calculate_timestamp(samples, SAMPLE_RATE, 1.5, 1.5);
- let expected = Duration::from_secs_f64(10.0);
+ let samples = samples_for_duration(1.0);
+ let result = tracker
+ .calculate_timestamp(samples, SAMPLE_RATE, 1.5, 1.5)
+ .expect("Should not be capped when sample time < wall clock");
+ let expected = Duration::from_secs_f64(1.0);
assert!(
(result.as_secs_f64() - expected.as_secs_f64()).abs() < 0.001,
- "During warmup: expected ~{:.3}s, got {:.3}s",
+ "Expected ~{:.3}s, got {:.3}s",
expected.as_secs_f64(),
result.as_secs_f64()
);
@@ -1454,7 +1529,7 @@ mod tests {
}
#[test]
- fn baseline_removes_initial_buffer_offset() {
+ fn returns_sample_based_time_after_warmup() {
let mut tracker = AudioDriftTracker::new();
let buffer_delay = 0.05;
@@ -1470,97 +1545,74 @@ mod tests {
let wall_clock_2 = 10.0;
let input_duration_2 = 10.0 + buffer_delay;
let samples_2 = samples_for_duration(input_duration_2);
- let result =
- tracker.calculate_timestamp(samples_2, SAMPLE_RATE, wall_clock_2, input_duration_2);
+ let result = tracker
+ .calculate_timestamp(samples_2, SAMPLE_RATE, wall_clock_2, input_duration_2)
+ .expect("Should not be capped");
- let expected = Duration::from_secs_f64(wall_clock_2);
+ let expected = Duration::from_secs_f64(input_duration_2);
assert!(
- (result.as_secs_f64() - expected.as_secs_f64()).abs() < 0.1,
- "With baseline correction: expected ~{:.3}s, got {:.3}s",
- expected.as_secs_f64(),
- result.as_secs_f64()
- );
- }
-
- #[test]
- fn corrects_drift_after_baseline() {
- let mut tracker = AudioDriftTracker::new();
- let buffer_delay = 0.05;
- let drift_factor = 1.005;
-
- let wall_clock_1 = 2.0;
- let input_duration_1 = 2.0 * drift_factor + buffer_delay;
- tracker.calculate_timestamp(
- samples_for_duration(input_duration_1),
- SAMPLE_RATE,
- wall_clock_1,
- input_duration_1,
- );
-
- let wall_clock_2 = 60.0;
- let input_duration_2 = 60.0 * drift_factor + buffer_delay;
- let samples_2 = samples_for_duration(input_duration_2);
- let result =
- tracker.calculate_timestamp(samples_2, SAMPLE_RATE, wall_clock_2, input_duration_2);
-
- let expected = Duration::from_secs_f64(wall_clock_2);
- assert!(
- (result.as_secs_f64() - expected.as_secs_f64()).abs() < 0.5,
- "With drift and baseline correction: expected ~{:.3}s, got {:.3}s",
+ (result.as_secs_f64() - expected.as_secs_f64()).abs() < 0.001,
+ "Expected sample-based time ~{:.3}s, got {:.3}s",
expected.as_secs_f64(),
result.as_secs_f64()
);
}
#[test]
- fn clamps_extreme_drift_after_baseline() {
+ fn continuous_timestamps_no_gaps() {
let mut tracker = AudioDriftTracker::new();
- tracker.calculate_timestamp(samples_for_duration(2.0), SAMPLE_RATE, 2.0, 2.0);
+ let mut samples = 0u64;
+ let mut last_timestamp = Duration::ZERO;
+ for i in 0..100 {
+ let wall_clock = i as f64 * 0.02;
+ let input_duration = samples as f64 / SAMPLE_RATE as f64;
+ if let Some(result) =
+ tracker.calculate_timestamp(samples, SAMPLE_RATE, wall_clock, input_duration)
+ {
+ if i > 0 {
+ let gap = result.as_secs_f64() - last_timestamp.as_secs_f64();
+ assert!(
+ gap >= 0.0 && gap < 0.05,
+ "Gap between frames should be small: {gap:.3}s at frame {i}"
+ );
+ }
- let samples = samples_for_duration(100.0);
- let result = tracker.calculate_timestamp(samples, SAMPLE_RATE, 100.0, 120.0);
- let expected_ratio = 0.95;
- let sample_time = 100.0;
- let expected_secs = sample_time * expected_ratio;
- assert!(
- (result.as_secs_f64() - expected_secs).abs() < 0.1,
- "Expected ~{:.3}s (clamped to 0.95), got {:.3}s",
- expected_secs,
- result.as_secs_f64()
- );
+ last_timestamp = result;
+ }
+ samples += 960;
+ }
}
#[test]
- fn final_timestamp_matches_wall_clock_with_buffer() {
+ fn continuous_across_warmup_boundary() {
let mut tracker = AudioDriftTracker::new();
- let buffer_delay = 0.1;
- let drift_factor = 1.004;
-
- let wall_clock_1 = 2.0;
- let input_duration_1 = wall_clock_1 * drift_factor + buffer_delay;
- tracker.calculate_timestamp(
- samples_for_duration(input_duration_1),
- SAMPLE_RATE,
- wall_clock_1,
- input_duration_1,
- );
-
- let wall_clock_final = 60.0;
- let input_duration_final = wall_clock_final * drift_factor + buffer_delay;
- let total_samples = samples_for_duration(input_duration_final);
- let result = tracker.calculate_timestamp(
- total_samples,
- SAMPLE_RATE,
- wall_clock_final,
- input_duration_final,
- );
- let corrected_time = result.as_secs_f64();
+ let samples_at_2s = samples_for_duration(2.0);
+ let result1 = tracker
+ .calculate_timestamp(
+ samples_at_2s,
+ SAMPLE_RATE,
+ 2.1,
+ samples_at_2s as f64 / SAMPLE_RATE as f64,
+ )
+ .expect("Should not be capped");
+
+ let samples_after = samples_at_2s + 960;
+ let result2 = tracker
+ .calculate_timestamp(
+ samples_after,
+ SAMPLE_RATE,
+ 2.2,
+ samples_after as f64 / SAMPLE_RATE as f64,
+ )
+ .expect("Should not be capped");
+
+ let gap = result2.as_secs_f64() - result1.as_secs_f64();
+ let expected_gap = 960.0 / SAMPLE_RATE as f64;
assert!(
- (corrected_time - wall_clock_final).abs() < 1.0,
- "Final timestamp should be close to wall clock. \
- Wall clock: {wall_clock_final:.3}s, corrected: {corrected_time:.3}s, input_duration: {input_duration_final:.3}s"
+ (gap - expected_gap).abs() < 0.001,
+ "Gap across warmup boundary should be continuous: expected {expected_gap:.3}s, got {gap:.3}s"
);
}
@@ -1579,31 +1631,20 @@ mod tests {
total_audio += step * (1.0 + drift_rate);
let samples = samples_for_duration(total_audio);
- let result =
- tracker.calculate_timestamp(samples, SAMPLE_RATE, wall_time, total_audio);
-
- if wall_time >= 2.0 {
- let error = (result.as_secs_f64() - total_audio).abs();
+ if let Some(result) =
+ tracker.calculate_timestamp(samples, SAMPLE_RATE, wall_time, total_audio)
+ {
+ let expected = samples as f64 / SAMPLE_RATE as f64;
+ let error = (result.as_secs_f64() - expected).abs();
assert!(
- error < total_audio * 0.02,
- "At wall_time={:.1}s: corrected {:.3}s should be close to audio {:.3}s",
+ error < 0.001,
+ "At wall_time={:.1}s: result {:.3}s should equal sample time {:.3}s",
wall_time,
result.as_secs_f64(),
- total_audio
+ expected
);
}
}
-
- let final_samples = samples_for_duration(total_audio);
- let final_result =
- tracker.calculate_timestamp(final_samples, SAMPLE_RATE, wall_time, total_audio);
-
- assert!(
- (final_result.as_secs_f64() - wall_time).abs() < 1.0,
- "Final timestamp {:.3}s should be close to wall clock {:.3}s",
- final_result.as_secs_f64(),
- wall_time
- );
}
#[test]
@@ -1717,14 +1758,17 @@ mod tests {
let camera = dur(100.0);
let wall_clock = dur(80.0);
let result = tracker.calculate_timestamp(camera, wall_clock);
- let expected_ratio = 0.95;
- let expected_secs = 100.0 * expected_ratio;
+ let max_allowed = 80.0 + VIDEO_WALL_CLOCK_TOLERANCE_SECS;
assert!(
- (result.as_secs_f64() - expected_secs).abs() < 0.1,
- "Expected ~{:.3}s (clamped to 0.95), got {:.3}s",
- expected_secs,
+ result.as_secs_f64() <= max_allowed + 0.001,
+ "Expected result to be capped at ~{:.3}s, got {:.3}s",
+ max_allowed,
result.as_secs_f64()
);
+ assert!(
+ tracker.capped_frame_count() > 0,
+ "Should have capped at least one frame"
+ );
}
#[test]
@@ -1777,5 +1821,46 @@ mod tests {
"Baseline should not change after initial capture"
);
}
+
+ #[test]
+ fn caps_to_wall_clock_during_warmup() {
+ let mut tracker = VideoDriftTracker::new();
+ let wall_clock = dur(1.0);
+ let camera_duration = dur(1.5);
+ let result = tracker.calculate_timestamp(camera_duration, wall_clock);
+ let max_allowed = 1.0 + VIDEO_WALL_CLOCK_TOLERANCE_SECS;
+ assert!(
+ result.as_secs_f64() <= max_allowed + 0.001,
+ "During warmup: expected ~{:.3}s (capped), got {:.3}s",
+ max_allowed,
+ result.as_secs_f64()
+ );
+ assert_eq!(
+ tracker.capped_frame_count(),
+ 1,
+ "Should have capped one frame"
+ );
+ }
+
+ #[test]
+ fn caps_to_wall_clock_after_warmup() {
+ let mut tracker = VideoDriftTracker::new();
+ tracker.calculate_timestamp(dur(2.0), dur(2.0));
+
+ let wall_clock = dur(5.0);
+ let camera_duration = dur(5.5);
+ let result = tracker.calculate_timestamp(camera_duration, wall_clock);
+ let max_allowed = 5.0 + VIDEO_WALL_CLOCK_TOLERANCE_SECS;
+ assert!(
+ result.as_secs_f64() <= max_allowed + 0.001,
+ "After warmup: expected ~{:.3}s (capped), got {:.3}s",
+ max_allowed,
+ result.as_secs_f64()
+ );
+ assert!(
+ tracker.capped_frame_count() > 0,
+ "Should have capped at least one frame"
+ );
+ }
}
}
diff --git a/crates/recording/src/output_pipeline/win.rs b/crates/recording/src/output_pipeline/win.rs
index b60825a42..6d3918b94 100644
--- a/crates/recording/src/output_pipeline/win.rs
+++ b/crates/recording/src/output_pipeline/win.rs
@@ -9,11 +9,81 @@ use std::{
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
- mpsc::{SyncSender, sync_channel},
+ mpsc::{RecvTimeoutError, SyncSender, TrySendError, sync_channel},
},
time::Duration,
};
use tracing::*;
+
+const DEFAULT_MUXER_BUFFER_SIZE: usize = 240;
+
+fn get_muxer_buffer_size() -> usize {
+ std::env::var("CAP_MUXER_BUFFER_SIZE")
+ .ok()
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(DEFAULT_MUXER_BUFFER_SIZE)
+}
+
+struct FrameDropTracker {
+ drops_in_window: u32,
+ frames_in_window: u32,
+ total_drops: u64,
+ total_frames: u64,
+ last_check: std::time::Instant,
+}
+
+impl FrameDropTracker {
+ fn new() -> Self {
+ Self {
+ drops_in_window: 0,
+ frames_in_window: 0,
+ total_drops: 0,
+ total_frames: 0,
+ last_check: std::time::Instant::now(),
+ }
+ }
+
+ fn record_frame(&mut self) {
+ self.frames_in_window += 1;
+ self.total_frames += 1;
+ self.check_drop_rate();
+ }
+
+ fn record_drop(&mut self) {
+ self.drops_in_window += 1;
+ self.total_drops += 1;
+ self.check_drop_rate();
+ }
+
+ fn check_drop_rate(&mut self) {
+ if self.last_check.elapsed() >= Duration::from_secs(5) {
+ let total_in_window = self.frames_in_window + self.drops_in_window;
+ if total_in_window > 0 {
+ let drop_rate = 100.0 * self.drops_in_window as f64 / total_in_window as f64;
+ if drop_rate > 5.0 {
+ warn!(
+ frames = self.frames_in_window,
+ drops = self.drops_in_window,
+ drop_rate_pct = format!("{:.1}%", drop_rate),
+ total_frames = self.total_frames,
+ total_drops = self.total_drops,
+ "Windows MP4 muxer frame drop rate exceeds 5% threshold"
+ );
+ } else if self.drops_in_window > 0 {
+ debug!(
+ frames = self.frames_in_window,
+ drops = self.drops_in_window,
+ drop_rate_pct = format!("{:.1}%", drop_rate),
+ "Windows MP4 muxer frame stats"
+ );
+ }
+ }
+ self.drops_in_window = 0;
+ self.frames_in_window = 0;
+ self.last_check = std::time::Instant::now();
+ }
+ }
+}
use windows::{
Foundation::TimeSpan,
Graphics::SizeInt32,
@@ -96,6 +166,7 @@ pub struct WindowsMuxer {
output: Arc<Mutex<ffmpeg::format::context::Output>>,
audio_encoder: Option<AACEncoder>,
pause: PauseTracker,
+ frame_drops: FrameDropTracker,
}
pub struct WindowsMuxerConfig {
@@ -132,9 +203,13 @@ impl Muxer for WindowsMuxer {
let output_size = config.output_size.unwrap_or(input_size);
let fragmented = config.fragmented;
let frag_duration_us = config.frag_duration_us;
- let queue_depth = ((config.frame_rate as f32 / 30.0 * 5.0).ceil() as usize).clamp(3, 12);
+ let buffer_size = get_muxer_buffer_size();
+ debug!(
+ buffer_size = buffer_size,
+ "Windows MP4 muxer encoder channel buffer size"
+ );
let (video_tx, video_rx) =
- sync_channel::<Option<(scap_direct3d::Frame, Duration)>>(queue_depth);
+ sync_channel::<Option<(scap_direct3d::Frame, Duration)>>(buffer_size);
let mut output = ffmpeg::format::output(&output_path)?;
@@ -283,25 +358,61 @@ impl Muxer for WindowsMuxer {
match encoder {
either::Left((mut encoder, mut muxer)) => {
- trace!("Running native encoder");
- let mut first_timestamp: Option<Duration> = None;
+ trace!("Running native encoder with frame pacing");
+ let frame_interval = Duration::from_secs_f64(1.0 / config.frame_rate as f64);
+ let mut last_texture: Option<windows::Win32::Graphics::Direct3D11::ID3D11Texture2D> = None;
+ let mut frame_count: u64 = 0;
+ let mut frames_reused: u64 = 0;
+
let result = encoder.run(
Arc::new(AtomicBool::default()),
|| {
- let Ok(Some((frame, timestamp))) = video_rx.recv() else {
- trace!("No more frames available");
- return Ok(None);
- };
+ match video_rx.recv_timeout(frame_interval) {
+ Ok(Some((frame, _timestamp))) => {
+ last_texture = Some(frame.texture().clone());
+ }
+ Ok(None) => {
+ trace!("End of stream signal received");
+ return Ok(None);
+ }
+ Err(RecvTimeoutError::Timeout) => {
+ if last_texture.is_some() {
+ frames_reused += 1;
+ if frames_reused.is_multiple_of(30) {
+ debug!(
+ frames_reused = frames_reused,
+ frame_count = frame_count,
+ "Frame pacing: reusing frames due to slow capture"
+ );
+ }
+ }
+ }
+ Err(RecvTimeoutError::Disconnected) => {
+ trace!("Channel disconnected");
+ return Ok(None);
+ }
+ }
- let relative = if let Some(first) = first_timestamp {
- timestamp.saturating_sub(first)
+ if let Some(ref texture) = last_texture {
+ let timestamp = Duration::from_nanos(
+ frame_count.saturating_mul(frame_interval.as_nanos() as u64)
+ );
+ frame_count += 1;
+ let frame_time = duration_to_timespan(timestamp);
+ Ok(Some((texture.clone(), frame_time)))
} else {
- first_timestamp = Some(timestamp);
- Duration::ZERO
- };
- let frame_time = duration_to_timespan(relative);
-
- Ok(Some((frame.texture().clone(), frame_time)))
+ match video_rx.recv() {
+ Ok(Some((frame, _timestamp))) => {
+ let texture = frame.texture().clone();
+ last_texture = Some(texture.clone());
+ let timestamp = Duration::ZERO;
+ frame_count = 1;
+ let frame_time = duration_to_timespan(timestamp);
+ Ok(Some((texture, frame_time)))
+ }
+ Ok(None) | Err(_) => Ok(None),
+ }
+ }
},
|output_sample| {
let Ok(mut output) = output.lock() else {
@@ -338,21 +449,58 @@ impl Muxer for WindowsMuxer {
}
}
either::Right(mut encoder) => {
- while let Ok(Some((frame, time))) = video_rx.recv() {
- let Ok(mut output) = output.lock() else {
+ trace!("Running software encoder with frame pacing");
+ let frame_interval = Duration::from_secs_f64(1.0 / config.frame_rate as f64);
+ let mut last_ffmpeg_frame: Option<ffmpeg::frame::Video> = None;
+ let mut frame_count: u64 = 0;
+
+ use scap_ffmpeg::AsFFmpeg;
+
+ loop {
+ let ffmpeg_frame = match video_rx.recv_timeout(frame_interval) {
+ Ok(Some((frame, _timestamp))) => {
+ match frame.as_ffmpeg() {
+ Ok(f) => {
+ last_ffmpeg_frame = Some(f.clone());
+ Some(f)
+ }
+ Err(e) => {
+ warn!("Failed to convert frame: {e:?}");
+ last_ffmpeg_frame.clone()
+ }
+ }
+ }
+ Ok(None) => break,
+ Err(RecvTimeoutError::Timeout) => {
+ last_ffmpeg_frame.clone()
+ }
+ Err(RecvTimeoutError::Disconnected) => break,
+ };
+
+ let Some(ffmpeg_frame) = ffmpeg_frame else {
+ match video_rx.recv() {
+ Ok(Some((frame, _timestamp))) => {
+ if let Ok(f) = frame.as_ffmpeg() {
+ last_ffmpeg_frame = Some(f);
+ }
+ }
+ Ok(None) | Err(_) => break,
+ }
continue;
};
- use scap_ffmpeg::AsFFmpeg;
+ let timestamp = Duration::from_nanos(
+ frame_count.saturating_mul(frame_interval.as_nanos() as u64)
+ );
+ frame_count += 1;
+
+ let Ok(mut output) = output.lock() else {
+ continue;
+ };
- frame
- .as_ffmpeg()
- .context("frame as_ffmpeg")
- .and_then(|frame| {
- encoder
- .queue_frame(frame, time, &mut output)
- .context("queue_frame")
- })?;
+ encoder
+ .queue_frame(ffmpeg_frame, timestamp, &mut output)
+ .context("queue_frame")?;
}
Ok(())
@@ -372,6 +520,7 @@ impl Muxer for WindowsMuxer {
output,
audio_encoder,
pause: PauseTracker::new(pause_flag),
+ frame_drops: FrameDropTracker::new(),
})
}
@@ -405,7 +554,17 @@ impl VideoMuxer for WindowsMuxer {
timestamp: Duration,
) -> anyhow::Result<()> {
if let Some(timestamp) = self.pause.adjust(timestamp)? {
- self.video_tx.send(Some((frame.frame, timestamp)))?;
+ match self.video_tx.try_send(Some((frame.frame, timestamp))) {
+ Ok(()) => {
+ self.frame_drops.record_frame();
+ }
+ Err(TrySendError::Full(_)) => {
+ self.frame_drops.record_drop();
+ }
+ Err(TrySendError::Disconnected(_)) => {
+ trace!("Windows MP4 encoder channel disconnected");
+ }
+ }
}
Ok(())
@@ -479,6 +638,7 @@ pub struct WindowsCameraMuxer {
output: Arc<Mutex<ffmpeg::format::context::Output>>,
audio_encoder: Option<AACEncoder>,
pause: PauseTracker,
+ frame_drops: FrameDropTracker,
}
pub struct WindowsCameraMuxerConfig {
@@ -486,6 +646,7 @@ pub struct WindowsCameraMuxerConfig {
pub fragmented: bool,
pub frag_duration_us: i64,
pub encoder_preferences: crate::capture_pipeline::EncoderPreferences,
+ pub expected_pixel_format: Option<ffmpeg::format::Pixel>,
}
impl Default for WindowsCameraMuxerConfig {
@@ -495,10 +656,21 @@ impl Default for WindowsCameraMuxerConfig {
fragmented: false,
frag_duration_us: 2_000_000,
encoder_preferences: crate::capture_pipeline::EncoderPreferences::new(),
+ expected_pixel_format: None,
}
}
}
+fn ffmpeg_pixel_to_dxgi(pixel: ffmpeg::format::Pixel) -> DXGI_FORMAT {
+ match pixel {
+ ffmpeg::format::Pixel::NV12 => DXGI_FORMAT_NV12,
+ ffmpeg::format::Pixel::YUYV422 | ffmpeg::format::Pixel::UYVY422 => DXGI_FORMAT_YUY2,
+ ffmpeg::format::Pixel::BGRA | ffmpeg::format::Pixel::RGBA => DXGI_FORMAT_B8G8R8A8_UNORM,
+ ffmpeg::format::Pixel::BGR24 | ffmpeg::format::Pixel::RGB24 => DXGI_FORMAT_R8G8B8A8_UNORM,
+ _ => DXGI_FORMAT_NV12,
+ }
+}
+
impl Muxer for WindowsCameraMuxer {
type Config = WindowsCameraMuxerConfig;
@@ -536,7 +708,13 @@ impl Muxer for WindowsCameraMuxer {
let fragmented = config.fragmented;
let frag_duration_us = config.frag_duration_us;
- let (video_tx, video_rx) = sync_channel::<Option<(NativeCameraFrame, Duration)>>(30);
+ let buffer_size = get_muxer_buffer_size();
+ debug!(
+ buffer_size = buffer_size,
+ "Windows MP4 camera muxer encoder channel buffer size"
+ );
+ let (video_tx, video_rx) =
+ sync_channel::<Option<(NativeCameraFrame, Duration)>>(buffer_size);
let mut output = ffmpeg::format::output(&output_path)?;
@@ -551,6 +729,11 @@ impl Muxer for WindowsCameraMuxer {
let output = Arc::new(Mutex::new(output));
let (ready_tx, ready_rx) = oneshot::channel::<anyhow::Result<()>>();
+ let expected_input_format = config
+ .expected_pixel_format
+ .map(ffmpeg_pixel_to_dxgi)
+ .unwrap_or_else(|| ffmpeg_pixel_to_dxgi(video_config.pixel_format));
+
{
let output = output.clone();
let encoder_preferences = config.encoder_preferences;
@@ -566,19 +749,7 @@ impl Muxer for WindowsCameraMuxer {
}
};
- let first_frame = match video_rx.recv() {
- Ok(Some(frame)) => frame,
- Ok(None) => {
- let _ = ready_tx.send(Ok(()));
- return Ok(());
- }
- Err(e) => {
- let _ = ready_tx.send(Err(anyhow!("No frames received: {e}")));
- return Err(anyhow!("No frames received: {e}"));
- }
- };
-
- let input_format = first_frame.0.dxgi_format();
+ let input_format = expected_input_format;
let encoder = (|| {
let fallback = |reason: Option<String>| {
@@ -677,7 +848,7 @@ impl Muxer for WindowsCameraMuxer {
match encoder {
either::Left((mut encoder, mut muxer)) => {
info!(
- "Windows camera encoder started (hardware): {:?} {}x{} -> NV12 {}x{} @ {}fps",
+ "Windows camera encoder started (hardware) with frame pacing: {:?} {}x{} -> NV12 {}x{} @ {}fps",
input_format,
input_size.Width,
input_size.Height,
@@ -686,78 +857,81 @@ impl Muxer for WindowsCameraMuxer {
frame_rate
);
- let mut first_timestamp: Option<Duration> = None;
+ let frame_interval = Duration::from_secs_f64(1.0 / frame_rate as f64);
+ let mut last_frame: Option<NativeCameraFrame> = None;
let mut frame_count = 0u64;
- let mut process_frame = |frame: NativeCameraFrame,
- timestamp: Duration|
- -> windows::core::Result<
- Option<(
- windows::Win32::Graphics::Direct3D11::ID3D11Texture2D,
- TimeSpan,
- )>,
- > {
- let relative = if let Some(first) = first_timestamp {
- timestamp.saturating_sub(first)
- } else {
- first_timestamp = Some(timestamp);
- Duration::ZERO
- };
-
- let texture = upload_mf_buffer_to_texture(&d3d_device, &frame)?;
- Ok(Some((texture, duration_to_timespan(relative))))
- };
-
- if let Ok(Some((texture, frame_time))) =
- process_frame(first_frame.0, first_frame.1)
- {
- let result = encoder.run(
- Arc::new(AtomicBool::default()),
- || {
- if frame_count > 0 {
- let Ok(Some((frame, timestamp))) = video_rx.recv() else {
- trace!("No more camera frames available");
- return Ok(None);
- };
- frame_count += 1;
- if frame_count.is_multiple_of(30) {
- debug!(
- "Windows camera encoder: processed {} frames",
- frame_count
- );
- }
- return process_frame(frame, timestamp);
+ let result = encoder.run(
+ Arc::new(AtomicBool::default()),
+ || {
+ match video_rx.recv_timeout(frame_interval) {
+ Ok(Some((frame, _timestamp))) => {
+ last_frame = Some(frame);
}
- frame_count += 1;
- Ok(Some((texture.clone(), frame_time)))
- },
- |output_sample| {
- let mut output = output.lock().unwrap();
- if let Err(e) = muxer.write_sample(&output_sample, &mut output)
- {
- tracing::error!("Camera WriteSample failed: {e}");
+ Ok(None) => {
+ trace!("End of camera stream signal received");
+ return Ok(None);
}
- Ok(())
- },
- );
+ Err(RecvTimeoutError::Timeout) => {
+ }
+ Err(RecvTimeoutError::Disconnected) => {
+ trace!("Camera channel disconnected");
+ return Ok(None);
+ }
+ }
- match result {
- Ok(health_status) => {
- info!(
- "Windows camera encoder finished (hardware): {} frames encoded",
- health_status.total_frames_encoded
+ if let Some(ref frame) = last_frame {
+ let timestamp = Duration::from_nanos(
+ frame_count.saturating_mul(frame_interval.as_nanos() as u64)
);
- }
- Err(e) => {
- if e.should_fallback() {
- error!(
- "Camera hardware encoder failed with recoverable error, marking for software fallback: {}",
- e
+ frame_count += 1;
+ if frame_count.is_multiple_of(30) {
+ debug!(
+ "Windows camera encoder: processed {} frames",
+ frame_count
);
- encoder_preferences.force_software_only();
}
- return Err(anyhow!("Camera hardware encoder error: {}", e));
+ let texture = upload_mf_buffer_to_texture(&d3d_device, frame)?;
+ Ok(Some((texture, duration_to_timespan(timestamp))))
+ } else {
+ match video_rx.recv() {
+ Ok(Some((frame, _timestamp))) => {
+ last_frame = Some(frame.clone());
+ let timestamp = Duration::ZERO;
+ frame_count = 1;
+ let texture = upload_mf_buffer_to_texture(&d3d_device, &frame)?;
+ Ok(Some((texture, duration_to_timespan(timestamp))))
+ }
+ Ok(None) | Err(_) => Ok(None),
+ }
+ }
+ },
+ |output_sample| {
+ let mut output = output.lock().unwrap();
+ if let Err(e) = muxer.write_sample(&output_sample, &mut output)
+ {
+ tracing::error!("Camera WriteSample failed: {e}");
+ }
+ Ok(())
+ },
+ );
+
+ match result {
+ Ok(health_status) => {
+ info!(
+ "Windows camera encoder finished (hardware): {} frames encoded",
+ health_status.total_frames_encoded
+ );
+ }
+ Err(e) => {
+ if e.should_fallback() {
+ error!(
+ "Camera hardware encoder failed with recoverable error, marking for software fallback: {}",
+ e
+ );
+ encoder_preferences.force_software_only();
}
+ return Err(anyhow!("Camera hardware encoder error: {}", e));
}
}
@@ -765,7 +939,7 @@ impl Muxer for WindowsCameraMuxer {
}
either::Right(mut encoder) => {
info!(
- "Windows camera encoder started (software): {}x{} -> {}x{} @ {}fps",
+ "Windows camera encoder started (software) with frame pacing: {}x{} -> {}x{} @ {}fps",
video_config.width,
video_config.height,
output_width,
@@ -773,46 +947,63 @@ impl Muxer for WindowsCameraMuxer {
frame_rate
);
- let mut first_timestamp: Option<Duration> = None;
+ let frame_interval = Duration::from_secs_f64(1.0 / frame_rate as f64);
+ let mut last_frame: Option<NativeCameraFrame> = None;
let mut frame_count = 0u64;
- let mut process_frame =
- |frame: NativeCameraFrame,
- timestamp: Duration|
- -> anyhow::Result<Option<Duration>> {
- let relative = if let Some(first) = first_timestamp {
- timestamp.saturating_sub(first)
- } else {
- first_timestamp = Some(timestamp);
- Duration::ZERO
- };
+ loop {
+ let frame_to_encode = match video_rx.recv_timeout(frame_interval) {
+ Ok(Some((frame, _timestamp))) => {
+ last_frame = Some(frame.clone());
+ Some(frame)
+ }
+ Ok(None) => break,
+ Err(RecvTimeoutError::Timeout) => {
+ last_frame.clone()
+ }
+ Err(RecvTimeoutError::Disconnected) => break,
+ };
- let ffmpeg_frame = camera_frame_to_ffmpeg(&frame)?;
+ let Some(frame) = frame_to_encode else {
+ match video_rx.recv() {
+ Ok(Some((frame, _timestamp))) => {
+ last_frame = Some(frame.clone());
+ }
+ Ok(None) | Err(_) => break,
+ }
+ continue;
+ };
- let Ok(mut output_guard) = output.lock() else {
- return Ok(None);
- };
+ let timestamp = Duration::from_nanos(
+ frame_count.saturating_mul(frame_interval.as_nanos() as u64)
+ );
- encoder
- .queue_frame(ffmpeg_frame, relative, &mut output_guard)
- .context("queue camera frame")?;
+ let ffmpeg_frame = match camera_frame_to_ffmpeg(&frame) {
+ Ok(f) => f,
+ Err(e) => {
+ error!("Failed to convert camera frame: {e}");
+ continue;
+ }
+ };
- Ok(Some(relative))
+ let Ok(mut output_guard) = output.lock() else {
+ continue;
};
- if process_frame(first_frame.0, first_frame.1)?.is_some() {
- frame_count += 1;
- }
+ if let Err(e) = encoder
+ .queue_frame(ffmpeg_frame, timestamp, &mut output_guard)
+ .context("queue camera frame")
+ {
+ error!("Failed to queue camera frame: {e}");
+ continue;
+ }
- while let Ok(Some((frame, timestamp))) = video_rx.recv() {
- if process_frame(frame, timestamp)?.is_some() {
- frame_count += 1;
- if frame_count.is_multiple_of(30) {
- debug!(
- "Windows camera encoder (software): processed {} frames",
- frame_count
- );
- }
+ frame_count += 1;
+ if frame_count.is_multiple_of(30) {
+ debug!(
+ "Windows camera encoder (software): processed {} frames",
+ frame_count
+ );
}
}
@@ -837,6 +1028,7 @@ impl Muxer for WindowsCameraMuxer {
output,
audio_encoder,
pause: PauseTracker::new(pause_flag),
+ frame_drops: FrameDropTracker::new(),
})
}
@@ -870,9 +1062,17 @@ impl VideoMuxer for WindowsCameraMuxer {
timestamp: Duration,
) -> anyhow::Result<()> {
if let Some(timestamp) = self.pause.adjust(timestamp)? {
- self.video_tx
- .send(Some((frame, timestamp)))
- .map_err(|_| anyhow!("Video channel closed"))?;
+ match self.video_tx.try_send(Some((frame, timestamp))) {
+ Ok(()) => {
+ self.frame_drops.record_frame();
+ }
+ Err(TrySendError::Full(_)) => {
+ self.frame_drops.record_drop();
+ }
+ Err(TrySendError::Disconnected(_)) => {
+ trace!("Windows MP4 camera encoder channel disconnected");
+ }
+ }
}
Ok(())
diff --git a/crates/recording/src/output_pipeline/win_fragmented_m4s.rs b/crates/recording/src/output_pipeline/win_fragmented_m4s.rs
index 980af6b1a..007c85526 100644
--- a/crates/recording/src/output_pipeline/win_fragmented_m4s.rs
+++ b/crates/recording/src/output_pipeline/win_fragmented_m4s.rs
@@ -15,18 +15,20 @@ use std::{
sync::{
Arc, Mutex,
atomic::AtomicBool,
- mpsc::{SyncSender, sync_channel},
+ mpsc::{RecvTimeoutError, SyncSender, sync_channel},
},
thread::JoinHandle,
time::Duration,
};
use tracing::*;
+const DEFAULT_MUXER_BUFFER_SIZE: usize = 240;
+
fn get_muxer_buffer_size() -> usize {
std::env::var("CAP_MUXER_BUFFER_SIZE")
.ok()
.and_then(|s| s.parse().ok())
- .unwrap_or(3)
+ .unwrap_or(DEFAULT_MUXER_BUFFER_SIZE)
}
struct FrameDropTracker {
@@ -54,6 +56,7 @@ impl FrameDropTracker {
self.check_drop_rate();
}
+ #[allow(dead_code)]
fn record_drop(&mut self) {
self.drops_in_window += 1;
self.total_drops += 1;
@@ -153,7 +156,7 @@ impl Muxer for WindowsFragmentedM4SMuxer {
.shared_pause_state
.unwrap_or_else(|| SharedPauseState::new(pause_flag));
- Ok(Self {
+ let mut muxer = Self {
base_path: output_path,
video_config,
segment_duration: config.segment_duration,
@@ -164,7 +167,11 @@ impl Muxer for WindowsFragmentedM4SMuxer {
frame_drops: FrameDropTracker::new(),
started: false,
disk_space_callback: config.disk_space_callback,
- })
+ };
+
+ muxer.start_encoder()?;
+
+ Ok(muxer)
}
fn stop(&mut self) {
@@ -257,6 +264,7 @@ impl WindowsFragmentedM4SMuxer {
let encoder = Arc::new(Mutex::new(encoder));
let encoder_clone = encoder.clone();
+ let video_config = self.video_config;
let encoder_handle = std::thread::Builder::new()
.name("win-m4s-segment-encoder".to_string())
.spawn(move || {
@@ -266,70 +274,185 @@ impl WindowsFragmentedM4SMuxer {
return Err(anyhow!("Failed to send ready signal - receiver dropped"));
}
+ let frame_interval = Duration::from_secs_f64(1.0 / video_config.fps() as f64);
+ let mut last_ffmpeg_frame: Option<ffmpeg::frame::Video> = None;
+ let mut last_timestamp: Option<Duration> = None;
+ let mut first_timestamp: Option<Duration> = None;
+
let mut slow_convert_count = 0u32;
let mut slow_encode_count = 0u32;
let mut total_frames = 0u64;
+ let mut duplicated_frames = 0u64;
const SLOW_THRESHOLD_MS: u128 = 5;
- while let Ok(Some((d3d_frame, timestamp))) = video_rx.recv() {
- let convert_start = std::time::Instant::now();
+ let normalize_timestamp =
+ |ts: Duration, first: &mut Option<Duration>| -> Duration {
+ if let Some(first_ts) = *first {
+ ts.checked_sub(first_ts).unwrap_or(Duration::ZERO)
+ } else {
+ *first = Some(ts);
+ Duration::ZERO
+ }
+ };
+
+ let encode_frame_fn = |ffmpeg_frame: ffmpeg::frame::Video,
+ timestamp: Duration,
+ slow_encode_count: &mut u32,
+ total_frames: &mut u64,
+ encoder: &Arc<Mutex<SegmentedVideoEncoder>>|
+ -> anyhow::Result<()> {
+ let encode_start = std::time::Instant::now();
+
+ match encoder.lock() {
+ Ok(mut enc) => {
+ if let Err(e) = enc.queue_frame(ffmpeg_frame, timestamp) {
+ warn!("Failed to encode frame: {e}");
+ }
+ }
+ Err(_) => {
+ return Err(anyhow!(
+ "Encoder mutex poisoned - all subsequent frames would be lost"
+ ));
+ }
+ }
- let ffmpeg_frame_result = d3d_frame.as_ffmpeg();
- let convert_elapsed_ms = convert_start.elapsed().as_millis();
+ let encode_elapsed_ms = encode_start.elapsed().as_millis();
- if convert_elapsed_ms > SLOW_THRESHOLD_MS {
- slow_convert_count += 1;
- if slow_convert_count <= 5 || slow_convert_count.is_multiple_of(100) {
+ if encode_elapsed_ms > SLOW_THRESHOLD_MS {
+ *slow_encode_count += 1;
+ if *slow_encode_count <= 5 || slow_encode_count.is_multiple_of(100) {
debug!(
- elapsed_ms = convert_elapsed_ms,
- count = slow_convert_count,
- "D3D11 frame conversion exceeded {}ms threshold",
+ elapsed_ms = encode_elapsed_ms,
+ count = *slow_encode_count,
+ "encoder.queue_frame exceeded {}ms threshold",
SLOW_THRESHOLD_MS
);
}
}
- match ffmpeg_frame_result {
- Ok(ffmpeg_frame) => {
- let encode_start = std::time::Instant::now();
+ *total_frames += 1;
+ Ok(())
+ };
- match encoder_clone.lock() {
- Ok(mut encoder) => {
- if let Err(e) = encoder.queue_frame(ffmpeg_frame, timestamp) {
- warn!("Failed to encode frame: {e}");
+ loop {
+ let convert_start = std::time::Instant::now();
+
+ let (ffmpeg_frame, timestamp) = match video_rx.recv_timeout(frame_interval) {
+ Ok(Some((frame, ts))) => match frame.as_ffmpeg() {
+ Ok(f) => {
+ last_ffmpeg_frame = Some(f.clone());
+ last_timestamp = Some(ts);
+ (Some(f), ts)
+ }
+ Err(e) => {
+ warn!("Failed to convert D3D11 frame: {e:?}");
+ match (&last_ffmpeg_frame, last_timestamp) {
+ (Some(f), Some(last_ts)) => {
+ let new_ts = last_ts.saturating_add(frame_interval);
+ last_timestamp = Some(new_ts);
+ duplicated_frames += 1;
+ (Some(f.clone()), new_ts)
}
+ _ => (None, Duration::ZERO),
}
- Err(_) => {
- error!("Encoder mutex poisoned - encoder thread likely panicked, stopping");
- return Err(anyhow!("Encoder mutex poisoned - all subsequent frames would be lost"));
+ }
+ },
+ Ok(None) | Err(RecvTimeoutError::Disconnected) => {
+ let mut drained = 0u64;
+ let drain_start = std::time::Instant::now();
+ let drain_timeout = Duration::from_millis(500);
+
+ loop {
+ match video_rx.recv_timeout(Duration::from_millis(10)) {
+ Ok(Some((frame, ts))) => {
+ if let Ok(f) = frame.as_ffmpeg() {
+ let normalized_ts =
+ normalize_timestamp(ts, &mut first_timestamp);
+ if let Err(e) = encode_frame_fn(
+ f,
+ normalized_ts,
+ &mut slow_encode_count,
+ &mut total_frames,
+ &encoder_clone,
+ ) {
+ warn!("Failed to encode drained frame: {e}");
+ break;
+ }
+ drained += 1;
+ }
+ }
+ Ok(None) => break,
+ Err(RecvTimeoutError::Timeout) => {
+ if drain_start.elapsed() > drain_timeout {
+ break;
+ }
+ }
+ Err(RecvTimeoutError::Disconnected) => break,
}
}
- let encode_elapsed_ms = encode_start.elapsed().as_millis();
-
- if encode_elapsed_ms > SLOW_THRESHOLD_MS {
- slow_encode_count += 1;
- if slow_encode_count <= 5 || slow_encode_count.is_multiple_of(100) {
- debug!(
- elapsed_ms = encode_elapsed_ms,
- count = slow_encode_count,
- "encoder.queue_frame exceeded {}ms threshold",
- SLOW_THRESHOLD_MS
- );
+ if drained > 0 {
+ debug!(drained = drained, "Drained remaining frames before exit");
+ }
+ break;
+ }
+ Err(RecvTimeoutError::Timeout) => {
+ match (&last_ffmpeg_frame, last_timestamp) {
+ (Some(f), Some(last_ts)) => {
+ let new_ts = last_ts.saturating_add(frame_interval);
+ last_timestamp = Some(new_ts);
+ duplicated_frames += 1;
+ (Some(f.clone()), new_ts)
}
+ _ => continue,
}
}
- Err(e) => {
- warn!("Failed to convert D3D11 frame to FFmpeg: {e:?}");
+ };
+
+ let convert_elapsed_ms = convert_start.elapsed().as_millis();
+
+ let Some(ffmpeg_frame) = ffmpeg_frame else {
+ match video_rx.recv() {
+ Ok(Some((frame, ts))) => {
+ if let Ok(f) = frame.as_ffmpeg() {
+ last_ffmpeg_frame = Some(f);
+ last_timestamp = Some(ts);
+ }
+ }
+ Ok(None) | Err(_) => break,
+ }
+ continue;
+ };
+
+ if convert_elapsed_ms > SLOW_THRESHOLD_MS {
+ slow_convert_count += 1;
+ if slow_convert_count <= 5 || slow_convert_count.is_multiple_of(100) {
+ debug!(
+ elapsed_ms = convert_elapsed_ms,
+ count = slow_convert_count,
+ "D3D11 frame conversion exceeded {}ms threshold",
+ SLOW_THRESHOLD_MS
+ );
}
}
- total_frames += 1;
+ let normalized_ts = normalize_timestamp(timestamp, &mut first_timestamp);
+ if let Err(e) = encode_frame_fn(
+ ffmpeg_frame,
+ normalized_ts,
+ &mut slow_encode_count,
+ &mut total_frames,
+ &encoder_clone,
+ ) {
+ error!("Encoder mutex poisoned - encoder thread likely panicked, stopping");
+ return Err(e);
+ }
}
if total_frames > 0 {
debug!(
total_frames = total_frames,
+ duplicated_frames = duplicated_frames,
slow_converts = slow_convert_count,
slow_encodes = slow_encode_count,
slow_convert_pct = format!(
@@ -380,26 +503,14 @@ impl VideoMuxer for WindowsFragmentedM4SMuxer {
return Ok(());
};
- if !self.started {
- self.start_encoder()?;
- }
-
if let Some(state) = &self.state {
- match state
- .video_tx
- .try_send(Some((frame.frame, adjusted_timestamp)))
- {
+ match state.video_tx.send(Some((frame.frame, adjusted_timestamp))) {
Ok(()) => {
self.frame_drops.record_frame();
}
- Err(e) => match e {
- std::sync::mpsc::TrySendError::Full(_) => {
- self.frame_drops.record_drop();
- }
- std::sync::mpsc::TrySendError::Disconnected(_) => {
- trace!("Windows M4S encoder channel disconnected");
- }
- },
+ Err(_) => {
+ trace!("Windows M4S encoder channel disconnected");
+ }
}
}
@@ -477,7 +588,7 @@ impl Muxer for WindowsFragmentedM4SCameraMuxer {
.shared_pause_state
.unwrap_or_else(|| SharedPauseState::new(pause_flag));
- Ok(Self {
+ let mut muxer = Self {
base_path: output_path,
video_config,
segment_duration: config.segment_duration,
@@ -488,7 +599,11 @@ impl Muxer for WindowsFragmentedM4SCameraMuxer {
frame_drops: FrameDropTracker::new(),
started: false,
disk_space_callback: config.disk_space_callback,
- })
+ };
+
+ muxer.start_encoder()?;
+
+ Ok(muxer)
}
fn stop(&mut self) {
@@ -583,6 +698,7 @@ impl WindowsFragmentedM4SCameraMuxer {
let encoder = Arc::new(Mutex::new(encoder));
let encoder_clone = encoder.clone();
+ let video_config = self.video_config;
let encoder_handle = std::thread::Builder::new()
.name("win-m4s-camera-segment-encoder".to_string())
.spawn(move || {
@@ -594,69 +710,183 @@ impl WindowsFragmentedM4SCameraMuxer {
));
}
+ let frame_interval = Duration::from_secs_f64(1.0 / video_config.fps() as f64);
+ let mut last_frame: Option<NativeCameraFrame> = None;
+ let mut last_timestamp: Option<Duration> = None;
+ let mut first_timestamp: Option<Duration> = None;
+
let mut slow_convert_count = 0u32;
let mut slow_encode_count = 0u32;
let mut total_frames = 0u64;
+ let mut duplicated_frames = 0u64;
const SLOW_THRESHOLD_MS: u128 = 5;
- while let Ok(Some((camera_frame, timestamp))) = video_rx.recv() {
- let convert_start = std::time::Instant::now();
- let ffmpeg_frame_result = camera_frame_to_ffmpeg(&camera_frame);
- let convert_elapsed_ms = convert_start.elapsed().as_millis();
-
- if convert_elapsed_ms > SLOW_THRESHOLD_MS {
- slow_convert_count += 1;
- if slow_convert_count <= 5 || slow_convert_count.is_multiple_of(100) {
- debug!(
- elapsed_ms = convert_elapsed_ms,
- count = slow_convert_count,
- "Camera frame conversion exceeded {}ms threshold",
- SLOW_THRESHOLD_MS
- );
+ let normalize_timestamp =
+ |ts: Duration, first: &mut Option<Duration>| -> Duration {
+ if let Some(first_ts) = *first {
+ ts.checked_sub(first_ts).unwrap_or(Duration::ZERO)
+ } else {
+ *first = Some(ts);
+ Duration::ZERO
+ }
+ };
+
+ let encode_camera_frame_fn =
+ |camera_frame: &NativeCameraFrame,
+ timestamp: Duration,
+ slow_convert_count: &mut u32,
+ slow_encode_count: &mut u32,
+ total_frames: &mut u64,
+ encoder: &Arc<Mutex<SegmentedVideoEncoder>>|
+ -> anyhow::Result<()> {
+ let convert_start = std::time::Instant::now();
+ let ffmpeg_frame_result = camera_frame_to_ffmpeg(camera_frame);
+ let convert_elapsed_ms = convert_start.elapsed().as_millis();
+
+ if convert_elapsed_ms > SLOW_THRESHOLD_MS {
+ *slow_convert_count += 1;
+ if *slow_convert_count <= 5 || slow_convert_count.is_multiple_of(100) {
+ debug!(
+ elapsed_ms = convert_elapsed_ms,
+ count = *slow_convert_count,
+ "Camera frame conversion exceeded {}ms threshold",
+ SLOW_THRESHOLD_MS
+ );
+ }
}
- }
- match ffmpeg_frame_result {
- Ok(ffmpeg_frame) => {
- let encode_start = std::time::Instant::now();
+ match ffmpeg_frame_result {
+ Ok(ffmpeg_frame) => {
+ let encode_start = std::time::Instant::now();
- match encoder_clone.lock() {
- Ok(mut encoder) => {
- if let Err(e) = encoder.queue_frame(ffmpeg_frame, timestamp) {
- warn!("Failed to encode camera frame: {e}");
+ match encoder.lock() {
+ Ok(mut enc) => {
+ if let Err(e) = enc.queue_frame(ffmpeg_frame, timestamp) {
+ warn!("Failed to encode camera frame: {e}");
+ }
+ }
+ Err(_) => {
+ return Err(anyhow!(
+ "Camera encoder mutex poisoned - all subsequent frames would be lost"
+ ));
}
}
- Err(_) => {
- error!("Camera encoder mutex poisoned - encoder thread likely panicked, stopping");
- return Err(anyhow!("Camera encoder mutex poisoned - all subsequent frames would be lost"));
+
+ let encode_elapsed_ms = encode_start.elapsed().as_millis();
+
+ if encode_elapsed_ms > SLOW_THRESHOLD_MS {
+ *slow_encode_count += 1;
+ if *slow_encode_count <= 5
+ || slow_encode_count.is_multiple_of(100)
+ {
+ debug!(
+ elapsed_ms = encode_elapsed_ms,
+ count = *slow_encode_count,
+ "Camera encoder.queue_frame exceeded {}ms threshold",
+ SLOW_THRESHOLD_MS
+ );
+ }
}
}
+ Err(e) => {
+ warn!("Failed to convert camera frame: {e:?}");
+ }
+ }
- let encode_elapsed_ms = encode_start.elapsed().as_millis();
-
- if encode_elapsed_ms > SLOW_THRESHOLD_MS {
- slow_encode_count += 1;
- if slow_encode_count <= 5 || slow_encode_count.is_multiple_of(100) {
- debug!(
- elapsed_ms = encode_elapsed_ms,
- count = slow_encode_count,
- "Camera encoder.queue_frame exceeded {}ms threshold",
- SLOW_THRESHOLD_MS
- );
+ *total_frames += 1;
+ Ok(())
+ };
+
+ loop {
+ let (frame_to_encode, timestamp) = match video_rx.recv_timeout(frame_interval) {
+ Ok(Some((frame, ts))) => {
+ last_frame = Some(frame.clone());
+ last_timestamp = Some(ts);
+ (Some(frame), ts)
+ }
+ Ok(None) | Err(RecvTimeoutError::Disconnected) => {
+ let mut drained = 0u64;
+ let drain_start = std::time::Instant::now();
+ let drain_timeout = Duration::from_millis(500);
+
+ loop {
+ match video_rx.recv_timeout(Duration::from_millis(10)) {
+ Ok(Some((frame, ts))) => {
+ let normalized_ts =
+ normalize_timestamp(ts, &mut first_timestamp);
+ if let Err(e) = encode_camera_frame_fn(
+ &frame,
+ normalized_ts,
+ &mut slow_convert_count,
+ &mut slow_encode_count,
+ &mut total_frames,
+ &encoder_clone,
+ ) {
+ warn!("Failed to encode drained camera frame: {e}");
+ break;
+ }
+ drained += 1;
+ }
+ Ok(None) => break,
+ Err(RecvTimeoutError::Timeout) => {
+ if drain_start.elapsed() > drain_timeout {
+ break;
+ }
+ }
+ Err(RecvTimeoutError::Disconnected) => break,
}
}
+
+ if drained > 0 {
+ debug!(
+ drained = drained,
+ "Drained remaining camera frames before exit"
+ );
+ }
+ break;
}
- Err(e) => {
- warn!("Failed to convert camera frame: {e:?}");
+ Err(RecvTimeoutError::Timeout) => {
+ match (&last_frame, last_timestamp) {
+ (Some(f), Some(last_ts)) => {
+ let new_ts = last_ts.saturating_add(frame_interval);
+ last_timestamp = Some(new_ts);
+ duplicated_frames += 1;
+ (Some(f.clone()), new_ts)
+ }
+ _ => continue,
+ }
}
- }
+ };
- total_frames += 1;
+ let Some(camera_frame) = frame_to_encode else {
+ match video_rx.recv() {
+ Ok(Some((frame, ts))) => {
+ last_frame = Some(frame);
+ last_timestamp = Some(ts);
+ }
+ Ok(None) | Err(_) => break,
+ }
+ continue;
+ };
+
+ let normalized_ts = normalize_timestamp(timestamp, &mut first_timestamp);
+ if let Err(e) = encode_camera_frame_fn(
+ &camera_frame,
+ normalized_ts,
+ &mut slow_convert_count,
+ &mut slow_encode_count,
+ &mut total_frames,
+ &encoder_clone,
+ ) {
+ error!("Camera encoder mutex poisoned - encoder thread likely panicked, stopping");
+ return Err(e);
+ }
}
if total_frames > 0 {
debug!(
total_frames = total_frames,
+ duplicated_frames = duplicated_frames,
slow_converts = slow_convert_count,
slow_encodes = slow_encode_count,
slow_convert_pct = format!(
@@ -707,23 +937,14 @@ impl VideoMuxer for WindowsFragmentedM4SCameraMuxer {
return Ok(());
};
- if !self.started {
- self.start_encoder()?;
- }
-
if let Some(state) = &self.state {
- match state.video_tx.try_send(Some((frame, adjusted_timestamp))) {
+ match state.video_tx.send(Some((frame, adjusted_timestamp))) {
Ok(()) => {
self.frame_drops.record_frame();
}
- Err(e) => match e {
- std::sync::mpsc::TrySendError::Full(_) => {
- self.frame_drops.record_drop();
- }
- std::sync::mpsc::TrySendError::Disconnected(_) => {
- trace!("Windows M4S camera encoder channel disconnected");
- }
- },
+ Err(_) => {
+ trace!("Windows M4S camera encoder channel disconnected");
+ }
}
}
diff --git a/crates/recording/src/sources/screen_capture/windows.rs b/crates/recording/src/sources/screen_capture/windows.rs
index a73932037..680f02a5c 100644
--- a/crates/recording/src/sources/screen_capture/windows.rs
+++ b/crates/recording/src/sources/screen_capture/windows.rs
@@ -183,23 +183,31 @@ impl output_pipeline::VideoSource for VideoSource {
};
let video_frame_counter: Arc<AtomicU32> = Arc::new(AtomicU32::new(0));
+ let video_drop_counter: Arc<AtomicU32> = Arc::new(AtomicU32::new(0));
let cancel_token = CancellationToken::new();
let res = scap_direct3d::Capturer::new(
capture_item,
settings,
{
- let video_frame_counter = video_frame_counter.clone();
- move |frame| {
- video_frame_counter.fetch_add(1, atomic::Ordering::Relaxed);
- let timestamp = frame.inner().SystemRelativeTime()?;
- let timestamp = Timestamp::PerformanceCounter(
- PerformanceCounterTimestamp::new(timestamp.Duration),
- );
- let _ = video_tx.try_send(VideoFrame { frame, timestamp });
-
- Ok(())
- }
+ let video_frame_counter = video_frame_counter.clone();
+ let video_drop_counter = video_drop_counter.clone();
+ move |frame| {
+ let timestamp = frame.inner().SystemRelativeTime()?;
+ let timestamp = Timestamp::PerformanceCounter(
+ PerformanceCounterTimestamp::new(timestamp.Duration),
+ );
+ match video_tx.try_send(VideoFrame { frame, timestamp }) {
+ Ok(()) => {
+ video_frame_counter.fetch_add(1, atomic::Ordering::Relaxed);
+ }
+ Err(_) => {
+ video_drop_counter.fetch_add(1, atomic::Ordering::Relaxed);
+ }
+ }
+
+ Ok(())
+ }
},
{
let mut error_tx = error_tx.clone();
@@ -230,16 +238,29 @@ impl output_pipeline::VideoSource for VideoSource {
tokio_rt.spawn(
async move {
- loop {
- tokio::time::sleep(Duration::from_secs(5)).await;
- debug!(
- "Captured {} frames",
- video_frame_counter.load(atomic::Ordering::Relaxed)
- );
- }
- }
- .with_cancellation_token_owned(cancel_token.clone())
- .in_current_span()
+ loop {
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ let captured = video_frame_counter.load(atomic::Ordering::Relaxed);
+ let dropped = video_drop_counter.load(atomic::Ordering::Relaxed);
+ let total = captured + dropped;
+ if dropped > 0 {
+ let drop_pct = if total > 0 { 100.0 * dropped as f64 / total as f64 } else { 0.0 };
+ warn!(
+ captured = captured,
+ dropped = dropped,
+ drop_pct = format!("{:.1}%", drop_pct),
+ "Screen capture source dropping frames due to full channel"
+ );
+ } else {
+ debug!(
+ captured = captured,
+ "Screen capture frames"
+ );
+ }
+ }
+ }
+ .with_cancellation_token_owned(cancel_token.clone())
+ .in_current_span()
);
let drop_guard = cancel_token.drop_guard();
diff --git a/crates/video-decode/Cargo.toml b/crates/video-decode/Cargo.toml
index 35f362662..a38c9bda9 100644
--- a/crates/video-decode/Cargo.toml
+++ b/crates/video-decode/Cargo.toml
@@ -10,6 +10,7 @@ workspace = true
ffmpeg.workspace = true
ffmpeg-hw-device = { path = "../ffmpeg-hw-device" }
num_cpus = "1.17.0"
+tempfile = "3"
tokio = { workspace = true, features = ["rt", "rt-multi-thread"] }
tracing = "0.1.41"
workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/video-decode/src/ffmpeg.rs b/crates/video-decode/src/ffmpeg.rs
index 7a7a69f29..f5bb10349 100644
--- a/crates/video-decode/src/ffmpeg.rs
+++ b/crates/video-decode/src/ffmpeg.rs
@@ -8,6 +8,7 @@ use ffmpeg::{
use ffmpeg_hw_device::{CodecContextExt, HwDevice};
use std::path::PathBuf;
use std::sync::OnceLock;
+use tempfile::NamedTempFile;
use tracing::*;
#[derive(Debug, Clone)]
@@ -176,6 +177,56 @@ pub struct FFmpegDecoder {
stream_index: usize,
hw_device: Option<HwDevice>,
start_time: i64,
+ _temp_file: Option<NamedTempFile>,
+}
+
+fn combine_fragmented_segments(dir_path: &std::path::Path) -> Result<NamedTempFile, String> {
+ let init_segment = dir_path.join("init.mp4");
+ if !init_segment.exists() {
+ return Err(format!(
+ "init.mp4 not found in fragmented directory: {}",
+ dir_path.display()
+ ));
+ }
+
+ let mut fragments: Vec<PathBuf> = std::fs::read_dir(dir_path)
+ .map_err(|e| format!("read fragmented directory / {e}"))?
+ .filter_map(|e| e.ok())
+ .map(|e| e.path())
+ .filter(|p| p.extension().is_some_and(|ext| ext == "m4s"))
+ .collect();
+
+ fragments.sort();
+
+ if fragments.is_empty() {
+ return Err(format!(
+ "no .m4s segments found in fragmented directory: {}",
+ dir_path.display()
+ ));
+ }
+
+ let mut combined_data =
+ std::fs::read(&init_segment).map_err(|e| format!("read init.mp4 / {e}"))?;
+
+ for fragment in &fragments {
+ let data = std::fs::read(fragment)
+ .map_err(|e| format!("read fragment {} / {e}", fragment.display()))?;
+ combined_data.extend(data);
+ }
+
+ let temp_file = NamedTempFile::new().map_err(|e| format!("create temp file / {e}"))?;
+
+ std::fs::write(temp_file.path(), &combined_data)
+ .map_err(|e| format!("write combined file / {e}"))?;
+
+ info!(
+ "Combined {} fragmented segments ({} bytes) into temp file: {}",
+ fragments.len(),
+ combined_data.len(),
+ temp_file.path().display()
+ );
+
+ Ok(temp_file)
}
impl FFmpegDecoder {
@@ -183,77 +234,80 @@ impl FFmpegDecoder {
path: impl Into<PathBuf>,
hw_device_type: Option<AVHWDeviceType>,
) -> Result<Self, String> {
- fn inner(
- path: PathBuf,
- hw_device_type: Option<AVHWDeviceType>,
- ) -> Result<FFmpegDecoder, String> {
- let input = ffmpeg::format::input(&path).map_err(|e| format!("open file / {e}"))?;
-
- let input_stream = input
- .streams()
- .best(avutil::media::Type::Video)
- .ok_or_else(|| "no video stream".to_string())?;
-
- let start_time = input_stream.start_time();
-
- let stream_index = input_stream.index();
-
- let mut decoder = avcodec::Context::from_parameters(input_stream.parameters())
- .map_err(|e| format!("decoder context / {e}"))?
- .decoder()
- .video()
- .map_err(|e| format!("video decoder / {e}"))?;
-
- decoder.set_time_base(input_stream.time_base());
-
- let width = decoder.width();
- let height = decoder.height();
-
- let hw_caps = get_hw_decoder_capabilities();
- let exceeds_hw_limits = width > hw_caps.max_width
- || height > hw_caps.max_height
- || !hw_caps.supports_hw_decode;
-
- let hw_device = hw_device_type.and_then(|hw_device_type| {
- if exceeds_hw_limits {
- warn!(
- "Video dimensions {width}x{height} exceed hardware decoder limits ({}x{}), using software decode",
- hw_caps.max_width, hw_caps.max_height
- );
- configure_software_threading(&mut decoder, width, height);
- None
- } else {
- match decoder.try_use_hw_device(hw_device_type) {
- Ok(device) => {
- info!(
- "Using hardware acceleration for {width}x{height} video (device: {:?})",
- hw_device_type
- );
- Some(device)
- }
- Err(error) => {
- warn!("Failed to enable hardware decoder: {error:?}, falling back to optimized software decode");
- configure_software_threading(&mut decoder, width, height);
- None
- }
- }
- }
- });
+ let path = path.into();
+
+ let (effective_path, temp_file): (PathBuf, Option<NamedTempFile>) = if path.is_dir() {
+ let temp = combine_fragmented_segments(&path)?;
+ (temp.path().to_path_buf(), Some(temp))
+ } else {
+ (path, None)
+ };
+
+ let input =
+ ffmpeg::format::input(&effective_path).map_err(|e| format!("open file / {e}"))?;
+
+ let input_stream = input
+ .streams()
+ .best(avutil::media::Type::Video)
+ .ok_or_else(|| "no video stream".to_string())?;
+
+ let start_time = input_stream.start_time();
+
+ let stream_index = input_stream.index();
+
+ let mut decoder = avcodec::Context::from_parameters(input_stream.parameters())
+ .map_err(|e| format!("decoder context / {e}"))?
+ .decoder()
+ .video()
+ .map_err(|e| format!("video decoder / {e}"))?;
- if hw_device.is_none() && hw_device_type.is_none() {
+ decoder.set_time_base(input_stream.time_base());
+
+ let width = decoder.width();
+ let height = decoder.height();
+
+ let hw_caps = get_hw_decoder_capabilities();
+ let exceeds_hw_limits =
+ width > hw_caps.max_width || height > hw_caps.max_height || !hw_caps.supports_hw_decode;
+
+ let hw_device = hw_device_type.and_then(|hw_device_type| {
+ if exceeds_hw_limits {
+ warn!(
+ "Video dimensions {width}x{height} exceed hardware decoder limits ({}x{}), using software decode",
+ hw_caps.max_width, hw_caps.max_height
+ );
configure_software_threading(&mut decoder, width, height);
+ None
+ } else {
+ match decoder.try_use_hw_device(hw_device_type) {
+ Ok(device) => {
+ info!(
+ "Using hardware acceleration for {width}x{height} video (device: {:?})",
+ hw_device_type
+ );
+ Some(device)
+ }
+ Err(error) => {
+ warn!("Failed to enable hardware decoder: {error:?}, falling back to optimized software decode");
+ configure_software_threading(&mut decoder, width, height);
+ None
+ }
+ }
}
+ });
- Ok(FFmpegDecoder {
- input,
- decoder,
- stream_index,
- hw_device,
- start_time,
- })
+ if hw_device.is_none() && hw_device_type.is_none() {
+ configure_software_threading(&mut decoder, width, height);
}
- inner(path.into(), hw_device_type)
+ Ok(FFmpegDecoder {
+ input,
+ decoder,
+ stream_index,
+ hw_device,
+ start_time,
+ _temp_file: temp_file,
+ })
}
pub fn reset(&mut self, requested_time: f32) -> Result<(), ffmpeg::Error> {